@configdirector/client-sdk 0.1.5 → 0.1.7

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.
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require(`eventsource-client`);var t=class{constructor(){this.handlerMap=new Map}on(e,t){let n=this.handlerMap.get(e);n?n.push(t):this.handlerMap.set(e,[t])}once(e,t){let n=this;function r(i){n.off(e,r),t.apply(n,i)}this.on(e,r)}off(e,t){let n=this.handlerMap.get(e);if(n)if(t){let e=n.indexOf(t);e>=0&&n.splice(e,1)}else this.handlerMap.set(e,[])}clear(){this.handlerMap.clear()}emit(e,t){let n=this.handlerMap.get(e);n&&n.slice().map(e=>e(t))}},n=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},r=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}};const i=e=>{if(e instanceof DOMException){if(e.name===`NotAllowedError`)return!0}else if(e instanceof TypeError)return!0;return!1};var a=class{constructor(e){this.options=e,this.eventEmitter=new t,this.options=e,this.logger=e.logger,this.url=new URL(`sse/v1`,e.baseUrl)}async connect(t,n){this.eventSource&&this.close();let r,i,a=async(e,t)=>{let n=await fetch(e,t);return r=n.status,n.ok||(i=await n.text()),n},o=new Promise((n,o)=>{this.eventSource=(0,e.createEventSource)({url:this.url,fetch:a,method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:t,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey}),onMessage:({data:e})=>{this.dispatchMessage(e)},onConnect:()=>{r&&this.isStatusFatal(r)?(this.close(),o(this.prepareFatalError(r,i))):(this.logger.debug(`[EventSourceTransport] Connected, status: %s`,r),n(this))},onScheduleReconnect:e=>{r&&this.isStatusFatal(r)?(this.close(),o(this.prepareFatalError(r,i))):this.logger.warn(`[EventSourceTransport] Scheduling reconnect in ${e.delay}. Response status: ${r}`)},onDisconnect:()=>{this.logger.debug(`[EventSourceTransport] Disconnected`)}})});return Promise.race([o,new Promise(e=>{setTimeout(()=>e(this),n)})])}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configSetReceived`,t)}catch(e){this.logger.error(`[EventSourceTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,t){let r=e??0;return new n(`${`Connection failed with status: ${e??`unknown`}`}${(t?.trim()?.length??0)>0?` (${t})`:``}. This is an unrecoverable error, will not attempt to reconnect.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}close(){this.eventSource?.close()}dispose(){this.close(),this.clear()}};const o=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},s=e=>e===`number`||e===`bigint`,c=(e,t)=>{let n=e.value,r=o(t);if(!n)return{parsedValue:t,requestedType:r,usedDefault:!0,reason:`value-missing`};if(typeof t==`string`)return{parsedValue:n,requestedType:r,usedDefault:!1,reason:`found-match`};if(typeof t==`boolean`&&e.type===`boolean`){let e=l(n),i=typeof e==`boolean`;return{parsedValue:i?e:t,requestedType:r,usedDefault:!i,reason:i?`found-match`:`invalid-boolean`}}if(s(typeof t)&&e.type===`integer`){let e=u(n),i=typeof e==`number`;return{parsedValue:i?e:t,requestedType:r,usedDefault:!i,reason:i?`found-match`:`invalid-number`}}if(s(typeof t)&&(e.type===`float`||e.type===`enum`)){let e=d(n),i=typeof e==`number`;return{parsedValue:i?e:t,requestedType:r,usedDefault:!i,reason:i?`found-match`:`invalid-number`}}return{parsedValue:n,requestedType:r,usedDefault:!1,reason:`found-match`}},l=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},u=e=>{if(!e)return;let t=Number.parseInt(e);if(!(isNaN(t)||!isFinite(t)))return t},d=e=>{if(!e)return;let t=Number.parseFloat(e);if(!(isNaN(t)||!isFinite(t)))return t},f={off:-1,error:0,warn:1,info:2,debug:3},p=()=>{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 m=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=p()}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){f[this.level]>=f[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},h=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const g=(e,t)=>new m(e??`warn`,t??new h);var _=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}))}},v=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}},y=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.url=new URL(`telemetry/v1`,e.baseUrl)}report({discreteEvents:e,aggregatedEvents:t,droppedEvents:n}){if(!this.executeRequests)return{success:!1,fatalError:!0};let r={clientSdkKey:this.sdkKey,discreteEvents:e,aggregatedEvents:t,droppedEvents:n};if(this.isReportEmpty(r))return{success:!0,fatalError:!1};let i=this.sendReport(r);return i.fatalError&&(this.executeRequests=!1),i}isReportEmpty(e){return this.isEventListEmpty(e.discreteEvents)&&this.isEventListEmpty(e.aggregatedEvents)&&this.isDroppedEventsEmpty(e.droppedEvents)}isDroppedEventsEmpty(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}isEventListEmpty(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}sendReport(e){try{return{success:navigator.sendBeacon(this.url,JSON.stringify(e)),fatalError:!1}}catch(e){return this.logger.warn(`[EventReporter] Fatal error attempting to send telemetry data: ${e}. No more telemetry data will be sent.`),{success:!1,fatalError:!0}}}};const b=e=>x(new TextEncoder().encode(e)).toString(16).padStart(8,`0`),x=e=>{let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e[n],t>>>=0;return t};var S=class{constructor(e){this.evaluationEventQueue=new v,this.aggregator=new _,this.collectEvents=!0,this.logger=e.logger,this.reporter=new y(e),this.flushIntervalDelay=3e4,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),5e3);try{document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&this.flush()})}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(e))}sanitizeEvaluatedConfigEvent(e){return{key:e.key,type:e.type,defaultValue:this.sanitizeValue(e.defaultValue,e.type),requestedType:e.requestedType,evaluatedValue:this.sanitizeValue(e.evaluatedValue,e.type),usedDefault:e.usedDefault,evaluationReason:e.evaluationReason}}sanitizeValue(e,t){if(t===`json`)try{return b(JSON.stringify(e))}catch{return e.toString().slice(0,500)}return e.toString().slice(0,500)}flushAndScheduleNext(){this.flush().fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay)}flush(){let e=this.evaluationEventQueue.takeSnapshot();return this.reporter.report({discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount}})}close(){this.collectEvents=!1,clearTimeout(this.flushTimeout),this.flush(),this.evaluationEventQueue.clear()}dispose(){this.close()}};const C=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(t,{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}};var w=class{constructor(e){this.options=e,this.eventEmitter=new t,this.fatalError=!1,this.options=e,this.logger=e.logger,this.url=new URL(`pull/v1`,e.baseUrl)}async connect(e,t){if(this.fatalError)return this.logger.warn(`[PullTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`),this;try{let r=await C(t,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey})},this.logger);if(!r.ok)throw this.isStatusFatal(r.status)?(this.fatalError=!0,this.prepareFatalResponseStatusError(r.status,await r.text())):new n(`Connection failed with status: ${r.status}`,r.status);let i=JSON.parse(await r.text());return this.eventEmitter.emit(`configSetReceived`,i),this}catch(e){throw i(e)?(this.fatalError=!0,new n(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new n(`Failed to parse the response from the server: ${e}`):new n(`Connection failed with error: ${e}.`)}}prepareFatalResponseStatusError(e,t){let r=e??0;return new n(`${`Connection failed with status: ${e??`unknown`}`}${(t?.trim()?.length??0)>0?` (${t})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}close(){}dispose(){this.close(),this.clear()}};const T=new URL(`https://client-sdk-api.configdirector.com`);var E=class{constructor(e,n,r){this.handlersMap=new Map,this.eventEmitter=new t,this.ready=!1,this.logger=r?.logger??g(),this.timeout=r?.connection?.timeout??3e3;let i=this.parseUrl(r?.connection?.url)??T;this.streaming=r?.connection?.streaming!==!1;let o=this.streaming?a:w;this.usageEventCollector=new S({sdkKey:e,logger:this.logger,baseUrl:i}),this.transport=new o({clientSdkKey:e,baseUrl:i,metaContext:{...r?.metadata,sdkName:n.sdkName,sdkVersion:n.sdkVersion,userAgent:navigator?.userAgent},logger:this.logger}),this.transport.on(`configSetReceived`,e=>{this.readyResolve?.();let t=Object.keys(e.configs);!this.configSet||e.kind==`full`?(this.configSet=e,this.eventEmitter.emit(`configsUpdated`,{keys:t}),this.updateWatchers(e.configs)):(this.configSet.configs={...this.configSet.configs,...e.configs},this.eventEmitter.emit(`configsUpdated`,{keys:t}),this.updateWatchers(e.configs)),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:t})})}async initialize(e){await this.connectToTransport(e,`initialization`)}async updateContext(e){await this.connectToTransport(e,`context update`)}async connectToTransport(e,t){try{this.ready=!1,this.readyPromise=new Promise(e=>{this.readyResolve=e}).then(()=>{this.ready=!0,this.eventEmitter.emit(`clientReady`,{action:t}),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`)});let n=new Date().getTime();await this.transport.connect(e??{},this.timeout),this.currentContext=e;let r=new Date().getTime()-n,i=this.timeout-r;if(i>0&&await Promise.race([this.readyPromise,new Promise(e=>{setTimeout(()=>e(),i)})]),!this.ready){let e=this.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 ${t} after ${this.timeout}ms. ${e}`)}}catch(e){this.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}updateWatchers(e){Object.values(e).forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){this.handlersMap.get(e.key)?.forEach(t=>{let n=this.getValueFromConfigState(e.key,e,t.defaultValue);t.handler(n)})}watch(e,t,n){this.validateDefaultValue(t);let r=this.handlersMap.get(e),i={handler:n,defaultValue:t,requestedType:typeof t};return r?r.push(i):this.handlersMap.set(e,[i]),()=>this.unwatch(e,n)}unwatch(e,t){let n=this.handlersMap.get(e);if(n)if(t){let e=n.findIndex(e=>e.handler==t);e>=0&&n?.splice(e,1)}else n.splice(0)}getValue(e,t){this.validateDefaultValue(t);let n=this.configSet?.configs[e];return this.getValueFromConfigState(e,n,t)}getValueFromConfigState(e,t,n){if(!t)return this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`),this.usageEventCollector.evaluatedConfig({contextId:this.currentContext?.id,key:e,defaultValue:n,requestedType:o(n),evaluatedValue:n,usedDefault:!0,evaluationReason:`config-state-missing`}),n;let r=c(t,n);return this.usageEventCollector.evaluatedConfig({contextId:this.currentContext?.id,key:e,defaultValue:n,requestedType:r.requestedType,evaluatedValue:r.parsedValue,usedDefault:r.usedDefault,evaluationReason:r.reason}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${r.parsedValue}'`),r.parsedValue}parseUrl(e){if(e)try{return new URL(e)}catch(t){throw new r(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateDefaultValue(e){if(e==null)throw new r(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new r(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.logger.debug(`[ConfigDirectorClient] clear() has been called, removing all observers`),this.eventEmitter.clear(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}close(){this.logger.debug(`[ConfigDirectorClient] close() has been called, closing connection to server`),this.transport.close(),this.ready=!1}dispose(){this.clear(),this.close()}};const D=(e,t)=>new E(e,{sdkName:`js-client-sdk`,sdkVersion:`0.1.7`},t),O=(e,t)=>g(e,t);exports.createClient=D,exports.createConsoleLogger=O;
@@ -0,0 +1,242 @@
1
+ //#region ../js-client-core/src/Emitter.d.ts
2
+ type EventType = string | symbol;
3
+ type EventsRecord = Record<EventType, any>;
4
+ type Handler<TEventsRecord extends EventsRecord, TKey extends keyof TEventsRecord> = (payload: TEventsRecord[TKey]) => void;
5
+ interface EventProvider<TEventsRecord extends EventsRecord> {
6
+ on<TName extends keyof TEventsRecord>(name: TName, handler: Handler<TEventsRecord, TName>): void;
7
+ off<TName extends keyof TEventsRecord>(name: TName, handler?: Handler<TEventsRecord, TName>): void;
8
+ clear(): void;
9
+ }
10
+ //#endregion
11
+ //#region ../js-client-core/src/types.d.ts
12
+ type ConfigEnumLikeType = {
13
+ [key: string]: string | number;
14
+ };
15
+ type ConfigValueType = string | number | boolean | object | ConfigEnumLikeType;
16
+ type ConfigDirectorLoggingLevel = "debug" | "info" | "warn" | "error" | "off";
17
+ interface ConfigDirectorLogger {
18
+ debug(message: string, ...args: any): void;
19
+ info(message: string, ...args: any): void;
20
+ warn(message: string, ...args: any): void;
21
+ error(message: string, ...args: any): void;
22
+ }
23
+ interface ConfigDirectorLogMessageDecorator {
24
+ decorateMessage(message: string): string;
25
+ }
26
+ /**
27
+ * The user's context to be sent to ConfigDirector. This context will be used for targeting
28
+ * rules evaluation.
29
+ */
30
+ type ConfigDirectorContext = {
31
+ /**
32
+ * The user's identifier. This should be a value that uniquely identifies an application
33
+ * user.
34
+ * In the case of anonymous users, you could generate a UUID or alternatively not provide
35
+ * the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
36
+ * value is used for segmenting users in percentage rollouts, and changes to the {@link id}
37
+ * could result in the user being assigned to a different percentile.
38
+ */
39
+ id?: string;
40
+ /**
41
+ * The user's display name. This will be shown in the ConfigDirector dashboard and may be
42
+ * used for targeting rules.
43
+ */
44
+ name?: string;
45
+ /**
46
+ * Any arbitrary traits for the current user. They will be shown in the ConfigDirector
47
+ * dashboard and may be used for targeting rules.
48
+ */
49
+ traits?: {
50
+ [key: string]: unknown;
51
+ };
52
+ };
53
+ /**
54
+ * Configuration options for the {@link ConfigDirectorClient}
55
+ */
56
+ type ConfigDirectorClientOptions = {
57
+ /**
58
+ * Application metadata that remains constant through the lifetime of the connection
59
+ */
60
+ metadata?: {
61
+ appVersion?: string;
62
+ appName?: string;
63
+ };
64
+ /**
65
+ * Connection options
66
+ */
67
+ connection?: {
68
+ /**
69
+ * Whether to open a streaming connection or use a one-time pull of configuration state.
70
+ * If set to true, the streaming connection will remain open and receive updates whenever
71
+ * config state is updated on the ConfigDirector dashboard.
72
+ * When set to false, there will be an initial request to retrieve config state during
73
+ * initialization, and an additional request whenever {@link ConfigDirectorClient.updateContext}
74
+ * is called. But not updates will be received after those requests.
75
+ *
76
+ * Defaults to true (streaming connection)
77
+ */
78
+ streaming?: boolean;
79
+ /**
80
+ * The timeout, in milliseconds, to be used in initialization and when updating the context.
81
+ * If streaming is enabled, the operation (initialization or context update) may still succeed
82
+ * after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
83
+ * If streaming is disabled, if the operation times out, it will not be retried.
84
+ */
85
+ timeout?: number;
86
+ /**
87
+ * The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
88
+ * proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
89
+ * a proxy for the client SDK.
90
+ */
91
+ url?: string;
92
+ };
93
+ /**
94
+ * A logger that implements {@link ConfigDirectorLogger}. It defaults to the ConfigDirector console
95
+ * logger set to 'warn' level.
96
+ *
97
+ * The log level of the default logger can be adjusted by creating a default logger with the desired
98
+ * level and providing it in this property:
99
+ * @example
100
+ * import { createClient, createConsoleLogger } from "@configdirector/client-sdk";
101
+ * const client = createClient(
102
+ * "YOUR-SDK-KEY",
103
+ * { logger: createConsoleLogger("debug") },
104
+ * );
105
+ */
106
+ logger?: ConfigDirectorLogger;
107
+ };
108
+ type ClientConnectAction = "initialization" | "context update";
109
+ type ClientEvents = {
110
+ configsUpdated: {
111
+ keys: string[];
112
+ };
113
+ clientReady: {
114
+ action: ClientConnectAction;
115
+ };
116
+ };
117
+ type WatchHandler<T extends ConfigValueType> = (message: T) => void;
118
+ /**
119
+ * The ConfigDirector SDK client object.
120
+ *
121
+ * Applications should create a single instance of `ConfigDirectorClient`, and call
122
+ * {@link initialize} during application initialization.
123
+ *
124
+ * After initialization, to update the user's context, so that targeting rules are evaluated
125
+ * with the updated context, call {@link updateContext}.
126
+ */
127
+ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
128
+ /**
129
+ * Initializes the connection to ConfigDirector to retrieve config evaluations. Until
130
+ * initialization is successful, all flags will return their default value provided to
131
+ * {@link watch} or {@link getValue}.
132
+ *
133
+ * If the connection fails or is interrupted with a transient error (network error,
134
+ * internal server error, etc) the client will continue to attempt to connect. However,
135
+ * if the connection fails with a persistent error, like an invalid SDK key, the client will
136
+ * not attempt to re-connect and an error will be logged to the console or the provided
137
+ * logger.
138
+ *
139
+ * @param context The current user's context to be used for evaluating targeting rules (optional).
140
+ */
141
+ initialize(context?: ConfigDirectorContext): Promise<void>;
142
+ /**
143
+ * Updates the user's context and re-evaluates all config and flag values based on the new context.
144
+ *
145
+ * @param context The current user's context to be used for evaluating targeting rules (required).
146
+ */
147
+ updateContext(context: ConfigDirectorContext): Promise<void>;
148
+ /**
149
+ * Returns whether or not the client is ready after calling {@link initialize} or {@link updateContext}
150
+ *
151
+ * The definition of ready is that the connection to the server was successful, and config state
152
+ * was received.
153
+ */
154
+ get isReady(): boolean;
155
+ /**
156
+ * Evaluates a config and returns its value based on the current context and targeting rules
157
+ *
158
+ * @returns The evaluated config value, or the `defaultValue` if the config state was unavailable
159
+ * @param configKey The config key to evaluate
160
+ * @param defaultValue The default value to be returned if the config state is unavailable. For
161
+ * example, if the client cannot connect to the server due to network conditions, or if getValue
162
+ * is called before initialization is done.
163
+ */
164
+ getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T;
165
+ /**
166
+ * Watches for changes to a a config evaluation value. Whenever the config value changes, the
167
+ * provided callback function will be called with the new value. Changes can happen due to updates
168
+ * to the config in the ConfigDirector dashboard, or if the context is updated via {@link updateContext}.
169
+ *
170
+ * @returns An 'unwatch' function that can be called to remove the subscriber
171
+ *
172
+ * @param configKey The config key to watch
173
+ * @param defaultValue The default value to be referenced if the config state is unavailable
174
+ * @param callback The callback function to be called whenever the config value is updated
175
+ */
176
+ watch<T extends ConfigValueType>(configKey: string, defaultValue: T, callback: WatchHandler<T>): () => void;
177
+ /**
178
+ * Removes a particular subscriber to the given `configKey`, or all subscribers if no callback
179
+ * is provided.
180
+ *
181
+ * @param configKey The config key to remove subscribers from
182
+ * @param callback The subscriber to be removed. If not provided, all subscribers are removed for
183
+ * the given `configKey`.
184
+ */
185
+ unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>): void;
186
+ /**
187
+ * Removes all subscribers from all config keys
188
+ */
189
+ unwatchAll(): void;
190
+ /**
191
+ * Disposes of the client. All connections are closed, and all event and config key subscribers
192
+ * are removed.
193
+ *
194
+ * Intended to be called when your application shuts down
195
+ */
196
+ dispose(): void;
197
+ }
198
+ //#endregion
199
+ //#region ../js-client-core/src/logger.d.ts
200
+ declare class DefaultConsoleLogger implements ConfigDirectorLogger {
201
+ private readonly level;
202
+ private readonly decorator;
203
+ private readonly dateFormatter;
204
+ constructor(level: ConfigDirectorLoggingLevel, decorator: ConfigDirectorLogMessageDecorator);
205
+ debug(message: string, ...args: any): void;
206
+ info(message: string, ...args: any): void;
207
+ warn(message: string, ...args: any): void;
208
+ error(message: string, ...args: any): void;
209
+ private log;
210
+ }
211
+ //#endregion
212
+ //#region ../js-client-core/src/errors.d.ts
213
+ declare class ConfigDirectorConnectionError extends Error {
214
+ readonly name: string;
215
+ readonly status?: number;
216
+ constructor(message: string, status?: number);
217
+ }
218
+ declare class ConfigDirectorValidationError extends Error {
219
+ readonly name: string;
220
+ constructor(message: string);
221
+ }
222
+ //#endregion
223
+ //#region src/api.d.ts
224
+ /**
225
+ * Creates a `ConfigDirectorClient` object with the given `clientSdkKey` and optional
226
+ * `clientOptions`. The returned client needs to be initialized before it is ready to serve
227
+ * config values.
228
+ *
229
+ * @param clientSdkKey The client SDK key obtained from the ConfigDirector dashboard
230
+ * @param clientOptions {@link ConfigDirectorClientOptions} options for the client (optional)
231
+ * @returns A {@link ConfigDirectorClient} object
232
+ *
233
+ * @example
234
+ * import { createClient } from "@configdirector/client-sdk";
235
+ * const client = createClient("YOUR-SDK-KEY");
236
+ * await client.initialize();
237
+ */
238
+ declare const createClient: (clientSdkKey: string, clientOptions?: ConfigDirectorClientOptions) => ConfigDirectorClient;
239
+ declare const createConsoleLogger: (level: ConfigDirectorLoggingLevel, messageDecorator?: ConfigDirectorLogMessageDecorator) => DefaultConsoleLogger;
240
+ //#endregion
241
+ export { type ConfigDirectorClient, type ConfigDirectorClientOptions, type ConfigDirectorConnectionError, type ConfigDirectorContext, type ConfigDirectorLogMessageDecorator, type ConfigDirectorLogger, type ConfigDirectorLoggingLevel, type ConfigDirectorValidationError, type ConfigValueType, createClient, createConsoleLogger };
242
+ //# sourceMappingURL=configdirector-client.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"configdirector-client.d.cts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../js-client-core/src/types.ts","../../js-client-core/src/logger.ts","../../js-client-core/src/errors.ts","../src/api.ts"],"mappings":";KAAK,SAAA;AAAA,KACA,YAAA,GAAe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,GAAmB,iCAAA,KAAiC,oBAAA"}
@@ -0,0 +1,242 @@
1
+ //#region ../js-client-core/src/Emitter.d.ts
2
+ type EventType = string | symbol;
3
+ type EventsRecord = Record<EventType, any>;
4
+ type Handler<TEventsRecord extends EventsRecord, TKey extends keyof TEventsRecord> = (payload: TEventsRecord[TKey]) => void;
5
+ interface EventProvider<TEventsRecord extends EventsRecord> {
6
+ on<TName extends keyof TEventsRecord>(name: TName, handler: Handler<TEventsRecord, TName>): void;
7
+ off<TName extends keyof TEventsRecord>(name: TName, handler?: Handler<TEventsRecord, TName>): void;
8
+ clear(): void;
9
+ }
10
+ //#endregion
11
+ //#region ../js-client-core/src/types.d.ts
12
+ type ConfigEnumLikeType = {
13
+ [key: string]: string | number;
14
+ };
15
+ type ConfigValueType = string | number | boolean | object | ConfigEnumLikeType;
16
+ type ConfigDirectorLoggingLevel = "debug" | "info" | "warn" | "error" | "off";
17
+ interface ConfigDirectorLogger {
18
+ debug(message: string, ...args: any): void;
19
+ info(message: string, ...args: any): void;
20
+ warn(message: string, ...args: any): void;
21
+ error(message: string, ...args: any): void;
22
+ }
23
+ interface ConfigDirectorLogMessageDecorator {
24
+ decorateMessage(message: string): string;
25
+ }
26
+ /**
27
+ * The user's context to be sent to ConfigDirector. This context will be used for targeting
28
+ * rules evaluation.
29
+ */
30
+ type ConfigDirectorContext = {
31
+ /**
32
+ * The user's identifier. This should be a value that uniquely identifies an application
33
+ * user.
34
+ * In the case of anonymous users, you could generate a UUID or alternatively not provide
35
+ * the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
36
+ * value is used for segmenting users in percentage rollouts, and changes to the {@link id}
37
+ * could result in the user being assigned to a different percentile.
38
+ */
39
+ id?: string;
40
+ /**
41
+ * The user's display name. This will be shown in the ConfigDirector dashboard and may be
42
+ * used for targeting rules.
43
+ */
44
+ name?: string;
45
+ /**
46
+ * Any arbitrary traits for the current user. They will be shown in the ConfigDirector
47
+ * dashboard and may be used for targeting rules.
48
+ */
49
+ traits?: {
50
+ [key: string]: unknown;
51
+ };
52
+ };
53
+ /**
54
+ * Configuration options for the {@link ConfigDirectorClient}
55
+ */
56
+ type ConfigDirectorClientOptions = {
57
+ /**
58
+ * Application metadata that remains constant through the lifetime of the connection
59
+ */
60
+ metadata?: {
61
+ appVersion?: string;
62
+ appName?: string;
63
+ };
64
+ /**
65
+ * Connection options
66
+ */
67
+ connection?: {
68
+ /**
69
+ * Whether to open a streaming connection or use a one-time pull of configuration state.
70
+ * If set to true, the streaming connection will remain open and receive updates whenever
71
+ * config state is updated on the ConfigDirector dashboard.
72
+ * When set to false, there will be an initial request to retrieve config state during
73
+ * initialization, and an additional request whenever {@link ConfigDirectorClient.updateContext}
74
+ * is called. But not updates will be received after those requests.
75
+ *
76
+ * Defaults to true (streaming connection)
77
+ */
78
+ streaming?: boolean;
79
+ /**
80
+ * The timeout, in milliseconds, to be used in initialization and when updating the context.
81
+ * If streaming is enabled, the operation (initialization or context update) may still succeed
82
+ * after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
83
+ * If streaming is disabled, if the operation times out, it will not be retried.
84
+ */
85
+ timeout?: number;
86
+ /**
87
+ * The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
88
+ * proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
89
+ * a proxy for the client SDK.
90
+ */
91
+ url?: string;
92
+ };
93
+ /**
94
+ * A logger that implements {@link ConfigDirectorLogger}. It defaults to the ConfigDirector console
95
+ * logger set to 'warn' level.
96
+ *
97
+ * The log level of the default logger can be adjusted by creating a default logger with the desired
98
+ * level and providing it in this property:
99
+ * @example
100
+ * import { createClient, createConsoleLogger } from "@configdirector/client-sdk";
101
+ * const client = createClient(
102
+ * "YOUR-SDK-KEY",
103
+ * { logger: createConsoleLogger("debug") },
104
+ * );
105
+ */
106
+ logger?: ConfigDirectorLogger;
107
+ };
108
+ type ClientConnectAction = "initialization" | "context update";
109
+ type ClientEvents = {
110
+ configsUpdated: {
111
+ keys: string[];
112
+ };
113
+ clientReady: {
114
+ action: ClientConnectAction;
115
+ };
116
+ };
117
+ type WatchHandler<T extends ConfigValueType> = (message: T) => void;
118
+ /**
119
+ * The ConfigDirector SDK client object.
120
+ *
121
+ * Applications should create a single instance of `ConfigDirectorClient`, and call
122
+ * {@link initialize} during application initialization.
123
+ *
124
+ * After initialization, to update the user's context, so that targeting rules are evaluated
125
+ * with the updated context, call {@link updateContext}.
126
+ */
127
+ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
128
+ /**
129
+ * Initializes the connection to ConfigDirector to retrieve config evaluations. Until
130
+ * initialization is successful, all flags will return their default value provided to
131
+ * {@link watch} or {@link getValue}.
132
+ *
133
+ * If the connection fails or is interrupted with a transient error (network error,
134
+ * internal server error, etc) the client will continue to attempt to connect. However,
135
+ * if the connection fails with a persistent error, like an invalid SDK key, the client will
136
+ * not attempt to re-connect and an error will be logged to the console or the provided
137
+ * logger.
138
+ *
139
+ * @param context The current user's context to be used for evaluating targeting rules (optional).
140
+ */
141
+ initialize(context?: ConfigDirectorContext): Promise<void>;
142
+ /**
143
+ * Updates the user's context and re-evaluates all config and flag values based on the new context.
144
+ *
145
+ * @param context The current user's context to be used for evaluating targeting rules (required).
146
+ */
147
+ updateContext(context: ConfigDirectorContext): Promise<void>;
148
+ /**
149
+ * Returns whether or not the client is ready after calling {@link initialize} or {@link updateContext}
150
+ *
151
+ * The definition of ready is that the connection to the server was successful, and config state
152
+ * was received.
153
+ */
154
+ get isReady(): boolean;
155
+ /**
156
+ * Evaluates a config and returns its value based on the current context and targeting rules
157
+ *
158
+ * @returns The evaluated config value, or the `defaultValue` if the config state was unavailable
159
+ * @param configKey The config key to evaluate
160
+ * @param defaultValue The default value to be returned if the config state is unavailable. For
161
+ * example, if the client cannot connect to the server due to network conditions, or if getValue
162
+ * is called before initialization is done.
163
+ */
164
+ getValue<T extends ConfigValueType>(configKey: string, defaultValue: T): T;
165
+ /**
166
+ * Watches for changes to a a config evaluation value. Whenever the config value changes, the
167
+ * provided callback function will be called with the new value. Changes can happen due to updates
168
+ * to the config in the ConfigDirector dashboard, or if the context is updated via {@link updateContext}.
169
+ *
170
+ * @returns An 'unwatch' function that can be called to remove the subscriber
171
+ *
172
+ * @param configKey The config key to watch
173
+ * @param defaultValue The default value to be referenced if the config state is unavailable
174
+ * @param callback The callback function to be called whenever the config value is updated
175
+ */
176
+ watch<T extends ConfigValueType>(configKey: string, defaultValue: T, callback: WatchHandler<T>): () => void;
177
+ /**
178
+ * Removes a particular subscriber to the given `configKey`, or all subscribers if no callback
179
+ * is provided.
180
+ *
181
+ * @param configKey The config key to remove subscribers from
182
+ * @param callback The subscriber to be removed. If not provided, all subscribers are removed for
183
+ * the given `configKey`.
184
+ */
185
+ unwatch<T extends ConfigValueType>(configKey: string, callback?: WatchHandler<T>): void;
186
+ /**
187
+ * Removes all subscribers from all config keys
188
+ */
189
+ unwatchAll(): void;
190
+ /**
191
+ * Disposes of the client. All connections are closed, and all event and config key subscribers
192
+ * are removed.
193
+ *
194
+ * Intended to be called when your application shuts down
195
+ */
196
+ dispose(): void;
197
+ }
198
+ //#endregion
199
+ //#region ../js-client-core/src/logger.d.ts
200
+ declare class DefaultConsoleLogger implements ConfigDirectorLogger {
201
+ private readonly level;
202
+ private readonly decorator;
203
+ private readonly dateFormatter;
204
+ constructor(level: ConfigDirectorLoggingLevel, decorator: ConfigDirectorLogMessageDecorator);
205
+ debug(message: string, ...args: any): void;
206
+ info(message: string, ...args: any): void;
207
+ warn(message: string, ...args: any): void;
208
+ error(message: string, ...args: any): void;
209
+ private log;
210
+ }
211
+ //#endregion
212
+ //#region ../js-client-core/src/errors.d.ts
213
+ declare class ConfigDirectorConnectionError extends Error {
214
+ readonly name: string;
215
+ readonly status?: number;
216
+ constructor(message: string, status?: number);
217
+ }
218
+ declare class ConfigDirectorValidationError extends Error {
219
+ readonly name: string;
220
+ constructor(message: string);
221
+ }
222
+ //#endregion
223
+ //#region src/api.d.ts
224
+ /**
225
+ * Creates a `ConfigDirectorClient` object with the given `clientSdkKey` and optional
226
+ * `clientOptions`. The returned client needs to be initialized before it is ready to serve
227
+ * config values.
228
+ *
229
+ * @param clientSdkKey The client SDK key obtained from the ConfigDirector dashboard
230
+ * @param clientOptions {@link ConfigDirectorClientOptions} options for the client (optional)
231
+ * @returns A {@link ConfigDirectorClient} object
232
+ *
233
+ * @example
234
+ * import { createClient } from "@configdirector/client-sdk";
235
+ * const client = createClient("YOUR-SDK-KEY");
236
+ * await client.initialize();
237
+ */
238
+ declare const createClient: (clientSdkKey: string, clientOptions?: ConfigDirectorClientOptions) => ConfigDirectorClient;
239
+ declare const createConsoleLogger: (level: ConfigDirectorLoggingLevel, messageDecorator?: ConfigDirectorLogMessageDecorator) => DefaultConsoleLogger;
240
+ //#endregion
241
+ export { type ConfigDirectorClient, type ConfigDirectorClientOptions, type ConfigDirectorConnectionError, type ConfigDirectorContext, type ConfigDirectorLogMessageDecorator, type ConfigDirectorLogger, type ConfigDirectorLoggingLevel, type ConfigDirectorValidationError, type ConfigValueType, createClient, createConsoleLogger };
242
+ //# sourceMappingURL=configdirector-client.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"configdirector-client.d.mts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../js-client-core/src/types.ts","../../js-client-core/src/logger.ts","../../js-client-core/src/errors.ts","../src/api.ts"],"mappings":";KAAK,SAAA;AAAA,KACA,YAAA,GAAe,MAAA,CAAO,SAAA;AAAA,KAEtB,OAAA,uBAA8B,YAAA,qBAAiC,aAAA,KAClE,OAAA,EAAS,aAAA,CAAc,IAAA;AAAA,UAGR,aAAA,uBAAoC,YAAA;EACnD,EAAA,qBAAuB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,EAAS,OAAA,CAAQ,aAAA,EAAe,KAAA;EACnF,GAAA,qBAAwB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,GAAU,OAAA,CAAQ,aAAA,EAAe,KAAA;EACrF,KAAA;AAAA;;;KCR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AAgB,eAAA,EAAiB,SAAA,UAAmB,YAAA,EAAc,CAAA,EAAG,QAAA,EAAU,YAAA,CAAa,CAAA;EAhC7C;;;;;;;;EA0C/C,OAAA,WAAkB,eAAA,EAAiB,SAAA,UAAmB,QAAA,GAAW,YAAA,CAAa,CAAA;EAV9E;;;EAeA,UAAA;EAfkE;;;;;;EAuBlE,OAAA;AAAA;;;cC/MW,oBAAA,YAAgC,oBAAA;EAAA,iBAGd,KAAA;EAAA,iBAAoD,SAAA;EAAA,iBAFhE,aAAA;cAEY,KAAA,EAAO,0BAAA,EAA6C,SAAA,EAAW,iCAAA;EAM5F,KAAA,CAAM,OAAA,aAAoB,IAAA;EAI1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAIzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAIzB,KAAA,CAAM,OAAA,aAAoB,IAAA;EAAA,QAIlB,GAAA;AAAA;;;cCxDG,6BAAA,SAAsC,KAAA;EAAA,SACxB,IAAA;EAAA,SACT,MAAA;cAEJ,OAAA,UAAiB,MAAA;AAAA;AAAA,cAQlB,6BAAA,SAAsC,KAAA;EAAA,SACxB,IAAA;cAEb,OAAA;AAAA;;;;;;;;AHfA;;;;;AACsB;;;;cIsBvB,YAAA,GACX,YAAA,UACA,aAAA,GAAgB,2BAAA,KACf,oBAAA;AAAA,cAQU,mBAAA,GACX,KAAA,EAAO,0BAAA,EACP,gBAAA,GAAmB,iCAAA,KAAiC,oBAAA"}
@@ -0,0 +1,2 @@
1
+ import{createEventSource as e}from"eventsource-client";var t=class{constructor(){this.handlerMap=new Map}on(e,t){let n=this.handlerMap.get(e);n?n.push(t):this.handlerMap.set(e,[t])}once(e,t){let n=this;function r(i){n.off(e,r),t.apply(n,i)}this.on(e,r)}off(e,t){let n=this.handlerMap.get(e);if(n)if(t){let e=n.indexOf(t);e>=0&&n.splice(e,1)}else this.handlerMap.set(e,[])}clear(){this.handlerMap.clear()}emit(e,t){let n=this.handlerMap.get(e);n&&n.slice().map(e=>e(t))}},n=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},r=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}};const i=e=>{if(e instanceof DOMException){if(e.name===`NotAllowedError`)return!0}else if(e instanceof TypeError)return!0;return!1};var a=class{constructor(e){this.options=e,this.eventEmitter=new t,this.options=e,this.logger=e.logger,this.url=new URL(`sse/v1`,e.baseUrl)}async connect(t,n){this.eventSource&&this.close();let r,i,a=async(e,t)=>{let n=await fetch(e,t);return r=n.status,n.ok||(i=await n.text()),n},o=new Promise((n,o)=>{this.eventSource=e({url:this.url,fetch:a,method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:t,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey}),onMessage:({data:e})=>{this.dispatchMessage(e)},onConnect:()=>{r&&this.isStatusFatal(r)?(this.close(),o(this.prepareFatalError(r,i))):(this.logger.debug(`[EventSourceTransport] Connected, status: %s`,r),n(this))},onScheduleReconnect:e=>{r&&this.isStatusFatal(r)?(this.close(),o(this.prepareFatalError(r,i))):this.logger.warn(`[EventSourceTransport] Scheduling reconnect in ${e.delay}. Response status: ${r}`)},onDisconnect:()=>{this.logger.debug(`[EventSourceTransport] Disconnected`)}})});return Promise.race([o,new Promise(e=>{setTimeout(()=>e(this),n)})])}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configSetReceived`,t)}catch(e){this.logger.error(`[EventSourceTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,t){let r=e??0;return new n(`${`Connection failed with status: ${e??`unknown`}`}${(t?.trim()?.length??0)>0?` (${t})`:``}. This is an unrecoverable error, will not attempt to reconnect.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}close(){this.eventSource?.close()}dispose(){this.close(),this.clear()}};const o=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},s=e=>e===`number`||e===`bigint`,c=(e,t)=>{let n=e.value,r=o(t);if(!n)return{parsedValue:t,requestedType:r,usedDefault:!0,reason:`value-missing`};if(typeof t==`string`)return{parsedValue:n,requestedType:r,usedDefault:!1,reason:`found-match`};if(typeof t==`boolean`&&e.type===`boolean`){let e=l(n),i=typeof e==`boolean`;return{parsedValue:i?e:t,requestedType:r,usedDefault:!i,reason:i?`found-match`:`invalid-boolean`}}if(s(typeof t)&&e.type===`integer`){let e=u(n),i=typeof e==`number`;return{parsedValue:i?e:t,requestedType:r,usedDefault:!i,reason:i?`found-match`:`invalid-number`}}if(s(typeof t)&&(e.type===`float`||e.type===`enum`)){let e=d(n),i=typeof e==`number`;return{parsedValue:i?e:t,requestedType:r,usedDefault:!i,reason:i?`found-match`:`invalid-number`}}return{parsedValue:n,requestedType:r,usedDefault:!1,reason:`found-match`}},l=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},u=e=>{if(!e)return;let t=Number.parseInt(e);if(!(isNaN(t)||!isFinite(t)))return t},d=e=>{if(!e)return;let t=Number.parseFloat(e);if(!(isNaN(t)||!isFinite(t)))return t},f={off:-1,error:0,warn:1,info:2,debug:3},p=()=>{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 m=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=p()}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){f[this.level]>=f[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},h=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const g=(e,t)=>new m(e??`warn`,t??new h);var _=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}))}},v=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}},y=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.url=new URL(`telemetry/v1`,e.baseUrl)}report({discreteEvents:e,aggregatedEvents:t,droppedEvents:n}){if(!this.executeRequests)return{success:!1,fatalError:!0};let r={clientSdkKey:this.sdkKey,discreteEvents:e,aggregatedEvents:t,droppedEvents:n};if(this.isReportEmpty(r))return{success:!0,fatalError:!1};let i=this.sendReport(r);return i.fatalError&&(this.executeRequests=!1),i}isReportEmpty(e){return this.isEventListEmpty(e.discreteEvents)&&this.isEventListEmpty(e.aggregatedEvents)&&this.isDroppedEventsEmpty(e.droppedEvents)}isDroppedEventsEmpty(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}isEventListEmpty(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}sendReport(e){try{return{success:navigator.sendBeacon(this.url,JSON.stringify(e)),fatalError:!1}}catch(e){return this.logger.warn(`[EventReporter] Fatal error attempting to send telemetry data: ${e}. No more telemetry data will be sent.`),{success:!1,fatalError:!0}}}};const b=e=>x(new TextEncoder().encode(e)).toString(16).padStart(8,`0`),x=e=>{let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e[n],t>>>=0;return t};var S=class{constructor(e){this.evaluationEventQueue=new v,this.aggregator=new _,this.collectEvents=!0,this.logger=e.logger,this.reporter=new y(e),this.flushIntervalDelay=3e4,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),5e3);try{document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&this.flush()})}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(e))}sanitizeEvaluatedConfigEvent(e){return{key:e.key,type:e.type,defaultValue:this.sanitizeValue(e.defaultValue,e.type),requestedType:e.requestedType,evaluatedValue:this.sanitizeValue(e.evaluatedValue,e.type),usedDefault:e.usedDefault,evaluationReason:e.evaluationReason}}sanitizeValue(e,t){if(t===`json`)try{return b(JSON.stringify(e))}catch{return e.toString().slice(0,500)}return e.toString().slice(0,500)}flushAndScheduleNext(){this.flush().fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay)}flush(){let e=this.evaluationEventQueue.takeSnapshot();return this.reporter.report({discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount}})}close(){this.collectEvents=!1,clearTimeout(this.flushTimeout),this.flush(),this.evaluationEventQueue.clear()}dispose(){this.close()}};const C=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(t,{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}};var w=class{constructor(e){this.options=e,this.eventEmitter=new t,this.fatalError=!1,this.options=e,this.logger=e.logger,this.url=new URL(`pull/v1`,e.baseUrl)}async connect(e,t){if(this.fatalError)return this.logger.warn(`[PullTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`),this;try{let r=await C(t,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:this.options.metaContext,clientSdkKey:this.options.clientSdkKey})},this.logger);if(!r.ok)throw this.isStatusFatal(r.status)?(this.fatalError=!0,this.prepareFatalResponseStatusError(r.status,await r.text())):new n(`Connection failed with status: ${r.status}`,r.status);let i=JSON.parse(await r.text());return this.eventEmitter.emit(`configSetReceived`,i),this}catch(e){throw i(e)?(this.fatalError=!0,new n(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new n(`Failed to parse the response from the server: ${e}`):new n(`Connection failed with error: ${e}.`)}}prepareFatalResponseStatusError(e,t){let r=e??0;return new n(`${`Connection failed with status: ${e??`unknown`}`}${(t?.trim()?.length??0)>0?` (${t})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}close(){}dispose(){this.close(),this.clear()}};const T=new URL(`https://client-sdk-api.configdirector.com`);var E=class{constructor(e,n,r){this.handlersMap=new Map,this.eventEmitter=new t,this.ready=!1,this.logger=r?.logger??g(),this.timeout=r?.connection?.timeout??3e3;let i=this.parseUrl(r?.connection?.url)??T;this.streaming=r?.connection?.streaming!==!1;let o=this.streaming?a:w;this.usageEventCollector=new S({sdkKey:e,logger:this.logger,baseUrl:i}),this.transport=new o({clientSdkKey:e,baseUrl:i,metaContext:{...r?.metadata,sdkName:n.sdkName,sdkVersion:n.sdkVersion,userAgent:navigator?.userAgent},logger:this.logger}),this.transport.on(`configSetReceived`,e=>{this.readyResolve?.();let t=Object.keys(e.configs);!this.configSet||e.kind==`full`?(this.configSet=e,this.eventEmitter.emit(`configsUpdated`,{keys:t}),this.updateWatchers(e.configs)):(this.configSet.configs={...this.configSet.configs,...e.configs},this.eventEmitter.emit(`configsUpdated`,{keys:t}),this.updateWatchers(e.configs)),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:t})})}async initialize(e){await this.connectToTransport(e,`initialization`)}async updateContext(e){await this.connectToTransport(e,`context update`)}async connectToTransport(e,t){try{this.ready=!1,this.readyPromise=new Promise(e=>{this.readyResolve=e}).then(()=>{this.ready=!0,this.eventEmitter.emit(`clientReady`,{action:t}),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`)});let n=new Date().getTime();await this.transport.connect(e??{},this.timeout),this.currentContext=e;let r=new Date().getTime()-n,i=this.timeout-r;if(i>0&&await Promise.race([this.readyPromise,new Promise(e=>{setTimeout(()=>e(),i)})]),!this.ready){let e=this.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 ${t} after ${this.timeout}ms. ${e}`)}}catch(e){this.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}updateWatchers(e){Object.values(e).forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){this.handlersMap.get(e.key)?.forEach(t=>{let n=this.getValueFromConfigState(e.key,e,t.defaultValue);t.handler(n)})}watch(e,t,n){this.validateDefaultValue(t);let r=this.handlersMap.get(e),i={handler:n,defaultValue:t,requestedType:typeof t};return r?r.push(i):this.handlersMap.set(e,[i]),()=>this.unwatch(e,n)}unwatch(e,t){let n=this.handlersMap.get(e);if(n)if(t){let e=n.findIndex(e=>e.handler==t);e>=0&&n?.splice(e,1)}else n.splice(0)}getValue(e,t){this.validateDefaultValue(t);let n=this.configSet?.configs[e];return this.getValueFromConfigState(e,n,t)}getValueFromConfigState(e,t,n){if(!t)return this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`),this.usageEventCollector.evaluatedConfig({contextId:this.currentContext?.id,key:e,defaultValue:n,requestedType:o(n),evaluatedValue:n,usedDefault:!0,evaluationReason:`config-state-missing`}),n;let r=c(t,n);return this.usageEventCollector.evaluatedConfig({contextId:this.currentContext?.id,key:e,defaultValue:n,requestedType:r.requestedType,evaluatedValue:r.parsedValue,usedDefault:r.usedDefault,evaluationReason:r.reason}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${r.parsedValue}'`),r.parsedValue}parseUrl(e){if(e)try{return new URL(e)}catch(t){throw new r(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateDefaultValue(e){if(e==null)throw new r(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new r(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.logger.debug(`[ConfigDirectorClient] clear() has been called, removing all observers`),this.eventEmitter.clear(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}close(){this.logger.debug(`[ConfigDirectorClient] close() has been called, closing connection to server`),this.transport.close(),this.ready=!1}dispose(){this.clear(),this.close()}};const D=(e,t)=>new E(e,{sdkName:`js-client-sdk`,sdkVersion:`0.1.7`},t),O=(e,t)=>g(e,t);export{D as createClient,O as createConsoleLogger};
2
+ //# sourceMappingURL=configdirector-client.mjs.map