@configdirector/server-sdk 1.9.1 → 1.11.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.
- package/README.md +5 -3
- package/dist/DefaultConfigDirectorClient-BoqR23zq.cjs +5 -0
- package/dist/DefaultConfigDirectorClient-z8HbdUmy.mjs +6 -0
- package/dist/DefaultConfigDirectorClient-z8HbdUmy.mjs.map +1 -0
- package/dist/configdirector-server-testing.cjs +1 -1
- package/dist/configdirector-server-testing.d.cts +8 -26
- package/dist/configdirector-server-testing.d.cts.map +1 -1
- package/dist/configdirector-server-testing.d.mts +8 -26
- package/dist/configdirector-server-testing.d.mts.map +1 -1
- package/dist/configdirector-server-testing.mjs +1 -1
- package/dist/configdirector-server-testing.mjs.map +1 -1
- package/dist/configdirector-server.cjs +1 -1
- package/dist/configdirector-server.d.cts +26 -3
- package/dist/configdirector-server.d.cts.map +1 -1
- package/dist/configdirector-server.d.mts +26 -3
- package/dist/configdirector-server.d.mts.map +1 -1
- package/dist/configdirector-server.mjs +1 -1
- package/dist/configdirector-server.mjs.map +1 -1
- package/dist/{types-CcUNxeqN.d.cts → errors-BCEfxVqM.d.mts} +130 -47
- package/dist/errors-BCEfxVqM.d.mts.map +1 -0
- package/dist/{types-BqIJGXWv.d.mts → errors-C7n65Oc5.d.cts} +130 -47
- package/dist/errors-C7n65Oc5.d.cts.map +1 -0
- package/package.json +1 -1
- package/dist/DefaultConfigDirectorClient-B1vsd-g7.cjs +0 -5
- package/dist/DefaultConfigDirectorClient-BH0eGfm_.mjs +0 -6
- package/dist/DefaultConfigDirectorClient-BH0eGfm_.mjs.map +0 -1
- package/dist/types-BqIJGXWv.d.mts.map +0 -1
- package/dist/types-CcUNxeqN.d.cts.map +0 -1
|
@@ -32,27 +32,40 @@ type ConfigEvaluation = {
|
|
|
32
32
|
context?: ConfigDirectorContext;
|
|
33
33
|
};
|
|
34
34
|
/**
|
|
35
|
-
* The
|
|
36
|
-
*
|
|
35
|
+
* The context to be sent to ConfigDirector: the user or other entity, such as a device or an
|
|
36
|
+
* organization, that configs are evaluated for. This context will be used for targeting rules
|
|
37
|
+
* evaluation.
|
|
37
38
|
*/
|
|
38
39
|
type ConfigDirectorContext = {
|
|
39
40
|
/**
|
|
40
|
-
* The
|
|
41
|
-
*
|
|
41
|
+
* The context's identifier. This should be a value that uniquely identifies the user or other
|
|
42
|
+
* entity among contexts of the same {@link kind}.
|
|
42
43
|
* In the case of anonymous users, you could generate a UUID or alternatively not provide
|
|
43
44
|
* the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
|
|
44
|
-
* value is used for segmenting
|
|
45
|
-
* could result in the
|
|
45
|
+
* value is used for segmenting contexts in percentage rollouts, and changes to the {@link id}
|
|
46
|
+
* could result in the context being assigned to a different percentile.
|
|
46
47
|
*/
|
|
47
48
|
id?: string;
|
|
48
49
|
/**
|
|
49
|
-
* The
|
|
50
|
+
* The kind of entity this context represents, such as `user`, `device`, `organization`,
|
|
51
|
+
* `tenant` or `listing`. You can use any other kind that fits your application. A kind has 1
|
|
52
|
+
* to 64 characters, using only lowercase letters (`a`-`z`), digits, `-` and `_`. It is used
|
|
53
|
+
* exactly as given, without trimming or changing its case.
|
|
54
|
+
*
|
|
55
|
+
* A context with an invalid kind is ignored as a whole: the SDK logs an error and evaluates
|
|
56
|
+
* as if no context had been provided.
|
|
57
|
+
*
|
|
58
|
+
* @default "user"
|
|
59
|
+
*/
|
|
60
|
+
kind?: string;
|
|
61
|
+
/**
|
|
62
|
+
* The context's display name. This will be shown in the ConfigDirector dashboard and may be
|
|
50
63
|
* used for targeting rules.
|
|
51
64
|
*/
|
|
52
65
|
name?: string;
|
|
53
66
|
/**
|
|
54
|
-
* Any arbitrary traits for the
|
|
55
|
-
*
|
|
67
|
+
* Any arbitrary traits for the context. They will be shown in the ConfigDirector dashboard
|
|
68
|
+
* and may be used for targeting rules.
|
|
56
69
|
*/
|
|
57
70
|
traits?: {
|
|
58
71
|
[key: string]: unknown;
|
|
@@ -74,9 +87,90 @@ type ConfigDirectorMetaContext = {
|
|
|
74
87
|
appVersion?: string;
|
|
75
88
|
appName?: string;
|
|
76
89
|
};
|
|
77
|
-
type ConnectionMode = "streaming" | "polling";
|
|
90
|
+
type ConnectionMode = "streaming" | "polling" | "offline";
|
|
91
|
+
//#endregion
|
|
92
|
+
//#region ../shared/src/native-values.d.ts
|
|
93
|
+
type NativeJsonValue = boolean | number | string | null | NativeJsonValue[] | {
|
|
94
|
+
[key: string]: NativeJsonValue;
|
|
95
|
+
};
|
|
96
|
+
type NativeValue = boolean | number | string | NativeJsonValue[] | {
|
|
97
|
+
[key: string]: NativeJsonValue;
|
|
98
|
+
};
|
|
99
|
+
type NativeValues = Record<string, NativeValue>;
|
|
78
100
|
//#endregion
|
|
79
101
|
//#region src/types.d.ts
|
|
102
|
+
/**
|
|
103
|
+
* One value an offline client serves for a config key. The config type follows from the value: a
|
|
104
|
+
* boolean, an integral number (`integer`), any other number (`float`), a string, or a plain object
|
|
105
|
+
* or array (`json`).
|
|
106
|
+
*/
|
|
107
|
+
type OfflineValue = NativeValue;
|
|
108
|
+
/**
|
|
109
|
+
* The values an offline client serves, keyed by config key. See {@link OfflineValue} for how each
|
|
110
|
+
* value's config type is decided. Every context receives the same value.
|
|
111
|
+
*/
|
|
112
|
+
type OfflineValues = NativeValues;
|
|
113
|
+
/**
|
|
114
|
+
* Connection options of the {@link ConfigDirectorClient}
|
|
115
|
+
*/
|
|
116
|
+
type ConnectionOptions = {
|
|
117
|
+
/**
|
|
118
|
+
* The connection mode to be used, one of `streaming` (default), `polling` or `offline`.
|
|
119
|
+
* If set to `streaming`, the connection will remain open and receive updates whenever
|
|
120
|
+
* config state is updated on the ConfigDirector dashboard.
|
|
121
|
+
* When set to `polling`, there will be an initial request to retrieve config state during
|
|
122
|
+
* initialization, and additional requests on a `pollingInterval`.
|
|
123
|
+
* When set to `offline`, the client never connects to ConfigDirector and sends nothing: it serves
|
|
124
|
+
* the values read from {@link file} or given in {@link values} to every context, or the in-code
|
|
125
|
+
* default values when neither is given. No SDK key is needed.
|
|
126
|
+
*
|
|
127
|
+
* Defaults to `streaming`
|
|
128
|
+
*/
|
|
129
|
+
mode?: ConnectionMode;
|
|
130
|
+
/**
|
|
131
|
+
* The path of a JSON file holding the values to serve in `offline` mode, resolved against the
|
|
132
|
+
* process working directory. The file holds one object with a value per config key, such as
|
|
133
|
+
* `{ "new-checkout": true, "max-items": 20 }`; see {@link OfflineValue} for how the config type
|
|
134
|
+
* of each value is decided. A file that is missing, unreadable, not a JSON object, or holding a
|
|
135
|
+
* value such as `null` makes `initialize` reject with a `ConfigDirectorInitializationError`.
|
|
136
|
+
*
|
|
137
|
+
* Only one of `file` and `values` can be given, and only in `offline` mode; otherwise
|
|
138
|
+
* `initialize` rejects.
|
|
139
|
+
*/
|
|
140
|
+
file?: string;
|
|
141
|
+
/**
|
|
142
|
+
* The values to serve in `offline` mode, keyed by config key. A value such as `null` makes
|
|
143
|
+
* `initialize` reject with a `ConfigDirectorInitializationError`.
|
|
144
|
+
*
|
|
145
|
+
* Only one of `file` and `values` can be given, and only in `offline` mode; otherwise
|
|
146
|
+
* `initialize` rejects.
|
|
147
|
+
*/
|
|
148
|
+
values?: OfflineValues;
|
|
149
|
+
/**
|
|
150
|
+
* The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
|
|
151
|
+
* effect in the other modes.
|
|
152
|
+
*
|
|
153
|
+
* Defaults to 300 seconds (5 minutes). The minimum is 60 seconds. A value below the minimum is
|
|
154
|
+
* raised to the minimum and a warning is logged.
|
|
155
|
+
*/
|
|
156
|
+
pollingInterval?: number;
|
|
157
|
+
/**
|
|
158
|
+
* The timeout, in milliseconds, to be used in initialization and when updating the context.
|
|
159
|
+
* If streaming is enabled, the operation (initialization or context update) may still succeed
|
|
160
|
+
* after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
|
|
161
|
+
* If streaming is disabled, if the operation times out, it will not be retried. This option has
|
|
162
|
+
* no effect in `offline` mode.
|
|
163
|
+
*
|
|
164
|
+
* Defaults to 3,000 milliseconds (3 seconds)
|
|
165
|
+
*/
|
|
166
|
+
timeout?: number;
|
|
167
|
+
/**
|
|
168
|
+
* The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
|
|
169
|
+
* proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
|
|
170
|
+
* a proxy for the client SDK. This option has no effect in `offline` mode.
|
|
171
|
+
*/
|
|
172
|
+
url?: string;
|
|
173
|
+
};
|
|
80
174
|
/**
|
|
81
175
|
* Configuration options for the {@link ConfigDirectorClient}
|
|
82
176
|
*/
|
|
@@ -88,41 +182,7 @@ type ConfigDirectorClientOptions = {
|
|
|
88
182
|
/**
|
|
89
183
|
* Connection options
|
|
90
184
|
*/
|
|
91
|
-
connection?:
|
|
92
|
-
/**
|
|
93
|
-
* The connection mode to be used, one of `streaming` (default) or `polling`.
|
|
94
|
-
* If set to `streaming`, the connection will remain open and receive updates whenever
|
|
95
|
-
* config state is updated on the ConfigDirector dashboard.
|
|
96
|
-
* When set to `polling`, there will be an initial request to retrieve config state during
|
|
97
|
-
* initialization, and additional requests on a `pollingInterval`.
|
|
98
|
-
*
|
|
99
|
-
* Defaults to `streaming`
|
|
100
|
-
*/
|
|
101
|
-
mode?: ConnectionMode;
|
|
102
|
-
/**
|
|
103
|
-
* The polling interval in _seconds_ when the `mode` is set to `polling`. This option has no
|
|
104
|
-
* effect when the `mode` is set to `streaming`.
|
|
105
|
-
*
|
|
106
|
-
* Defaults to 300 seconds (5 minutes). The minimum is 60 seconds. A value below the minimum is
|
|
107
|
-
* raised to the minimum and a warning is logged.
|
|
108
|
-
*/
|
|
109
|
-
pollingInterval?: number;
|
|
110
|
-
/**
|
|
111
|
-
* The timeout, in milliseconds, to be used in initialization and when updating the context.
|
|
112
|
-
* If streaming is enabled, the operation (initialization or context update) may still succeed
|
|
113
|
-
* after it times out if no unrecoverable errors are encountered (like an invalid SDK key).
|
|
114
|
-
* If streaming is disabled, if the operation times out, it will not be retried.
|
|
115
|
-
*
|
|
116
|
-
* Defaults to 3,000 milliseconds (3 seconds)
|
|
117
|
-
*/
|
|
118
|
-
timeout?: number;
|
|
119
|
-
/**
|
|
120
|
-
* The base URL to the ConfigDirector SDK server. To be used only when needing to route through a
|
|
121
|
-
* proxy to connect to the ConfigDirector SDK server. Please refer to the docs on how to configure
|
|
122
|
-
* a proxy for the client SDK.
|
|
123
|
-
*/
|
|
124
|
-
url?: string;
|
|
125
|
-
};
|
|
185
|
+
connection?: ConnectionOptions;
|
|
126
186
|
/**
|
|
127
187
|
* A logger that implements {@link ConfigDirectorLogger}. It defaults to the ConfigDirector console
|
|
128
188
|
* logger set to 'warn' level.
|
|
@@ -182,6 +242,14 @@ type ConfigDirectorClientOptions = {
|
|
|
182
242
|
*/
|
|
183
243
|
hooks?: ClientHooks;
|
|
184
244
|
};
|
|
245
|
+
/**
|
|
246
|
+
* The options of a client created without an SDK key: the connection mode is `offline`.
|
|
247
|
+
*/
|
|
248
|
+
type OfflineClientOptions = ConfigDirectorClientOptions & {
|
|
249
|
+
connection: ConnectionOptions & {
|
|
250
|
+
mode: "offline";
|
|
251
|
+
};
|
|
252
|
+
};
|
|
185
253
|
type ClientEvents = {
|
|
186
254
|
configsUpdated: {
|
|
187
255
|
keys: string[];
|
|
@@ -288,5 +356,20 @@ interface ConfigDirectorClient {
|
|
|
288
356
|
dispose(): void;
|
|
289
357
|
}
|
|
290
358
|
//#endregion
|
|
291
|
-
|
|
292
|
-
|
|
359
|
+
//#region ../shared/src/errors.d.ts
|
|
360
|
+
declare class ConfigDirectorConnectionError extends Error {
|
|
361
|
+
readonly name: string;
|
|
362
|
+
readonly status?: number;
|
|
363
|
+
constructor(message: string, status?: number);
|
|
364
|
+
}
|
|
365
|
+
declare class ConfigDirectorValidationError extends Error {
|
|
366
|
+
readonly name: string;
|
|
367
|
+
constructor(message: string);
|
|
368
|
+
}
|
|
369
|
+
declare class ConfigDirectorInitializationError extends Error {
|
|
370
|
+
readonly name: string;
|
|
371
|
+
constructor(message: string);
|
|
372
|
+
}
|
|
373
|
+
//#endregion
|
|
374
|
+
export { ConfigValueType as _, ConfigDirectorClientOptions as a, OfflineValues as c, NativeValues as d, ConfigDirectorContext as f, ConfigDirectorMetaContext as g, ConfigDirectorLoggingLevel as h, ConfigDirectorClient as i, NativeJsonValue as l, ConfigDirectorLogger as m, ConfigDirectorInitializationError as n, OfflineClientOptions as o, ConfigDirectorLogMessageDecorator as p, ConfigDirectorValidationError as r, OfflineValue as s, ConfigDirectorConnectionError as t, NativeValue as u };
|
|
375
|
+
//# sourceMappingURL=errors-C7n65Oc5.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-C7n65Oc5.d.cts","names":[],"sources":["../../shared/src/types.ts","../../shared/src/native-values.ts","../src/types.ts","../../shared/src/errors.ts"],"mappings":";cAAa,cAAA;AAAA,KAUD,UAAA,WAAqB,cAAA;AAAA,KAErB,kBAAA;EAAA,CAAwB,GAAA;AAAA;AAAA,KAExB,eAAA,wCAAuD,kBAAA;AAAA,KAEvD,WAAA;EACV,EAAA;EACA,GAAA;EACA,IAAA,EAAM,UAAA;EACN,KAAA;EACA,OAAA;AAAA;AAAA,KAQU,0BAAA;AAAA,UAEK,oBAAA;EACf,KAAA,CAAM,OAAA,aAAoB,IAAA;EAE1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,KAAA,CAAM,OAAA,aAAoB,IAAA;AAAA;AAAA,UAGX,iCAAA;EACf,eAAA,CAAgB,OAAA;AAAA;AAAA,KAGN,gBAAA;AAAA,KAUA,gBAAA;EACV,GAAA;EACA,KAAA,EAAO,eAAA;EACP,OAAA;EACA,cAAA;EACA,MAAA,EAAQ,gBAAA;EACR,OAAA,GAAU,qBAAA;AAAA;;;AA9BZ;;;KAqCY,qBAAA;EApCV;;;;;;;;EA6CA,EAAA;EAvCA;;;;;AAGF;;;;;AAIA;EA6CE,IAAA;;;;AAnCF;EAyCE,IAAA;;;;;EAMA,MAAA;IAAA,CAAY,GAAA;EAAA;EA7CZ;;;;;;;EAsDA,SAAA;AAAA;;AA3CF;;;KAkDY,yBAAA;EACV,UAAA;EACA,OAAA;AAAA;AAAA,KAGU,cAAA;;;KCxHA,eAAA,sCAAqD,eAAA;EAAA,CAAuB,GAAA,WAAc,eAAA;AAAA;AAAA,KAE1F,WAAA,+BAA0C,eAAA;EAAA,CAAuB,GAAA,WAAc,eAAA;AAAA;AAAA,KAE/E,YAAA,GAAe,MAAA,SAAe,WAAA;;;;ADG1C;;;;KEqBY,YAAA,GAAe,WAAA;AFnB3B;;;;AAAA,KEyBY,aAAA,GAAgB,YAAA;AFvB5B;;;AAAA,KE4BY,iBAAA;EF5ByE;AAErF;;;;;;;;;;;EEuCE,IAAA,GAAO,cAAA;EF1BG;;;;;AAEZ;;;;;EEmCE,IAAA;EFlC0B;;;;;;;EE0C1B,MAAA,GAAS,aAAA;EFpCH;;;;AAGR;;;EEyCE,eAAA;EFxC+B;AAGjC;;;;;AAUA;;;EEqCE,OAAA;EFhCQ;;;;;EEsCR,GAAA;AAAA;;;;KAMU,2BAAA;EF3CV;;;EE+CA,QAAA,GAAW,yBAAA;EFxCD;;;EE4CV,UAAA,GAAa,iBAAA;EFnCb;;;;;;;;AAyCF;;;;;EEQE,MAAA,GAAS,oBAAA;EFHe;;;;;;;EEYxB,SAAA;IDpIyB;;;;;;;;AAE3B;IC4II,eAAA;ID5IkD;;;;;;;AAEtD;ICoJI,aAAA;EAAA;EDpJuB;;;;;ACwB3B;;;;;AAMA;;;;;EAwIE,KAAA,GAAQ,WAAA;AAAA;;;;KAME,oBAAA,GAAuB,2BAAA;EACjC,UAAA,EAAY,iBAAA;IAAsB,IAAA;EAAA;AAAA;AAAA,KAGxB,YAAA;EACV,cAAA;IAAkB,IAAA;IAAgB,WAAA;EAAA;EAClC,WAAA;EACA,eAAA;IAAmB,UAAA,EAAY,gBAAA;EAAA;EAC/B,eAAA;IAAmB,KAAA,EAAO,KAAA;EAAA;AAAA;AAAA,KAGhB,WAAA;EACV,WAAA,GAAc,WAAA,kBAA6B,WAAA;EAC3C,cAAA,GAAiB,WAAA,qBAAgC,WAAA;EACjD,eAAA,GAAkB,WAAA,sBAAiC,WAAA;EACnD,eAAA,GAAkB,WAAA,sBAAiC,WAAA;AAAA;AAAA,KAGzC,WAAA,sBAAiC,YAAA,KAAiB,OAAA,EAAS,YAAA,CAAa,MAAA;AAAA,KAExE,YAAA,WAAuB,eAAA,KAAoB,OAAA,EAAS,CAAA;;;;;;AApBhE;UA4BiB,oBAAA;;;;;;;;;AAxBjB;;;EAoCE,UAAA,IAAc,OAAA;EAnCd;;;;;;EAAA,IA2CI,OAAA;EAxCJ;;;;;AAGF;;;;;EAiDE,QAAA,WAAmB,eAAA,EAAiB,SAAA,UAAmB,YAAA,EAAc,CAAA,EAAG,OAAA,GAAU,qBAAA,GAAwB,CAAA;EA/CzD;;;;;;;;;;;;EA6DjD,KAAA,WAAgB,eAAA,EACd,SAAA,UACA,YAAA,EAAc,CAAA,EACd,QAAA,EAAU,YAAA,CAAa,CAAA,GACvB,OAAA,GAAU,qBAAA;EAhEZ;;;;;;;;EA2EA,OAAA,WAAkB,eAAA,EAAiB,SAAA,UAAmB,QAAA,GAAW,YAAA,CAAa,CAAA;EAvEzD;;;EA4ErB,UAAA;EA5EkF;;;;;;;EAqFlF,aAAA,CAAc,OAAA;IACZ,OAAA,GAAU,qBAAA;IACV,UAAA;EAAA,IACE,MAAA,SAAe,WAAA;EAEnB,EAAA,iBAAmB,YAAA,EAAc,SAAA,EAAW,CAAA,EAAG,OAAA,GAAU,IAAA,EAAM,YAAA,CAAa,CAAA;EAE5E,GAAA,iBAAoB,YAAA,EAAc,SAAA,EAAW,CAAA,EAAG,OAAA,IAAW,IAAA,EAAM,YAAA,CAAa,CAAA;EA1Ff;;;;;;EAkG/D,OAAA;AAAA;;;cCzSW,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,5 +0,0 @@
|
|
|
1
|
-
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`node:events`);c=s(c);let l=require(`node:crypto`),u=require(`luxon`),d=require(`semver`);d=s(d);let ee=require(`rapidhash-js`);var f=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},p=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},m=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},h=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},g=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},_=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},v=class{constructor(e){this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=e.onEvent??(()=>{}),this.onRetry=e.onRetry,this.onComment=e.onComment}parse(e){let t=e;this.isFirstChunk&&(this.isFirstChunk=!1,t.startsWith(``)?t=t.slice(1):t.startsWith(``)&&(t=t.slice(3)));let n=this.scanLines(this.bufferedInput+t);for(let e of n)this.dispatchLine(e)}finish(){this.bufferedInput=``}scanLines(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];i===`\r`||i===`
|
|
2
|
-
`?(t.push(e.slice(n,r)),i===`\r`&&e[r+1]===`
|
|
3
|
-
`&&r++,r++,n=r):r++}return this.bufferedInput=e.slice(n),t}dispatchLine(e){if(e.startsWith(`:`)){this.onComment?.(this.extractValue(e,1));return}if(e===``){this.emitEvent();return}this.applyField(this.parseField(e))}emitEvent(){let e=this.currentEvent.data.endsWith(`
|
|
4
|
-
`)?this.currentEvent.data.slice(0,-1):this.currentEvent.data;e!==``&&this.onEvent({...this.currentEvent,id:this.lastEventId,data:e}),this.currentEvent={data:``}}applyField(e){switch(e.field){case`event`:this.currentEvent.type=e.value;break;case`data`:this.currentEvent.data+=e.value+`
|
|
5
|
-
`;break;case`id`:e.value.includes(`\0`)||(this.lastEventId=e.value);break;case`retry`:/^\d+$/.test(e.value)&&this.onRetry?.(Number.parseInt(e.value,10));break;default:break}}parseField(e){let t=e.indexOf(`:`);return t===-1?{field:e,value:``}:{field:e.slice(0,t),value:this.extractValue(e,t+1)}}extractValue(e,t){return e[t]===` `?e.slice(t+1):e.slice(t)}};let y=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var b=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=y.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers={Accept:`text/event-stream`,...e.headers};let t=e.body;this.body=typeof t==`function`?t:()=>t,this.requestOptions={method:e.method??`GET`,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=e.fetch??((e,t)=>fetch(e,t)),this._onError=this.resolveCallback(e.onError,()=>{},`onError`),this._onConnect=this.resolveCallback(e.onConnect,()=>{},`onConnect`),this._onDisconnect=this.resolveCallback(e.onDisconnect,()=>{},`onDisconnect`),this._onMessage=this.resolveCallback(e.onMessage,()=>{},`onMessage`),this._onComment=this.resolveCallback(e.onComment,()=>{},`onComment`),this._shouldReconnect=this.resolveCallback(e.shouldReconnect,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`),this._calculateReconnectDelay=this.resolveCallback(e.calculateReconnectDelay,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`calculateReconnectDelay`)}set onError(e){this._onError=this.resolveCallback(e,()=>{},`onError`)}set onMessage(e){this._onMessage=this.resolveCallback(e,()=>{},`onMessage`)}set onComment(e){this._onComment=this.resolveCallback(e,()=>{},`onComment`)}set onConnect(e){this._onConnect=this.resolveCallback(e,()=>{},`onConnect`)}set onDisconnect(e){this._onDisconnect=this.resolveCallback(e,()=>{},`onDisconnect`)}set shouldReconnect(e){this._shouldReconnect=this.resolveCallback(e,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`)}set calculateReconnectDelay(e){this._calculateReconnectDelay=this.resolveCallback(e,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`shouldReconnect`)}get readyState(){return this._readyState}connect(){this._readyState===y.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=y.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=y.CONNECTING,this._fetch(this.url,{...this.requestOptions,body:this.body(),headers:this.buildRequestHeaders(),signal:this.abortController.signal,cache:`no-store`}).then(e=>this.handleFetchResponse(e)).catch(e=>{if(e.name===`AbortError`||this.abortController.signal.aborted){this.close();return}this._onError(e),this.scheduleReconnect({error:e})})}async handleFetchResponse(e){let{body:t,status:n}=e;if(n===204){this.disconnected();return}if(n>=400){this.scheduleReconnect({status:n});return}if(!t)throw new h(`The server response did not have a body`);this._readyState=y.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new v({onEvent:e=>{typeof e.id==`string`&&(this.lastEventId=e.id),this._onMessage(e)},onComment:e=>this._onComment(e),onRetry:e=>this.serverReconnectionTime=e});await this.readResponseStream(t,r),this.scheduleReconnect({status:n,error:new m(`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=y.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return{...this.headers,...e}}scheduleReconnect(e){if(this.abortController.signal.aborted)return;clearTimeout(this.reconnectTimeout),this.reconnectAttempt+=1;let t={attempt:this.reconnectAttempt,status:e.status,error:e.error,serverReconnectionTime:this.serverReconnectionTime};if(!this._shouldReconnect(t)){this.disconnected();return}this._readyState=y.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new _(`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 g(`${n} must be a function`);return e}};const x=e=>new b(e),S=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}},C=9e4;var te=class{constructor(e){this.options=e,this.eventEmitter=new c.EventEmitter,this.options=e,this.logger=e.logger,this.url=new URL(`server/sse/v1`,e.baseUrl),this.heartbeatUrl=new URL(`server/heartbeat/v1`,e.baseUrl)}async connect(e){this.eventSource&&this.close();let t=new Promise((e,t)=>{this.eventSource=x({url:this.url,method:`POST`,headers:{"Content-Type":`application/json`},body:()=>this.buildRequestBody(),onMessage:({data:e})=>{this.dispatchMessage(e)},onConnect:()=>{this.logger.debug(`[StreamingTransport] Connected`),e(this)},shouldReconnect:e=>{let n=!this.isStatusFatal(e.status);if(!n){this.stopHeartbeat();let n=this.prepareFatalError(e.status,e.error);this.eventEmitter.emit(`connectionError`,n),t(n)}return n},calculateReconnectDelay:e=>{let t=2**Math.min(e.attempt,9)*1e3,n=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?this.logger.info(n):this.logger.warn(n),t},onDisconnect:()=>{this.logger.debug(`[StreamingTransport] Disconnected`)}}),this.eventSource.connect()});this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),C);let n;try{return await Promise.race([t,new Promise(t=>{n=setTimeout(()=>t(this),e)})])}finally{clearTimeout(n)}}get sessionId(){return this._sessionId}sendHeartbeat(){!this.isConnected||!this._sessionId||S(C,this.heartbeatUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({serverSdkKey:this.options.serverSdkKey,sessionId:this._sessionId})},this.logger).then(e=>{e.ok||this.logger.debug(`[StreamingTransport] Heartbeat failed with status: ${e.status}`)}).catch(e=>{this.logger.debug(`[StreamingTransport] Heartbeat failed: `,e)})}buildRequestBody(){return this._sessionId=(0,l.randomUUID)(),JSON.stringify({metaContext:this.options.metaContext,serverSdkKey:this.options.serverSdkKey,sessionId:this._sessionId})}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configBundleReceived`,t)}catch(e){this.logger.error(`[StreamingTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,t){let n=e??0;return new f(`${`Connection failed with status: ${e??`unknown`}.`}${t?` Error: ${t}.`:``} This is an unrecoverable error, will not attempt to reconnect.`,n)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}get isConnected(){return this.eventSource?.readyState==`open`}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}clear(){this.eventEmitter.removeAllListeners()}stopHeartbeat(){clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0}close(){this.stopHeartbeat(),this.eventSource?.close()}dispose(){this.close(),this.clear()}},ne=class{constructor(){this.fatalError=!1}clearPollingInterval(){clearInterval(this.pollingInterval)}schedulePollingInterval(e){clearInterval(this.pollingInterval),!(this.pollingIntervalSeconds<=0)&&(this.pollingInterval=setInterval(e,this.pollingIntervalSeconds*1e3))}async handleNonOkResponse(e){if(!e.ok)throw this.isStatusFatal(e.status)?(this.fatalError=!0,this.close(),this.prepareFatalResponseStatusError(e.status,await e.text())):new f(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new f(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new f(`Failed to parse the response from the server: ${e}`):new f(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){let n=e??0;return new f(`${`Connection failed with status: ${e??`unknown`}`}${(t?.trim()?.length??0)>0?` (${t})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,n)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}isFetchErrorFatal(e){return e?.name===`NotAllowedError`}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}},w=class extends ne{constructor(e){super(),this.options=e,this.eventEmitter=new c.EventEmitter,this._sessionId=(0,l.randomUUID)(),this.options=e,this.logger=e.logger,this.url=new URL(`server/polling/v1`,e.baseUrl),this.pollingIntervalSeconds=e.pollingInterval??300}async connect(e){this.clearPollingInterval();try{await this.fetchConfigs(e)}finally{this.fatalError||this.schedulePollingInterval(()=>{this.fetchConfigs(e).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})})}return this}get sessionId(){return this._sessionId}async fetchConfigs(e){if(this.fatalError){this.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let t=await S(e,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({metaContext:this.options.metaContext,serverSdkKey:this.options.serverSdkKey,lastUpdateTimestamp:this.lastUpdateTimestamp,sessionId:this._sessionId})},this.logger);if(await this.handleNonOkResponse(t),t.status===200){let e=JSON.parse(await t.text());this.lastUpdateTimestamp=e.timestamp,this.eventEmitter.emit(`configBundleReceived`,e)}}catch(e){try{this.handleFetchError(e)}catch(e){throw this.fatalError&&this.eventEmitter.emit(`connectionError`,e),e}}}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}clear(){this.eventEmitter.removeAllListeners()}};const T=/^(?:0|[1-9][0-9]*)$/,E=/~(?![01])/,D=Object.prototype.propertyIsEnumerable,re=e=>{if(!E.test(e))return e.replace(/~1/g,`/`).replace(/~0/g,`~`)},ie=(e,t)=>{if(Array.isArray(e))return T.test(t)&&D.call(e,t)?e[Number(t)]:void 0;if(typeof e==`object`&&e)return D.call(e,t)?e[t]:void 0},ae=(e,t)=>{if(e===``)return t;if(!e.startsWith(`/`))return;let n=t;for(let t of e.slice(1).split(`/`)){let e=re(t);if(e===void 0||(n=ie(n,e),n===void 0))return}return n},oe=(e,t,n)=>{let r=n[0];switch(t.toLowerCase()){case`=`:case`equals`:return r!==void 0&&e===r;case`!=`:case`does not equal`:return r!==void 0&&e!==r;case`is one of`:return n.includes(e);case`is not one of`:return!n.includes(e);case`starts with any of`:return n.some(t=>e.startsWith(t));case`does not start with any of`:return!n.some(t=>e.startsWith(t));case`ends with any of`:return n.some(t=>e.endsWith(t));case`does not end with any of`:return!n.some(t=>e.endsWith(t));default:return!1}},se=(e,t,n)=>{let r=t.toLowerCase(),i=O(e);if(i===void 0)return r===`!=`||r===`does not equal`;let a=n[0];if(a===void 0)return!1;let o=O(a);if(o===void 0)return!1;switch(r){case`=`:case`equals`:return i===o;case`!=`:case`does not equal`:return i!==o;case`<`:return i<o;case`<=`:return i<=o;case`>`:return i>o;case`>=`:return i>=o;default:return!1}},O=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(typeof e!=`string`||e.length===0||!ce(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0},ce=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},le=(e,t,n)=>{let r=n[0];if(r===void 0)return!1;let i=k(e),a=k(r);if(i===void 0||a===void 0)return!1;switch(t){case`is after`:return i>a;case`is before`:return i<a;default:return!1}},k=e=>{let t=u.DateTime.fromISO(e,{zone:`utc`});return t.isValid?t.toMillis():void 0},A=(e,t,n)=>{let r=t.toLowerCase();if(e.trim().length===0)return r===`is not one of`;let i=d.coerce(e),a=n.map(e=>d.coerce(e)),o=a[0]??null;switch(r){case`=`:return j(i,o);case`<`:return M(i,o,d.lt);case`<=`:return M(i,o,d.lte);case`>`:return M(i,o,d.gt);case`>=`:return M(i,o,d.gte);case`is one of`:return a.some(e=>j(i,e));case`is not one of`:return!a.some(e=>j(i,e));default:return!1}},j=(e,t)=>e!==null&&t!==null&&d.eq(e,t),M=(e,t,n)=>e!==null&&t!==null&&n(e,t),N=Symbol(`absent`),P=Symbol(`unknown-attribute`),F=e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`,I=e=>e===N||e==null?``:F(e)?L(e):``,L=e=>typeof e==`string`?e:String(e),R=e=>e===N?void 0:e,z=e=>e===P?`unknown-attribute`:e===N?`absent`:F(e)?`scalar`:Array.isArray(e)?`array`:`object`,B=(e,t,n)=>{let r=t.toLowerCase();if(!Array.isArray(e))return r===`does not contain any of`;let i=e.filter(F).map(L);switch(r){case`contains any of`:return i.some(e=>n.includes(e));case`does not contain any of`:return!i.some(e=>n.includes(e));default:return!1}};var V=class{evaluate(e,t){return this.explain(e,t).matched}explain(e,t){let n=this.resolve(e,t),r=z(n),i=n===N||n===P?void 0:n;return n===P?{matched:!1,resolvedValue:i,resolvedType:r}:{matched:this.compare(e,n),resolvedValue:i,resolvedType:r}}compare(e,t){let n=e.targetValues??[];switch(e.targetType){case`text`:return oe(I(t),e.operator,n);case`number`:return se(R(t),e.operator,n);case`datetime`:return le(I(t),e.operator,n);case`semver`:return A(I(t),e.operator,n);case`array`:return B(R(t),e.operator,n)}return!1}resolve(e,t){switch(e.attribute){case`identifier`:return H(t?.context?.id);case`name`:return H(t?.context?.name);case`appName`:return H(t?.metadata?.appName);case`appVersion`:return H(t?.metadata?.appVersion);case`traits`:return e.trait?H(ae(e.trait,t?.context?.traits)):N;default:return P}}};const H=e=>e??N;var U=class{constructor(e){this.conditionEvaluator=e}explain(e,t,n){let r=t?.[e.segmentId];if(r===void 0||!W(r))return{matched:!1,segmentFound:!1,matchedGroupIndex:void 0};let i=this.matchingGroupIndex(r,n),a=i!==void 0;return{matched:this.operatorHolds(e,a),segmentFound:!0,matchedGroupIndex:i}}operatorHolds(e,t){switch(e.operator.toLowerCase()){case`in`:return t;case`not in`:return!t;default:return!1}}matchingGroupIndex(e,t){let n=(e.groups??[]).findIndex(e=>(e??[]).every(e=>this.conditionEvaluator.evaluate(e,t)));return n===-1?void 0:n}};const W=e=>(e.groups??[]).every(e=>(e??[]).every(e=>e.kind===void 0||e.kind===`attribute`)),ue=e=>{let t=`${e.contextIdentifier}-${e.configId}`;return Number((0,ee.rapidhash)(t,{seed:15426857351n})%1000n)/10};var de=class{constructor(e){if(this.logger=e,this.conditionEvaluator=new V,this.segmentEvaluator=new U(this.conditionEvaluator),!e||!e.warn||!e.error||!e.info)throw TypeError(`The provided logger is not a valid 'ConfigDirectorLogger'`);this.logger=e}evaluate(e,t,n){return{id:e.id,key:e.key,type:e.type,value:this.explain(e,t,n).value}}explain(e,t,n){let r=[...e.target?.rules??[]].sort((e,t)=>(e.order??2**53-1)-(t.order??2**53-1)),i=[],a;for(let o of r){if(a){i.push({ruleId:o.id,outcome:`not-evaluated`,conditions:[],bucket:void 0});continue}let r=this.explainRule(o,e,t,n);i.push(r.explanation),r.value!==void 0&&(a={ruleId:o.id,value:r.value})}return{value:a?.value??e.target?.defaultValue,servedBy:a?{kind:`rule`,ruleId:a.ruleId}:{kind:`default`},rules:i}}explainRule(e,t,n,r){let i={ruleId:e.id,outcome:`not-matched`,conditions:[],bucket:void 0};try{let a;return e.type==`percentage`?a=this.explainPercentage(e.percentages??[],t,n,i):e.type==`conditional`&&(a=this.explainConditionalRule(e,t,n,r,i)),a!==void 0&&(i.outcome=`matched`),{explanation:i,value:a}}catch(n){return this.logger.warn(`There was an error while evaluating a targeting rule '${e?.id}' for '${t?.key}'. The rule will be disregarded.`,{error:n,configKey:t?.key,ruleId:e?.id}),{explanation:{ruleId:e.id,outcome:`errored`,conditions:[],bucket:void 0},value:void 0}}}explainPercentage(e,t,n,r){let i=n?.context?.id??void 0,a=i===void 0?0:ue({configId:t.id,contextIdentifier:i}),o=[],s=0,c;for(let t of e){let e=s+t.percentage;o.push({percentageId:t.id,from:s,to:e,value:t.value?.toString()}),c===void 0&&a<e&&(c=t),s=e}return r.bucket={identifier:i,defaultedToPredefinedBucket:i===void 0,assignedPercentage:a,shares:o,selectedPercentageId:c?.id},c?.value==null?void 0:c.value.toString()}explainConditionalRule(e,t,n,r,i){let a=!1;for(let t of e.conditions??[]){if(a){i.conditions.push({conditionId:t.id,outcome:`not-evaluated`});continue}let e=this.explainCondition(t,n,r);i.conditions.push(e),a=e.outcome!==`matched`}if(!a){if(e.target==`value`)return e.value==null?void 0:e.value.toString();if(e.target==`percentage`)return this.explainPercentage(e.percentages??[],t,n,i)}}explainCondition(e,t,n){if(e.kind===`segment`){let r=this.segmentEvaluator.explain(e,n,t);return{conditionId:e.id,kind:`segment`,outcome:r.matched?`matched`:`not-matched`,segmentId:e.segmentId,segmentFound:r.segmentFound,matchedGroupIndex:r.matchedGroupIndex}}let r=this.conditionEvaluator.explain(e,t);return{conditionId:e.id,kind:`attribute`,outcome:r.matched?`matched`:`not-matched`,resolvedValue:r.resolvedValue,resolvedType:r.resolvedType}}};const G=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},K=e=>e===`number`||e===`bigint`,q=new Set([`boolean`,`integer`,`float`]),fe=(e,t)=>{let n=e.value,r=G(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return _e(n,t,r,e.valueId);if(typeof t==`string`)return q.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=pe(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(K(typeof t)&&e.type===`integer`){let i=me(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(K(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=he(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`}},pe=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},me=e=>{let t=J(e);return t==null?void 0:Math.trunc(t)},he=e=>J(e),J=e=>{if(!e||!ge(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},ge=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},_e=(e,t,n,r)=>{if(typeof t==`string`)return{parsedValue:e,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`};try{let i=JSON.parse(e);return ve(i,t)?{parsedValue:i,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`}:{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`type-mismatch`}}catch{return{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`invalid-json`}}},ve=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},Y={off:-1,error:0,warn:1,info:2,debug:3},ye=()=>{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 be=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=ye()}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){Y[this.level]>=Y[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},xe=class{decorateMessage(e){return`[ConfigDirector:js-server-sdk] ${e}`}};const X=(e,t)=>new be(e??`warn`,t??new xe),Se=(e,t)=>new URL(e,t?.toString()),Ce=(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.`},Z=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,Q=e=>{if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch{return{value:e.value.toString(),type:`json`}}}let t=e.value?.toString();return t&&t.length<=500?{value:t}:e.valueId?{valueId:e.valueId}:{value:t}},$=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},we=e=>{if(!e)return!0;let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]??0)>0)return!1;return!0};var Te=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.sdkIdentity=e.sdkIdentity,this.logger=e.logger,this.metaContext=e.metaContext,this.url=new URL(`server/telemetry/v1`,e.baseUrl.toString())}async report({discreteEvents:e,aggregatedEvents:t,droppedEvents:n}){if(!this.executeRequests)return{success:!1,fatalError:!0};let r={serverSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},discreteEvents:e,aggregatedEvents:t,droppedEvents:n};if(this.isReportEmpty(r))return{success:!0,fatalError:!1};let i=await this.sendReport(r);return i.fatalError&&(this.executeRequests=!1),i}isReportEmpty(e){return $(e.discreteEvents)&&$(e.aggregatedEvents)&&we(e.droppedEvents)}async sendReport(e){try{let t=await S(5e3,this.url,{method:`POST`,body:JSON.stringify(e)},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:!1}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},Ee=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}))}},De=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}},Oe=class{constructor(e){this.aggregator=new Ee,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new De(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},ke=class extends Map{constructor(e,t){super(t),this._droppedCount=0,this.limit=e,this.enforceLimit()}set(e,t){return super.set(e,t),this.enforceLimit(),this}get droppedCount(){return this._droppedCount}clearAndReset(){this.clear(),this._droppedCount=0}enforceLimit(){for(;this.size>this.limit;){let e=this.keys().next().value;e!==void 0&&(this.delete(e),this._droppedCount+=1)}}},Ae=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(e){let t=await Promise.all(e.events.map(async e=>({...e,defaultValue:await Z(e.defaultValue,this.valueIdGenerator),evaluatedValue:await Z(e.evaluatedValue,this.valueIdGenerator)})));return{...e,events:t}}},je=class extends Oe{constructor(e){super(e),this.reporter=new Te(e),this.contexts=new ke(e.contextLimit??1e3),this.evaluationEventSnapshotPreprocessor=new Ae(e.valueIdGenerator)}evaluatedConfig(e){if(!this.collectEvents)return;e.context?.id&&!e.context.anonymous&&this.contexts.set(e.context.id,e.context);let t={...e.evaluation,contextId:e.context?.anonymous?void 0:e.context?.id};this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(t))}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:Q({value:e.defaultValue,type:e.type}),evaluatedValue:Q({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}snapshotContexts(){let e=Array.from(this.contexts.values()),t=this.contexts.droppedCount;return this.contexts.clearAndReset(),{contexts:e,droppedCount:t}}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot()),t=this.snapshotContexts();return await this.reporter?.report({context:this._context,discreteEvents:{capturedContexts:t.contexts},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount,capturedContexts:t.droppedCount}})}};const Me=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},Ne=Math.ceil(128/Math.log2(62)),Pe=async e=>Me((0,l.createHash)(`sha256`).update(e?.toString()??``).digest().subarray(0,16),Ne),Fe=new URL(`https://server-sdk-api.configdirector.com`),Ie=(e,t)=>(e.target?.rules??[]).some(e=>e.type===`conditional`&&(e.conditions??[]).some(e=>e.kind===`segment`&&t.has(e.segmentId)));var Le=class{constructor(e,t,n,r){this.handlersMap=new Map,this.eventEmitter=new c.default,this.ready=!1,this.logger=n?.logger??X(),this.timeout=n?.connection?.timeout??3e3,this.metaContext=n?.metadata??{},this.validateSdkKeyPresence(e),this.configEvaluator=new de(this.logger);let i=this.parseUrl(n?.connection?.url)??Fe;this.connectionMode=n?.connection?.mode??`streaming`,this.usageEventCollector=r?.telemetry??this.buildTelemetryCollector(e,t,i,n),this.transport=r?.transport??this.buildTransport(e,t,i,n),this.transport.on(`configBundleReceived`,e=>{this.readyResolve?.(!1);let t=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:(this.configSet.configs={...this.configSet.configs,...e.configs},this.configSet.segments={...this.configSet.segments,...e.segments});let n=this.findKeysUpdatedBy(e);this.eventEmitter.emit(`configsUpdated`,{keys:n,removedKeys:t}),this.updateWatchers([...n,...t]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server with ${n.length} key(s) and ${t.length} removed key(s)`,{keys:n,removedKeys:t})}),this.transport.on(`connectionError`,e=>{this.logger.error(`[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.`,e),this.eventEmitter.emit(`connectionError`,{error:e})}),this.registerHandler(`clientReady`,n?.hooks?.clientReady),this.registerHandler(`configEvaluated`,n?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,n?.hooks?.configsUpdated),this.registerHandler(`connectionError`,n?.hooks?.connectionError)}registerHandler(e,t){if(!t)return;let n=Array.isArray(t)?t:[t];for(let t of n)typeof t==`function`&&this.on(e,t)}async initialize(){try{this.ready=!1,this.readyPromise=new Promise(e=>{this.readyResolve=e}).then(e=>{e||(this.ready=!0,this.eventEmitter.emit(`clientReady`),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))}),this.usageEventCollector.start();let e=new Date().getTime();await this.transport.connect(this.timeout);let t=new Date().getTime()-e,n=this.timeout-t;if(n>0&&(await Promise.race([this.readyPromise,new Promise(e=>{this.readyTimer=setTimeout(()=>e(),n)})]),this.clearReadyTimer()),!this.ready){let e=this.connectionMode===`streaming`?`The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`:`Since the client was configured without streaming, configs may not update and always return the default value.`;this.logger.warn(`[ConfigDirectorClient] Timed out waiting for initialization after ${this.timeout}ms. ${e}`)}}catch(e){this.logger.error(`[ConfigDirectorClient] An error occurred during initialization: `,e)}}resolvePollingIntervalForMode(e){if(this.connectionMode!==`polling`)return;let t=Ce(e,{defaultSeconds:300,minimumSeconds:60});return t.warning&&this.logger.warn(`[ConfigDirectorClient] ${t.warning}`),t.seconds}buildTelemetryCollector(e,t,n,r){let i=r?.telemetry?.eventQueueLimit??5e3;return new je({sdkKey:e,sdkIdentity:t,metaContext:r?.metadata??{},logger:this.logger,baseUrl:n,flushIntervalDelay:r?.telemetry?.flushInterval??3e4,evaluationQueueLimit:Math.ceil(i*.7),contextLimit:Math.floor(i*.3),urlFactory:Se,valueIdGenerator:Pe})}buildTransport(e,t,n,r){return new(this.getTransportConstructor(this.connectionMode))({serverSdkKey:e,baseUrl:n,metaContext:{...r?.metadata,sdkName:t.sdkName,sdkVersion:t.sdkVersion},logger:this.logger,pollingInterval:this.resolvePollingIntervalForMode(r?.connection?.pollingInterval)})}getTransportConstructor(e){switch(e){case`polling`:return w;default:return te}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}findKeysUpdatedBy(e){let t=new Set(Object.keys(e.segments??{})),n=Object.entries(this.configSet?.configs??{}).filter(([,e])=>Ie(e,t)).map(([e])=>e);return[...new Set([...Object.keys(e.configs),...n])]}updateWatchers(e){e.forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){let t=this.configSet?.configs[e];this.handlersMap.get(e)?.forEach(n=>{let r=this.getValueFromConfigDefinition(e,t,n.defaultValue,n.context);n.handler(r)})}watch(e,t,n,r){this.validateDefaultValue(t);let i=this.handlersMap.get(e),a={handler:n,defaultValue:t,requestedType:typeof t,context:r};return i?i.push(a):this.handlersMap.set(e,[a]),()=>this.unwatch(e,n)}unwatch(e,t){let n=this.handlersMap.get(e);if(n)if(t){let e=n.findIndex(e=>e.handler==t);e>=0&&n?.splice(e,1)}else n.splice(0)}getValue(e,t,n){this.validateDefaultValue(t);let r=this.configSet?.configs[e];return this.getValueFromConfigDefinition(e,r,t,n)}getValueFromConfigDefinition(e,t,n,r){if(t){let i=this.configEvaluator.evaluate(t,{context:r,metadata:this.metaContext},this.configSet?.segments),a=fe(i,n);return this.usageEventCollector.evaluatedConfig({context:r,evaluation:{key:e,type:i.type,defaultValue:n,requestedType:a.requestedType,evaluatedValue:a.parsedValue,evaluatedValueId:a.parsedValueId,usedDefault:a.usedDefault,evaluationReason:a.reason}}),this.dispatchEvaluationEvent({key:e,value:a.parsedValue,valueId:a.parsedValueId??void 0,isDefaultValue:a.usedDefault,reason:a.reason,context:r}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${a.parsedValue}'`),a.parsedValue}else{this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`);let t=this.isReady?`config-state-missing`:`client-not-ready`;return this.usageEventCollector.evaluatedConfig({context:r,evaluation:{key:e,defaultValue:n,requestedType:G(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:r}),n}}dispatchEvaluationEvent(e){setTimeout(()=>this.eventEmitter.emit(`configEvaluated`,{evaluation:e}),0)}parseUrl(e){if(e)try{return new URL(e)}catch(t){throw new p(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateSdkKeyPresence(e){if(!e||e.trim().length==0)throw new p(`No server SDK key was provided, the client cannot be instantiated without a valid server SDK key`)}validateDefaultValue(e){if(e==null)throw new p(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new p(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}removeAllObservers(){this.logger.debug(`[ConfigDirectorClient] removeAllObservers() has been called, removing all observers`),this.eventEmitter.removeAllListeners(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}getAllConfigs(e){if(!this.configSet)return{};let t=Object.entries(this.configSet.configs),n=e?.configKeys?t.filter(([t])=>e.configKeys?.includes(t)):t;return Object.fromEntries(n.map(([t,n])=>[t,this.configEvaluator.evaluate(n,{context:e?.context,metadata:this.metaContext},this.configSet?.segments)]))}closeConnection(){this.logger.debug(`[ConfigDirectorClient] closeConnection() has been called, closing connection to server`),this.transport.close(),this.ready=!1}clearReadyTimer(){clearTimeout(this.readyTimer),this.readyTimer=void 0}dispose(){this.removeAllObservers(),this.closeConnection(),this.readyResolve?.(!0),this.clearReadyTimer(),this.usageEventCollector.close().catch(e=>{this.logger.warn(`[ConfigDirectorClient] Error flushing telemetry while disposing the client: `,e)})}};Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return Le}});
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import e,{EventEmitter as t}from"node:events";import{createHash as n,randomUUID as r}from"node:crypto";import{DateTime as i}from"luxon";import*as a from"semver";import{rapidhash as o}from"rapidhash-js";var s=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},c=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},ee=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},l=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},u=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},d=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},te=class{constructor(e){this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=e.onEvent??(()=>{}),this.onRetry=e.onRetry,this.onComment=e.onComment}parse(e){let t=e;this.isFirstChunk&&(this.isFirstChunk=!1,t.startsWith(``)?t=t.slice(1):t.startsWith(``)&&(t=t.slice(3)));let n=this.scanLines(this.bufferedInput+t);for(let e of n)this.dispatchLine(e)}finish(){this.bufferedInput=``}scanLines(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];i===`\r`||i===`
|
|
2
|
-
`?(t.push(e.slice(n,r)),i===`\r`&&e[r+1]===`
|
|
3
|
-
`&&r++,r++,n=r):r++}return this.bufferedInput=e.slice(n),t}dispatchLine(e){if(e.startsWith(`:`)){this.onComment?.(this.extractValue(e,1));return}if(e===``){this.emitEvent();return}this.applyField(this.parseField(e))}emitEvent(){let e=this.currentEvent.data.endsWith(`
|
|
4
|
-
`)?this.currentEvent.data.slice(0,-1):this.currentEvent.data;e!==``&&this.onEvent({...this.currentEvent,id:this.lastEventId,data:e}),this.currentEvent={data:``}}applyField(e){switch(e.field){case`event`:this.currentEvent.type=e.value;break;case`data`:this.currentEvent.data+=e.value+`
|
|
5
|
-
`;break;case`id`:e.value.includes(`\0`)||(this.lastEventId=e.value);break;case`retry`:/^\d+$/.test(e.value)&&this.onRetry?.(Number.parseInt(e.value,10));break;default:break}}parseField(e){let t=e.indexOf(`:`);return t===-1?{field:e,value:``}:{field:e.slice(0,t),value:this.extractValue(e,t+1)}}extractValue(e,t){return e[t]===` `?e.slice(t+1):e.slice(t)}};let f=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var p=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=f.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers={Accept:`text/event-stream`,...e.headers};let t=e.body;this.body=typeof t==`function`?t:()=>t,this.requestOptions={method:e.method??`GET`,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=e.fetch??((e,t)=>fetch(e,t)),this._onError=this.resolveCallback(e.onError,()=>{},`onError`),this._onConnect=this.resolveCallback(e.onConnect,()=>{},`onConnect`),this._onDisconnect=this.resolveCallback(e.onDisconnect,()=>{},`onDisconnect`),this._onMessage=this.resolveCallback(e.onMessage,()=>{},`onMessage`),this._onComment=this.resolveCallback(e.onComment,()=>{},`onComment`),this._shouldReconnect=this.resolveCallback(e.shouldReconnect,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`),this._calculateReconnectDelay=this.resolveCallback(e.calculateReconnectDelay,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`calculateReconnectDelay`)}set onError(e){this._onError=this.resolveCallback(e,()=>{},`onError`)}set onMessage(e){this._onMessage=this.resolveCallback(e,()=>{},`onMessage`)}set onComment(e){this._onComment=this.resolveCallback(e,()=>{},`onComment`)}set onConnect(e){this._onConnect=this.resolveCallback(e,()=>{},`onConnect`)}set onDisconnect(e){this._onDisconnect=this.resolveCallback(e,()=>{},`onDisconnect`)}set shouldReconnect(e){this._shouldReconnect=this.resolveCallback(e,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`)}set calculateReconnectDelay(e){this._calculateReconnectDelay=this.resolveCallback(e,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`shouldReconnect`)}get readyState(){return this._readyState}connect(){this._readyState===f.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=f.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=f.CONNECTING,this._fetch(this.url,{...this.requestOptions,body:this.body(),headers:this.buildRequestHeaders(),signal:this.abortController.signal,cache:`no-store`}).then(e=>this.handleFetchResponse(e)).catch(e=>{if(e.name===`AbortError`||this.abortController.signal.aborted){this.close();return}this._onError(e),this.scheduleReconnect({error:e})})}async handleFetchResponse(e){let{body:t,status:n}=e;if(n===204){this.disconnected();return}if(n>=400){this.scheduleReconnect({status:n});return}if(!t)throw new l(`The server response did not have a body`);this._readyState=f.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new te({onEvent:e=>{typeof e.id==`string`&&(this.lastEventId=e.id),this._onMessage(e)},onComment:e=>this._onComment(e),onRetry:e=>this.serverReconnectionTime=e});await this.readResponseStream(t,r),this.scheduleReconnect({status:n,error:new ee(`The server response stream was closed`)})}async readResponseStream(e,t){let n=e.getReader(),r=new TextDecoder,i=!1;for(;!i;){let e=await n.read();e.value&&t.parse(r.decode(e.value,{stream:!0})),i=e.done}t.finish()}disconnected(){clearTimeout(this.reconnectTimeout),this._readyState=f.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return{...this.headers,...e}}scheduleReconnect(e){if(this.abortController.signal.aborted)return;clearTimeout(this.reconnectTimeout),this.reconnectAttempt+=1;let t={attempt:this.reconnectAttempt,status:e.status,error:e.error,serverReconnectionTime:this.serverReconnectionTime};if(!this._shouldReconnect(t)){this.disconnected();return}this._readyState=f.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new d(`The calculated reconnect delay is out of range: ${n}. Defaulting to ${this.serverReconnectionTime}`)),n=this.serverReconnectionTime),this.reconnectTimeout=setTimeout(()=>this.initiateConnection(),n)}resolveCallback(e,t,n){if(e==null)return t;if(typeof e!=`function`)throw new u(`${n} must be a function`);return e}};const m=e=>new p(e),h=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}},g=9e4;var _=class{constructor(e){this.options=e,this.eventEmitter=new t,this.options=e,this.logger=e.logger,this.url=new URL(`server/sse/v1`,e.baseUrl),this.heartbeatUrl=new URL(`server/heartbeat/v1`,e.baseUrl)}async connect(e){this.eventSource&&this.close();let t=new Promise((e,t)=>{this.eventSource=m({url:this.url,method:`POST`,headers:{"Content-Type":`application/json`},body:()=>this.buildRequestBody(),onMessage:({data:e})=>{this.dispatchMessage(e)},onConnect:()=>{this.logger.debug(`[StreamingTransport] Connected`),e(this)},shouldReconnect:e=>{let n=!this.isStatusFatal(e.status);if(!n){this.stopHeartbeat();let n=this.prepareFatalError(e.status,e.error);this.eventEmitter.emit(`connectionError`,n),t(n)}return n},calculateReconnectDelay:e=>{let t=2**Math.min(e.attempt,9)*1e3,n=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?this.logger.info(n):this.logger.warn(n),t},onDisconnect:()=>{this.logger.debug(`[StreamingTransport] Disconnected`)}}),this.eventSource.connect()});this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),g);let n;try{return await Promise.race([t,new Promise(t=>{n=setTimeout(()=>t(this),e)})])}finally{clearTimeout(n)}}get sessionId(){return this._sessionId}sendHeartbeat(){!this.isConnected||!this._sessionId||h(g,this.heartbeatUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({serverSdkKey:this.options.serverSdkKey,sessionId:this._sessionId})},this.logger).then(e=>{e.ok||this.logger.debug(`[StreamingTransport] Heartbeat failed with status: ${e.status}`)}).catch(e=>{this.logger.debug(`[StreamingTransport] Heartbeat failed: `,e)})}buildRequestBody(){return this._sessionId=r(),JSON.stringify({metaContext:this.options.metaContext,serverSdkKey:this.options.serverSdkKey,sessionId:this._sessionId})}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configBundleReceived`,t)}catch(e){this.logger.error(`[StreamingTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,t){let n=e??0;return new s(`${`Connection failed with status: ${e??`unknown`}.`}${t?` Error: ${t}.`:``} This is an unrecoverable error, will not attempt to reconnect.`,n)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}get isConnected(){return this.eventSource?.readyState==`open`}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}clear(){this.eventEmitter.removeAllListeners()}stopHeartbeat(){clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0}close(){this.stopHeartbeat(),this.eventSource?.close()}dispose(){this.close(),this.clear()}},v=class{constructor(){this.fatalError=!1}clearPollingInterval(){clearInterval(this.pollingInterval)}schedulePollingInterval(e){clearInterval(this.pollingInterval),!(this.pollingIntervalSeconds<=0)&&(this.pollingInterval=setInterval(e,this.pollingIntervalSeconds*1e3))}async handleNonOkResponse(e){if(!e.ok)throw this.isStatusFatal(e.status)?(this.fatalError=!0,this.close(),this.prepareFatalResponseStatusError(e.status,await e.text())):new s(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new s(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new s(`Failed to parse the response from the server: ${e}`):new s(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){let n=e??0;return new s(`${`Connection failed with status: ${e??`unknown`}`}${(t?.trim()?.length??0)>0?` (${t})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,n)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}isFetchErrorFatal(e){return e?.name===`NotAllowedError`}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}},y=class extends v{constructor(e){super(),this.options=e,this.eventEmitter=new t,this._sessionId=r(),this.options=e,this.logger=e.logger,this.url=new URL(`server/polling/v1`,e.baseUrl),this.pollingIntervalSeconds=e.pollingInterval??300}async connect(e){this.clearPollingInterval();try{await this.fetchConfigs(e)}finally{this.fatalError||this.schedulePollingInterval(()=>{this.fetchConfigs(e).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})})}return this}get sessionId(){return this._sessionId}async fetchConfigs(e){if(this.fatalError){this.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let t=await h(e,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({metaContext:this.options.metaContext,serverSdkKey:this.options.serverSdkKey,lastUpdateTimestamp:this.lastUpdateTimestamp,sessionId:this._sessionId})},this.logger);if(await this.handleNonOkResponse(t),t.status===200){let e=JSON.parse(await t.text());this.lastUpdateTimestamp=e.timestamp,this.eventEmitter.emit(`configBundleReceived`,e)}}catch(e){try{this.handleFetchError(e)}catch(e){throw this.fatalError&&this.eventEmitter.emit(`connectionError`,e),e}}}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}clear(){this.eventEmitter.removeAllListeners()}};const b=/^(?:0|[1-9][0-9]*)$/,x=/~(?![01])/,S=Object.prototype.propertyIsEnumerable,C=e=>{if(!x.test(e))return e.replace(/~1/g,`/`).replace(/~0/g,`~`)},ne=(e,t)=>{if(Array.isArray(e))return b.test(t)&&S.call(e,t)?e[Number(t)]:void 0;if(typeof e==`object`&&e)return S.call(e,t)?e[t]:void 0},re=(e,t)=>{if(e===``)return t;if(!e.startsWith(`/`))return;let n=t;for(let t of e.slice(1).split(`/`)){let e=C(t);if(e===void 0||(n=ne(n,e),n===void 0))return}return n},ie=(e,t,n)=>{let r=n[0];switch(t.toLowerCase()){case`=`:case`equals`:return r!==void 0&&e===r;case`!=`:case`does not equal`:return r!==void 0&&e!==r;case`is one of`:return n.includes(e);case`is not one of`:return!n.includes(e);case`starts with any of`:return n.some(t=>e.startsWith(t));case`does not start with any of`:return!n.some(t=>e.startsWith(t));case`ends with any of`:return n.some(t=>e.endsWith(t));case`does not end with any of`:return!n.some(t=>e.endsWith(t));default:return!1}},ae=(e,t,n)=>{let r=t.toLowerCase(),i=w(e);if(i===void 0)return r===`!=`||r===`does not equal`;let a=n[0];if(a===void 0)return!1;let o=w(a);if(o===void 0)return!1;switch(r){case`=`:case`equals`:return i===o;case`!=`:case`does not equal`:return i!==o;case`<`:return i<o;case`<=`:return i<=o;case`>`:return i>o;case`>=`:return i>=o;default:return!1}},w=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(typeof e!=`string`||e.length===0||!oe(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0},oe=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},se=(e,t,n)=>{let r=n[0];if(r===void 0)return!1;let i=T(e),a=T(r);if(i===void 0||a===void 0)return!1;switch(t){case`is after`:return i>a;case`is before`:return i<a;default:return!1}},T=e=>{let t=i.fromISO(e,{zone:`utc`});return t.isValid?t.toMillis():void 0},E=(e,t,n)=>{let r=t.toLowerCase();if(e.trim().length===0)return r===`is not one of`;let i=a.coerce(e),o=n.map(e=>a.coerce(e)),s=o[0]??null;switch(r){case`=`:return D(i,s);case`<`:return O(i,s,a.lt);case`<=`:return O(i,s,a.lte);case`>`:return O(i,s,a.gt);case`>=`:return O(i,s,a.gte);case`is one of`:return o.some(e=>D(i,e));case`is not one of`:return!o.some(e=>D(i,e));default:return!1}},D=(e,t)=>e!==null&&t!==null&&a.eq(e,t),O=(e,t,n)=>e!==null&&t!==null&&n(e,t),k=Symbol(`absent`),A=Symbol(`unknown-attribute`),j=e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`,M=e=>e===k||e==null?``:j(e)?N(e):``,N=e=>typeof e==`string`?e:String(e),P=e=>e===k?void 0:e,F=e=>e===A?`unknown-attribute`:e===k?`absent`:j(e)?`scalar`:Array.isArray(e)?`array`:`object`,I=(e,t,n)=>{let r=t.toLowerCase();if(!Array.isArray(e))return r===`does not contain any of`;let i=e.filter(j).map(N);switch(r){case`contains any of`:return i.some(e=>n.includes(e));case`does not contain any of`:return!i.some(e=>n.includes(e));default:return!1}};var L=class{evaluate(e,t){return this.explain(e,t).matched}explain(e,t){let n=this.resolve(e,t),r=F(n),i=n===k||n===A?void 0:n;return n===A?{matched:!1,resolvedValue:i,resolvedType:r}:{matched:this.compare(e,n),resolvedValue:i,resolvedType:r}}compare(e,t){let n=e.targetValues??[];switch(e.targetType){case`text`:return ie(M(t),e.operator,n);case`number`:return ae(P(t),e.operator,n);case`datetime`:return se(M(t),e.operator,n);case`semver`:return E(M(t),e.operator,n);case`array`:return I(P(t),e.operator,n)}return!1}resolve(e,t){switch(e.attribute){case`identifier`:return R(t?.context?.id);case`name`:return R(t?.context?.name);case`appName`:return R(t?.metadata?.appName);case`appVersion`:return R(t?.metadata?.appVersion);case`traits`:return e.trait?R(re(e.trait,t?.context?.traits)):k;default:return A}}};const R=e=>e??k;var z=class{constructor(e){this.conditionEvaluator=e}explain(e,t,n){let r=t?.[e.segmentId];if(r===void 0||!B(r))return{matched:!1,segmentFound:!1,matchedGroupIndex:void 0};let i=this.matchingGroupIndex(r,n),a=i!==void 0;return{matched:this.operatorHolds(e,a),segmentFound:!0,matchedGroupIndex:i}}operatorHolds(e,t){switch(e.operator.toLowerCase()){case`in`:return t;case`not in`:return!t;default:return!1}}matchingGroupIndex(e,t){let n=(e.groups??[]).findIndex(e=>(e??[]).every(e=>this.conditionEvaluator.evaluate(e,t)));return n===-1?void 0:n}};const B=e=>(e.groups??[]).every(e=>(e??[]).every(e=>e.kind===void 0||e.kind===`attribute`)),V=e=>{let t=`${e.contextIdentifier}-${e.configId}`;return Number(o(t,{seed:15426857351n})%1000n)/10};var H=class{constructor(e){if(this.logger=e,this.conditionEvaluator=new L,this.segmentEvaluator=new z(this.conditionEvaluator),!e||!e.warn||!e.error||!e.info)throw TypeError(`The provided logger is not a valid 'ConfigDirectorLogger'`);this.logger=e}evaluate(e,t,n){return{id:e.id,key:e.key,type:e.type,value:this.explain(e,t,n).value}}explain(e,t,n){let r=[...e.target?.rules??[]].sort((e,t)=>(e.order??2**53-1)-(t.order??2**53-1)),i=[],a;for(let o of r){if(a){i.push({ruleId:o.id,outcome:`not-evaluated`,conditions:[],bucket:void 0});continue}let r=this.explainRule(o,e,t,n);i.push(r.explanation),r.value!==void 0&&(a={ruleId:o.id,value:r.value})}return{value:a?.value??e.target?.defaultValue,servedBy:a?{kind:`rule`,ruleId:a.ruleId}:{kind:`default`},rules:i}}explainRule(e,t,n,r){let i={ruleId:e.id,outcome:`not-matched`,conditions:[],bucket:void 0};try{let a;return e.type==`percentage`?a=this.explainPercentage(e.percentages??[],t,n,i):e.type==`conditional`&&(a=this.explainConditionalRule(e,t,n,r,i)),a!==void 0&&(i.outcome=`matched`),{explanation:i,value:a}}catch(n){return this.logger.warn(`There was an error while evaluating a targeting rule '${e?.id}' for '${t?.key}'. The rule will be disregarded.`,{error:n,configKey:t?.key,ruleId:e?.id}),{explanation:{ruleId:e.id,outcome:`errored`,conditions:[],bucket:void 0},value:void 0}}}explainPercentage(e,t,n,r){let i=n?.context?.id??void 0,a=i===void 0?0:V({configId:t.id,contextIdentifier:i}),o=[],s=0,c;for(let t of e){let e=s+t.percentage;o.push({percentageId:t.id,from:s,to:e,value:t.value?.toString()}),c===void 0&&a<e&&(c=t),s=e}return r.bucket={identifier:i,defaultedToPredefinedBucket:i===void 0,assignedPercentage:a,shares:o,selectedPercentageId:c?.id},c?.value==null?void 0:c.value.toString()}explainConditionalRule(e,t,n,r,i){let a=!1;for(let t of e.conditions??[]){if(a){i.conditions.push({conditionId:t.id,outcome:`not-evaluated`});continue}let e=this.explainCondition(t,n,r);i.conditions.push(e),a=e.outcome!==`matched`}if(!a){if(e.target==`value`)return e.value==null?void 0:e.value.toString();if(e.target==`percentage`)return this.explainPercentage(e.percentages??[],t,n,i)}}explainCondition(e,t,n){if(e.kind===`segment`){let r=this.segmentEvaluator.explain(e,n,t);return{conditionId:e.id,kind:`segment`,outcome:r.matched?`matched`:`not-matched`,segmentId:e.segmentId,segmentFound:r.segmentFound,matchedGroupIndex:r.matchedGroupIndex}}let r=this.conditionEvaluator.explain(e,t);return{conditionId:e.id,kind:`attribute`,outcome:r.matched?`matched`:`not-matched`,resolvedValue:r.resolvedValue,resolvedType:r.resolvedType}}};const U=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},W=e=>e===`number`||e===`bigint`,G=new Set([`boolean`,`integer`,`float`]),K=(e,t)=>{let n=e.value,r=U(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return fe(n,t,r,e.valueId);if(typeof t==`string`)return G.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=ce(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(W(typeof t)&&e.type===`integer`){let i=le(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(W(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=ue(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}},ce=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},le=e=>{let t=q(e);return t==null?void 0:Math.trunc(t)},ue=e=>q(e),q=e=>{if(!e||!de(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},de=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},fe=(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 pe(i,t)?{parsedValue:i,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`}:{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`type-mismatch`}}catch{return{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`invalid-json`}}},pe=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},J={off:-1,error:0,warn:1,info:2,debug:3},me=()=>{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 he=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=me()}debug(e,...t){this.log(console.debug,`debug`,e,...t)}info(e,...t){this.log(console.info,`info`,e,...t)}warn(e,...t){this.log(console.warn,`warn`,e,...t)}error(e,...t){this.log(console.error,`error`,e,...t)}log(e,t,n,...r){J[this.level]>=J[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},ge=class{decorateMessage(e){return`[ConfigDirector:js-server-sdk] ${e}`}};const Y=(e,t)=>new he(e??`warn`,t??new ge),_e=(e,t)=>new URL(e,t?.toString()),ve=(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.`},X=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,Z=e=>{if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch{return{value:e.value.toString(),type:`json`}}}let t=e.value?.toString();return t&&t.length<=500?{value:t}:e.valueId?{valueId:e.valueId}:{value:t}},Q=e=>{let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]?.length??0)>0)return!1;return!0},ye=e=>{if(!e)return!0;let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]??0)>0)return!1;return!0};var be=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.sdkIdentity=e.sdkIdentity,this.logger=e.logger,this.metaContext=e.metaContext,this.url=new URL(`server/telemetry/v1`,e.baseUrl.toString())}async report({discreteEvents:e,aggregatedEvents:t,droppedEvents:n}){if(!this.executeRequests)return{success:!1,fatalError:!0};let r={serverSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},discreteEvents:e,aggregatedEvents:t,droppedEvents:n};if(this.isReportEmpty(r))return{success:!0,fatalError:!1};let i=await this.sendReport(r);return i.fatalError&&(this.executeRequests=!1),i}isReportEmpty(e){return Q(e.discreteEvents)&&Q(e.aggregatedEvents)&&ye(e.droppedEvents)}async sendReport(e){try{let t=await h(5e3,this.url,{method:`POST`,body:JSON.stringify(e)},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:!1}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},xe=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}))}},Se=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||(this.startTime=new Date);let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},Ce=class{constructor(e){this.aggregator=new xe,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new Se(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},$=class extends Map{constructor(e,t){super(t),this._droppedCount=0,this.limit=e,this.enforceLimit()}set(e,t){return super.set(e,t),this.enforceLimit(),this}get droppedCount(){return this._droppedCount}clearAndReset(){this.clear(),this._droppedCount=0}enforceLimit(){for(;this.size>this.limit;){let e=this.keys().next().value;e!==void 0&&(this.delete(e),this._droppedCount+=1)}}},we=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(e){let t=await Promise.all(e.events.map(async e=>({...e,defaultValue:await X(e.defaultValue,this.valueIdGenerator),evaluatedValue:await X(e.evaluatedValue,this.valueIdGenerator)})));return{...e,events:t}}},Te=class extends Ce{constructor(e){super(e),this.reporter=new be(e),this.contexts=new $(e.contextLimit??1e3),this.evaluationEventSnapshotPreprocessor=new we(e.valueIdGenerator)}evaluatedConfig(e){if(!this.collectEvents)return;e.context?.id&&!e.context.anonymous&&this.contexts.set(e.context.id,e.context);let t={...e.evaluation,contextId:e.context?.anonymous?void 0:e.context?.id};this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(t))}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:Z({value:e.defaultValue,type:e.type}),evaluatedValue:Z({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}snapshotContexts(){let e=Array.from(this.contexts.values()),t=this.contexts.droppedCount;return this.contexts.clearAndReset(),{contexts:e,droppedCount:t}}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot()),t=this.snapshotContexts();return await this.reporter?.report({context:this._context,discreteEvents:{capturedContexts:t.contexts},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount,capturedContexts:t.droppedCount}})}};const Ee=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},De=Math.ceil(128/Math.log2(62)),Oe=async e=>Ee(n(`sha256`).update(e?.toString()??``).digest().subarray(0,16),De),ke=new URL(`https://server-sdk-api.configdirector.com`),Ae=(e,t)=>(e.target?.rules??[]).some(e=>e.type===`conditional`&&(e.conditions??[]).some(e=>e.kind===`segment`&&t.has(e.segmentId)));var je=class{constructor(t,n,r,i){this.handlersMap=new Map,this.eventEmitter=new e,this.ready=!1,this.logger=r?.logger??Y(),this.timeout=r?.connection?.timeout??3e3,this.metaContext=r?.metadata??{},this.validateSdkKeyPresence(t),this.configEvaluator=new H(this.logger);let a=this.parseUrl(r?.connection?.url)??ke;this.connectionMode=r?.connection?.mode??`streaming`,this.usageEventCollector=i?.telemetry??this.buildTelemetryCollector(t,n,a,r),this.transport=i?.transport??this.buildTransport(t,n,a,r),this.transport.on(`configBundleReceived`,e=>{this.readyResolve?.(!1);let t=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:(this.configSet.configs={...this.configSet.configs,...e.configs},this.configSet.segments={...this.configSet.segments,...e.segments});let n=this.findKeysUpdatedBy(e);this.eventEmitter.emit(`configsUpdated`,{keys:n,removedKeys:t}),this.updateWatchers([...n,...t]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server with ${n.length} key(s) and ${t.length} removed key(s)`,{keys:n,removedKeys:t})}),this.transport.on(`connectionError`,e=>{this.logger.error(`[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.`,e),this.eventEmitter.emit(`connectionError`,{error:e})}),this.registerHandler(`clientReady`,r?.hooks?.clientReady),this.registerHandler(`configEvaluated`,r?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,r?.hooks?.configsUpdated),this.registerHandler(`connectionError`,r?.hooks?.connectionError)}registerHandler(e,t){if(!t)return;let n=Array.isArray(t)?t:[t];for(let t of n)typeof t==`function`&&this.on(e,t)}async initialize(){try{this.ready=!1,this.readyPromise=new Promise(e=>{this.readyResolve=e}).then(e=>{e||(this.ready=!0,this.eventEmitter.emit(`clientReady`),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))}),this.usageEventCollector.start();let e=new Date().getTime();await this.transport.connect(this.timeout);let t=new Date().getTime()-e,n=this.timeout-t;if(n>0&&(await Promise.race([this.readyPromise,new Promise(e=>{this.readyTimer=setTimeout(()=>e(),n)})]),this.clearReadyTimer()),!this.ready){let e=this.connectionMode===`streaming`?`The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`:`Since the client was configured without streaming, configs may not update and always return the default value.`;this.logger.warn(`[ConfigDirectorClient] Timed out waiting for initialization after ${this.timeout}ms. ${e}`)}}catch(e){this.logger.error(`[ConfigDirectorClient] An error occurred during initialization: `,e)}}resolvePollingIntervalForMode(e){if(this.connectionMode!==`polling`)return;let t=ve(e,{defaultSeconds:300,minimumSeconds:60});return t.warning&&this.logger.warn(`[ConfigDirectorClient] ${t.warning}`),t.seconds}buildTelemetryCollector(e,t,n,r){let i=r?.telemetry?.eventQueueLimit??5e3;return new Te({sdkKey:e,sdkIdentity:t,metaContext:r?.metadata??{},logger:this.logger,baseUrl:n,flushIntervalDelay:r?.telemetry?.flushInterval??3e4,evaluationQueueLimit:Math.ceil(i*.7),contextLimit:Math.floor(i*.3),urlFactory:_e,valueIdGenerator:Oe})}buildTransport(e,t,n,r){return new(this.getTransportConstructor(this.connectionMode))({serverSdkKey:e,baseUrl:n,metaContext:{...r?.metadata,sdkName:t.sdkName,sdkVersion:t.sdkVersion},logger:this.logger,pollingInterval:this.resolvePollingIntervalForMode(r?.connection?.pollingInterval)})}getTransportConstructor(e){switch(e){case`polling`:return y;default:return _}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}findKeysUpdatedBy(e){let t=new Set(Object.keys(e.segments??{})),n=Object.entries(this.configSet?.configs??{}).filter(([,e])=>Ae(e,t)).map(([e])=>e);return[...new Set([...Object.keys(e.configs),...n])]}updateWatchers(e){e.forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){let t=this.configSet?.configs[e];this.handlersMap.get(e)?.forEach(n=>{let r=this.getValueFromConfigDefinition(e,t,n.defaultValue,n.context);n.handler(r)})}watch(e,t,n,r){this.validateDefaultValue(t);let i=this.handlersMap.get(e),a={handler:n,defaultValue:t,requestedType:typeof t,context:r};return i?i.push(a):this.handlersMap.set(e,[a]),()=>this.unwatch(e,n)}unwatch(e,t){let n=this.handlersMap.get(e);if(n)if(t){let e=n.findIndex(e=>e.handler==t);e>=0&&n?.splice(e,1)}else n.splice(0)}getValue(e,t,n){this.validateDefaultValue(t);let r=this.configSet?.configs[e];return this.getValueFromConfigDefinition(e,r,t,n)}getValueFromConfigDefinition(e,t,n,r){if(t){let i=this.configEvaluator.evaluate(t,{context:r,metadata:this.metaContext},this.configSet?.segments),a=K(i,n);return this.usageEventCollector.evaluatedConfig({context:r,evaluation:{key:e,type:i.type,defaultValue:n,requestedType:a.requestedType,evaluatedValue:a.parsedValue,evaluatedValueId:a.parsedValueId,usedDefault:a.usedDefault,evaluationReason:a.reason}}),this.dispatchEvaluationEvent({key:e,value:a.parsedValue,valueId:a.parsedValueId??void 0,isDefaultValue:a.usedDefault,reason:a.reason,context:r}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${a.parsedValue}'`),a.parsedValue}else{this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`);let t=this.isReady?`config-state-missing`:`client-not-ready`;return this.usageEventCollector.evaluatedConfig({context:r,evaluation:{key:e,defaultValue:n,requestedType:U(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:r}),n}}dispatchEvaluationEvent(e){setTimeout(()=>this.eventEmitter.emit(`configEvaluated`,{evaluation:e}),0)}parseUrl(e){if(e)try{return new URL(e)}catch(t){throw new c(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateSdkKeyPresence(e){if(!e||e.trim().length==0)throw new c(`No server SDK key was provided, the client cannot be instantiated without a valid server SDK key`)}validateDefaultValue(e){if(e==null)throw new c(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new c(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}removeAllObservers(){this.logger.debug(`[ConfigDirectorClient] removeAllObservers() has been called, removing all observers`),this.eventEmitter.removeAllListeners(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}getAllConfigs(e){if(!this.configSet)return{};let t=Object.entries(this.configSet.configs),n=e?.configKeys?t.filter(([t])=>e.configKeys?.includes(t)):t;return Object.fromEntries(n.map(([t,n])=>[t,this.configEvaluator.evaluate(n,{context:e?.context,metadata:this.metaContext},this.configSet?.segments)]))}closeConnection(){this.logger.debug(`[ConfigDirectorClient] closeConnection() has been called, closing connection to server`),this.transport.close(),this.ready=!1}clearReadyTimer(){clearTimeout(this.readyTimer),this.readyTimer=void 0}dispose(){this.removeAllObservers(),this.closeConnection(),this.readyResolve?.(!0),this.clearReadyTimer(),this.usageEventCollector.close().catch(e=>{this.logger.warn(`[ConfigDirectorClient] Error flushing telemetry while disposing the client: `,e)})}};export{c as i,Y as n,s as r,je as t};
|
|
6
|
-
//# sourceMappingURL=DefaultConfigDirectorClient-BH0eGfm_.mjs.map
|