@configdirector/client-sdk 1.7.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23,7 +23,7 @@ interface ConfigDirectorLogger {
23
23
  interface ConfigDirectorLogMessageDecorator {
24
24
  decorateMessage(message: string): string;
25
25
  }
26
- type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean";
26
+ type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
27
27
  type ConfigEvaluation = {
28
28
  key: string;
29
29
  value: ConfigValueType;
@@ -42,9 +42,11 @@ type ConfigDirectorContext = {
42
42
  * The context's identifier. This should be a value that uniquely identifies the user or other
43
43
  * entity among contexts of the same {@link kind}.
44
44
  * In the case of anonymous users, you could generate a UUID or alternatively not provide
45
- * the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
46
- * value is used for segmenting contexts in percentage rollouts, and changes to the {@link id}
47
- * could result in the context being assigned to a different percentile.
45
+ * the {@link id}. In a client SDK, ConfigDirector then derives an identifier from an ID the SDK
46
+ * stores for the app install or the website, so it stays the same until the app is uninstalled
47
+ * or the site's data is cleared. However, keep in mind that this value is used for segmenting
48
+ * contexts in percentage rollouts, and changes to the {@link id} could result in the context
49
+ * being assigned to a different percentile.
48
50
  */
49
51
  id?: string;
50
52
  /**
@@ -88,9 +90,115 @@ type ConfigDirectorMetaContext = {
88
90
  appVersion?: string;
89
91
  appName?: string;
90
92
  };
91
- type ConnectionMode = "streaming" | "polling";
93
+ type ConnectionMode = "streaming" | "polling" | "offline";
94
+ //#endregion
95
+ //#region ../shared/src/native-values.d.ts
96
+ type NativeJsonValue = boolean | number | string | null | NativeJsonValue[] | {
97
+ [key: string]: NativeJsonValue;
98
+ };
99
+ type NativeValue = boolean | number | string | NativeJsonValue[] | {
100
+ [key: string]: NativeJsonValue;
101
+ };
102
+ type NativeValues = Record<string, NativeValue>;
92
103
  //#endregion
93
104
  //#region ../js-client-core/src/types.d.ts
105
+ /**
106
+ * A store for the values the client keeps on the device between launches. One provider instance
107
+ * serves one client: the provider decides where the entry lives, and the SDK owns the entry's
108
+ * format, which may change between SDK versions.
109
+ */
110
+ type CachingProvider = {
111
+ /**
112
+ * Returns the stored entry, or `null` or `undefined` when nothing is stored.
113
+ */
114
+ read(): string | null | undefined | Promise<string | null | undefined>;
115
+ /**
116
+ * Replaces the stored entry. The SDK never writes an entry larger than {@link sizeLimit}.
117
+ */
118
+ write(value: string): void | Promise<void>;
119
+ /**
120
+ * Removes the stored entry.
121
+ */
122
+ remove(): void | Promise<void>;
123
+ /**
124
+ * The largest entry, in UTF-8 bytes, the provider accepts. When the values received from
125
+ * ConfigDirector exceed it, the SDK removes the stored entry and keeps nothing on the device.
126
+ */
127
+ sizeLimit(): number;
128
+ };
129
+ /**
130
+ * Options for the values the client keeps on the device, served on the next launch of the same
131
+ * context until live values arrive. Ignored in `offline` mode.
132
+ */
133
+ type CachingOptions = {
134
+ /**
135
+ * Whether to keep the last values received on the device. Defaults to `true`.
136
+ */
137
+ enabled?: boolean;
138
+ /**
139
+ * The store for the values. Defaults to the platform's own store: `localStorage` in the
140
+ * browser, AsyncStorage on React Native.
141
+ */
142
+ provider?: CachingProvider;
143
+ };
144
+ /**
145
+ * One value an offline client serves for a config key. The config type follows from the value: a
146
+ * boolean, an integral number (`integer`), any other number (`float`), a string, or a plain object
147
+ * or array (`json`).
148
+ */
149
+ type OfflineValue = NativeValue;
150
+ /**
151
+ * The values an offline client serves, keyed by config key. See {@link OfflineValue} for how each
152
+ * value's config type is decided. Every context receives the same value.
153
+ */
154
+ type OfflineValues = NativeValues;
155
+ /**
156
+ * Connection options of the {@link ConfigDirectorClient}
157
+ */
158
+ type ConnectionOptions = {
159
+ /**
160
+ * The connection mode to be used, one of `streaming` (default), `polling` or `offline`.
161
+ * If set to `streaming`, the connection will remain open and receive updates whenever
162
+ * config state is updated on the ConfigDirector dashboard.
163
+ * When set to `polling`, there will be an initial request to retrieve config state during
164
+ * initialization, and additional requests on a `pollingInterval`.
165
+ * When set to `offline`, the client never connects to ConfigDirector and sends nothing: it serves
166
+ * the values given in {@link values} to every context, or the in-code default values when none
167
+ * are given. No SDK key is needed.
168
+ *
169
+ * Defaults to `streaming`
170
+ */
171
+ mode?: ConnectionMode;
172
+ /**
173
+ * The values to serve in `offline` mode, keyed by config key. A value such as `null` makes
174
+ * `initialize` reject with a `ConfigDirectorInitializationError`.
175
+ *
176
+ * Can be given only in `offline` mode; otherwise `initialize` rejects.
177
+ */
178
+ values?: OfflineValues;
179
+ /**
180
+ * The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
181
+ * effect in the other modes.
182
+ *
183
+ * Defaults to 60 seconds. The minimum is 30 seconds. A value below the minimum is raised to the
184
+ * minimum and a warning is logged.
185
+ */
186
+ pollingInterval?: number;
187
+ /**
188
+ * The timeout, in _milliseconds_, to be used in initialization and when updating the context.
189
+ * If streaming is enabled, the operation (initialization or context update) may still succeed
190
+ * after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
191
+ * If streaming is disabled, if the operation times out, it will not be retried. This option has
192
+ * no effect in `offline` mode.
193
+ */
194
+ timeout?: number;
195
+ /**
196
+ * The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
197
+ * proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
198
+ * a proxy for the client SDK. This option has no effect in `offline` mode.
199
+ */
200
+ url?: string;
201
+ };
94
202
  /**
95
203
  * Configuration options for the {@link ConfigDirectorClient}
96
204
  */
@@ -102,39 +210,13 @@ type ConfigDirectorClientOptions = {
102
210
  /**
103
211
  * Connection options
104
212
  */
105
- connection?: {
106
- /**
107
- * The connection mode to be used, one of `streaming` (default) or `polling`.
108
- * If set to `streaming`, the connection will remain open and receive updates whenever
109
- * config state is updated on the ConfigDirector dashboard.
110
- * When set to `polling`, there will be an initial request to retrieve config state during
111
- * initialization, and additional requests on a `pollingInterval`.
112
- *
113
- * Defaults to `streaming`
114
- */
115
- mode?: ConnectionMode;
116
- /**
117
- * The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
118
- * effect when the `mode` is set to `streaming`.
119
- *
120
- * Defaults to 60 seconds. The minimum is 30 seconds. A value below the minimum is raised to the
121
- * minimum and a warning is logged.
122
- */
123
- pollingInterval?: number;
124
- /**
125
- * The timeout, in _milliseconds_, to be used in initialization and when updating the context.
126
- * If streaming is enabled, the operation (initialization or context update) may still succeed
127
- * after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
128
- * If streaming is disabled, if the operation times out, it will not be retried.
129
- */
130
- timeout?: number;
131
- /**
132
- * The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
133
- * proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
134
- * a proxy for the client SDK.
135
- */
136
- url?: string;
137
- };
213
+ connection?: ConnectionOptions;
214
+ /**
215
+ * Options for the values the client keeps on the device between launches. The last values
216
+ * received are kept by default and served, with the evaluation reason `cached`, on the next
217
+ * launch of the same context until live values arrive. See {@link CachingOptions}.
218
+ */
219
+ caching?: CachingOptions;
138
220
  /**
139
221
  * A logger that implements {@link ConfigDirectorLogger}. It defaults to the ConfigDirector console
140
222
  * logger set to 'warn' level.
@@ -166,12 +248,21 @@ type ConfigDirectorClientOptions = {
166
248
  */
167
249
  hooks?: ClientHooks;
168
250
  };
251
+ /**
252
+ * The options of a client created without a client SDK key: the connection mode is `offline`.
253
+ */
254
+ type OfflineClientOptions = ConfigDirectorClientOptions & {
255
+ connection: ConnectionOptions & {
256
+ mode: "offline";
257
+ };
258
+ };
169
259
  type ClientHooks = {
170
260
  clientReady?: HookHandler<"clientReady"> | HookHandler<"clientReady">[];
171
261
  configsUpdated?: HookHandler<"configsUpdated"> | HookHandler<"configsUpdated">[];
172
262
  contextUpdated?: HookHandler<"contextUpdated"> | HookHandler<"contextUpdated">[];
173
263
  configEvaluated?: HookHandler<"configEvaluated"> | HookHandler<"configEvaluated">[];
174
264
  connectionError?: HookHandler<"connectionError"> | HookHandler<"connectionError">[];
265
+ cachedValuesLoaded?: HookHandler<"cachedValuesLoaded"> | HookHandler<"cachedValuesLoaded">[];
175
266
  };
176
267
  type ClientConnectAction = "initialization" | "context update" | "network resume";
177
268
  type HookHandler<TEvent extends keyof ClientEvents> = (payload: ClientEvents[TEvent]) => void;
@@ -192,6 +283,7 @@ type ClientEvents = {
192
283
  connectionError: {
193
284
  error: Error;
194
285
  };
286
+ cachedValuesLoaded: Record<string, never>;
195
287
  };
196
288
  type WatchHandler<T extends ConfigValueType> = (message: T) => void;
197
289
  /**
@@ -323,6 +415,10 @@ declare class ConfigDirectorValidationError extends Error {
323
415
  readonly name: string;
324
416
  constructor(message: string);
325
417
  }
418
+ declare class ConfigDirectorInitializationError extends Error {
419
+ readonly name: string;
420
+ constructor(message: string);
421
+ }
326
422
  //#endregion
327
- export { ConfigDirectorContext as a, ConfigDirectorLoggingLevel as c, ConfigDirectorClientOptions as i, ConfigValueType as l, ConfigDirectorValidationError as n, ConfigDirectorLogMessageDecorator as o, ConfigDirectorClient as r, ConfigDirectorLogger as s, ConfigDirectorConnectionError as t };
328
- //# sourceMappingURL=errors-T_hDavJF.d.mts.map
423
+ export { ConfigDirectorLoggingLevel as _, CachingProvider as a, OfflineClientOptions as c, NativeJsonValue as d, NativeValue as f, ConfigDirectorLogger as g, ConfigDirectorLogMessageDecorator as h, CachingOptions as i, OfflineValue as l, ConfigDirectorContext as m, ConfigDirectorInitializationError as n, ConfigDirectorClient as o, NativeValues as p, ConfigDirectorValidationError as r, ConfigDirectorClientOptions as s, ConfigDirectorConnectionError as t, OfflineValues as u, ConfigValueType as v };
424
+ //# sourceMappingURL=errors-K27PrStP.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-K27PrStP.d.mts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/types.ts","../../shared/src/native-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A,IAAiB,OAAA;EA5HG;;;;;;EAoIpB,OAAA;AAAA;;;cC7WW,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;AAAA,cAOD,iCAAA,SAA0C,KAAA;EAAA,SAC5B,IAAA;cAEb,OAAA;AAAA"}
@@ -23,7 +23,7 @@ interface ConfigDirectorLogger {
23
23
  interface ConfigDirectorLogMessageDecorator {
24
24
  decorateMessage(message: string): string;
25
25
  }
26
- type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean";
26
+ type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
27
27
  type ConfigEvaluation = {
28
28
  key: string;
29
29
  value: ConfigValueType;
@@ -42,9 +42,11 @@ type ConfigDirectorContext = {
42
42
  * The context's identifier. This should be a value that uniquely identifies the user or other
43
43
  * entity among contexts of the same {@link kind}.
44
44
  * In the case of anonymous users, you could generate a UUID or alternatively not provide
45
- * the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
46
- * value is used for segmenting contexts in percentage rollouts, and changes to the {@link id}
47
- * could result in the context being assigned to a different percentile.
45
+ * the {@link id}. In a client SDK, ConfigDirector then derives an identifier from an ID the SDK
46
+ * stores for the app install or the website, so it stays the same until the app is uninstalled
47
+ * or the site's data is cleared. However, keep in mind that this value is used for segmenting
48
+ * contexts in percentage rollouts, and changes to the {@link id} could result in the context
49
+ * being assigned to a different percentile.
48
50
  */
49
51
  id?: string;
50
52
  /**
@@ -88,9 +90,115 @@ type ConfigDirectorMetaContext = {
88
90
  appVersion?: string;
89
91
  appName?: string;
90
92
  };
91
- type ConnectionMode = "streaming" | "polling";
93
+ type ConnectionMode = "streaming" | "polling" | "offline";
94
+ //#endregion
95
+ //#region ../shared/src/native-values.d.ts
96
+ type NativeJsonValue = boolean | number | string | null | NativeJsonValue[] | {
97
+ [key: string]: NativeJsonValue;
98
+ };
99
+ type NativeValue = boolean | number | string | NativeJsonValue[] | {
100
+ [key: string]: NativeJsonValue;
101
+ };
102
+ type NativeValues = Record<string, NativeValue>;
92
103
  //#endregion
93
104
  //#region ../js-client-core/src/types.d.ts
105
+ /**
106
+ * A store for the values the client keeps on the device between launches. One provider instance
107
+ * serves one client: the provider decides where the entry lives, and the SDK owns the entry's
108
+ * format, which may change between SDK versions.
109
+ */
110
+ type CachingProvider = {
111
+ /**
112
+ * Returns the stored entry, or `null` or `undefined` when nothing is stored.
113
+ */
114
+ read(): string | null | undefined | Promise<string | null | undefined>;
115
+ /**
116
+ * Replaces the stored entry. The SDK never writes an entry larger than {@link sizeLimit}.
117
+ */
118
+ write(value: string): void | Promise<void>;
119
+ /**
120
+ * Removes the stored entry.
121
+ */
122
+ remove(): void | Promise<void>;
123
+ /**
124
+ * The largest entry, in UTF-8 bytes, the provider accepts. When the values received from
125
+ * ConfigDirector exceed it, the SDK removes the stored entry and keeps nothing on the device.
126
+ */
127
+ sizeLimit(): number;
128
+ };
129
+ /**
130
+ * Options for the values the client keeps on the device, served on the next launch of the same
131
+ * context until live values arrive. Ignored in `offline` mode.
132
+ */
133
+ type CachingOptions = {
134
+ /**
135
+ * Whether to keep the last values received on the device. Defaults to `true`.
136
+ */
137
+ enabled?: boolean;
138
+ /**
139
+ * The store for the values. Defaults to the platform's own store: `localStorage` in the
140
+ * browser, AsyncStorage on React Native.
141
+ */
142
+ provider?: CachingProvider;
143
+ };
144
+ /**
145
+ * One value an offline client serves for a config key. The config type follows from the value: a
146
+ * boolean, an integral number (`integer`), any other number (`float`), a string, or a plain object
147
+ * or array (`json`).
148
+ */
149
+ type OfflineValue = NativeValue;
150
+ /**
151
+ * The values an offline client serves, keyed by config key. See {@link OfflineValue} for how each
152
+ * value's config type is decided. Every context receives the same value.
153
+ */
154
+ type OfflineValues = NativeValues;
155
+ /**
156
+ * Connection options of the {@link ConfigDirectorClient}
157
+ */
158
+ type ConnectionOptions = {
159
+ /**
160
+ * The connection mode to be used, one of `streaming` (default), `polling` or `offline`.
161
+ * If set to `streaming`, the connection will remain open and receive updates whenever
162
+ * config state is updated on the ConfigDirector dashboard.
163
+ * When set to `polling`, there will be an initial request to retrieve config state during
164
+ * initialization, and additional requests on a `pollingInterval`.
165
+ * When set to `offline`, the client never connects to ConfigDirector and sends nothing: it serves
166
+ * the values given in {@link values} to every context, or the in-code default values when none
167
+ * are given. No SDK key is needed.
168
+ *
169
+ * Defaults to `streaming`
170
+ */
171
+ mode?: ConnectionMode;
172
+ /**
173
+ * The values to serve in `offline` mode, keyed by config key. A value such as `null` makes
174
+ * `initialize` reject with a `ConfigDirectorInitializationError`.
175
+ *
176
+ * Can be given only in `offline` mode; otherwise `initialize` rejects.
177
+ */
178
+ values?: OfflineValues;
179
+ /**
180
+ * The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
181
+ * effect in the other modes.
182
+ *
183
+ * Defaults to 60 seconds. The minimum is 30 seconds. A value below the minimum is raised to the
184
+ * minimum and a warning is logged.
185
+ */
186
+ pollingInterval?: number;
187
+ /**
188
+ * The timeout, in _milliseconds_, to be used in initialization and when updating the context.
189
+ * If streaming is enabled, the operation (initialization or context update) may still succeed
190
+ * after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
191
+ * If streaming is disabled, if the operation times out, it will not be retried. This option has
192
+ * no effect in `offline` mode.
193
+ */
194
+ timeout?: number;
195
+ /**
196
+ * The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
197
+ * proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
198
+ * a proxy for the client SDK. This option has no effect in `offline` mode.
199
+ */
200
+ url?: string;
201
+ };
94
202
  /**
95
203
  * Configuration options for the {@link ConfigDirectorClient}
96
204
  */
@@ -102,39 +210,13 @@ type ConfigDirectorClientOptions = {
102
210
  /**
103
211
  * Connection options
104
212
  */
105
- connection?: {
106
- /**
107
- * The connection mode to be used, one of `streaming` (default) or `polling`.
108
- * If set to `streaming`, the connection will remain open and receive updates whenever
109
- * config state is updated on the ConfigDirector dashboard.
110
- * When set to `polling`, there will be an initial request to retrieve config state during
111
- * initialization, and additional requests on a `pollingInterval`.
112
- *
113
- * Defaults to `streaming`
114
- */
115
- mode?: ConnectionMode;
116
- /**
117
- * The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
118
- * effect when the `mode` is set to `streaming`.
119
- *
120
- * Defaults to 60 seconds. The minimum is 30 seconds. A value below the minimum is raised to the
121
- * minimum and a warning is logged.
122
- */
123
- pollingInterval?: number;
124
- /**
125
- * The timeout, in _milliseconds_, to be used in initialization and when updating the context.
126
- * If streaming is enabled, the operation (initialization or context update) may still succeed
127
- * after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
128
- * If streaming is disabled, if the operation times out, it will not be retried.
129
- */
130
- timeout?: number;
131
- /**
132
- * The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
133
- * proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
134
- * a proxy for the client SDK.
135
- */
136
- url?: string;
137
- };
213
+ connection?: ConnectionOptions;
214
+ /**
215
+ * Options for the values the client keeps on the device between launches. The last values
216
+ * received are kept by default and served, with the evaluation reason `cached`, on the next
217
+ * launch of the same context until live values arrive. See {@link CachingOptions}.
218
+ */
219
+ caching?: CachingOptions;
138
220
  /**
139
221
  * A logger that implements {@link ConfigDirectorLogger}. It defaults to the ConfigDirector console
140
222
  * logger set to 'warn' level.
@@ -166,12 +248,21 @@ type ConfigDirectorClientOptions = {
166
248
  */
167
249
  hooks?: ClientHooks;
168
250
  };
251
+ /**
252
+ * The options of a client created without a client SDK key: the connection mode is `offline`.
253
+ */
254
+ type OfflineClientOptions = ConfigDirectorClientOptions & {
255
+ connection: ConnectionOptions & {
256
+ mode: "offline";
257
+ };
258
+ };
169
259
  type ClientHooks = {
170
260
  clientReady?: HookHandler<"clientReady"> | HookHandler<"clientReady">[];
171
261
  configsUpdated?: HookHandler<"configsUpdated"> | HookHandler<"configsUpdated">[];
172
262
  contextUpdated?: HookHandler<"contextUpdated"> | HookHandler<"contextUpdated">[];
173
263
  configEvaluated?: HookHandler<"configEvaluated"> | HookHandler<"configEvaluated">[];
174
264
  connectionError?: HookHandler<"connectionError"> | HookHandler<"connectionError">[];
265
+ cachedValuesLoaded?: HookHandler<"cachedValuesLoaded"> | HookHandler<"cachedValuesLoaded">[];
175
266
  };
176
267
  type ClientConnectAction = "initialization" | "context update" | "network resume";
177
268
  type HookHandler<TEvent extends keyof ClientEvents> = (payload: ClientEvents[TEvent]) => void;
@@ -192,6 +283,7 @@ type ClientEvents = {
192
283
  connectionError: {
193
284
  error: Error;
194
285
  };
286
+ cachedValuesLoaded: Record<string, never>;
195
287
  };
196
288
  type WatchHandler<T extends ConfigValueType> = (message: T) => void;
197
289
  /**
@@ -323,6 +415,10 @@ declare class ConfigDirectorValidationError extends Error {
323
415
  readonly name: string;
324
416
  constructor(message: string);
325
417
  }
418
+ declare class ConfigDirectorInitializationError extends Error {
419
+ readonly name: string;
420
+ constructor(message: string);
421
+ }
326
422
  //#endregion
327
- export { ConfigDirectorContext as a, ConfigDirectorLoggingLevel as c, ConfigDirectorClientOptions as i, ConfigValueType as l, ConfigDirectorValidationError as n, ConfigDirectorLogMessageDecorator as o, ConfigDirectorClient as r, ConfigDirectorLogger as s, ConfigDirectorConnectionError as t };
328
- //# sourceMappingURL=errors-DTlTJsJh.d.cts.map
423
+ export { ConfigDirectorLoggingLevel as _, CachingProvider as a, OfflineClientOptions as c, NativeJsonValue as d, NativeValue as f, ConfigDirectorLogger as g, ConfigDirectorLogMessageDecorator as h, CachingOptions as i, OfflineValue as l, ConfigDirectorContext as m, ConfigDirectorInitializationError as n, ConfigDirectorClient as o, NativeValues as p, ConfigDirectorValidationError as r, ConfigDirectorClientOptions as s, ConfigDirectorConnectionError as t, OfflineValues as u, ConfigValueType as v };
424
+ //# sourceMappingURL=errors-s1a-WKkm.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-s1a-WKkm.d.cts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/types.ts","../../shared/src/native-values.ts","../../js-client-core/src/types.ts","../../shared/src/errors.ts"],"mappings":";KAAK,SAAA;AAAA,KACA,YAAA,GAAe,MAAA,CAAO,SAAA;AAAA,KAEtB,OAAA,uBAA8B,YAAA,qBAAiC,aAAA,KAClE,OAAA,EAAS,aAAA,CAAc,IAAA;AAAA,UAGR,aAAA,uBAAoC,YAAA;EACnD,EAAA,qBAAuB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,EAAS,OAAA,CAAQ,aAAA,EAAe,KAAA;EACnF,GAAA,qBAAwB,aAAA,EAAe,IAAA,EAAM,KAAA,EAAO,OAAA,GAAU,OAAA,CAAQ,aAAA,EAAe,KAAA;EACrF,KAAA;AAAA;;;KCEU,kBAAA;EAAA,CAAwB,GAAA;AAAA;AAAA,KAExB,eAAA,wCAAuD,kBAAA;AAAA,KAevD,0BAAA;AAAA,UAEK,oBAAA;EACf,KAAA,CAAM,OAAA,aAAoB,IAAA;EAE1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,KAAA,CAAM,OAAA,aAAoB,IAAA;AAAA;AAAA,UAGX,iCAAA;EACf,eAAA,CAAgB,OAAA;AAAA;AAAA,KAGN,gBAAA;AAAA,KAWA,gBAAA;EACV,GAAA;EACA,KAAA,EAAO,eAAA;EACP,OAAA;EACA,cAAA;EACA,MAAA,EAAQ,gBAAA;EACR,OAAA,GAAU,qBAAA;AAAA;;;;;;KAOA,qBAAA;ED5DoD;;;;;;;;;;ECuE9D,EAAA;EDxEoE;;;;;;;;;;;ECqFpE,IAAA;EDnFA;;;;ECyFA,IAAA;;AAvFF;;;EA6FE,MAAA;IAAA,CAAY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a,CAAA;EAxG/D;;;;AAE/B;;;;EAgHE,OAAA,WAAkB,eAAA,EAAiB,SAAA,UAAmB,QAAA,GAAW,YAAA,CAAa,CAAA;EAhHI;;;EAqHlF,UAAA;EArH2C;;;;;;AAE7C;EA4HE,YAAA;;;;;EAMA,aAAA,IAAiB,OAAA;EA5HG;;;;;;EAoIpB,OAAA;AAAA;;;cC7WW,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;AAAA,cAOD,iCAAA,SAA0C,KAAA;EAAA,SAC5B,IAAA;cAEb,OAAA;AAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@configdirector/client-sdk",
3
- "version": "1.7.0",
3
+ "version": "1.9.0",
4
4
  "description": "Javascript client 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
- var e=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))}},t=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},n=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},r=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},i=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},a=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},o=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}};function s(e){"@babel/helpers - typeof";return s=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},s(e)}function c(e,t){if(s(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(s(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function l(e){var t=c(e,`string`);return s(t)==`symbol`?t:t+``}function u(e,t,n){return(t=l(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function d(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function f(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?d(Object(n),!0).forEach(function(t){u(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):d(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var p=class{constructor(e){var t;this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=(t=e.onEvent)==null?(()=>{}):t,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(`:`)){var t;(t=this.onComment)==null||t.call(this,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(f(f({},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`:if(/^\d+$/.test(e.value)){var t;(t=this.onRetry)==null||t.call(this,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 m=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var h=class{constructor(e){var t,n;this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=m.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers=f({Accept:`text/event-stream`},e.headers);let r=e.body;this.body=typeof r==`function`?r:()=>r,this.requestOptions={method:(t=e.method)==null?`GET`:t,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=(n=e.fetch)==null?((e,t)=>fetch(e,t)):n,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===m.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=m.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=m.CONNECTING,this._fetch(this.url,f(f({},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){var t=this;let{body:n,status:a}=e;if(a===204){t.disconnected();return}if(a>=400){t.scheduleReconnect({status:a});return}if(!n)throw new i(`The server response did not have a body`);t._readyState=m.OPEN,t._onConnect(),t.reconnectAttempt=0;let o=new p({onEvent:e=>{typeof e.id==`string`&&(t.lastEventId=e.id),t._onMessage(e)},onComment:e=>t._onComment(e),onRetry:e=>t.serverReconnectionTime=e});await t.readResponseStream(n,o),t.scheduleReconnect({status:a,error:new r(`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=m.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return f(f({},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=m.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new o(`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 a(`${n} must be a function`);return e}};const g=e=>new h(e);var _=class{constructor(t){this.options=t,this.eventEmitter=new e,this.connectionGeneration=0,this.options=t,this.logger=t.logger,this.url=t.resolveUrl(`client/sse/v1`,t.baseUrl)}async connect(e,t){var n=this;let r=++n.connectionGeneration,i=await n.options.clientSession;if(r!==n.connectionGeneration)return n;n.eventSource&&n.close();let a=new Promise((t,r)=>{n.eventSource=g({url:n.url,method:`POST`,headers:{"Content-Type":`application/json`},fetch:n.options.fetch,body:JSON.stringify({givenContext:e,metaContext:n.options.metaContext,clientSdkKey:n.options.clientSdkKey,instanceId:i.instanceId,ephemeral:i.ephemeral}),onMessage:({data:e})=>{n.dispatchMessage(e)},onConnect:()=>{n.logger.debug(`[StreamingTransport] Connected`),t(n)},shouldReconnect:e=>{let t=!n.isStatusFatal(e.status);if(!t){let t=n.prepareFatalError(e.status,e.error);n.eventEmitter.emit(`connectionError`,t),r(t)}return t},calculateReconnectDelay:e=>{let t=n.options.connectionRetryDelay(e.attempt),r=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?n.logger.info(r):n.logger.warn(r),t},onError:e=>{n.logger.debug(`[StreamingTransport] Error: `,e)},onDisconnect:()=>{n.logger.debug(`[StreamingTransport] Disconnected`)}}),n.eventSource.connect()});return clearTimeout(n.timeoutTimer),n.timeoutTimer=void 0,Promise.race([a,new Promise(e=>{n.timeoutTimer=setTimeout(()=>e(n),t)})]).finally(()=>clearTimeout(n.timeoutTimer))}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configSetReceived`,t)}catch(e){this.logger.error(`[StreamingTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,n){let r=e==null?0:e;return new t(`${`Connection failed with status: ${e==null?`unknown`:e}.`}${n?` Error: ${n}`:``}. This is an unrecoverable error, will not attempt to reconnect.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}close(){var e;this.connectionGeneration++,(e=this.eventSource)==null||e.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const v=e=>{let t=typeof e;if(t===`object`)try{var n,r;return(n=(r=e.constructor)==null?void 0:r.name)==null?t:n}catch(e){return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch(e){return t}return t},y=e=>e===`number`||e===`bigint`,b=new Set([`boolean`,`integer`,`float`]),x=(e,t)=>{let n=e.value,r=v(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return D(n,t,r,e.valueId);if(typeof t==`string`)return b.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=S(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(y(typeof t)&&e.type===`integer`){let i=C(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(y(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=w(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`}},S=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},C=e=>{let t=T(e);return t==null?void 0:Math.trunc(t)},w=e=>T(e),T=e=>{if(!e||!E(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},E=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},D=(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 O(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(e){return{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`invalid-json`}}},O=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},k={off:-1,error:0,warn:1,info:2,debug:3},A=()=>{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,f(f({},e),{},{fractionalSecondDigits:3}))}catch(t){return new Intl.DateTimeFormat(void 0,e)}};var j=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=A()}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){if(k[this.level]>=k[t]){var i;e(`[${this.dateFormatter.format(new Date)}] ${(i=this.decorator)==null?void 0:i.decorateMessage(n)}`,...r)}}},M=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const N=(e,t)=>new j(e==null?`warn`:e,t==null?new M:t),P=(e,t)=>new URL(e,t==null?void 0:t.toString()),F=e=>{if(e)try{return new URL(e)}catch(t){throw new n(`Invalid URL '${e}'. Parsing failed: ${t}`)}},I=`https://client-sdk-api.configdirector.com`,L=(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.`},R=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)}),z=`configdirector-sdk:instance-id`,B=1e3,V=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,H=(e,t)=>{let n=t;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return n>>>0},U=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=H(n,2166136261);return H(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},W=()=>{try{var e;return(e=globalThis.localStorage)==null?void 0:e}catch(e){return}},G=e=>{if(!e||typeof e!=`object`)return!1;let{v:t,id:n,createdAt:r,checksum:i}=e;return t!==1||typeof n!=`string`||typeof i!=`string`||typeof r!=`number`||!Number.isInteger(r)||r<=0||!V.test(n)?!1:i===U(n,r)},K=async(e,t)=>{let n;try{n=await e.getItem(z)}catch(e){return t.debug(`[ConfigDirectorClient] Could not read the stored instance id, using an ephemeral one`,e),{outcome:`failed`}}if(typeof n!=`string`||n===``)return{outcome:`nothing usable`};let r;try{r=JSON.parse(n)}catch(e){return t.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`),{outcome:`nothing usable`}}if(!G(r))return t.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`),{outcome:`nothing usable`};let i=Date.now()-r.createdAt;return i<0||i>=216e5?(t.debug(`[ConfigDirectorClient] The stored instance id has expired, generating a new one`),{outcome:`nothing usable`}):{outcome:`stored`,instanceId:r.id}},q=async(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:U(t,r)};try{return await e.setItem(z,JSON.stringify(i)),!0}catch(e){return n.debug(`[ConfigDirectorClient] Could not persist the instance id, using it as an ephemeral one`,e),!1}},J=async(e,t,n,r)=>{let i=await K(e,r);switch(i.outcome){case`stored`:return{instanceId:i.instanceId};case`failed`:return{instanceId:t,ephemeral:!0};case`nothing usable`:break}return n.passed?{instanceId:t,ephemeral:!0}:await q(e,t,r)?{instanceId:t}:{instanceId:t,ephemeral:!0}},Y=(e,t=W())=>{let n=R();if(!t)return e.debug(`[ConfigDirectorClient] No instance id storage is available, using an ephemeral instance id`),Promise.resolve({instanceId:n,ephemeral:!0});let r={passed:!1},i,a=new Promise(t=>{i=setTimeout(()=>{r.passed=!0,e.warn(`[ConfigDirectorClient] The instance id storage did not respond within ${B}ms, using an ephemeral instance id`),t({instanceId:n,ephemeral:!0})},B)});return Promise.race([J(t,n,r,e),a]).finally(()=>clearTimeout(i))};var X=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){var n=this;if(!e.ok)throw n.isStatusFatal(e.status)?(n.fatalError=!0,n.close(),n.prepareFatalResponseStatusError(e.status,await e.text())):new t(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new t(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new t(`Failed to parse the response from the server: ${e}`):new t(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,n){var r,i;let a=e==null?0:e;return new t(`${`Connection failed with status: ${e==null?`unknown`:e}`}${((r=n==null||(i=n.trim())==null?void 0:i.length)==null?0:r)>0?` (${n})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,a)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}isFetchErrorFatal(e){return(e==null?void 0:e.name)===`NotAllowedError`}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}};const Z=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(),f(f({},n),{},{signal:i.signal}));return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}};var Q=class extends X{constructor(t){var n;super(),this.options=t,this.eventEmitter=new e,this.connectionGeneration=0,this.options=t,this.logger=t.logger,this.url=t.resolveUrl(`client/polling/v1`,t.baseUrl),this.pollingIntervalSeconds=(n=t.pollingInterval)==null?60:n}async connect(e,t){var n=this;let r=++n.connectionGeneration;n.clearPollingInterval();let i=await n.options.clientSession;if(r!==n.connectionGeneration)return n;try{await n.fetchConfigs(e,t,i)}finally{n.fatalError||n.schedulePollingInterval(()=>{n.fetchConfigs(e,t,i).catch(e=>{n.logger.error(`[PollingTransport] Error during polling:`,e)})})}return n}close(){this.connectionGeneration++,super.close()}async fetchConfigs(e,t,n){var r=this;if(r.fatalError){r.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let i=await Z(t,r.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:r.options.metaContext,clientSdkKey:r.options.clientSdkKey,instanceId:n.instanceId,ephemeral:n.ephemeral,lastUpdateTimestamp:r.lastUpdateTimestamp})},r.logger);if(await r.handleNonOkResponse(i),i.status==200){let e=JSON.parse(await i.text());r.lastUpdateTimestamp=e.timestamp,r.eventEmitter.emit(`configSetReceived`,e)}}catch(e){try{r.handleFetchError(e)}catch(e){throw r.fatalError&&r.eventEmitter.emit(`connectionError`,e),e}}}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}};const $=e=>{try{return e(globalThis)}catch(e){return}},ee=()=>$(e=>{var t;return(t=e.navigator)==null?void 0:t.userAgent}),te=()=>$(e=>{var t;return(t=e.location)==null?void 0:t.host}),ne=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,re=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!ne(t))return!1;return!0},ie=e=>e==null||typeof e==`string`&&re(e),ae=e=>{if(typeof e==`string`)return e;try{return String(e)}catch(t){return Object.prototype.toString.call(e)}},oe=(e,t)=>{let n=``,r=0;for(let i of e){if(r===t)break;n+=i,r+=1}return n},se=e=>{let t=e==null?void 0:e.kind;return ie(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:oe(ae(t),128)}};var ce=class{constructor(t,n,r,i,a){var o,s,c,l,u,d,p,m,h,g,_,v,y,b;this.handlersMap=new Map,this.eventEmitter=new e,this.ready=!1,this.initializing=!1,this.hasReceivedConfigSet=!1,this.logger=(o=i==null?void 0:i.logger)==null?N():o,this.clientSession=Y(this.logger,a==null?void 0:a.instanceIdStorage),this.timeout=(s=i==null||(c=i.connection)==null?void 0:c.timeout)==null?3e3:s,this.validateSdkKeyPresence(n);let x=(l=a==null?void 0:a.urlFactory)==null?P:l,S=(u=this.parseUrl(i==null||(d=i.connection)==null?void 0:d.url,x))==null?I:u;this.connectionMode=(p=i==null||(m=i.connection)==null?void 0:m.mode)==null?`streaming`:p,this.telemetryClient=t,this.transport=(h=a==null?void 0:a.transport)==null?this.buildTransport(n,r,S,x,i,a):h,this.transport.on(`configSetReceived`,e=>{var t;this.hasReceivedConfigSet=!0,(t=this.readyResolve)==null||t.call(this);let n=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:this.configSet.configs=f(f({},this.configSet.configs),e.configs);let r=Object.keys(e.configs);this.emit(`configsUpdated`,{keys:r,removedKeys:n}),this.updateWatchers([...r,...n]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:r,removedKeys:n})}),this.transport.on(`connectionError`,e=>{this.initializing=!1,this.logger.error(`[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.`,e),this.emit(`connectionError`,{error:e})}),this.registerHandler(`clientReady`,i==null||(g=i.hooks)==null?void 0:g.clientReady),this.registerHandler(`configEvaluated`,i==null||(_=i.hooks)==null?void 0:_.configEvaluated),this.registerHandler(`configsUpdated`,i==null||(v=i.hooks)==null?void 0:v.configsUpdated),this.registerHandler(`contextUpdated`,i==null||(y=i.hooks)==null?void 0:y.contextUpdated),this.registerHandler(`connectionError`,i==null||(b=i.hooks)==null?void 0:b.connectionError)}registerHandler(e,t){if(!t)return;let n=Array.isArray(t)?t:[t];for(let t of n)typeof t==`function`&&this.on(e,t)}resolvePollingIntervalForMode(e){if(this.connectionMode!==`polling`)return;let t=L(e,{defaultSeconds:60,minimumSeconds:30});return t.warning&&this.logger.warn(`[ConfigDirectorClient] ${t.warning}`),t.seconds}buildTransport(e,t,n,r,i,a){var o,s;return new(this.getTransportConstructor(this.connectionMode))({clientSession:this.clientSession,clientSdkKey:e,baseUrl:n,resolveUrl:r,metaContext:f(f({},i==null?void 0:i.metadata),{},{sdkName:t.sdkName,sdkVersion:t.sdkVersion,userAgent:ee(),host:te()}),logger:this.logger,fetch:a==null?void 0:a.fetch,connectionRetryDelay:(o=a==null?void 0:a.connectionRetryDelay)==null?(e=>2**Math.min(e,9)*1e3):o,pollingInterval:this.resolvePollingIntervalForMode(i==null||(s=i.connection)==null?void 0:s.pollingInterval)})}getTransportConstructor(e){switch(e){case`polling`:return Q;default:return _}}async initialize(e){var t=this;t.hasReceivedConfigSet||(t.initializing=!0),await t.submitContext(e,`initialization`)}async updateContext(e){await this.submitContext(e,`context update`)}async submitContext(e,t){var n=this;await n.connectToTransport(n.contextToConnectWith(e,t),t)}contextToConnectWith(e,t){let n=se(e);switch(n.outcome){case`admitted`:return n.context;case`ignored`:this.logger.error(`[ConfigDirectorClient] Ignored the context supplied for ${t} because its kind '${n.kindSample}' is invalid; connecting as if no context was supplied. A context kind has 1 to 64 characters, using only lowercase letters, digits, '-' and '_'.`),this.telemetryClient.recordInvalidContext(n.kindSample);return}}get context(){return this.currentContext}async connectToTransport(e,t){var n=this;try{n.ready=!1,n.readyPromise=new Promise(e=>{n.readyResolve=e}).then(e=>{e||(n.ready=!0,n.initializing=!1,n.emit(`clientReady`,{action:t}),n.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))});let r=new Date().getTime();await n.transport.connect(e==null?{}:e,n.timeout,t),n.currentContext=e,n.telemetryClient.updateContext(e).catch(e=>n.logger.warn(`[ConfigDirectorClient] Telemetry could not update the context: `,e)),n.emit(`contextUpdated`,{context:e});let i=new Date().getTime()-r,a=n.timeout-i;clearTimeout(n.timeoutTimer),n.timeoutTimer=void 0,a>0&&await Promise.race([n.readyPromise,new Promise(e=>{n.timeoutTimer=setTimeout(()=>e(),a)})]).finally(()=>clearTimeout(n.timeoutTimer)),n.ready||n.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${t} after ${n.timeout}ms. The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`)}catch(e){n.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}updateWatchers(e){e.forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){var t,n;let r=(t=this.configSet)==null?void 0:t.configs[e];(n=this.handlersMap.get(e))==null||n.forEach(t=>{let n=this.getValueFromConfigState(e,r,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==null||n.splice(e,1))}else n.splice(0)}getValue(e,t){var n;this.validateDefaultValue(t);let r=(n=this.configSet)==null?void 0:n.configs[e];return this.getValueFromConfigState(e,r,t)}getValueFromConfigState(e,t,n){var r,i;if(!t){var a;this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`);let t=this.isReady?`config-state-missing`:`client-not-ready`;return this.telemetryClient.evaluatedConfig({contextId:(a=this.currentContext)==null?void 0:a.id,key:e,defaultValue:n,requestedType:v(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let o=x(t,n);return this.telemetryClient.evaluatedConfig({contextId:(r=this.currentContext)==null?void 0:r.id,type:t.type,key:e,defaultValue:n,requestedType:o.requestedType,evaluatedValue:o.parsedValue,evaluatedValueId:o.parsedValueId,usedDefault:o.usedDefault,evaluationReason:o.reason}),this.dispatchEvaluationEvent({key:e,value:o.parsedValue,valueId:(i=o.parsedValueId)==null?void 0:i,isDefaultValue:o.usedDefault,reason:o.reason,context:this.context}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${o.parsedValue}'`),o.parsedValue}dispatchEvaluationEvent(e){setTimeout(()=>this.emit(`configEvaluated`,{evaluation:e}),0)}emit(e,t){try{this.eventEmitter.emit(e,t)}catch(t){this.logger.error(`[ConfigDirectorClient] Error executing event handlers for '${e}'`,t)}}parseUrl(e,t){if(e)try{return t(e)}catch(t){throw new n(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateSdkKeyPresence(e){if(!e||e.trim().length==0)throw new n(`No client SDK key was provided, the client cannot be instantiated without a valid client SDK key`)}validateDefaultValue(e){if(e==null)throw new n(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new n(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}get isInitializing(){return this.initializing}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.logger.debug(`[ConfigDirectorClient] clear() has been called, removing all observers`),this.eventEmitter.clear(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}pauseNetwork(){this.logger.debug(`[ConfigDirectorClient] pauseNetwork() called, pausing transport connection`),clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,this.transport.close(),this.ready=!1}async resumeNetwork(){var e=this;await e.connectToTransport(e.currentContext,`network resume`)}async close(){var e=this,t;e.logger.debug(`[ConfigDirectorClient] close() has been called, closing connection to server`),clearTimeout(e.timeoutTimer),(t=e.readyResolve)==null||t.call(e,!0),e.telemetryClient.close().catch(t=>e.logger.warn(`[ConfigDirectorClient] Telemetry could not close: `,t)),e.transport.close(),e.ready=!1,e.initializing=!1}dispose(){this.clear(),this.close()}};export{N as a,n as c,F as i,e as l,I as n,f as o,P as r,t as s,ce as t};
6
- //# sourceMappingURL=DefaultConfigDirectorClient-DWgN1o7o.mjs.map