@configdirector/server-sdk 1.7.0 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -0
- package/dist/DefaultConfigDirectorClient-BZu8tv38.cjs +5 -0
- package/dist/DefaultConfigDirectorClient-DbkqrtUI.mjs +6 -0
- package/dist/DefaultConfigDirectorClient-DbkqrtUI.mjs.map +1 -0
- package/dist/configdirector-server-testing.cjs +1 -0
- package/dist/configdirector-server-testing.d.cts +111 -0
- package/dist/configdirector-server-testing.d.cts.map +1 -0
- package/dist/configdirector-server-testing.d.mts +111 -0
- package/dist/configdirector-server-testing.d.mts.map +1 -0
- package/dist/configdirector-server-testing.mjs +2 -0
- package/dist/configdirector-server-testing.mjs.map +1 -0
- package/dist/configdirector-server.cjs +1 -5
- package/dist/configdirector-server.d.cts +2 -288
- package/dist/configdirector-server.d.cts.map +1 -1
- package/dist/configdirector-server.d.mts +2 -288
- package/dist/configdirector-server.d.mts.map +1 -1
- package/dist/configdirector-server.mjs +1 -5
- package/dist/configdirector-server.mjs.map +1 -1
- package/dist/types-BqIJGXWv.d.mts +292 -0
- package/dist/types-BqIJGXWv.d.mts.map +1 -0
- package/dist/types-CcUNxeqN.d.cts +292 -0
- package/dist/types-CcUNxeqN.d.cts.map +1 -0
- package/package.json +19 -3
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { a as ConfigDirectorLogger, t as ConfigDirectorClient } from "./types-CcUNxeqN.cjs";
|
|
2
|
+
|
|
3
|
+
//#region ../shared/src/testing/values.d.ts
|
|
4
|
+
type TestJsonValue = boolean | number | string | null | TestJsonValue[] | {
|
|
5
|
+
[key: string]: TestJsonValue;
|
|
6
|
+
};
|
|
7
|
+
type TestValue = boolean | number | string | TestJsonValue[] | {
|
|
8
|
+
[key: string]: TestJsonValue;
|
|
9
|
+
};
|
|
10
|
+
type TestValues = Record<string, TestValue>;
|
|
11
|
+
//#endregion
|
|
12
|
+
//#region src/testing/TestClient.d.ts
|
|
13
|
+
/**
|
|
14
|
+
* Options for {@link createTestClient}. Every option is optional.
|
|
15
|
+
*/
|
|
16
|
+
type TestClientOptions = {
|
|
17
|
+
/**
|
|
18
|
+
* The config values the test client serves once its client connects, keyed by config key. The
|
|
19
|
+
* config type follows from each value: a boolean, an integral number (`integer`), any other
|
|
20
|
+
* number (`float`), a string, or a plain object or array (`json`). Every context receives the
|
|
21
|
+
* same value.
|
|
22
|
+
*/
|
|
23
|
+
values?: TestValues;
|
|
24
|
+
/**
|
|
25
|
+
* The connection timeout of the SDK client, in milliseconds. It bounds how long a held
|
|
26
|
+
* `initialize` waits. Defaults to the SDK's production timeout.
|
|
27
|
+
*/
|
|
28
|
+
timeout?: number;
|
|
29
|
+
/**
|
|
30
|
+
* The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level.
|
|
31
|
+
*/
|
|
32
|
+
logger?: ConfigDirectorLogger;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* A real ConfigDirector client connected to an in-memory server that the test controls.
|
|
36
|
+
*
|
|
37
|
+
* The client under {@link TestClient.client} is the SDK's production client: value parsing,
|
|
38
|
+
* targeting evaluation, watchers, events, and readiness behave as they do against ConfigDirector.
|
|
39
|
+
* Only the network connection and telemetry are replaced, so no request is ever made and nothing
|
|
40
|
+
* is left running after the client is disposed.
|
|
41
|
+
*/
|
|
42
|
+
interface TestClient {
|
|
43
|
+
/**
|
|
44
|
+
* The SDK client to hand to the code under test. It starts uninitialized, like a production
|
|
45
|
+
* client; `initialize` completes at once with the seeded values unless initialization is held.
|
|
46
|
+
*/
|
|
47
|
+
readonly client: ConfigDirectorClient;
|
|
48
|
+
/**
|
|
49
|
+
* Stores `value` under `key` and, when the client is connected, delivers it as an update, so
|
|
50
|
+
* reads, watchers, and `configsUpdated` handlers see it.
|
|
51
|
+
*/
|
|
52
|
+
setValue(key: string, value: TestValue): void;
|
|
53
|
+
/**
|
|
54
|
+
* Removes `key` and, when the client is connected, delivers a full update without it, so reads
|
|
55
|
+
* fall back to the in-code default value and watchers of `key` receive that default.
|
|
56
|
+
*/
|
|
57
|
+
removeValue(key: string): void;
|
|
58
|
+
/**
|
|
59
|
+
* Replaces every stored value with `values`, disarms any armed hold or failure, and, when the
|
|
60
|
+
* client is connected, delivers the new values as a full update.
|
|
61
|
+
*/
|
|
62
|
+
replaceValues(values: TestValues): void;
|
|
63
|
+
/**
|
|
64
|
+
* Makes the next `initialize` wait until {@link completeInitialization} or
|
|
65
|
+
* {@link failInitialization} is called, or until the client's timeout elapses.
|
|
66
|
+
*/
|
|
67
|
+
holdInitialization(): void;
|
|
68
|
+
/**
|
|
69
|
+
* Delivers the stored values to a held `initialize`, so it completes with the client ready. When
|
|
70
|
+
* a hold is armed but no `initialize` has started, it disarms the hold instead.
|
|
71
|
+
*/
|
|
72
|
+
completeInitialization(): void;
|
|
73
|
+
/**
|
|
74
|
+
* Fails a held `initialize` with an unrecoverable connection error, or arms the next `initialize`
|
|
75
|
+
* to fail. `initialize` completes promptly with the client not ready and `connectionError` fires.
|
|
76
|
+
*/
|
|
77
|
+
failInitialization(): void;
|
|
78
|
+
}
|
|
79
|
+
//#endregion
|
|
80
|
+
//#region ../shared/src/errors.d.ts
|
|
81
|
+
declare class ConfigDirectorConnectionError extends Error {
|
|
82
|
+
readonly name: string;
|
|
83
|
+
readonly status?: number;
|
|
84
|
+
constructor(message: string, status?: number);
|
|
85
|
+
}
|
|
86
|
+
declare class ConfigDirectorValidationError extends Error {
|
|
87
|
+
readonly name: string;
|
|
88
|
+
constructor(message: string);
|
|
89
|
+
}
|
|
90
|
+
//#endregion
|
|
91
|
+
//#region src/testing.d.ts
|
|
92
|
+
/**
|
|
93
|
+
* Creates a {@link TestClient}: a real `ConfigDirectorClient` connected to an in-memory server
|
|
94
|
+
* that the test controls. No network connection is opened and no telemetry is sent.
|
|
95
|
+
*
|
|
96
|
+
* @param options {@link TestClientOptions}: the initial values, the client's timeout, and its logger
|
|
97
|
+
* @returns A {@link TestClient} whose `client` is passed to the code under test
|
|
98
|
+
*
|
|
99
|
+
* @example
|
|
100
|
+
* import { createTestClient } from "@configdirector/server-sdk/testing";
|
|
101
|
+
*
|
|
102
|
+
* const testClient = createTestClient({ values: { "new-checkout": true } });
|
|
103
|
+
* await testClient.client.initialize();
|
|
104
|
+
* expect(testClient.client.getValue("new-checkout", false)).toBe(true);
|
|
105
|
+
*
|
|
106
|
+
* testClient.setValue("new-checkout", false);
|
|
107
|
+
*/
|
|
108
|
+
declare const createTestClient: (options?: TestClientOptions) => TestClient;
|
|
109
|
+
//#endregion
|
|
110
|
+
export { ConfigDirectorConnectionError, ConfigDirectorValidationError, type TestClient, type TestClientOptions, type TestJsonValue, type TestValue, type TestValues, createTestClient };
|
|
111
|
+
//# sourceMappingURL=configdirector-server-testing.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"configdirector-server-testing.d.cts","names":[],"sources":["../../shared/src/testing/values.ts","../src/testing/TestClient.ts","../../shared/src/errors.ts","../src/testing.ts"],"mappings":";;;KAGY,aAAA,sCAAmD,aAAA;EAAA,CAAqB,GAAA,WAAc,aAAA;AAAA;AAAA,KAEtF,SAAA,+BAAwC,aAAA;EAAA,CAAqB,GAAA,WAAc,aAAA;AAAA;AAAA,KAE3E,UAAA,GAAa,MAAA,SAAe,SAAA;;;;AAJxC;;KCSY,iBAAA;EDTmG;;;;;;ECgB7G,MAAA,GAAS,UAAA;EDdU;;;;ECmBnB,OAAA;EDnBqF;;;ECuBrF,MAAA,GAAS,oBAAA;AAAA;;;;;;;AAhBX;;UA2BiB,UAAA;EAXc;;;;EAAA,SAgBpB,MAAA,EAAQ,oBAAA;EAhBR;;;AAWX;EAWE,QAAA,CAAS,GAAA,UAAa,KAAA,EAAO,SAAA;;;;;EAM7B,WAAA,CAAY,GAAA;EAMoB;;;;EAAhC,aAAA,CAAc,MAAA,EAAQ,UAAA;EAZO;;;;EAkB7B,kBAAA;EANsB;;;;EAYtB,sBAAA;EAMkB;;;;EAAlB,kBAAA;AAAA;;;cChFW,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;;;;;;;;;;;AFVd;;;;;;;;cGkBa,gBAAA,GAAoB,OAAA,GAAU,iBAAA,KAAoB,UAAA"}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { a as ConfigDirectorLogger, t as ConfigDirectorClient } from "./types-BqIJGXWv.mjs";
|
|
2
|
+
|
|
3
|
+
//#region ../shared/src/testing/values.d.ts
|
|
4
|
+
type TestJsonValue = boolean | number | string | null | TestJsonValue[] | {
|
|
5
|
+
[key: string]: TestJsonValue;
|
|
6
|
+
};
|
|
7
|
+
type TestValue = boolean | number | string | TestJsonValue[] | {
|
|
8
|
+
[key: string]: TestJsonValue;
|
|
9
|
+
};
|
|
10
|
+
type TestValues = Record<string, TestValue>;
|
|
11
|
+
//#endregion
|
|
12
|
+
//#region src/testing/TestClient.d.ts
|
|
13
|
+
/**
|
|
14
|
+
* Options for {@link createTestClient}. Every option is optional.
|
|
15
|
+
*/
|
|
16
|
+
type TestClientOptions = {
|
|
17
|
+
/**
|
|
18
|
+
* The config values the test client serves once its client connects, keyed by config key. The
|
|
19
|
+
* config type follows from each value: a boolean, an integral number (`integer`), any other
|
|
20
|
+
* number (`float`), a string, or a plain object or array (`json`). Every context receives the
|
|
21
|
+
* same value.
|
|
22
|
+
*/
|
|
23
|
+
values?: TestValues;
|
|
24
|
+
/**
|
|
25
|
+
* The connection timeout of the SDK client, in milliseconds. It bounds how long a held
|
|
26
|
+
* `initialize` waits. Defaults to the SDK's production timeout.
|
|
27
|
+
*/
|
|
28
|
+
timeout?: number;
|
|
29
|
+
/**
|
|
30
|
+
* The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level.
|
|
31
|
+
*/
|
|
32
|
+
logger?: ConfigDirectorLogger;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* A real ConfigDirector client connected to an in-memory server that the test controls.
|
|
36
|
+
*
|
|
37
|
+
* The client under {@link TestClient.client} is the SDK's production client: value parsing,
|
|
38
|
+
* targeting evaluation, watchers, events, and readiness behave as they do against ConfigDirector.
|
|
39
|
+
* Only the network connection and telemetry are replaced, so no request is ever made and nothing
|
|
40
|
+
* is left running after the client is disposed.
|
|
41
|
+
*/
|
|
42
|
+
interface TestClient {
|
|
43
|
+
/**
|
|
44
|
+
* The SDK client to hand to the code under test. It starts uninitialized, like a production
|
|
45
|
+
* client; `initialize` completes at once with the seeded values unless initialization is held.
|
|
46
|
+
*/
|
|
47
|
+
readonly client: ConfigDirectorClient;
|
|
48
|
+
/**
|
|
49
|
+
* Stores `value` under `key` and, when the client is connected, delivers it as an update, so
|
|
50
|
+
* reads, watchers, and `configsUpdated` handlers see it.
|
|
51
|
+
*/
|
|
52
|
+
setValue(key: string, value: TestValue): void;
|
|
53
|
+
/**
|
|
54
|
+
* Removes `key` and, when the client is connected, delivers a full update without it, so reads
|
|
55
|
+
* fall back to the in-code default value and watchers of `key` receive that default.
|
|
56
|
+
*/
|
|
57
|
+
removeValue(key: string): void;
|
|
58
|
+
/**
|
|
59
|
+
* Replaces every stored value with `values`, disarms any armed hold or failure, and, when the
|
|
60
|
+
* client is connected, delivers the new values as a full update.
|
|
61
|
+
*/
|
|
62
|
+
replaceValues(values: TestValues): void;
|
|
63
|
+
/**
|
|
64
|
+
* Makes the next `initialize` wait until {@link completeInitialization} or
|
|
65
|
+
* {@link failInitialization} is called, or until the client's timeout elapses.
|
|
66
|
+
*/
|
|
67
|
+
holdInitialization(): void;
|
|
68
|
+
/**
|
|
69
|
+
* Delivers the stored values to a held `initialize`, so it completes with the client ready. When
|
|
70
|
+
* a hold is armed but no `initialize` has started, it disarms the hold instead.
|
|
71
|
+
*/
|
|
72
|
+
completeInitialization(): void;
|
|
73
|
+
/**
|
|
74
|
+
* Fails a held `initialize` with an unrecoverable connection error, or arms the next `initialize`
|
|
75
|
+
* to fail. `initialize` completes promptly with the client not ready and `connectionError` fires.
|
|
76
|
+
*/
|
|
77
|
+
failInitialization(): void;
|
|
78
|
+
}
|
|
79
|
+
//#endregion
|
|
80
|
+
//#region ../shared/src/errors.d.ts
|
|
81
|
+
declare class ConfigDirectorConnectionError extends Error {
|
|
82
|
+
readonly name: string;
|
|
83
|
+
readonly status?: number;
|
|
84
|
+
constructor(message: string, status?: number);
|
|
85
|
+
}
|
|
86
|
+
declare class ConfigDirectorValidationError extends Error {
|
|
87
|
+
readonly name: string;
|
|
88
|
+
constructor(message: string);
|
|
89
|
+
}
|
|
90
|
+
//#endregion
|
|
91
|
+
//#region src/testing.d.ts
|
|
92
|
+
/**
|
|
93
|
+
* Creates a {@link TestClient}: a real `ConfigDirectorClient` connected to an in-memory server
|
|
94
|
+
* that the test controls. No network connection is opened and no telemetry is sent.
|
|
95
|
+
*
|
|
96
|
+
* @param options {@link TestClientOptions}: the initial values, the client's timeout, and its logger
|
|
97
|
+
* @returns A {@link TestClient} whose `client` is passed to the code under test
|
|
98
|
+
*
|
|
99
|
+
* @example
|
|
100
|
+
* import { createTestClient } from "@configdirector/server-sdk/testing";
|
|
101
|
+
*
|
|
102
|
+
* const testClient = createTestClient({ values: { "new-checkout": true } });
|
|
103
|
+
* await testClient.client.initialize();
|
|
104
|
+
* expect(testClient.client.getValue("new-checkout", false)).toBe(true);
|
|
105
|
+
*
|
|
106
|
+
* testClient.setValue("new-checkout", false);
|
|
107
|
+
*/
|
|
108
|
+
declare const createTestClient: (options?: TestClientOptions) => TestClient;
|
|
109
|
+
//#endregion
|
|
110
|
+
export { ConfigDirectorConnectionError, ConfigDirectorValidationError, type TestClient, type TestClientOptions, type TestJsonValue, type TestValue, type TestValues, createTestClient };
|
|
111
|
+
//# sourceMappingURL=configdirector-server-testing.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"configdirector-server-testing.d.mts","names":[],"sources":["../../shared/src/testing/values.ts","../src/testing/TestClient.ts","../../shared/src/errors.ts","../src/testing.ts"],"mappings":";;;KAGY,aAAA,sCAAmD,aAAA;EAAA,CAAqB,GAAA,WAAc,aAAA;AAAA;AAAA,KAEtF,SAAA,+BAAwC,aAAA;EAAA,CAAqB,GAAA,WAAc,aAAA;AAAA;AAAA,KAE3E,UAAA,GAAa,MAAA,SAAe,SAAA;;;;AAJxC;;KCSY,iBAAA;EDTmG;;;;;;ECgB7G,MAAA,GAAS,UAAA;EDdU;;;;ECmBnB,OAAA;EDnBqF;;;ECuBrF,MAAA,GAAS,oBAAA;AAAA;;;;;;;AAhBX;;UA2BiB,UAAA;EAXc;;;;EAAA,SAgBpB,MAAA,EAAQ,oBAAA;EAhBR;;;AAWX;EAWE,QAAA,CAAS,GAAA,UAAa,KAAA,EAAO,SAAA;;;;;EAM7B,WAAA,CAAY,GAAA;EAMoB;;;;EAAhC,aAAA,CAAc,MAAA,EAAQ,UAAA;EAZO;;;;EAkB7B,kBAAA;EANsB;;;;EAYtB,sBAAA;EAMkB;;;;EAAlB,kBAAA;AAAA;;;cChFW,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;;;;;;;;;;;AFVd;;;;;;;;cGkBa,gBAAA,GAAoB,OAAA,GAAU,iBAAA,KAAoB,UAAA"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{i as e,n as t,r as n,t as r}from"./DefaultConfigDirectorClient-DbkqrtUI.mjs";import i from"node:events";const a=(t,n)=>{if(t.trim().length==0)throw new e(`Invalid config key. The key of a test value cannot be empty.`);return o(t,n)},o=(t,n)=>{switch(typeof n){case`boolean`:return{type:`boolean`,value:n?`true`:`false`};case`number`:return s(t,n);case`string`:return{type:`string`,value:n};case`object`:if(n!==null)return l(t,n,``),{type:`json`,value:JSON.stringify(n)}}throw new e(`Invalid test value for '${t}': ${f(n)}. Use a boolean, a number, a string, a plain object, or an array.`)},s=(t,n)=>{if(!Number.isFinite(n))throw new e(`Invalid test value for '${t}': ${f(n)} is not a finite number.`);if(Number.isInteger(n)){if(!Number.isSafeInteger(n))throw new e(`Invalid test value for '${t}': ${n} is not a safe integer, so the SDK could not read it back exactly.`);return{type:`integer`,value:String(n)}}return{type:`float`,value:c(n)}},c=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}`},l=(e,t,n)=>{if(!(t===null||typeof t==`boolean`||typeof t==`string`)){if(typeof t==`number`){if(!Number.isFinite(t))throw u(e,n,`${f(t)} is not a finite number`);return}if(Array.isArray(t)){t.forEach((t,r)=>l(e,t,`${n}[${r}]`));return}if(d(t)){for(let[r,i]of Object.entries(t))l(e,i,n?`${n}.${r}`:r);return}throw u(e,n,`${f(t)} cannot be encoded as JSON`)}},u=(t,n,r)=>new e(`Invalid test value for '${t}'${n?` at '${n}'`:``}: ${r}. JSON contents can hold booleans, finite numbers, strings, null, arrays, and plain objects.`),d=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},f=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),p=(e,t)=>{let n=a(e,t);return{id:`test-config:${e}`,key:e,type:n.type,variations:[{name:null,value:n.value}],target:{defaultValue:n.value,rules:[]}}},m={environmentId:`test-environment`,projectId:`test-project`};var h=class{constructor(e,t){this.logger=e,this.emitter=new i,this.configs=new Map,this.pendingDeliveries=[],this.armed=`nothing`,this.connected=!1,this.delivering=!1,this.encodeAll(t).forEach((e,t)=>this.configs.set(t,e))}setValue(e,t){let n=p(e,t);this.configs.set(e,n),this.deliverIfConnected({...m,kind:`delta`,configs:{[e]:n}})}removeValue(e){this.configs.delete(e),this.deliverIfConnected(this.fullUpdate())}replaceValues(e){let t=this.encodeAll(e);this.configs.clear(),t.forEach((e,t)=>this.configs.set(t,e)),this.armed=`nothing`,this.deliverIfConnected(this.fullUpdate())}hold(){this.armed=`hold`}complete(){this.pendingHold?this.pendingHold.complete():this.armed===`hold`&&(this.armed=`nothing`)}fail(){this.pendingHold?this.pendingHold.fail():this.armed=`failure`}connect(e){this.endAttempt();let t=this.armed;switch(this.armed=`nothing`,t){case`failure`:return this.failNow();case`hold`:return this.holdNow(e);default:return this.connectNow(),Promise.resolve(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.endAttempt()}dispose(){this.close(),this.emitter.removeAllListeners()}endAttempt(){this.connected=!1,this.pendingHold?.end()}connectNow(){this.connected=!0,this.deliver(this.fullUpdate())}holdNow(e){return new Promise((t,n)=>{let r=setTimeout(()=>this.pendingHold?.end(),e),i=()=>{clearTimeout(r),this.pendingHold=void 0};this.pendingHold={end:()=>{i(),t(this)},complete:()=>{i(),this.connectNow(),t(this)},fail:()=>{i();let e=this.fatalError();this.emitter.emit(`connectionError`,e),n(e)}}})}failNow(){let e=this.fatalError();return this.emitter.emit(`connectionError`,e),Promise.reject(e)}fatalError(){return new n(`Connection failed with status: 401. Error: the test client failed this initialization. This is an unrecoverable error, will not attempt to reconnect.`,401)}deliverIfConnected(e){this.connected&&this.deliver(e)}deliver(e){if(this.pendingDeliveries.push(e),!this.delivering){this.delivering=!0;try{let e=this.pendingDeliveries.shift();for(;e;)this.emitCaught(e),e=this.pendingDeliveries.shift()}finally{this.delivering=!1}}}emitCaught(e){try{this.emitter.emit(`configBundleReceived`,e)}catch(e){this.logger.error(`[InMemoryConnection] Error dispatching a config update from the test client: `,e)}}fullUpdate(){return{...m,kind:`full`,configs:Object.fromEntries(this.configs)}}encodeAll(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,p(n,r));return t}};const g={start:()=>{},evaluatedConfig:()=>{},close:async()=>{}};var _=class{constructor(e,t){this.client=e,this.connection=t}setValue(e,t){this.connection.setValue(e,t)}removeValue(e){this.connection.removeValue(e)}replaceValues(e){this.connection.replaceValues(e)}holdInitialization(){this.connection.hold()}completeInitialization(){this.connection.complete()}failInitialization(){this.connection.fail()}};const v=(e,n)=>{let i=n?.logger??t(),a=new h(i,n?.values??{});return new _(new r(`test-client`,e,{logger:i,connection:{timeout:n?.timeout}},{transport:a,telemetry:g}),a)},y=e=>v({sdkName:`js-server-sdk`,sdkVersion:`1.9.0`},e);export{n as ConfigDirectorConnectionError,e as ConfigDirectorValidationError,y as createTestClient};
|
|
2
|
+
//# sourceMappingURL=configdirector-server-testing.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"configdirector-server-testing.mjs","names":["encodeTestValue","encodeShared","createTestClient"],"sources":["../../shared/src/testing/values.ts","../src/testing/values.ts","../src/testing/InMemoryConnection.ts","../src/testing/TestClient.ts","../src/testing.ts"],"sourcesContent":["import type { ConfigType } from \"../types\";\nimport { ConfigDirectorValidationError } from \"../errors\";\n\nexport type TestJsonValue = boolean | number | string | null | TestJsonValue[] | { [key: string]: TestJsonValue };\n\nexport type TestValue = boolean | number | string | TestJsonValue[] | { [key: string]: TestJsonValue };\n\nexport type TestValues = Record<string, TestValue>;\n\nexport type EncodedTestValue = { type: ConfigType; value: string };\n\nexport const encodeTestValue = (key: string, value: TestValue): EncodedTestValue => {\n if (key.trim().length == 0) {\n throw new ConfigDirectorValidationError(\"Invalid config key. The key of a test value cannot be empty.\");\n }\n return encode(key, value);\n};\n\nconst encode = (key: string, value: TestValue): EncodedTestValue => {\n switch (typeof value) {\n case \"boolean\":\n return { type: \"boolean\", value: value ? \"true\" : \"false\" };\n case \"number\":\n return encodeNumber(key, value);\n case \"string\":\n return { type: \"string\", value };\n case \"object\":\n if (value !== null) {\n assertJsonContents(key, value, \"\");\n return { type: \"json\", value: JSON.stringify(value) };\n }\n }\n throw new ConfigDirectorValidationError(\n `Invalid test value for '${key}': ${describe(value)}. Use a boolean, a number, a string, a plain object, or an array.`,\n );\n};\n\nconst encodeNumber = (key: string, value: number): EncodedTestValue => {\n if (!Number.isFinite(value)) {\n throw new ConfigDirectorValidationError(`Invalid test value for '${key}': ${describe(value)} is not a finite number.`);\n }\n if (Number.isInteger(value)) {\n if (!Number.isSafeInteger(value)) {\n throw new ConfigDirectorValidationError(\n `Invalid test value for '${key}': ${value} is not a safe integer, so the SDK could not read it back exactly.`,\n );\n }\n return { type: \"integer\", value: String(value) };\n }\n return { type: \"float\", value: toPlainDecimal(value) };\n};\n\nconst toPlainDecimal = (value: number): string => {\n const text = String(value);\n const exponentIndex = text.indexOf(\"e-\");\n if (exponentIndex < 0) {\n return text;\n }\n const sign = text.startsWith(\"-\") ? \"-\" : \"\";\n const [integerDigits = \"\", fractionDigits = \"\"] = text.slice(sign.length, exponentIndex).split(\".\");\n const leadingZeros = Number(text.slice(exponentIndex + 2)) - integerDigits.length;\n return `${sign}0.${\"0\".repeat(leadingZeros)}${integerDigits}${fractionDigits}`;\n};\n\nconst assertJsonContents = (key: string, value: unknown, path: string): void => {\n if (value === null || typeof value === \"boolean\" || typeof value === \"string\") {\n return;\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw invalidJsonContents(key, path, `${describe(value)} is not a finite number`);\n }\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((item, index) => assertJsonContents(key, item, `${path}[${index}]`));\n return;\n }\n if (isPlainObject(value)) {\n for (const [property, item] of Object.entries(value)) {\n assertJsonContents(key, item, path ? `${path}.${property}` : property);\n }\n return;\n }\n throw invalidJsonContents(key, path, `${describe(value)} cannot be encoded as JSON`);\n};\n\nconst invalidJsonContents = (key: string, path: string, problem: string) =>\n new ConfigDirectorValidationError(\n `Invalid test value for '${key}'${path ? ` at '${path}'` : \"\"}: ${problem}. JSON contents can hold booleans, finite numbers, strings, null, arrays, and plain objects.`,\n );\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n};\n\nconst describe = (value: unknown): string => {\n if (value === null) {\n return \"null\";\n }\n if (typeof value === \"function\") {\n return \"a function\";\n }\n if (typeof value === \"object\") {\n return `a ${value.constructor?.name ?? \"object\"} instance`;\n }\n if (typeof value === \"symbol\") {\n return \"a symbol\";\n }\n return String(value);\n};\n","import type { ConfigDefinition } from \"../types\";\nimport { encodeTestValue as encodeShared } from \"@shared/testing/values\";\nimport type { TestValue } from \"@shared/testing/values\";\n\nexport type { TestJsonValue, TestValue, TestValues } from \"@shared/testing/values\";\n\nexport const encodeTestValue = (key: string, value: TestValue): ConfigDefinition => {\n const encoded = encodeShared(key, value);\n return {\n id: `test-config:${key}`,\n key,\n type: encoded.type,\n variations: [{ name: null, value: encoded.value }],\n target: { defaultValue: encoded.value, rules: [] },\n };\n};\n","import EventEmitter from \"node:events\";\nimport type { ConfigBundle, ConfigDefinition, ConfigDirectorLogger, Transport, TransportEvents } from \"../types\";\nimport { ConfigDirectorConnectionError } from \"@shared/errors\";\nimport { encodeTestValue, type TestValue, type TestValues } from \"./values\";\n\ntype Armed = \"nothing\" | \"hold\" | \"failure\";\n\ntype PendingHold = {\n end: () => void;\n complete: () => void;\n fail: () => void;\n};\n\nconst TEST_ENVIRONMENT = { environmentId: \"test-environment\", projectId: \"test-project\" };\n\nexport class InMemoryConnection implements Transport {\n private readonly emitter = new EventEmitter();\n private readonly configs = new Map<string, ConfigDefinition>();\n private readonly pendingDeliveries: ConfigBundle[] = [];\n private armed: Armed = \"nothing\";\n private pendingHold: PendingHold | undefined;\n private connected = false;\n private delivering = false;\n\n constructor(\n private readonly logger: ConfigDirectorLogger,\n values: TestValues,\n ) {\n this.encodeAll(values).forEach((definition, key) => this.configs.set(key, definition));\n }\n\n public setValue(key: string, value: TestValue) {\n const definition = encodeTestValue(key, value);\n this.configs.set(key, definition);\n this.deliverIfConnected({ ...TEST_ENVIRONMENT, kind: \"delta\", configs: { [key]: definition } });\n }\n\n public removeValue(key: string) {\n this.configs.delete(key);\n this.deliverIfConnected(this.fullUpdate());\n }\n\n public replaceValues(values: TestValues) {\n const encoded = this.encodeAll(values);\n this.configs.clear();\n encoded.forEach((definition, key) => this.configs.set(key, definition));\n this.armed = \"nothing\";\n this.deliverIfConnected(this.fullUpdate());\n }\n\n public hold() {\n this.armed = \"hold\";\n }\n\n public complete() {\n if (this.pendingHold) {\n this.pendingHold.complete();\n } else if (this.armed === \"hold\") {\n this.armed = \"nothing\";\n }\n }\n\n public fail() {\n if (this.pendingHold) {\n this.pendingHold.fail();\n } else {\n this.armed = \"failure\";\n }\n }\n\n public connect(timeout: number): Promise<this> {\n this.endAttempt();\n const armed = this.armed;\n this.armed = \"nothing\";\n switch (armed) {\n case \"failure\":\n return this.failNow();\n case \"hold\":\n return this.holdNow(timeout);\n default:\n this.connectNow();\n return Promise.resolve(this);\n }\n }\n\n public get isConnected(): boolean {\n return this.connected;\n }\n\n public on<TName extends keyof TransportEvents>(name: TName, handler: (payload: TransportEvents[TName]) => void) {\n this.emitter.on(name, handler);\n }\n\n public off<TName extends keyof TransportEvents>(name: TName, handler?: (payload: TransportEvents[TName]) => void) {\n if (handler) {\n this.emitter.off(name, handler);\n } else {\n this.emitter.removeAllListeners(name);\n }\n }\n\n public close() {\n this.endAttempt();\n }\n\n public dispose() {\n this.close();\n this.emitter.removeAllListeners();\n }\n\n private endAttempt() {\n this.connected = false;\n this.pendingHold?.end();\n }\n\n private connectNow() {\n this.connected = true;\n this.deliver(this.fullUpdate());\n }\n\n private holdNow(timeout: number): Promise<this> {\n return new Promise<this>((resolve, reject) => {\n const timer = setTimeout(() => this.pendingHold?.end(), timeout);\n const release = () => {\n clearTimeout(timer);\n this.pendingHold = undefined;\n };\n this.pendingHold = {\n end: () => {\n release();\n resolve(this);\n },\n complete: () => {\n release();\n this.connectNow();\n resolve(this);\n },\n fail: () => {\n release();\n const error = this.fatalError();\n this.emitter.emit(\"connectionError\", error);\n reject(error);\n },\n };\n });\n }\n\n private failNow(): Promise<this> {\n const error = this.fatalError();\n this.emitter.emit(\"connectionError\", error);\n return Promise.reject(error);\n }\n\n private fatalError() {\n return new ConfigDirectorConnectionError(\n \"Connection failed with status: 401. Error: the test client failed this initialization. This is an unrecoverable error, will not attempt to reconnect.\",\n 401,\n );\n }\n\n private deliverIfConnected(configBundle: ConfigBundle) {\n if (this.connected) {\n this.deliver(configBundle);\n }\n }\n\n private deliver(configBundle: ConfigBundle) {\n this.pendingDeliveries.push(configBundle);\n if (this.delivering) {\n return;\n }\n this.delivering = true;\n try {\n let next = this.pendingDeliveries.shift();\n while (next) {\n this.emitCaught(next);\n next = this.pendingDeliveries.shift();\n }\n } finally {\n this.delivering = false;\n }\n }\n\n private emitCaught(configBundle: ConfigBundle) {\n try {\n this.emitter.emit(\"configBundleReceived\", configBundle);\n } catch (error) {\n this.logger.error(\"[InMemoryConnection] Error dispatching a config update from the test client: \", error);\n }\n }\n\n private fullUpdate(): ConfigBundle {\n return { ...TEST_ENVIRONMENT, kind: \"full\", configs: Object.fromEntries(this.configs) };\n }\n\n private encodeAll(values: TestValues): Map<string, ConfigDefinition> {\n const encoded = new Map<string, ConfigDefinition>();\n for (const [key, value] of Object.entries(values)) {\n encoded.set(key, encodeTestValue(key, value));\n }\n return encoded;\n }\n}\n","import { DefaultConfigDirectorClient } from \"../DefaultConfigDirectorClient\";\nimport { createDefaultLogger } from \"../logger\";\nimport type { ConfigDirectorClient, ConfigDirectorLogger, IdentifyingSdkOptions } from \"../types\";\nimport type { ServerTelemetryClient } from \"../telemetry\";\nimport { InMemoryConnection } from \"./InMemoryConnection\";\nimport type { TestValue, TestValues } from \"./values\";\n\nconst TEST_CLIENT_SDK_KEY = \"test-client\";\n\n/**\n * Options for {@link createTestClient}. Every option is optional.\n */\nexport type TestClientOptions = {\n /**\n * The config values the test client serves once its client connects, keyed by config key. The\n * config type follows from each value: a boolean, an integral number (`integer`), any other\n * number (`float`), a string, or a plain object or array (`json`). Every context receives the\n * same value.\n */\n values?: TestValues;\n /**\n * The connection timeout of the SDK client, in milliseconds. It bounds how long a held\n * `initialize` waits. Defaults to the SDK's production timeout.\n */\n timeout?: number;\n /**\n * The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level.\n */\n logger?: ConfigDirectorLogger;\n};\n\n/**\n * A real ConfigDirector client connected to an in-memory server that the test controls.\n *\n * The client under {@link TestClient.client} is the SDK's production client: value parsing,\n * targeting evaluation, watchers, events, and readiness behave as they do against ConfigDirector.\n * Only the network connection and telemetry are replaced, so no request is ever made and nothing\n * is left running after the client is disposed.\n */\nexport interface TestClient {\n /**\n * The SDK client to hand to the code under test. It starts uninitialized, like a production\n * client; `initialize` completes at once with the seeded values unless initialization is held.\n */\n readonly client: ConfigDirectorClient;\n\n /**\n * Stores `value` under `key` and, when the client is connected, delivers it as an update, so\n * reads, watchers, and `configsUpdated` handlers see it.\n */\n setValue(key: string, value: TestValue): void;\n\n /**\n * Removes `key` and, when the client is connected, delivers a full update without it, so reads\n * fall back to the in-code default value and watchers of `key` receive that default.\n */\n removeValue(key: string): void;\n\n /**\n * Replaces every stored value with `values`, disarms any armed hold or failure, and, when the\n * client is connected, delivers the new values as a full update.\n */\n replaceValues(values: TestValues): void;\n\n /**\n * Makes the next `initialize` wait until {@link completeInitialization} or\n * {@link failInitialization} is called, or until the client's timeout elapses.\n */\n holdInitialization(): void;\n\n /**\n * Delivers the stored values to a held `initialize`, so it completes with the client ready. When\n * a hold is armed but no `initialize` has started, it disarms the hold instead.\n */\n completeInitialization(): void;\n\n /**\n * Fails a held `initialize` with an unrecoverable connection error, or arms the next `initialize`\n * to fail. `initialize` completes promptly with the client not ready and `connectionError` fires.\n */\n failInitialization(): void;\n}\n\nconst noopTelemetryClient: ServerTelemetryClient = {\n start: () => {},\n evaluatedConfig: () => {},\n close: async () => {},\n};\n\nclass InMemoryTestClient implements TestClient {\n constructor(\n public readonly client: ConfigDirectorClient,\n private readonly connection: InMemoryConnection,\n ) {}\n\n public setValue(key: string, value: TestValue) {\n this.connection.setValue(key, value);\n }\n\n public removeValue(key: string) {\n this.connection.removeValue(key);\n }\n\n public replaceValues(values: TestValues) {\n this.connection.replaceValues(values);\n }\n\n public holdInitialization() {\n this.connection.hold();\n }\n\n public completeInitialization() {\n this.connection.complete();\n }\n\n public failInitialization() {\n this.connection.fail();\n }\n}\n\nexport const createTestClient = (sdkOptions: IdentifyingSdkOptions, options?: TestClientOptions): TestClient => {\n const logger = options?.logger ?? createDefaultLogger();\n const connection = new InMemoryConnection(logger, options?.values ?? {});\n const client = new DefaultConfigDirectorClient(\n TEST_CLIENT_SDK_KEY,\n sdkOptions,\n { logger, connection: { timeout: options?.timeout } },\n { transport: connection, telemetry: noopTelemetryClient },\n );\n return new InMemoryTestClient(client, connection);\n};\n","import { createTestClient as createInMemoryTestClient } from \"./testing/TestClient\";\nimport type { TestClient, TestClientOptions } from \"./testing/TestClient\";\n\nexport type { TestClient, TestClientOptions } from \"./testing/TestClient\";\nexport type { TestValue, TestValues, TestJsonValue } from \"./testing/values\";\nexport { ConfigDirectorConnectionError, ConfigDirectorValidationError } from \"@shared/errors\";\n\n/**\n * Creates a {@link TestClient}: a real `ConfigDirectorClient` connected to an in-memory server\n * that the test controls. No network connection is opened and no telemetry is sent.\n *\n * @param options {@link TestClientOptions}: the initial values, the client's timeout, and its logger\n * @returns A {@link TestClient} whose `client` is passed to the code under test\n *\n * @example\n * import { createTestClient } from \"@configdirector/server-sdk/testing\";\n *\n * const testClient = createTestClient({ values: { \"new-checkout\": true } });\n * await testClient.client.initialize();\n * expect(testClient.client.getValue(\"new-checkout\", false)).toBe(true);\n *\n * testClient.setValue(\"new-checkout\", false);\n */\nexport const createTestClient = (options?: T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,WAAY,CAAE,QAAS,GAAS,QAAS,CAAE,CACrD,CAAE,UAAW,EAAY,UAAW,EAAqB,CAC1D,CACqC,EAAW,EC1GtC,EAAoB,GACxB,EAAyB,CAAE,QAAS,gBAAiB,WAAY,QAAe,CAAE,EAAQ"}
|
|
@@ -1,5 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});
|
|
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 v=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var y=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=v.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===v.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=v.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=v.CONNECTING,this._fetch(this.url,{...this.requestOptions,body:this.body(),headers:this.buildRequestHeaders(),signal:this.abortController.signal,cache:`no-store`}).then(e=>this.handleFetchResponse(e)).catch(e=>{if(e.name===`AbortError`||this.abortController.signal.aborted){this.close();return}this._onError(e),this.scheduleReconnect({error:e})})}async handleFetchResponse(e){let{body:t,status:n}=e;if(n===204){this.disconnected();return}if(n>=400){this.scheduleReconnect({status:n});return}if(!t)throw new h(`The server response did not have a body`);this._readyState=v.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new ne({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 te(`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=v.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=v.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new _(`The calculated reconnect delay is out of range: ${n}. Defaulting to ${this.serverReconnectionTime}`)),n=this.serverReconnectionTime),this.reconnectTimeout=setTimeout(()=>this.initiateConnection(),n)}resolveCallback(e,t,n){if(e==null)return t;if(typeof e!=`function`)throw new g(`${n} must be a function`);return e}};const re=e=>new y(e),b=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}},x=9e4;var ie=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=re({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){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()});return this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),x),Promise.race([t,new Promise(t=>{setTimeout(()=>t(this),e)})])}get sessionId(){return this._sessionId}sendHeartbeat(){!this.isConnected||!this._sessionId||b(x,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()}close(){clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0,this.eventSource?.close()}dispose(){this.close(),this.clear()}},S=class{constructor(){this.fatalError=!1,this.pollingIntervalSeconds=60}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()}},C=class extends S{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 b(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 w=(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}},T=(e,t,n)=>{let r=t.toLowerCase(),i=E(e);if(i===void 0)return r===`!=`||r===`does not equal`;let a=n[0];if(a===void 0)return!1;let o=E(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}},E=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(typeof e!=`string`||e.length===0||!ae(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0},ae=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},oe=(e,t,n)=>{let r=n[0];if(r===void 0)return!1;let i=D(e),a=D(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}},D=e=>{let t=d.DateTime.fromISO(e,{zone:`utc`});return t.isValid?t.toMillis():void 0},se=(e,t,n)=>{let r=t.toLowerCase();if(e.trim().length===0)return r===`is not one of`;let i=f.coerce(e),a=n.map(e=>f.coerce(e)),o=a[0]??null;switch(r){case`=`:return O(i,o);case`<`:return k(i,o,f.lt);case`<=`:return k(i,o,f.lte);case`>`:return k(i,o,f.gt);case`>=`:return k(i,o,f.gte);case`is one of`:return a.some(e=>O(i,e));case`is not one of`:return!a.some(e=>O(i,e));default:return!1}},O=(e,t)=>e!==null&&t!==null&&f.eq(e,t),k=(e,t,n)=>e!==null&&t!==null&&n(e,t),A=Symbol(`absent`),j=Symbol(`unknown-attribute`),M=e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`,N=e=>e===A||e==null?``:M(e)?P(e):``,P=e=>typeof e==`string`?e:String(e),F=e=>e===A?void 0:e,I=e=>e===j?`unknown-attribute`:e===A?`absent`:M(e)?`scalar`:Array.isArray(e)?`array`:`object`,L=(e,t,n)=>{let r=t.toLowerCase();if(!Array.isArray(e))return r===`does not contain any of`;let i=e.filter(M).map(P);switch(r){case`contains any of`:return i.some(e=>n.includes(e));case`does not contain any of`:return!i.some(e=>n.includes(e));default:return!1}};var R=class{evaluate(e,t){return this.explain(e,t).matched}explain(e,t){let n=this.resolve(e,t),r=I(n),i=n===A||n===j?void 0:n;return n===j?{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 w(N(t),e.operator,n);case`number`:return T(F(t),e.operator,n);case`datetime`:return oe(N(t),e.operator,n);case`semver`:return se(N(t),e.operator,n);case`array`:return L(F(t),e.operator,n)}return!1}resolve(e,t){switch(e.attribute){case`identifier`:return z(t?.context?.id);case`name`:return z(t?.context?.name);case`appName`:return z(t?.metadata?.appName);case`appVersion`:return z(t?.metadata?.appVersion);case`traits`:return e.trait?z(this.findTraitValue(t?.context?.traits,e.trait)):A;default:return j}}findTraitValue(e,t){try{return(0,u.findByPointer)(t,e).val}catch{return}}};const z=e=>e??A,B=e=>{let t=`${e.contextIdentifier}-${e.configId}`;return Number((0,ee.rapidhash)(t,{seed:15426857351n})%1000n)/10};var V=class{constructor(e){if(this.logger=e,this.conditionEvaluator=new R,!e||!e.warn||!e.error||!e.info)throw TypeError(`The provided logger is not a valid 'ConfigDirectorLogger'`);this.logger=e}evaluate(e,t){return{id:e.id,key:e.key,type:e.type,value:this.explain(e,t).value}}explain(e,t){let n=[...e.target?.rules??[]].sort((e,t)=>(e.order??2**53-1)-(t.order??2**53-1)),r=[],i;for(let a of n){if(i){r.push({ruleId:a.id,outcome:`not-evaluated`,conditions:[],bucket:void 0});continue}let n=this.explainRule(a,e,t);r.push(n.explanation),n.value!==void 0&&(i={ruleId:a.id,value:n.value})}return{value:i?.value??e.target?.defaultValue,servedBy:i?{kind:`rule`,ruleId:i.ruleId}:{kind:`default`},rules:r}}explainRule(e,t,n){let r={ruleId:e.id,outcome:`not-matched`,conditions:[],bucket:void 0};try{let i;return e.type==`percentage`?i=this.explainPercentage(e.percentages??[],t,n,r):e.type==`conditional`&&(i=this.explainConditionalRule(e,t,n,r)),i!==void 0&&(r.outcome=`matched`),{explanation:r,value:i}}catch(n){return this.logger.warn(`There was an error while evaluating a targeting rule '${e?.id}' for '${t?.key}'. The rule will be disregarded.`,{error:n,configKey:t?.key,ruleId:e?.id}),{explanation:{ruleId:e.id,outcome:`errored`,conditions:[],bucket:void 0},value:void 0}}}explainPercentage(e,t,n,r){let i=n?.context?.id??void 0,a=i===void 0?0:B({configId:t.id,contextIdentifier:i}),o=[],s=0,c;for(let t of e){let e=s+t.percentage;o.push({percentageId:t.id,from:s,to:e,value:t.value?.toString()}),c===void 0&&a<e&&(c=t),s=e}return r.bucket={identifier:i,defaultedToPredefinedBucket:i===void 0,assignedPercentage:a,shares:o,selectedPercentageId:c?.id},c?.value==null?void 0:c.value.toString()}explainConditionalRule(e,t,n,r){let i=!1;for(let t of e.conditions??[]){if(i){r.conditions.push({conditionId:t.id,outcome:`not-evaluated`});continue}let e=this.conditionEvaluator.explain(t,n);r.conditions.push({conditionId:t.id,outcome:e.matched?`matched`:`not-matched`,resolvedValue:e.resolvedValue,resolvedType:e.resolvedType}),i=!e.matched}if(!i){if(e.target==`value`)return e.value==null?void 0:e.value.toString();if(e.target==`percentage`)return this.explainPercentage(e.percentages??[],t,n,r)}}};const H=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},U=e=>e===`number`||e===`bigint`,W=new Set([`boolean`,`integer`,`float`]),G=(e,t)=>{let n=e.value,r=H(t);if(n==null)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return ue(n,t,r,e.valueId);if(typeof t==`string`)return W.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=K(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(U(typeof t)&&e.type===`integer`){let i=ce(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(U(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=q(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`}},K=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},ce=e=>{let t=J(e);return t==null?void 0:Math.trunc(t)},q=e=>J(e),J=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},ue=(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 de(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`}}},de=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},Y={off:-1,error:0,warn:1,info:2,debug:3},fe=()=>{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 pe=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=fe()}debug(e,...t){this.log(console.debug,`debug`,e,...t)}info(e,...t){this.log(console.info,`info`,e,...t)}warn(e,...t){this.log(console.warn,`warn`,e,...t)}error(e,...t){this.log(console.error,`error`,e,...t)}log(e,t,n,...r){Y[this.level]>=Y[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},me=class{decorateMessage(e){return`[ConfigDirector:js-server-sdk] ${e}`}};const X=(e,t)=>new pe(e??`warn`,t??new me),he=(e,t)=>new URL(e,t?.toString()),Z=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,Q=e=>{if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch{return{value:e.value.toString(),type:`json`}}}let t=e.value?.toString();return t&&t.length<=500?{value:t}:e.valueId?{valueId:e.valueId}:{value:t}},$=e=>{let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]?.length??0)>0)return!1;return!0},ge=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 $(e.discreteEvents)&&$(e.aggregatedEvents)&&ge(e.droppedEvents)}async sendReport(e){try{let t=await b(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}},ve=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}))}},ye=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}},be=class{constructor(e){this.aggregator=new ve,this.collectEvents=!0,this.logger=e.logger,this.evaluationEventQueue=new ye(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4;let t=e.initialFlushIntervalDelay??5e3;this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),t)}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()}},xe=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)}}},Se=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(e){let t=await Promise.all(e.events.map(async e=>({...e,defaultValue:await Z(e.defaultValue,this.valueIdGenerator),evaluatedValue:await Z(e.evaluatedValue,this.valueIdGenerator)})));return{...e,events:t}}},Ce=class extends be{constructor(e){super(e),this.reporter=new _e(e),this.contexts=new xe(e.contextLimit??1e3),this.evaluationEventSnapshotPreprocessor=new Se(e.valueIdGenerator)}evaluatedConfig(e){if(!this.collectEvents)return;e.context?.id&&!e.context.anonymous&&this.contexts.set(e.context.id,e.context);let t={...e.evaluation,contextId:e.context?.anonymous?void 0:e.context?.id};this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(t))}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:Q({value:e.defaultValue,type:e.type}),evaluatedValue:Q({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}snapshotContexts(){let e=Array.from(this.contexts.values()),t=this.contexts.droppedCount;return this.contexts.clearAndReset(),{contexts:e,droppedCount:t}}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot()),t=this.snapshotContexts();return await this.reporter?.report({context:this._context,discreteEvents:{capturedContexts:t.contexts},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount,capturedContexts:t.droppedCount}})}};const we=(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`)},Te=Math.ceil(128/Math.log2(62)),Ee=async e=>we((0,l.createHash)(`sha256`).update(e?.toString()??``).digest().subarray(0,16),Te),De=new URL(`https://server-sdk-api.configdirector.com`);var Oe=class{constructor(e,t,n){this.handlersMap=new Map,this.eventEmitter=new c.default,this.ready=!1,this.logger=n?.logger??X(),this.timeout=n?.connection?.timeout??3e3,this.metaContext=n?.metadata??{},this.validateSdkKeyPresence(e),this.configEvaluator=new V(this.logger);let r=this.parseUrl(n?.connection?.url)??De;this.connectionMode=n?.connection?.mode??`streaming`;let i=this.getTransportConstructor(this.connectionMode),a=n?.telemetry?.eventQueueLimit??5e3;this.usageEventCollector=new Ce({sdkKey:e,sdkIdentity:t,metaContext:n?.metadata??{},logger:this.logger,baseUrl:r,flushIntervalDelay:n?.telemetry?.flushInterval??3e4,evaluationQueueLimit:Math.ceil(a*.7),contextLimit:Math.floor(a*.3),urlFactory:he,valueIdGenerator:Ee}),this.transport=new i({serverSdkKey:e,baseUrl:r,metaContext:{...n?.metadata,sdkName:t.sdkName,sdkVersion:t.sdkVersion},logger:this.logger,pollingInterval:n?.connection?.pollingInterval}),this.transport.on(`configBundleReceived`,e=>{this.readyResolve?.();let t=Object.keys(e.configs);!this.configSet||e.kind==`full`?(this.configSet=e,this.eventEmitter.emit(`configsUpdated`,{keys:t}),this.updateWatchers(e.configs)):(this.configSet.configs={...this.configSet.configs,...e.configs},this.eventEmitter.emit(`configsUpdated`,{keys:t}),this.updateWatchers(e.configs)),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server with ${t.length} key(s)`,{keys: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(()=>{this.ready=!0,this.eventEmitter.emit(`clientReady`),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`)});let e=new Date().getTime();await this.transport.connect(this.timeout);let t=new Date().getTime()-e,n=this.timeout-t;if(n>0&&await Promise.race([this.readyPromise,new Promise(e=>{setTimeout(()=>e(),n)})]),!this.ready){let e=this.connectionMode===`streaming`?`The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`:`Since the client was configured without streaming, configs may not update and always return the default value.`;this.logger.warn(`[ConfigDirectorClient] Timed out waiting for initialization after ${this.timeout}ms. ${e}`)}}catch(e){this.logger.error(`[ConfigDirectorClient] An error occurred during initialization: `,e)}}getTransportConstructor(e){switch(e){case`polling`:return C;default:return ie}}updateWatchers(e){Object.values(e).forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){this.handlersMap.get(e.key)?.forEach(t=>{let n=this.getValueFromConfigDefinition(e.key,e,t.defaultValue,t.context);t.handler(n)})}watch(e,t,n,r){this.validateDefaultValue(t);let i=this.handlersMap.get(e),a={handler:n,defaultValue:t,requestedType:typeof t,context:r};return i?i.push(a):this.handlersMap.set(e,[a]),()=>this.unwatch(e,n)}unwatch(e,t){let n=this.handlersMap.get(e);if(n)if(t){let e=n.findIndex(e=>e.handler==t);e>=0&&n?.splice(e,1)}else n.splice(0)}getValue(e,t,n){this.validateDefaultValue(t);let r=this.configSet?.configs[e];return this.getValueFromConfigDefinition(e,r,t,n)}getValueFromConfigDefinition(e,t,n,r){if(t){let i=this.configEvaluator.evaluate(t,{context:r,metadata:this.metaContext}),a=G(i,n);return this.usageEventCollector.evaluatedConfig({context:r,evaluation:{key:e,type:i.type,defaultValue:n,requestedType:a.requestedType,evaluatedValue:a.parsedValue,evaluatedValueId:a.parsedValueId,usedDefault:a.usedDefault,evaluationReason:a.reason}}),this.dispatchEvaluationEvent({key:e,value:a.parsedValue,valueId:a.parsedValueId??void 0,isDefaultValue:a.usedDefault,reason:a.reason,context:r}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${a.parsedValue}'`),a.parsedValue}else{this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`);let t=this.isReady?`config-state-missing`:`client-not-ready`;return this.usageEventCollector.evaluatedConfig({context:r,evaluation:{key:e,defaultValue:n,requestedType:H(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:r}),n}}dispatchEvaluationEvent(e){setTimeout(()=>this.eventEmitter.emit(`configEvaluated`,{evaluation:e}),0)}parseUrl(e){if(e)try{return new URL(e)}catch(t){throw new m(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateSdkKeyPresence(e){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`)}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){if(!this.configSet)return{};let t=Object.entries(this.configSet.configs),n=e?.configKeys?t.filter(([t])=>e.configKeys?.includes(t)):t;return Object.fromEntries(n.map(([t,n])=>[t,this.configEvaluator.evaluate(n,{context:e?.context,metadata:this.metaContext})]))}closeConnection(){this.logger.debug(`[ConfigDirectorClient] closeConnection() has been called, closing connection to server`),this.transport.close(),this.ready=!1}dispose(){this.removeAllObservers(),this.closeConnection(),this.usageEventCollector.close().catch(e=>{this.logger.warn(`[ConfigDirectorClient] Error flushing telemetry while disposing the client: `,e)})}};const ke=(e,t)=>new Oe(e,{sdkName:`js-server-sdk`,sdkVersion:`1.7.0`},t),Ae=(e,t)=>X(e,t);exports.createClient=ke,exports.createConsoleLogger=Ae;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./DefaultConfigDirectorClient-BZu8tv38.cjs`),t=(t,n)=>new e.t(t,{sdkName:`js-server-sdk`,sdkVersion:`1.9.0`},n),n=(t,n)=>e.n(t,n);exports.createClient=t,exports.createConsoleLogger=n;
|