@configdirector/server-sdk 1.12.0 → 1.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/DefaultConfigDirectorClient-BaDqRkjV.mjs +6 -0
- package/dist/DefaultConfigDirectorClient-BaDqRkjV.mjs.map +1 -0
- package/dist/DefaultConfigDirectorClient-fROPEpwq.cjs +5 -0
- package/dist/configdirector-server-testing.cjs +1 -1
- package/dist/configdirector-server-testing.d.cts +12 -3
- package/dist/configdirector-server-testing.d.cts.map +1 -1
- package/dist/configdirector-server-testing.d.mts +12 -3
- package/dist/configdirector-server-testing.d.mts.map +1 -1
- package/dist/configdirector-server-testing.mjs +1 -1
- package/dist/configdirector-server-testing.mjs.map +1 -1
- package/dist/configdirector-server.cjs +1 -1
- package/dist/configdirector-server.d.cts +2 -2
- package/dist/configdirector-server.d.mts +2 -2
- package/dist/configdirector-server.mjs +1 -1
- package/dist/{errors-D1cUkGGT.d.cts → errors-BKtOuEGy.d.cts} +76 -7
- package/dist/errors-BKtOuEGy.d.cts.map +1 -0
- package/dist/{errors-BdOy58jI.d.mts → errors-Dk_CsOtN.d.mts} +76 -7
- package/dist/errors-Dk_CsOtN.d.mts.map +1 -0
- package/package.json +1 -1
- package/dist/DefaultConfigDirectorClient-BORbruxY.cjs +0 -5
- package/dist/DefaultConfigDirectorClient-ZR0xPXNQ.mjs +0 -6
- package/dist/DefaultConfigDirectorClient-ZR0xPXNQ.mjs.map +0 -1
- package/dist/errors-BdOy58jI.d.mts.map +0 -1
- package/dist/errors-D1cUkGGT.d.cts.map +0 -1
|
@@ -11,6 +11,12 @@ type ConfigState = {
|
|
|
11
11
|
type: ConfigType;
|
|
12
12
|
value: string | undefined | null;
|
|
13
13
|
valueId?: string | undefined | null;
|
|
14
|
+
variation?: {
|
|
15
|
+
id: string;
|
|
16
|
+
name?: string | undefined | null;
|
|
17
|
+
} | undefined | null;
|
|
18
|
+
ruleId?: string | undefined | null;
|
|
19
|
+
shareId?: string | undefined | null;
|
|
14
20
|
};
|
|
15
21
|
type ConfigDirectorLoggingLevel = "debug" | "info" | "warn" | "error" | "off";
|
|
16
22
|
interface ConfigDirectorLogger {
|
|
@@ -24,24 +30,72 @@ interface ConfigDirectorLogMessageDecorator {
|
|
|
24
30
|
}
|
|
25
31
|
/**
|
|
26
32
|
* Why an evaluation returned the value it did. `found-match` returns a value from ConfigDirector,
|
|
27
|
-
* and `cached` a value kept on the device while a client SDK waits for live values.
|
|
33
|
+
* and `cached` a value kept on the device while a client SDK waits for live values.
|
|
34
|
+
* `rollout-skipped-no-identifier` returns the default targeting rule value: a server SDK skipped a
|
|
35
|
+
* percentage rollout because the context has no `id` to place it in a share. `value-missing`
|
|
28
36
|
* returns the in-code default value because the config has no value. Every other reason returns the
|
|
29
37
|
* in-code default value because of an error: the config does not exist (`config-state-missing`), no
|
|
30
38
|
* values have arrived yet (`client-not-ready`), or the value cannot be read as the type of the in-code
|
|
31
39
|
* default value.
|
|
32
40
|
*/
|
|
33
|
-
type EvaluationReason = "found-match" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
|
|
41
|
+
type EvaluationReason = "found-match" | "rollout-skipped-no-identifier" | "config-state-missing" | "client-not-ready" | "type-mismatch" | "value-missing" | "invalid-number" | "invalid-json" | "invalid-boolean" | "cached";
|
|
42
|
+
/**
|
|
43
|
+
* One of the values a config can serve, such as the control or a treatment of an experiment.
|
|
44
|
+
*/
|
|
45
|
+
type Variation = {
|
|
46
|
+
/** The ID ConfigDirector assigned to the variation, which stays the same when it is renamed. */id: string; /** The variation's name, when it has one. */
|
|
47
|
+
name?: string;
|
|
48
|
+
};
|
|
34
49
|
/**
|
|
35
50
|
* One evaluation of a config: the value it returned, why, and the context it was evaluated for.
|
|
36
51
|
*/
|
|
37
52
|
type ConfigEvaluation<T extends ConfigValueType = ConfigValueType> = {
|
|
38
53
|
/** The config key that was evaluated. */key: string; /** The value returned, which is the in-code default value when {@link isDefaultValue} is `true`. */
|
|
39
54
|
value: T; /** The ID ConfigDirector assigned to the value returned, when ConfigDirector sent one with it. */
|
|
40
|
-
valueId?: string;
|
|
55
|
+
valueId?: string;
|
|
56
|
+
/**
|
|
57
|
+
* The variation that was served. It is `undefined` when the config has no variations or the
|
|
58
|
+
* in-code default value is returned.
|
|
59
|
+
*/
|
|
60
|
+
variation?: Variation; /** Whether the evaluation returned the in-code default value. */
|
|
41
61
|
isDefaultValue: boolean; /** Why the evaluation returned this value. */
|
|
42
62
|
reason: EvaluationReason; /** The context the config was evaluated for, if any. */
|
|
43
63
|
context?: ConfigDirectorContext;
|
|
44
64
|
};
|
|
65
|
+
/**
|
|
66
|
+
* A value in the details of a tracked event: a string, a number, a boolean, or an array or object
|
|
67
|
+
* of such values.
|
|
68
|
+
*/
|
|
69
|
+
type TrackedEventDetailValue = string | number | boolean | TrackedEventDetailValue[] | {
|
|
70
|
+
[key: string]: TrackedEventDetailValue;
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* Details of a tracked event, such as the plan a customer chose. Details with more than 20
|
|
74
|
+
* top-level keys, or larger than 1 KB as JSON, are left out and the event is still reported.
|
|
75
|
+
*/
|
|
76
|
+
type TrackedEventDetails = {
|
|
77
|
+
[key: string]: TrackedEventDetailValue;
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* What a tracked event carries besides its name.
|
|
81
|
+
*/
|
|
82
|
+
type TrackOptions = {
|
|
83
|
+
/**
|
|
84
|
+
* A number the event measures, such as an amount of money, a count or a duration. A value that
|
|
85
|
+
* is not a finite number is left out and the event is still reported.
|
|
86
|
+
*/
|
|
87
|
+
value?: number; /** Details of the event. */
|
|
88
|
+
details?: TrackedEventDetails;
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* An event the code under test tracked, as a test client recorded it.
|
|
92
|
+
*/
|
|
93
|
+
type TrackedEvent = {
|
|
94
|
+
/** The name the event was tracked with. */name: string; /** The context the event was tracked for, if any. */
|
|
95
|
+
context?: ConfigDirectorContext; /** The value the event was tracked with, when it is a finite number. */
|
|
96
|
+
value?: number; /** The details the event was tracked with, when they are within the limits. */
|
|
97
|
+
details?: TrackedEventDetails;
|
|
98
|
+
};
|
|
45
99
|
/**
|
|
46
100
|
* The context to be sent to ConfigDirector: the user or other entity, such as a device or an
|
|
47
101
|
* organization, that configs are evaluated for. This context will be used for targeting rules
|
|
@@ -323,8 +377,8 @@ interface ConfigDirectorClient {
|
|
|
323
377
|
getValue<T extends ConfigValueType>(configKey: string, defaultValue: T, context?: ConfigDirectorContext): T;
|
|
324
378
|
/**
|
|
325
379
|
* Evaluates a config as {@link getValue} does and returns the evaluation: the value, the reason it
|
|
326
|
-
* was served
|
|
327
|
-
* telemetry.
|
|
380
|
+
* was served, its value ID and its variation. Like every read, it fires `configEvaluated` and is
|
|
381
|
+
* counted in telemetry.
|
|
328
382
|
*
|
|
329
383
|
* @returns The evaluation, whose `value` is what {@link getValue} returns
|
|
330
384
|
* @param configKey The config key to evaluate
|
|
@@ -369,6 +423,21 @@ interface ConfigDirectorClient {
|
|
|
369
423
|
context?: ConfigDirectorContext;
|
|
370
424
|
configKeys?: string[];
|
|
371
425
|
}): Record<string, ConfigState>;
|
|
426
|
+
/**
|
|
427
|
+
* Reports to ConfigDirector that something happened, such as a completed checkout, so it can be
|
|
428
|
+
* counted. The event is sent with the next telemetry batch. `track` never throws, and does nothing
|
|
429
|
+
* in `offline` mode.
|
|
430
|
+
*
|
|
431
|
+
* An event counts for an experiment only when it is tracked for a context with an `id`, the one
|
|
432
|
+
* the experiment's config was evaluated for. Without a context, or for a context without an
|
|
433
|
+
* `id`, the event is still reported.
|
|
434
|
+
*
|
|
435
|
+
* @param eventName The name of the event, 1 to 150 characters. An event with any other name is
|
|
436
|
+
* not reported and a warning is logged.
|
|
437
|
+
* @param context The context the event happened for (optional)
|
|
438
|
+
* @param options The event's {@link TrackOptions.value} and {@link TrackOptions.details} (optional)
|
|
439
|
+
*/
|
|
440
|
+
track(eventName: string, context?: ConfigDirectorContext, options?: TrackOptions): void;
|
|
372
441
|
on<T extends keyof ClientEvents>(eventName: T, handler: (args: ClientEvents[T]) => void): void;
|
|
373
442
|
off<T extends keyof ClientEvents>(eventName: T, handler?: (args: ClientEvents[T]) => void): void;
|
|
374
443
|
/**
|
|
@@ -395,5 +464,5 @@ declare class ConfigDirectorInitializationError extends Error {
|
|
|
395
464
|
constructor(message: string);
|
|
396
465
|
}
|
|
397
466
|
//#endregion
|
|
398
|
-
export { ConfigEvaluation as _, ConfigDirectorClientOptions as a, OfflineValues as c, NativeValues as d, ConfigDirectorContext as f, ConfigDirectorMetaContext as g, ConfigDirectorLoggingLevel as h, ConfigDirectorClient as i, NativeJsonValue as l, ConfigDirectorLogger as m, ConfigDirectorInitializationError as n, OfflineClientOptions as o, ConfigDirectorLogMessageDecorator as p, ConfigDirectorValidationError as r, OfflineValue as s, ConfigDirectorConnectionError as t, NativeValue as u, ConfigValueType as v, EvaluationReason as y };
|
|
399
|
-
//# sourceMappingURL=errors-
|
|
467
|
+
export { TrackedEventDetails as C, TrackedEventDetailValue as S, ConfigEvaluation as _, ConfigDirectorClientOptions as a, TrackOptions as b, OfflineValues as c, NativeValues as d, ConfigDirectorContext as f, ConfigDirectorMetaContext as g, ConfigDirectorLoggingLevel as h, ConfigDirectorClient as i, NativeJsonValue as l, ConfigDirectorLogger as m, ConfigDirectorInitializationError as n, OfflineClientOptions as o, ConfigDirectorLogMessageDecorator as p, ConfigDirectorValidationError as r, OfflineValue as s, ConfigDirectorConnectionError as t, NativeValue as u, ConfigValueType as v, Variation as w, TrackedEvent as x, EvaluationReason as y };
|
|
468
|
+
//# sourceMappingURL=errors-Dk_CsOtN.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-Dk_CsOtN.d.mts","names":[],"sources":["../../shared/src/types.ts","../../shared/src/native-values.ts","../src/types.ts","../../shared/src/errors.ts"],"mappings":";cAAa,cAAA;AAAA,KAUD,UAAA,WAAqB,cAAA;AAAA,KAErB,kBAAA;EAAA,CAAwB,GAAA;AAAA;AAAA,KAExB,eAAA,wCAAuD,kBAAA;AAAA,KAEvD,WAAA;EACV,EAAA;EACA,GAAA;EACA,IAAA,EAAM,UAAA;EACN,KAAA;EACA,OAAA;EACA,SAAA;IAAc,EAAA;IAAY,IAAA;EAAA;EAC1B,MAAA;EACA,OAAA;AAAA;AAAA,KAQU,0BAAA;AAAA,UAEK,oBAAA;EACf,KAAA,CAAM,OAAA,aAAoB,IAAA;EAE1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,KAAA,CAAM,OAAA,aAAoB,IAAA;AAAA;AAAA,UAGX,iCAAA;EACf,eAAA,CAAgB,OAAA;AAAA;;;;;;AAblB;;;;;KA0BY,gBAAA;;;;KAeA,SAAA;EAtCJ,gGAwCN,EAAA,UAtCA;EAwCA,IAAA;AAAA;;;;KAMU,gBAAA,WAA2B,eAAA,GAAkB,eAAA;EA1CjD,yCA4CN,GAAA,UA5C8B;EA8C9B,KAAA,EAAO,CAAA,EA3CQ;EA6Cf,OAAA;;;;AA/BF;EAoCE,SAAA,GAAY,SAAA;EAEZ,cAAA,WAtC0B;EAwC1B,MAAA,EAAQ,gBAAA,EAzBW;EA2BnB,OAAA,GAAU,qBAAA;AAAA;;AAjBZ;;;KAwBY,uBAAA,+BAIR,uBAAA;EAAA,CACG,GAAA,WAAc,uBAAA;AAAA;;;;;KAMT,mBAAA;EAAA,CAAyB,GAAA,WAAc,uBAAA;AAAA;;;;KAKvC,YAAA;EAlCV;;;;EAuCA,KAAA,WA9BQ;EAgCR,OAAA,GAAU,mBAAA;AAAA;;;AAvBZ;KA6BY,YAAA;6CAEV,IAAA,UA3BE;EA6BF,OAAA,GAAU,qBAAA,EA5BS;EA8BnB,KAAA,WA9B0C;EAgC1C,OAAA,GAAU,mBAAA;AAAA;;;;AArBZ;;KA6BY,qBAAA;EAtBmB;;;;;;AAM/B;;;;EA2BE,EAAA;EAvBA;;;;;;;AAYF;;;;EAwBE,IAAA;EAAA;;;;EAMA,IAAA;EAeS;;AAOX;;EAhBE,MAAA;IAAA,CAAY,GAAA;EAAA;EAqBF;;;;;;;EAZV,SAAA;AAAA;;;;;KAOU,yBAAA;EACV,UAAA;EACA,OAAA;AAAA;AAAA,KAGU,cAAA;;;KC9MA,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;;;;KE0BY,YAAA,GAAe,WAAA;AFxB3B;;;;AAAA,KE8BY,aAAA,GAAgB,YAAA;AF5B5B;;;AAAA,KEiCY,iBAAA;EFjCyE;AAErF;;;;;;;;;;;EE4CE,IAAA,GAAO,cAAA;EFtCmB;;;;;AAU5B;;;;;EEuCE,IAAA;EFrCmC;;;;;;;EE6CnC,MAAA,GAAS,aAAA;EF1CgB;;;;;;;EEkDzB,eAAA;EF9C8B;AAGhC;;;;;AAcA;;;EEuCE,OAAA;EFvC0B;AAe5B;;;;EE8BE,GAAA;AAAA;;;;KAMU,2BAAA;EFtBH;;;EE0BP,QAAA,GAAW,yBAAA;EFboB;;;EEiB/B,UAAA,GAAa,iBAAA;EFlC0C;;;;;;;;;;;;;EEgDvD,MAAA,GAAS,oBAAA;EFxBC;;;;;;;EEiCV,SAAA;IF5B0C;AAM5C;;;;;AAKA;;;IE2BI,eAAA;IFtBF;;;;;AAQF;;;IEwBI,aAAA;EAAA;EFpBF;;;;;;;AAYF;;;;;;;;EE0BE,KAAA,GAAQ,WAAA;AAAA;;;AF0BV;KEpBY,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;;;;;ADrMhE;;UC6MiB,oBAAA;ED7MU;;;;;AC6B3B;;;;;AAMA;EAsLE,UAAA,IAAc,OAAA;;;;AAjLhB;;;MAyLM,OAAA;EA5KJ;;;;;;;;;;EAwLA,QAAA,WAAmB,eAAA,EAAiB,SAAA,UAAmB,YAAA,EAAc,CAAA,EAAG,OAAA,GAAU,qBAAA,GAAwB,CAAA;EAvIrE;;;;;;;;;;EAmJrC,QAAA,WAAmB,eAAA,EACjB,SAAA,UACA,YAAA,EAAc,CAAA,EACd,OAAA,GAAU,qBAAA,GACT,gBAAA,CAAiB,CAAA;EA/IP;;;;;;;;;;AAmEf;;EA0FE,KAAA,WAAgB,eAAA,EACd,SAAA,UACA,YAAA,EAAc,CAAA,EACd,QAAA,EAAU,YAAA,CAAa,CAAA,GACvB,OAAA,GAAU,qBAAA;EA7FiB;;;;;;;AAG/B;EAqGE,OAAA,WAAkB,eAAA,EAAiB,SAAA,UAAmB,QAAA,GAAW,YAAA,CAAa,CAAA;;;;EAK9E,UAAA;EAzGkC;;;;;;;EAkHlC,aAAA,CAAc,OAAA;IACZ,OAAA,GAAU,qBAAA;IACV,UAAA;EAAA,IACE,MAAA,SAAe,WAAA;EA/GE;;;;;;;;;;;;;;EA+HrB,KAAA,CAAM,SAAA,UAAmB,OAAA,GAAU,qBAAA,EAAuB,OAAA,GAAU,YAAA;EAEpE,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;EAjI7B;;;;;;EAyIjD,OAAA;AAAA;;;cC9UW,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(`node:fs/promises`),d=require(`node:path`),ee=require(`luxon`),f=require(`semver`);f=s(f);let te=require(`rapidhash-js`);var p=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},m=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},h=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorInitializationError`,Object.setPrototypeOf(this,e.prototype)}},ne=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},re=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},ie=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},ae=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},oe=class{constructor(e){this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=e.onEvent??(()=>{}),this.onRetry=e.onRetry,this.onComment=e.onComment}parse(e){let t=e;this.isFirstChunk&&(this.isFirstChunk=!1,t.startsWith(``)?t=t.slice(1):t.startsWith(``)&&(t=t.slice(3)));let n=this.scanLines(this.bufferedInput+t);for(let e of n)this.dispatchLine(e)}finish(){this.bufferedInput=``}scanLines(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];i===`\r`||i===`
|
|
2
|
-
`?(t.push(e.slice(n,r)),i===`\r`&&e[r+1]===`
|
|
3
|
-
`&&r++,r++,n=r):r++}return this.bufferedInput=e.slice(n),t}dispatchLine(e){if(e.startsWith(`:`)){this.onComment?.(this.extractValue(e,1));return}if(e===``){this.emitEvent();return}this.applyField(this.parseField(e))}emitEvent(){let e=this.currentEvent.data.endsWith(`
|
|
4
|
-
`)?this.currentEvent.data.slice(0,-1):this.currentEvent.data;e!==``&&this.onEvent({...this.currentEvent,id:this.lastEventId,data:e}),this.currentEvent={data:``}}applyField(e){switch(e.field){case`event`:this.currentEvent.type=e.value;break;case`data`:this.currentEvent.data+=e.value+`
|
|
5
|
-
`;break;case`id`:e.value.includes(`\0`)||(this.lastEventId=e.value);break;case`retry`:/^\d+$/.test(e.value)&&this.onRetry?.(Number.parseInt(e.value,10));break;default:break}}parseField(e){let t=e.indexOf(`:`);return t===-1?{field:e,value:``}:{field:e.slice(0,t),value:this.extractValue(e,t+1)}}extractValue(e,t){return e[t]===` `?e.slice(t+1):e.slice(t)}};let g=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var se=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=g.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers={Accept:`text/event-stream`,...e.headers};let t=e.body;this.body=typeof t==`function`?t:()=>t,this.requestOptions={method:e.method??`GET`,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=e.fetch??((e,t)=>fetch(e,t)),this._onError=this.resolveCallback(e.onError,()=>{},`onError`),this._onConnect=this.resolveCallback(e.onConnect,()=>{},`onConnect`),this._onDisconnect=this.resolveCallback(e.onDisconnect,()=>{},`onDisconnect`),this._onMessage=this.resolveCallback(e.onMessage,()=>{},`onMessage`),this._onComment=this.resolveCallback(e.onComment,()=>{},`onComment`),this._shouldReconnect=this.resolveCallback(e.shouldReconnect,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`),this._calculateReconnectDelay=this.resolveCallback(e.calculateReconnectDelay,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`calculateReconnectDelay`)}set onError(e){this._onError=this.resolveCallback(e,()=>{},`onError`)}set onMessage(e){this._onMessage=this.resolveCallback(e,()=>{},`onMessage`)}set onComment(e){this._onComment=this.resolveCallback(e,()=>{},`onComment`)}set onConnect(e){this._onConnect=this.resolveCallback(e,()=>{},`onConnect`)}set onDisconnect(e){this._onDisconnect=this.resolveCallback(e,()=>{},`onDisconnect`)}set shouldReconnect(e){this._shouldReconnect=this.resolveCallback(e,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`)}set calculateReconnectDelay(e){this._calculateReconnectDelay=this.resolveCallback(e,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`shouldReconnect`)}get readyState(){return this._readyState}connect(){this._readyState===g.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=g.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=g.CONNECTING,this._fetch(this.url,{...this.requestOptions,body:this.body(),headers:this.buildRequestHeaders(),signal:this.abortController.signal,cache:`no-store`}).then(e=>this.handleFetchResponse(e)).catch(e=>{if(e.name===`AbortError`||this.abortController.signal.aborted){this.close();return}this._onError(e),this.scheduleReconnect({error:e})})}async handleFetchResponse(e){let{body:t,status:n}=e;if(n===204){this.disconnected();return}if(n>=400){this.scheduleReconnect({status:n});return}if(!t)throw new re(`The server response did not have a body`);this._readyState=g.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new oe({onEvent:e=>{typeof e.id==`string`&&(this.lastEventId=e.id),this._onMessage(e)},onComment:e=>this._onComment(e),onRetry:e=>this.serverReconnectionTime=e});await this.readResponseStream(t,r),this.scheduleReconnect({status:n,error:new ne(`The server response stream was closed`)})}async readResponseStream(e,t){let n=e.getReader(),r=new TextDecoder,i=!1;for(;!i;){let e=await n.read();e.value&&t.parse(r.decode(e.value,{stream:!0})),i=e.done}t.finish()}disconnected(){clearTimeout(this.reconnectTimeout),this._readyState=g.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return{...this.headers,...e}}scheduleReconnect(e){if(this.abortController.signal.aborted)return;clearTimeout(this.reconnectTimeout),this.reconnectAttempt+=1;let t={attempt:this.reconnectAttempt,status:e.status,error:e.error,serverReconnectionTime:this.serverReconnectionTime};if(!this._shouldReconnect(t)){this.disconnected();return}this._readyState=g.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new ae(`The calculated reconnect delay is out of range: ${n}. Defaulting to ${this.serverReconnectionTime}`)),n=this.serverReconnectionTime),this.reconnectTimeout=setTimeout(()=>this.initiateConnection(),n)}resolveCallback(e,t,n){if(e==null)return t;if(typeof e!=`function`)throw new ie(`${n} must be a function`);return e}};const ce=e=>new se(e),_=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}},v=9e4;var le=class{constructor(e){this.options=e,this.eventEmitter=new c.EventEmitter,this.options=e,this.logger=e.logger,this.url=new URL(`server/sse/v1`,e.baseUrl),this.heartbeatUrl=new URL(`server/heartbeat/v1`,e.baseUrl)}async connect(e){this.eventSource&&this.close();let t=new Promise((e,t)=>{this.eventSource=ce({url:this.url,method:`POST`,headers:{"Content-Type":`application/json`},body:()=>this.buildRequestBody(),onMessage:({data:e})=>{this.dispatchMessage(e)},onConnect:()=>{this.logger.debug(`[StreamingTransport] Connected`),e(this)},shouldReconnect:e=>{let n=!this.isStatusFatal(e.status);if(!n){this.stopHeartbeat();let n=this.prepareFatalError(e.status,e.error);this.eventEmitter.emit(`connectionError`,n),t(n)}return n},calculateReconnectDelay:e=>{let t=2**Math.min(e.attempt,9)*1e3,n=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?this.logger.info(n):this.logger.warn(n),t},onDisconnect:()=>{this.logger.debug(`[StreamingTransport] Disconnected`)}}),this.eventSource.connect()});this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),v);let n;try{return await Promise.race([t,new Promise(t=>{n=setTimeout(()=>t(this),e)})])}finally{clearTimeout(n)}}get sessionId(){return this._sessionId}sendHeartbeat(){!this.isConnected||!this._sessionId||_(v,this.heartbeatUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({serverSdkKey:this.options.serverSdkKey,sessionId:this._sessionId})},this.logger).then(e=>{e.ok||this.logger.debug(`[StreamingTransport] Heartbeat failed with status: ${e.status}`)}).catch(e=>{this.logger.debug(`[StreamingTransport] Heartbeat failed: `,e)})}buildRequestBody(){return this._sessionId=(0,l.randomUUID)(),JSON.stringify({metaContext:this.options.metaContext,serverSdkKey:this.options.serverSdkKey,sessionId:this._sessionId})}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configBundleReceived`,t)}catch(e){this.logger.error(`[StreamingTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,t){let n=e??0;return new p(`${`Connection failed with status: ${e??`unknown`}.`}${t?` Error: ${t}.`:``} This is an unrecoverable error, will not attempt to reconnect.`,n)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}get isConnected(){return this.eventSource?.readyState==`open`}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}clear(){this.eventEmitter.removeAllListeners()}stopHeartbeat(){clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0}close(){this.stopHeartbeat(),this.eventSource?.close()}dispose(){this.close(),this.clear()}},ue=class{constructor(){this.fatalError=!1}clearPollingInterval(){clearInterval(this.pollingInterval)}schedulePollingInterval(e){clearInterval(this.pollingInterval),!(this.pollingIntervalSeconds<=0)&&(this.pollingInterval=setInterval(e,this.pollingIntervalSeconds*1e3))}async handleNonOkResponse(e){if(!e.ok)throw this.isStatusFatal(e.status)?(this.fatalError=!0,this.close(),this.prepareFatalResponseStatusError(e.status,await e.text())):new p(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new p(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new p(`Failed to parse the response from the server: ${e}`):new p(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){let n=e??0;return new p(`${`Connection failed with status: ${e??`unknown`}`}${(t?.trim()?.length??0)>0?` (${t})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,n)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}isFetchErrorFatal(e){return e?.name===`NotAllowedError`}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}},de=class extends ue{constructor(e){super(),this.options=e,this.eventEmitter=new c.EventEmitter,this._sessionId=(0,l.randomUUID)(),this.options=e,this.logger=e.logger,this.url=new URL(`server/polling/v1`,e.baseUrl),this.pollingIntervalSeconds=e.pollingInterval??300}async connect(e){this.clearPollingInterval();try{await this.fetchConfigs(e)}finally{this.fatalError||this.schedulePollingInterval(()=>{this.fetchConfigs(e).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})})}return this}get sessionId(){return this._sessionId}async fetchConfigs(e){if(this.fatalError){this.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let t=await _(e,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({metaContext:this.options.metaContext,serverSdkKey:this.options.serverSdkKey,lastUpdateTimestamp:this.lastUpdateTimestamp,sessionId:this._sessionId})},this.logger);if(await this.handleNonOkResponse(t),t.status===200){let e=JSON.parse(await t.text());this.lastUpdateTimestamp=e.timestamp,this.eventEmitter.emit(`configBundleReceived`,e)}}catch(e){try{this.handleFetchError(e)}catch(e){throw this.fatalError&&this.eventEmitter.emit(`connectionError`,e),e}}}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}clear(){this.eventEmitter.removeAllListeners()}};const fe=(e,t)=>{if(e.trim().length==0)throw new m(`Invalid config key. The key of a value cannot be empty.`);return pe(e,t)},pe=(e,t)=>{switch(typeof t){case`boolean`:return{type:`boolean`,value:t?`true`:`false`};case`number`:return me(e,t);case`string`:return{type:`string`,value:t};case`object`:if(t!==null)return b(e,t,``),{type:`json`,value:JSON.stringify(t)}}throw new m(`Invalid value for '${e}': ${S(t)}. Use a boolean, a number, a string, a plain object, or an array.`)},me=(e,t)=>{if(!Number.isFinite(t))throw new m(`Invalid value for '${e}': ${S(t)} is not a finite number.`);if(Number.isInteger(t)){if(!Number.isSafeInteger(t))throw new m(`Invalid value for '${e}': ${t} is not a safe integer, so the SDK could not read it back exactly.`);return{type:`integer`,value:String(t)}}return{type:`float`,value:y(t)}},y=e=>{let t=String(e),n=t.indexOf(`e-`);if(n<0)return t;let r=t.startsWith(`-`)?`-`:``,[i=``,a=``]=t.slice(r.length,n).split(`.`),o=Number(t.slice(n+2))-i.length;return`${r}0.${`0`.repeat(o)}${i}${a}`},b=(e,t,n)=>{if(!(t===null||typeof t==`boolean`||typeof t==`string`)){if(typeof t==`number`){if(!Number.isFinite(t))throw x(e,n,`${S(t)} is not a finite number`);return}if(Array.isArray(t)){t.forEach((t,r)=>b(e,t,`${n}[${r}]`));return}if(he(t)){for(let[r,i]of Object.entries(t))b(e,i,n?`${n}.${r}`:r);return}throw x(e,n,`${S(t)} cannot be encoded as JSON`)}},x=(e,t,n)=>new m(`Invalid value for '${e}'${t?` at '${t}'`:``}: ${n}. JSON contents can hold booleans, finite numbers, strings, null, arrays, and plain objects.`),he=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},S=e=>e===null?`null`:typeof e==`function`?`a function`:typeof e==`object`?`a ${e.constructor?.name??`object`} instance`:typeof e==`symbol`?`a symbol`:String(e),C=(e,t,n)=>{let r=fe(t,n);return{id:e,key:t,type:r.type,variations:[{name:null,value:r.value}],target:{defaultValue:r.value,rules:[]}}},ge={environmentId:`offline`,projectId:`offline`};var _e=class{constructor(e){this.source=e,this.emitter=new c.default,this.connected=!1}async connect(){let e=await ve(this.source);return this.connected=!0,this.emitter.emit(`configBundleReceived`,{...ge,kind:`full`,configs:e}),this}get isConnected(){return this.connected}on(e,t){this.emitter.on(e,t)}off(e,t){t?this.emitter.off(e,t):this.emitter.removeAllListeners(e)}close(){this.connected=!1}dispose(){this.close(),this.emitter.removeAllListeners()}};const ve=async e=>{switch(e.kind){case`in-code-defaults`:return{};case`values`:return w(e.values,`The offline values`);case`file`:return w(await ye(e.path),`The offline values file '${e.path}'`);case`rejected`:throw new h(e.message)}},ye=async e=>{let t;try{t=await(0,u.readFile)((0,d.resolve)(e),`utf8`)}catch(t){throw new h(`The offline values file '${e}' could not be read: ${T(t)}`)}let n;try{n=JSON.parse(t)}catch(t){throw new h(`The offline values file '${e}' is not valid JSON: ${T(t)}`)}if(!be(n))throw new h(`The offline values file '${e}' must hold a JSON object with one value per config key, but holds ${xe(n)}.`);return n},w=(e,t)=>{try{return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,C(`offline:${e}`,e,t)]))}catch(e){throw e instanceof m?new h(`${t} could not be loaded. ${e.message}`):e}},be=e=>typeof e==`object`&&!!e&&!Array.isArray(e),xe=e=>e===null?`null`:Array.isArray(e)?`an array`:`a ${typeof e}`,T=e=>e instanceof Error?e.message:String(e),Se=new URL(`https://server-sdk-api.configdirector.com`),Ce=(e,t)=>{if(t?.mode===`offline`)return{kind:`stay-offline`,source:D(t)};let n=t?.mode??`streaming`;if(!e||e.trim().length==0)throw new m(`No server SDK key was provided, the client cannot be instantiated without a valid server SDK key`);return t?.file!==void 0||t?.values!==void 0?{kind:`stay-offline`,source:{kind:`rejected`,message:`The connection options 'file' and 'values' apply only when the connection mode is 'offline', but the mode is '${n}'.`}}:{kind:`connect`,mode:n,serverSdkKey:e,baseUrl:E(t?.url)}},E=e=>{if(!e)return Se;try{return new URL(e)}catch(t){throw new m(`Invalid base URL '${e}'. Parsing failed: ${t}`)}},D=e=>e.file!==void 0&&e.values!==void 0?{kind:`rejected`,message:`An offline connection takes either 'file' or 'values', not both.`}:e.file===void 0?e.values===void 0?{kind:`in-code-defaults`}:{kind:`values`,values:e.values}:{kind:`file`,path:e.file},O=/^(?:0|[1-9][0-9]*)$/,k=/~(?![01])/,A=Object.prototype.propertyIsEnumerable,we=e=>{if(!k.test(e))return e.replace(/~1/g,`/`).replace(/~0/g,`~`)},Te=(e,t)=>{if(Array.isArray(e))return O.test(t)&&A.call(e,t)?e[Number(t)]:void 0;if(typeof e==`object`&&e)return A.call(e,t)?e[t]:void 0},Ee=(e,t)=>{if(e===``)return t;if(!e.startsWith(`/`))return;let n=t;for(let t of e.slice(1).split(`/`)){let e=we(t);if(e===void 0||(n=Te(n,e),n===void 0))return}return n},De=(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}},Oe=(e,t,n)=>{let r=t.toLowerCase(),i=j(e);if(i===void 0)return r===`!=`||r===`does not equal`;let a=n[0];if(a===void 0)return!1;let o=j(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}},j=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(typeof e!=`string`||e.length===0||!ke(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0},ke=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},Ae=(e,t,n)=>{let r=n[0];if(r===void 0)return!1;let i=M(e),a=M(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}},M=e=>{let t=ee.DateTime.fromISO(e,{zone:`utc`});return t.isValid?t.toMillis():void 0},je=(e,t,n)=>{let r=t.toLowerCase();if(e.trim().length===0)return r===`is not one of`;let i=f.coerce(e),a=n.map(e=>f.coerce(e)),o=a[0]??null;switch(r){case`=`:return N(i,o);case`<`:return P(i,o,f.lt);case`<=`:return P(i,o,f.lte);case`>`:return P(i,o,f.gt);case`>=`:return P(i,o,f.gte);case`is one of`:return a.some(e=>N(i,e));case`is not one of`:return!a.some(e=>N(i,e));default:return!1}},N=(e,t)=>e!==null&&t!==null&&f.eq(e,t),P=(e,t,n)=>e!==null&&t!==null&&n(e,t),F=Symbol(`absent`),I=Symbol(`unknown-attribute`),L=e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`,R=e=>e===F||e==null?``:L(e)?z(e):``,z=e=>typeof e==`string`?e:String(e),B=e=>e===F?void 0:e,Me=e=>e===I?`unknown-attribute`:e===F?`absent`:L(e)?`scalar`:Array.isArray(e)?`array`:`object`,Ne=(e,t,n)=>{let r=t.toLowerCase();if(!Array.isArray(e))return r===`does not contain any of`;let i=e.filter(L).map(z);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}},V=e=>e?.context?.kind??`user`;var Pe=class{evaluate(e,t){return this.explain(e,t).matched}explain(e,t){let n=this.resolve(e,t),r=Me(n),i=n===F||n===I?void 0:n;return n===I?{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 De(R(t),e.operator,n);case`number`:return Oe(B(t),e.operator,n);case`datetime`:return Ae(R(t),e.operator,n);case`semver`:return je(R(t),e.operator,n);case`array`:return Ne(B(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`kind`:return V(t);case`appName`:return H(t?.metadata?.appName);case`appVersion`:return H(t?.metadata?.appVersion);case`traits`:return e.trait?H(Ee(e.trait,t?.context?.traits)):F;default:return I}}};const H=e=>e??F;var Fe=class{constructor(e){this.conditionEvaluator=e}explain(e,t,n){let r=t?.[e.segmentId];if(r===void 0||!Ie(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 Ie=e=>(e.groups??[]).every(e=>(e??[]).every(e=>e.kind===void 0||e.kind===`attribute`)),U=({configId:e,contextIdentifier:t,contextKind:n})=>{let r=n===`user`?`${t}-${e}`:`${t}-${e}:${n}`;return Number((0,te.rapidhash)(r,{seed:15426857351n})%1000n)/10};var Le=class{constructor(e){if(this.logger=e,this.conditionEvaluator=new Pe,this.segmentEvaluator=new Fe(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){let r=this.explain(e,t,n);return{id:e.id,key:e.key,type:e.type,value:r.value,valueId:r.valueId}}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.served!==void 0&&(a={ruleId:o.id,...r.served})}return a?{value:a.value,valueId:a.valueId,servedBy:{kind:`rule`,ruleId:a.ruleId},rules:i}:{value:e.target?.defaultValue,valueId:e.target?.defaultValueId,servedBy:{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,served: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},served:void 0}}}explainPercentage(e,t,n,r){let i=n?.context?.id??void 0,a=i===void 0?0:U({configId:t.id,contextIdentifier:i,contextKind:V(n)}),o=[],s=0,c;for(let t of e){let e=s+t.percentage;o.push({percentageId:t.id,from:s,to:e,value:t.value?.toString()}),c===void 0&&a<e&&(c=t),s=e}return r.bucket={identifier:i,defaultedToPredefinedBucket:i===void 0,assignedPercentage:a,shares:o,selectedPercentageId:c?.id},c?.value==null?void 0:{value:c.value.toString(),valueId:c.valueId}}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:{value:e.value.toString(),valueId:e.valueId};if(e.target==`percentage`)return this.explainPercentage(e.percentages??[],t,n,i)}}explainCondition(e,t,n){if(e.kind===`segment`){let r=this.segmentEvaluator.explain(e,n,t);return{conditionId:e.id,kind:`segment`,outcome:r.matched?`matched`:`not-matched`,segmentId:e.segmentId,segmentFound:r.segmentFound,matchedGroupIndex:r.matchedGroupIndex}}let r=this.conditionEvaluator.explain(e,t);return{conditionId:e.id,kind:`attribute`,outcome:r.matched?`matched`:`not-matched`,resolvedValue:r.resolvedValue,resolvedType:r.resolvedType}}};const W=e=>{let t=typeof e;if(t===`object`)try{return e.constructor?.name??t}catch{return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch{return t}return t},G=e=>e===`number`||e===`bigint`,Re=new Set([`boolean`,`integer`,`float`]),ze=(e,t)=>{let n=e.value,r=W(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return We(n,t,r,e.valueId);if(typeof t==`string`)return Re.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=Be(n),a=typeof i==`boolean`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-boolean`}}if(G(typeof t)&&e.type===`integer`){let i=Ve(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}if(G(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=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`}},Be=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},Ve=e=>{let t=K(e);return t==null?void 0:Math.trunc(t)},He=e=>K(e),K=e=>{if(!e||!Ue(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},Ue=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},We=(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 Ge(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`}}},Ge=(e,t)=>e===null?!1:q(e)===q(t),q=e=>{if(Array.isArray(e))return`array`;let t=typeof e;return t===`bigint`?`number`:t},J={off:-1,error:0,warn:1,info:2,debug:3},Ke=()=>{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 qe=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=Ke()}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)}},Je=class{decorateMessage(e){return`[ConfigDirector:js-server-sdk] ${e}`}};const Y=(e,t)=>new qe(e??`warn`,t??new Je),Ye=(e,t)=>new URL(e,t?.toString()),Xe=(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.`},Ze=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,Qe=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!Ze(t))return!1;return!0},$e=e=>e==null||typeof e==`string`&&Qe(e),et=e=>{if(typeof e==`string`)return e;try{return String(e)}catch{return Object.prototype.toString.call(e)}},tt=(e,t)=>{let n=``,r=0;for(let i of e){if(r===t)break;n+=i,r+=1}return n},nt=e=>{let t=e?.kind;return $e(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:tt(et(t),128)}};var rt=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}};const 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},it=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 at=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)&&it(e.droppedEvents)}async sendReport(e){try{let t=await _(5e3,this.url,{method:`POST`,body:JSON.stringify(e)},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{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}},ot=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}))}},st=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}},ct=class{constructor(e){this.aggregator=new ot,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new st(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()}},lt=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)}}},ut=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}}},dt=class extends ct{constructor(e){super(e),this.invalidContextSubmissions=new rt,this.reporter=new at(e),this.contexts=new lt(e.contextLimit??1e3),this.evaluationEventSnapshotPreprocessor=new ut(e.valueIdGenerator)}evaluatedConfig(e){if(!this.collectEvents)return;let t=e.context??void 0,n=V({context:t}),r=t?.anonymous?void 0:t?.id;r&&this.contexts.set(`${n}:${r}`,{...t,kind:n});let i={...e.evaluation,contextId:r,contextKind:r===void 0?void 0:n};this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(i))}recordInvalidContext(e){return this.invalidContextSubmissions.record(e)}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:Z({value:e.defaultValue,type:e.type}),evaluatedValue:Z({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}snapshotContexts(){let e=Array.from(this.contexts.values()),t=this.contexts.droppedCount;return this.contexts.clearAndReset(),{contexts:e,droppedCount:t}}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot()),t=this.snapshotContexts();return await this.reporter?.report({context:this._context,discreteEvents:{capturedContexts:t.contexts},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e),invalidContext:this.invalidContextSubmissions.takeSnapshot()},droppedEvents:{evaluatedConfig:e.droppedCount,capturedContexts:t.droppedCount}})}};const $={start:()=>{},evaluatedConfig:()=>{},recordInvalidContext:()=>`new-kind-sample`,close:async()=>{}},ft=(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`)},pt=Math.ceil(128/Math.log2(62)),mt=async e=>ft((0,l.createHash)(`sha256`).update(e?.toString()??``).digest().subarray(0,16),pt),ht={streaming:`The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`,polling:`Since the client was configured without streaming, configs may not update and always return the default value.`},gt={"new-kind-sample":(e,t)=>e.error(`[ConfigDirectorClient] Ignored a context with the invalid kind '${t}' and evaluated as if no context was supplied. A context kind has 1 to 64 characters, using only lowercase letters, digits, '-' and '_'.`),"known-kind-sample":()=>{},"first-beyond-sample-limit":e=>e.error(`[ConfigDirectorClient] Ignored a context with another invalid kind and evaluated as if no context was supplied. 20 different invalid kinds were logged recently, so further invalid kinds are not logged individually.`),"beyond-sample-limit":()=>{}},_t=(e,t)=>(e.target?.rules??[]).some(e=>e.type===`conditional`&&(e.conditions??[]).some(e=>e.kind===`segment`&&t.has(e.segmentId)));var vt=class e{static from(t,n,r){return typeof t==`object`?new e(void 0,n,t):new e(t,n,r)}constructor(e,t,n,r){this.handlersMap=new Map,this.eventEmitter=new c.default,this.ready=!1,this.logger=n?.logger??Y(),this.timeout=n?.connection?.timeout??3e3,this.metaContext=n?.metadata??{},this.connectionPlan=Ce(e,n?.connection),this.configEvaluator=new Le(this.logger),this.usageEventCollector=r?.telemetry??this.buildTelemetryClient(t,n),this.transport=r?.transport??this.buildTransport(t,n),this.transport.on(`configBundleReceived`,e=>{this.readyResolve?.(!1);let t=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:(this.configSet.configs={...this.configSet.configs,...e.configs},this.configSet.segments={...this.configSet.segments,...e.segments});let n=this.findKeysUpdatedBy(e);this.eventEmitter.emit(`configsUpdated`,{keys:n,removedKeys:t}),this.updateWatchers([...n,...t]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server with ${n.length} key(s) and ${t.length} removed key(s)`,{keys:n,removedKeys:t})}),this.transport.on(`connectionError`,e=>{this.logger.error(`[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.`,e),this.eventEmitter.emit(`connectionError`,{error:e})}),this.registerHandler(`clientReady`,n?.hooks?.clientReady),this.registerHandler(`configEvaluated`,n?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,n?.hooks?.configsUpdated),this.registerHandler(`connectionError`,n?.hooks?.connectionError)}registerHandler(e,t){if(!t)return;let n=Array.isArray(t)?t:[t];for(let t of n)typeof t==`function`&&this.on(e,t)}async initialize(){try{this.ready=!1,this.readyPromise=new Promise(e=>{this.readyResolve=e}).then(e=>{e||(this.ready=!0,this.eventEmitter.emit(`clientReady`),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))}),this.usageEventCollector.start();let e=new Date().getTime();await this.transport.connect(this.timeout);let t=new Date().getTime()-e,n=this.timeout-t;n>0&&(await Promise.race([this.readyPromise,new Promise(e=>{this.readyTimer=setTimeout(()=>e(),n)})]),this.clearReadyTimer()),this.ready||this.logger.warn(`[ConfigDirectorClient] Timed out waiting for initialization after ${this.timeout}ms. ${this.timeoutWarningDetails()}`)}catch(e){if(e instanceof h)throw e;this.logger.error(`[ConfigDirectorClient] An error occurred during initialization: `,e)}}timeoutWarningDetails(){switch(this.connectionPlan.kind){case`connect`:return ht[this.connectionPlan.mode];case`stay-offline`:return`The offline values were not delivered, so configs return the default value.`}}pollingIntervalFor(e,t){if(e!==`polling`)return;let n=Xe(t,{defaultSeconds:300,minimumSeconds:60});return n.warning&&this.logger.warn(`[ConfigDirectorClient] ${n.warning}`),n.seconds}buildTelemetryClient(e,t){let n=this.connectionPlan;switch(n.kind){case`stay-offline`:return $;case`connect`:{let r=t?.telemetry?.eventQueueLimit??5e3;return new dt({sdkKey:n.serverSdkKey,sdkIdentity:e,metaContext:t?.metadata??{},logger:this.logger,baseUrl:n.baseUrl,flushIntervalDelay:t?.telemetry?.flushInterval??3e4,evaluationQueueLimit:Math.ceil(r*.7),contextLimit:Math.floor(r*.3),urlFactory:Ye,valueIdGenerator:mt})}}}buildTransport(e,t){let n=this.connectionPlan;switch(n.kind){case`stay-offline`:return new _e(n.source);case`connect`:return new(this.getTransportConstructor(n.mode))({serverSdkKey:n.serverSdkKey,baseUrl:n.baseUrl,metaContext:{...t?.metadata,sdkName:e.sdkName,sdkVersion:e.sdkVersion},logger:this.logger,pollingInterval:this.pollingIntervalFor(n.mode,t?.connection?.pollingInterval)})}}getTransportConstructor(e){switch(e){case`polling`:return de;case`streaming`:return le}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}findKeysUpdatedBy(e){let t=new Set(Object.keys(e.segments??{})),n=Object.entries(this.configSet?.configs??{}).filter(([,e])=>_t(e,t)).map(([e])=>e);return[...new Set([...Object.keys(e.configs),...n])]}updateWatchers(e){e.forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){let t=this.configSet?.configs[e];this.handlersMap.get(e)?.forEach(n=>{let r=this.evaluationOf(e,t,n.defaultValue,n.context).value;n.handler(r)})}watch(e,t,n,r){this.validateDefaultValue(t);let i=this.handlersMap.get(e),a={handler:n,defaultValue:t,requestedType:typeof t,context:r};return i?i.push(a):this.handlersMap.set(e,[a]),()=>this.unwatch(e,n)}unwatch(e,t){let n=this.handlersMap.get(e);if(n)if(t){let e=n.findIndex(e=>e.handler==t);e>=0&&n?.splice(e,1)}else n.splice(0)}getValue(e,t,n){return this.evaluate(e,t,n).value}evaluate(e,t,n){this.validateDefaultValue(t);let r=this.configSet?.configs[e];return this.evaluationOf(e,r,t,n)}evaluationOf(e,t,n,r){let i=this.contextToEvaluate(r);if(t){let r=this.configEvaluator.evaluate(t,{context:i,metadata:this.metaContext},this.configSet?.segments),a=ze(r,n);this.usageEventCollector.evaluatedConfig({context:i,evaluation:{key:e,type:r.type,defaultValue:n,requestedType:a.requestedType,evaluatedValue:a.parsedValue,evaluatedValueId:a.parsedValueId,usedDefault:a.usedDefault,evaluationReason:a.reason}});let o={key:e,value:a.parsedValue,valueId:a.parsedValueId??void 0,isDefaultValue:a.usedDefault,reason:a.reason,context:i};return this.dispatchEvaluationEvent(o),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${a.parsedValue}'`),o}else{this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`);let t=this.isReady?`config-state-missing`:`client-not-ready`;this.usageEventCollector.evaluatedConfig({context:i,evaluation:{key:e,defaultValue:n,requestedType:W(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}});let r={key:e,value:n,isDefaultValue:!0,reason:t,context:i};return this.dispatchEvaluationEvent(r),r}}contextToEvaluate(e){let t=nt(e);switch(t.outcome){case`admitted`:return t.context;case`ignored`:gt[this.usageEventCollector.recordInvalidContext(t.kindSample)](this.logger,t.kindSample);return}}dispatchEvaluationEvent(e){setTimeout(()=>this.eventEmitter.emit(`configEvaluated`,{evaluation:e}),0)}validateDefaultValue(e){if(e==null)throw new m(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new m(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}removeAllObservers(){this.logger.debug(`[ConfigDirectorClient] removeAllObservers() has been called, removing all observers`),this.eventEmitter.removeAllListeners(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}getAllConfigs(e){let t=this.contextToEvaluate(e?.context);if(!this.configSet)return{};let n=Object.entries(this.configSet.configs),r=e?.configKeys?n.filter(([t])=>e.configKeys?.includes(t)):n;return Object.fromEntries(r.map(([e,n])=>[e,this.configEvaluator.evaluate(n,{context:t,metadata:this.metaContext},this.configSet?.segments)]))}closeConnection(){this.logger.debug(`[ConfigDirectorClient] closeConnection() has been called, closing connection to server`),this.transport.close(),this.ready=!1}clearReadyTimer(){clearTimeout(this.readyTimer),this.readyTimer=void 0}dispose(){this.removeAllObservers(),this.closeConnection(),this.readyResolve?.(!0),this.clearReadyTimer(),this.usageEventCollector.close().catch(e=>{this.logger.warn(`[ConfigDirectorClient] Error flushing telemetry while disposing the client: `,e)})}};Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return vt}});
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import e,{EventEmitter as t}from"node:events";import{createHash as n,randomUUID as r}from"node:crypto";import{readFile as i}from"node:fs/promises";import{resolve as a}from"node:path";import{DateTime as o}from"luxon";import*as s from"semver";import{rapidhash as c}from"rapidhash-js";var l=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},u=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},d=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorInitializationError`,Object.setPrototypeOf(this,e.prototype)}},ee=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},te=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},ne=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},re=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},ie=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 te(`The server response did not have a body`);this._readyState=f.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new ie({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 re(`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 ne(`${n} must be a function`);return e}};const ae=e=>new p(e),m=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}},h=9e4;var oe=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=ae({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(),h);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||m(h,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 l(`${`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()}},se=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 l(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new l(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new l(`Failed to parse the response from the server: ${e}`):new l(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){let n=e??0;return new l(`${`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()}},ce=class extends se{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 m(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 le=(e,t)=>{if(e.trim().length==0)throw new u(`Invalid config key. The key of a value cannot be empty.`);return ue(e,t)},ue=(e,t)=>{switch(typeof t){case`boolean`:return{type:`boolean`,value:t?`true`:`false`};case`number`:return g(e,t);case`string`:return{type:`string`,value:t};case`object`:if(t!==null)return v(e,t,``),{type:`json`,value:JSON.stringify(t)}}throw new u(`Invalid value for '${e}': ${b(t)}. Use a boolean, a number, a string, a plain object, or an array.`)},g=(e,t)=>{if(!Number.isFinite(t))throw new u(`Invalid value for '${e}': ${b(t)} is not a finite number.`);if(Number.isInteger(t)){if(!Number.isSafeInteger(t))throw new u(`Invalid value for '${e}': ${t} is not a safe integer, so the SDK could not read it back exactly.`);return{type:`integer`,value:String(t)}}return{type:`float`,value:_(t)}},_=e=>{let t=String(e),n=t.indexOf(`e-`);if(n<0)return t;let r=t.startsWith(`-`)?`-`:``,[i=``,a=``]=t.slice(r.length,n).split(`.`),o=Number(t.slice(n+2))-i.length;return`${r}0.${`0`.repeat(o)}${i}${a}`},v=(e,t,n)=>{if(!(t===null||typeof t==`boolean`||typeof t==`string`)){if(typeof t==`number`){if(!Number.isFinite(t))throw y(e,n,`${b(t)} is not a finite number`);return}if(Array.isArray(t)){t.forEach((t,r)=>v(e,t,`${n}[${r}]`));return}if(de(t)){for(let[r,i]of Object.entries(t))v(e,i,n?`${n}.${r}`:r);return}throw y(e,n,`${b(t)} cannot be encoded as JSON`)}},y=(e,t,n)=>new u(`Invalid value for '${e}'${t?` at '${t}'`:``}: ${n}. JSON contents can hold booleans, finite numbers, strings, null, arrays, and plain objects.`),de=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},b=e=>e===null?`null`:typeof e==`function`?`a function`:typeof e==`object`?`a ${e.constructor?.name??`object`} instance`:typeof e==`symbol`?`a symbol`:String(e),x=(e,t,n)=>{let r=le(t,n);return{id:e,key:t,type:r.type,variations:[{name:null,value:r.value}],target:{defaultValue:r.value,rules:[]}}},fe={environmentId:`offline`,projectId:`offline`};var pe=class{constructor(t){this.source=t,this.emitter=new e,this.connected=!1}async connect(){let e=await me(this.source);return this.connected=!0,this.emitter.emit(`configBundleReceived`,{...fe,kind:`full`,configs:e}),this}get isConnected(){return this.connected}on(e,t){this.emitter.on(e,t)}off(e,t){t?this.emitter.off(e,t):this.emitter.removeAllListeners(e)}close(){this.connected=!1}dispose(){this.close(),this.emitter.removeAllListeners()}};const me=async e=>{switch(e.kind){case`in-code-defaults`:return{};case`values`:return S(e.values,`The offline values`);case`file`:return S(await he(e.path),`The offline values file '${e.path}'`);case`rejected`:throw new d(e.message)}},he=async e=>{let t;try{t=await i(a(e),`utf8`)}catch(t){throw new d(`The offline values file '${e}' could not be read: ${C(t)}`)}let n;try{n=JSON.parse(t)}catch(t){throw new d(`The offline values file '${e}' is not valid JSON: ${C(t)}`)}if(!ge(n))throw new d(`The offline values file '${e}' must hold a JSON object with one value per config key, but holds ${_e(n)}.`);return n},S=(e,t)=>{try{return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,x(`offline:${e}`,e,t)]))}catch(e){throw e instanceof u?new d(`${t} could not be loaded. ${e.message}`):e}},ge=e=>typeof e==`object`&&!!e&&!Array.isArray(e),_e=e=>e===null?`null`:Array.isArray(e)?`an array`:`a ${typeof e}`,C=e=>e instanceof Error?e.message:String(e),ve=new URL(`https://server-sdk-api.configdirector.com`),ye=(e,t)=>{if(t?.mode===`offline`)return{kind:`stay-offline`,source:xe(t)};let n=t?.mode??`streaming`;if(!e||e.trim().length==0)throw new u(`No server SDK key was provided, the client cannot be instantiated without a valid server SDK key`);return t?.file!==void 0||t?.values!==void 0?{kind:`stay-offline`,source:{kind:`rejected`,message:`The connection options 'file' and 'values' apply only when the connection mode is 'offline', but the mode is '${n}'.`}}:{kind:`connect`,mode:n,serverSdkKey:e,baseUrl:be(t?.url)}},be=e=>{if(!e)return ve;try{return new URL(e)}catch(t){throw new u(`Invalid base URL '${e}'. Parsing failed: ${t}`)}},xe=e=>e.file!==void 0&&e.values!==void 0?{kind:`rejected`,message:`An offline connection takes either 'file' or 'values', not both.`}:e.file===void 0?e.values===void 0?{kind:`in-code-defaults`}:{kind:`values`,values:e.values}:{kind:`file`,path:e.file},w=/^(?:0|[1-9][0-9]*)$/,T=/~(?![01])/,E=Object.prototype.propertyIsEnumerable,D=e=>{if(!T.test(e))return e.replace(/~1/g,`/`).replace(/~0/g,`~`)},O=(e,t)=>{if(Array.isArray(e))return w.test(t)&&E.call(e,t)?e[Number(t)]:void 0;if(typeof e==`object`&&e)return E.call(e,t)?e[t]:void 0},k=(e,t)=>{if(e===``)return t;if(!e.startsWith(`/`))return;let n=t;for(let t of e.slice(1).split(`/`)){let e=D(t);if(e===void 0||(n=O(n,e),n===void 0))return}return n},A=(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}},j=(e,t,n)=>{let r=t.toLowerCase(),i=M(e);if(i===void 0)return r===`!=`||r===`does not equal`;let a=n[0];if(a===void 0)return!1;let o=M(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}},M=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(typeof e!=`string`||e.length===0||!Se(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0},Se=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},Ce=(e,t,n)=>{let r=n[0];if(r===void 0)return!1;let i=N(e),a=N(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}},N=e=>{let t=o.fromISO(e,{zone:`utc`});return t.isValid?t.toMillis():void 0},we=(e,t,n)=>{let r=t.toLowerCase();if(e.trim().length===0)return r===`is not one of`;let i=s.coerce(e),a=n.map(e=>s.coerce(e)),o=a[0]??null;switch(r){case`=`:return P(i,o);case`<`:return F(i,o,s.lt);case`<=`:return F(i,o,s.lte);case`>`:return F(i,o,s.gt);case`>=`:return F(i,o,s.gte);case`is one of`:return a.some(e=>P(i,e));case`is not one of`:return!a.some(e=>P(i,e));default:return!1}},P=(e,t)=>e!==null&&t!==null&&s.eq(e,t),F=(e,t,n)=>e!==null&&t!==null&&n(e,t),I=Symbol(`absent`),L=Symbol(`unknown-attribute`),R=e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`,z=e=>e===I||e==null?``:R(e)?B(e):``,B=e=>typeof e==`string`?e:String(e),V=e=>e===I?void 0:e,Te=e=>e===L?`unknown-attribute`:e===I?`absent`:R(e)?`scalar`:Array.isArray(e)?`array`:`object`,Ee=(e,t,n)=>{let r=t.toLowerCase();if(!Array.isArray(e))return r===`does not contain any of`;let i=e.filter(R).map(B);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}},H=e=>e?.context?.kind??`user`;var De=class{evaluate(e,t){return this.explain(e,t).matched}explain(e,t){let n=this.resolve(e,t),r=Te(n),i=n===I||n===L?void 0:n;return n===L?{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 A(z(t),e.operator,n);case`number`:return j(V(t),e.operator,n);case`datetime`:return Ce(z(t),e.operator,n);case`semver`:return we(z(t),e.operator,n);case`array`:return Ee(V(t),e.operator,n)}return!1}resolve(e,t){switch(e.attribute){case`identifier`:return U(t?.context?.id);case`name`:return U(t?.context?.name);case`kind`:return H(t);case`appName`:return U(t?.metadata?.appName);case`appVersion`:return U(t?.metadata?.appVersion);case`traits`:return e.trait?U(k(e.trait,t?.context?.traits)):I;default:return L}}};const U=e=>e??I;var Oe=class{constructor(e){this.conditionEvaluator=e}explain(e,t,n){let r=t?.[e.segmentId];if(r===void 0||!ke(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 ke=e=>(e.groups??[]).every(e=>(e??[]).every(e=>e.kind===void 0||e.kind===`attribute`)),Ae=({configId:e,contextIdentifier:t,contextKind:n})=>{let r=n===`user`?`${t}-${e}`:`${t}-${e}:${n}`;return Number(c(r,{seed:15426857351n})%1000n)/10};var je=class{constructor(e){if(this.logger=e,this.conditionEvaluator=new De,this.segmentEvaluator=new Oe(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){let r=this.explain(e,t,n);return{id:e.id,key:e.key,type:e.type,value:r.value,valueId:r.valueId}}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.served!==void 0&&(a={ruleId:o.id,...r.served})}return a?{value:a.value,valueId:a.valueId,servedBy:{kind:`rule`,ruleId:a.ruleId},rules:i}:{value:e.target?.defaultValue,valueId:e.target?.defaultValueId,servedBy:{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,served: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},served:void 0}}}explainPercentage(e,t,n,r){let i=n?.context?.id??void 0,a=i===void 0?0:Ae({configId:t.id,contextIdentifier:i,contextKind:H(n)}),o=[],s=0,c;for(let t of e){let e=s+t.percentage;o.push({percentageId:t.id,from:s,to:e,value:t.value?.toString()}),c===void 0&&a<e&&(c=t),s=e}return r.bucket={identifier:i,defaultedToPredefinedBucket:i===void 0,assignedPercentage:a,shares:o,selectedPercentageId:c?.id},c?.value==null?void 0:{value:c.value.toString(),valueId:c.valueId}}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:{value:e.value.toString(),valueId:e.valueId};if(e.target==`percentage`)return this.explainPercentage(e.percentages??[],t,n,i)}}explainCondition(e,t,n){if(e.kind===`segment`){let r=this.segmentEvaluator.explain(e,n,t);return{conditionId:e.id,kind:`segment`,outcome:r.matched?`matched`:`not-matched`,segmentId:e.segmentId,segmentFound:r.segmentFound,matchedGroupIndex:r.matchedGroupIndex}}let r=this.conditionEvaluator.explain(e,t);return{conditionId:e.id,kind:`attribute`,outcome:r.matched?`matched`:`not-matched`,resolvedValue:r.resolvedValue,resolvedType:r.resolvedType}}};const W=e=>{let t=typeof e;if(t===`object`)try{return e.constructor?.name??t}catch{return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch{return t}return t},G=e=>e===`number`||e===`bigint`,Me=new Set([`boolean`,`integer`,`float`]),Ne=(e,t)=>{let n=e.value,r=W(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return Re(n,t,r,e.valueId);if(typeof t==`string`)return Me.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(G(typeof t)&&e.type===`integer`){let i=Fe(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}if(G(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=Ie(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`},Fe=e=>{let t=K(e);return t==null?void 0:Math.trunc(t)},Ie=e=>K(e),K=e=>{if(!e||!Le(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},Le=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},Re=(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 ze(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`}}},ze=(e,t)=>e===null?!1:q(e)===q(t),q=e=>{if(Array.isArray(e))return`array`;let t=typeof e;return t===`bigint`?`number`:t},J={off:-1,error:0,warn:1,info:2,debug:3},Be=()=>{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 Ve=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=Be()}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)}},He=class{decorateMessage(e){return`[ConfigDirector:js-server-sdk] ${e}`}};const Y=(e,t)=>new Ve(e??`warn`,t??new He),Ue=(e,t)=>new URL(e,t?.toString()),We=(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.`},Ge=e=>e>=`a`&&e<=`z`||e>=`0`&&e<=`9`||e===`-`||e===`_`,Ke=e=>{if(e.length<1||e.length>64)return!1;for(let t of e)if(!Ge(t))return!1;return!0},qe=e=>e==null||typeof e==`string`&&Ke(e),Je=e=>{if(typeof e==`string`)return e;try{return String(e)}catch{return Object.prototype.toString.call(e)}},Ye=(e,t)=>{let n=``,r=0;for(let i of e){if(r===t)break;n+=i,r+=1}return n},Xe=e=>{let t=e?.kind;return qe(t)?{outcome:`admitted`,context:e}:{outcome:`ignored`,kindSample:Ye(Je(t),128)}};var Ze=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??(this.startTime=new Date),this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}};const X=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,Z=e=>{if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch{return{value:e.value.toString(),type:`json`}}}let t=e.value?.toString();return t&&t.length<=500?{value:t}:e.valueId?{valueId:e.valueId}:{value:t}},Q=e=>{let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]?.length??0)>0)return!1;return!0},Qe=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 $e=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)&&Qe(e.droppedEvents)}async sendReport(e){try{let t=await m(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}},et=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}))}},tt=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}},nt=class{constructor(e){this.aggregator=new et,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new tt(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()}},rt=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)}}},it=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}}},at=class extends nt{constructor(e){super(e),this.invalidContextSubmissions=new Ze,this.reporter=new $e(e),this.contexts=new rt(e.contextLimit??1e3),this.evaluationEventSnapshotPreprocessor=new it(e.valueIdGenerator)}evaluatedConfig(e){if(!this.collectEvents)return;let t=e.context??void 0,n=H({context:t}),r=t?.anonymous?void 0:t?.id;r&&this.contexts.set(`${n}:${r}`,{...t,kind:n});let i={...e.evaluation,contextId:r,contextKind:r===void 0?void 0:n};this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(i))}recordInvalidContext(e){return this.invalidContextSubmissions.record(e)}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:Z({value:e.defaultValue,type:e.type}),evaluatedValue:Z({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}snapshotContexts(){let e=Array.from(this.contexts.values()),t=this.contexts.droppedCount;return this.contexts.clearAndReset(),{contexts:e,droppedCount:t}}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot()),t=this.snapshotContexts();return await this.reporter?.report({context:this._context,discreteEvents:{capturedContexts:t.contexts},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e),invalidContext:this.invalidContextSubmissions.takeSnapshot()},droppedEvents:{evaluatedConfig:e.droppedCount,capturedContexts:t.droppedCount}})}};const $={start:()=>{},evaluatedConfig:()=>{},recordInvalidContext:()=>`new-kind-sample`,close:async()=>{}},ot=(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`)},st=Math.ceil(128/Math.log2(62)),ct=async e=>ot(n(`sha256`).update(e?.toString()??``).digest().subarray(0,16),st),lt={streaming:`The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`,polling:`Since the client was configured without streaming, configs may not update and always return the default value.`},ut={"new-kind-sample":(e,t)=>e.error(`[ConfigDirectorClient] Ignored a context with the invalid kind '${t}' and evaluated as if no context was supplied. A context kind has 1 to 64 characters, using only lowercase letters, digits, '-' and '_'.`),"known-kind-sample":()=>{},"first-beyond-sample-limit":e=>e.error(`[ConfigDirectorClient] Ignored a context with another invalid kind and evaluated as if no context was supplied. 20 different invalid kinds were logged recently, so further invalid kinds are not logged individually.`),"beyond-sample-limit":()=>{}},dt=(e,t)=>(e.target?.rules??[]).some(e=>e.type===`conditional`&&(e.conditions??[]).some(e=>e.kind===`segment`&&t.has(e.segmentId)));var ft=class t{static from(e,n,r){return typeof e==`object`?new t(void 0,n,e):new t(e,n,r)}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.connectionPlan=ye(t,r?.connection),this.configEvaluator=new je(this.logger),this.usageEventCollector=i?.telemetry??this.buildTelemetryClient(n,r),this.transport=i?.transport??this.buildTransport(n,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;n>0&&(await Promise.race([this.readyPromise,new Promise(e=>{this.readyTimer=setTimeout(()=>e(),n)})]),this.clearReadyTimer()),this.ready||this.logger.warn(`[ConfigDirectorClient] Timed out waiting for initialization after ${this.timeout}ms. ${this.timeoutWarningDetails()}`)}catch(e){if(e instanceof d)throw e;this.logger.error(`[ConfigDirectorClient] An error occurred during initialization: `,e)}}timeoutWarningDetails(){switch(this.connectionPlan.kind){case`connect`:return lt[this.connectionPlan.mode];case`stay-offline`:return`The offline values were not delivered, so configs return the default value.`}}pollingIntervalFor(e,t){if(e!==`polling`)return;let n=We(t,{defaultSeconds:300,minimumSeconds:60});return n.warning&&this.logger.warn(`[ConfigDirectorClient] ${n.warning}`),n.seconds}buildTelemetryClient(e,t){let n=this.connectionPlan;switch(n.kind){case`stay-offline`:return $;case`connect`:{let r=t?.telemetry?.eventQueueLimit??5e3;return new at({sdkKey:n.serverSdkKey,sdkIdentity:e,metaContext:t?.metadata??{},logger:this.logger,baseUrl:n.baseUrl,flushIntervalDelay:t?.telemetry?.flushInterval??3e4,evaluationQueueLimit:Math.ceil(r*.7),contextLimit:Math.floor(r*.3),urlFactory:Ue,valueIdGenerator:ct})}}}buildTransport(e,t){let n=this.connectionPlan;switch(n.kind){case`stay-offline`:return new pe(n.source);case`connect`:return new(this.getTransportConstructor(n.mode))({serverSdkKey:n.serverSdkKey,baseUrl:n.baseUrl,metaContext:{...t?.metadata,sdkName:e.sdkName,sdkVersion:e.sdkVersion},logger:this.logger,pollingInterval:this.pollingIntervalFor(n.mode,t?.connection?.pollingInterval)})}}getTransportConstructor(e){switch(e){case`polling`:return ce;case`streaming`:return oe}}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])=>dt(e,t)).map(([e])=>e);return[...new Set([...Object.keys(e.configs),...n])]}updateWatchers(e){e.forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){let t=this.configSet?.configs[e];this.handlersMap.get(e)?.forEach(n=>{let r=this.evaluationOf(e,t,n.defaultValue,n.context).value;n.handler(r)})}watch(e,t,n,r){this.validateDefaultValue(t);let i=this.handlersMap.get(e),a={handler:n,defaultValue:t,requestedType:typeof t,context:r};return i?i.push(a):this.handlersMap.set(e,[a]),()=>this.unwatch(e,n)}unwatch(e,t){let n=this.handlersMap.get(e);if(n)if(t){let e=n.findIndex(e=>e.handler==t);e>=0&&n?.splice(e,1)}else n.splice(0)}getValue(e,t,n){return this.evaluate(e,t,n).value}evaluate(e,t,n){this.validateDefaultValue(t);let r=this.configSet?.configs[e];return this.evaluationOf(e,r,t,n)}evaluationOf(e,t,n,r){let i=this.contextToEvaluate(r);if(t){let r=this.configEvaluator.evaluate(t,{context:i,metadata:this.metaContext},this.configSet?.segments),a=Ne(r,n);this.usageEventCollector.evaluatedConfig({context:i,evaluation:{key:e,type:r.type,defaultValue:n,requestedType:a.requestedType,evaluatedValue:a.parsedValue,evaluatedValueId:a.parsedValueId,usedDefault:a.usedDefault,evaluationReason:a.reason}});let o={key:e,value:a.parsedValue,valueId:a.parsedValueId??void 0,isDefaultValue:a.usedDefault,reason:a.reason,context:i};return this.dispatchEvaluationEvent(o),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${a.parsedValue}'`),o}else{this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`);let t=this.isReady?`config-state-missing`:`client-not-ready`;this.usageEventCollector.evaluatedConfig({context:i,evaluation:{key:e,defaultValue:n,requestedType:W(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}});let r={key:e,value:n,isDefaultValue:!0,reason:t,context:i};return this.dispatchEvaluationEvent(r),r}}contextToEvaluate(e){let t=Xe(e);switch(t.outcome){case`admitted`:return t.context;case`ignored`:ut[this.usageEventCollector.recordInvalidContext(t.kindSample)](this.logger,t.kindSample);return}}dispatchEvaluationEvent(e){setTimeout(()=>this.eventEmitter.emit(`configEvaluated`,{evaluation:e}),0)}validateDefaultValue(e){if(e==null)throw new u(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new u(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}removeAllObservers(){this.logger.debug(`[ConfigDirectorClient] removeAllObservers() has been called, removing all observers`),this.eventEmitter.removeAllListeners(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}getAllConfigs(e){let t=this.contextToEvaluate(e?.context);if(!this.configSet)return{};let n=Object.entries(this.configSet.configs),r=e?.configKeys?n.filter(([t])=>e.configKeys?.includes(t)):n;return Object.fromEntries(r.map(([e,n])=>[e,this.configEvaluator.evaluate(n,{context:t,metadata:this.metaContext},this.configSet?.segments)]))}closeConnection(){this.logger.debug(`[ConfigDirectorClient] closeConnection() has been called, closing connection to server`),this.transport.close(),this.ready=!1}clearReadyTimer(){clearTimeout(this.readyTimer),this.readyTimer=void 0}dispose(){this.removeAllObservers(),this.closeConnection(),this.readyResolve?.(!0),this.clearReadyTimer(),this.usageEventCollector.close().catch(e=>{this.logger.warn(`[ConfigDirectorClient] Error flushing telemetry while disposing the client: `,e)})}};export{l as a,x as i,$ as n,d as o,Y as r,u as s,ft as t};
|
|
6
|
-
//# sourceMappingURL=DefaultConfigDirectorClient-ZR0xPXNQ.mjs.map
|