@configdirector/server-sdk 1.9.1 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -3
- package/dist/DefaultConfigDirectorClient-CJqto-ZO.mjs +6 -0
- package/dist/DefaultConfigDirectorClient-CJqto-ZO.mjs.map +1 -0
- package/dist/DefaultConfigDirectorClient-Cr8DoZII.cjs +5 -0
- package/dist/configdirector-server-testing.cjs +1 -1
- package/dist/configdirector-server-testing.d.cts +4 -2
- package/dist/configdirector-server-testing.d.cts.map +1 -1
- package/dist/configdirector-server-testing.d.mts +4 -2
- 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 +1 -1
- package/dist/configdirector-server.d.mts +1 -1
- package/dist/configdirector-server.mjs +1 -1
- package/dist/configdirector-server.mjs.map +1 -1
- package/dist/{types-CcUNxeqN.d.cts → types-BvNBpCHC.d.mts} +23 -10
- package/dist/types-BvNBpCHC.d.mts.map +1 -0
- package/dist/{types-BqIJGXWv.d.mts → types-KjDfmG_p.d.cts} +23 -10
- package/dist/types-KjDfmG_p.d.cts.map +1 -0
- package/package.json +1 -1
- package/dist/DefaultConfigDirectorClient-B1vsd-g7.cjs +0 -5
- package/dist/DefaultConfigDirectorClient-BH0eGfm_.mjs +0 -6
- package/dist/DefaultConfigDirectorClient-BH0eGfm_.mjs.map +0 -1
- package/dist/types-BqIJGXWv.d.mts.map +0 -1
- package/dist/types-CcUNxeqN.d.cts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./DefaultConfigDirectorClient-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./DefaultConfigDirectorClient-Cr8DoZII.cjs`);let t=require(`node:events`);t=e.a(t);const n=(t,n)=>{if(t.trim().length==0)throw new e.i(`Invalid config key. The key of a test value cannot be empty.`);return r(t,n)},r=(t,n)=>{switch(typeof n){case`boolean`:return{type:`boolean`,value:n?`true`:`false`};case`number`:return i(t,n);case`string`:return{type:`string`,value:n};case`object`:if(n!==null)return o(t,n,``),{type:`json`,value:JSON.stringify(n)}}throw new e.i(`Invalid test value for '${t}': ${l(n)}. Use a boolean, a number, a string, a plain object, or an array.`)},i=(t,n)=>{if(!Number.isFinite(n))throw new e.i(`Invalid test value for '${t}': ${l(n)} is not a finite number.`);if(Number.isInteger(n)){if(!Number.isSafeInteger(n))throw new e.i(`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:a(n)}},a=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}`},o=(e,t,n)=>{if(!(t===null||typeof t==`boolean`||typeof t==`string`)){if(typeof t==`number`){if(!Number.isFinite(t))throw s(e,n,`${l(t)} is not a finite number`);return}if(Array.isArray(t)){t.forEach((t,r)=>o(e,t,`${n}[${r}]`));return}if(c(t)){for(let[r,i]of Object.entries(t))o(e,i,n?`${n}.${r}`:r);return}throw s(e,n,`${l(t)} cannot be encoded as JSON`)}},s=(t,n,r)=>new e.i(`Invalid test value for '${t}'${n?` at '${n}'`:``}: ${r}. JSON contents can hold booleans, finite numbers, strings, null, arrays, and plain objects.`),c=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},l=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),u=(e,t)=>{let r=n(e,t);return{id:`test-config:${e}`,key:e,type:r.type,variations:[{name:null,value:r.value}],target:{defaultValue:r.value,rules:[]}}},d={environmentId:`test-environment`,projectId:`test-project`};var f=class{constructor(e,n){this.logger=e,this.emitter=new t.default,this.configs=new Map,this.pendingDeliveries=[],this.armed=`nothing`,this.connected=!1,this.delivering=!1,this.encodeAll(n).forEach((e,t)=>this.configs.set(t,e))}setValue(e,t){let n=u(e,t);this.configs.set(e,n),this.deliverIfConnected({...d,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 e.r(`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{...d,kind:`full`,configs:Object.fromEntries(this.configs)}}encodeAll(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,u(n,r));return t}};const p={start:()=>{},evaluatedConfig:()=>{},recordInvalidContext:()=>`new-kind-sample`,close:async()=>{}};var m=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 h=(t,n)=>{let r=n?.logger??e.n(),i=new f(r,n?.values??{});return new m(new e.t(`test-client`,t,{logger:r,connection:{timeout:n?.timeout}},{transport:i,telemetry:p}),i)},g=e=>h({sdkName:`js-server-sdk`,sdkVersion:`1.10.0`},e);exports.ConfigDirectorConnectionError=e.r,exports.ConfigDirectorValidationError=e.i,exports.createTestClient=g;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as ConfigDirectorLogger, t as ConfigDirectorClient } from "./types-
|
|
1
|
+
import { a as ConfigDirectorLogger, t as ConfigDirectorClient } from "./types-KjDfmG_p.cjs";
|
|
2
2
|
|
|
3
3
|
//#region ../shared/src/testing/values.d.ts
|
|
4
4
|
type TestJsonValue = boolean | number | string | null | TestJsonValue[] | {
|
|
@@ -27,7 +27,9 @@ type TestClientOptions = {
|
|
|
27
27
|
*/
|
|
28
28
|
timeout?: number;
|
|
29
29
|
/**
|
|
30
|
-
* The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level.
|
|
30
|
+
* The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level. Since
|
|
31
|
+
* the test client sends no telemetry, every read that supplies a context with an invalid kind
|
|
32
|
+
* logs an error, rather than each invalid kind once per telemetry interval.
|
|
31
33
|
*/
|
|
32
34
|
logger?: ConfigDirectorLogger;
|
|
33
35
|
};
|
|
@@ -1 +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;;;
|
|
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;;;AAEvF;;ECuBE,MAAA,GAAS,oBAAA;AAAA;;;;;AAlBX;;;;UA6BiB,UAAA;EAtBN;;;;EAAA,SA2BA,MAAA,EAAQ,oBAAA;EAhBY;AAW/B;;;EAWE,QAAA,CAAS,GAAA,UAAa,KAAA,EAAO,SAAA;EAAA;;;;EAM7B,WAAA,CAAY,GAAA;EAZK;;;;EAkBjB,aAAA,CAAc,MAAA,EAAQ,UAAA;EANtB;;;;EAYA,kBAAA;EAAA;;;;EAMA,sBAAA;;;;AC5EF;EDkFE,kBAAA;AAAA;;;cClFW,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"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as ConfigDirectorLogger, t as ConfigDirectorClient } from "./types-
|
|
1
|
+
import { a as ConfigDirectorLogger, t as ConfigDirectorClient } from "./types-BvNBpCHC.mjs";
|
|
2
2
|
|
|
3
3
|
//#region ../shared/src/testing/values.d.ts
|
|
4
4
|
type TestJsonValue = boolean | number | string | null | TestJsonValue[] | {
|
|
@@ -27,7 +27,9 @@ type TestClientOptions = {
|
|
|
27
27
|
*/
|
|
28
28
|
timeout?: number;
|
|
29
29
|
/**
|
|
30
|
-
* The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level.
|
|
30
|
+
* The logger the SDK client uses. Defaults to the SDK's console logger at `warn` level. Since
|
|
31
|
+
* the test client sends no telemetry, every read that supplies a context with an invalid kind
|
|
32
|
+
* logs an error, rather than each invalid kind once per telemetry interval.
|
|
31
33
|
*/
|
|
32
34
|
logger?: ConfigDirectorLogger;
|
|
33
35
|
};
|
|
@@ -1 +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;;;
|
|
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;;;AAEvF;;ECuBE,MAAA,GAAS,oBAAA;AAAA;;;;;AAlBX;;;;UA6BiB,UAAA;EAtBN;;;;EAAA,SA2BA,MAAA,EAAQ,oBAAA;EAhBY;AAW/B;;;EAWE,QAAA,CAAS,GAAA,UAAa,KAAA,EAAO,SAAA;EAAA;;;;EAM7B,WAAA,CAAY,GAAA;EAZK;;;;EAkBjB,aAAA,CAAc,MAAA,EAAQ,UAAA;EANtB;;;;EAYA,kBAAA;EAAA;;;;EAMA,sBAAA;;;;AC5EF;EDkFE,kBAAA;AAAA;;;cClFW,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"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{i as e,n as t,r as n,t as r}from"./DefaultConfigDirectorClient-
|
|
1
|
+
import{i as e,n as t,r as n,t as r}from"./DefaultConfigDirectorClient-CJqto-ZO.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:()=>{},recordInvalidContext:()=>`new-kind-sample`,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.10.0`},e);export{n as ConfigDirectorConnectionError,e as ConfigDirectorValidationError,y as createTestClient};
|
|
2
2
|
//# sourceMappingURL=configdirector-server-testing.mjs.map
|
|
@@ -1 +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?: TestClientOptions): TestClient => {\n return createInMemoryTestClient({ sdkName: \"js-server-sdk\", sdkVersion: \"__VERSION__\" }, options);\n};\n"],"mappings":"+GAWA,MAAaA,GAAmB,EAAa,IAAuC,CAClF,GAAI,EAAI,MAAM,CAAC,QAAU,EACvB,MAAM,IAAI,EAA8B,+DAA+D,CAEzG,OAAO,EAAO,EAAK,EAAM,EAGrB,GAAU,EAAa,IAAuC,CAClE,OAAQ,OAAO,EAAf,CACE,IAAK,UACH,MAAO,CAAE,KAAM,UAAW,MAAO,EAAQ,OAAS,QAAS,CAC7D,IAAK,SACH,OAAO,EAAa,EAAK,EAAM,CACjC,IAAK,SACH,MAAO,CAAE,KAAM,SAAU,QAAO,CAClC,IAAK,SACH,GAAI,IAAU,KAEZ,OADA,EAAmB,EAAK,EAAO,GAAG,CAC3B,CAAE,KAAM,OAAQ,MAAO,KAAK,UAAU,EAAM,CAAE,CAG3D,MAAM,IAAI,EACR,2BAA2B,EAAI,KAAK,EAAS,EAAM,CAAC,mEACrD,EAGG,GAAgB,EAAa,IAAoC,CACrE,GAAI,CAAC,OAAO,SAAS,EAAM,CACzB,MAAM,IAAI,EAA8B,2BAA2B,EAAI,KAAK,EAAS,EAAM,CAAC,0BAA0B,CAExH,GAAI,OAAO,UAAU,EAAM,CAAE,CAC3B,GAAI,CAAC,OAAO,cAAc,EAAM,CAC9B,MAAM,IAAI,EACR,2BAA2B,EAAI,KAAK,EAAM,oEAC3C,CAEH,MAAO,CAAE,KAAM,UAAW,MAAO,OAAO,EAAM,CAAE,CAElD,MAAO,CAAE,KAAM,QAAS,MAAO,EAAe,EAAM,CAAE,EAGlD,EAAkB,GAA0B,CAChD,IAAM,EAAO,OAAO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1B,MAAaC,GAAoB,EAAmC,IAA4C,CAC9G,IAAM,EAAS,GAAS,QAAU,GAAqB,CACjD,EAAa,IAAI,EAAmB,EAAQ,GAAS,QAAU,EAAE,CAAC,CAOxE,OAAO,IAAI,EANI,IAAI,EACjB,cACA,EACA,CAAE,SAAQ,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
|
+
{"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. Since\n * the test client sends no telemetry, every read that supplies a context with an invalid kind\n * logs an error, rather than each invalid kind once per telemetry interval.\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 recordInvalidContext: () => \"new-kind-sample\",\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?: TestClientOptions): TestClient => {\n return createInMemoryTestClient({ sdkName: \"js-server-sdk\", sdkVersion: \"__VERSION__\" }, options);\n};\n"],"mappings":"+GAWA,MAAaA,GAAmB,EAAa,IAA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B,GACxB,EAAyB,CAAE,QAAS,gBAAiB,WAAY,SAAe,CAAE,EAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./DefaultConfigDirectorClient-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./DefaultConfigDirectorClient-Cr8DoZII.cjs`),t=(t,n)=>new e.t(t,{sdkName:`js-server-sdk`,sdkVersion:`1.10.0`},n),n=(t,n)=>e.n(t,n);exports.createClient=t,exports.createConsoleLogger=n;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as ConfigDirectorLogger, c as ConfigValueType, i as ConfigDirectorLogMessageDecorator, n as ConfigDirectorClientOptions, o as ConfigDirectorLoggingLevel, r as ConfigDirectorContext, s as ConfigDirectorMetaContext, t as ConfigDirectorClient } from "./types-
|
|
1
|
+
import { a as ConfigDirectorLogger, c as ConfigValueType, i as ConfigDirectorLogMessageDecorator, n as ConfigDirectorClientOptions, o as ConfigDirectorLoggingLevel, r as ConfigDirectorContext, s as ConfigDirectorMetaContext, t as ConfigDirectorClient } from "./types-KjDfmG_p.cjs";
|
|
2
2
|
|
|
3
3
|
//#region ../shared/src/logger.d.ts
|
|
4
4
|
declare class DefaultConsoleLogger implements ConfigDirectorLogger {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as ConfigDirectorLogger, c as ConfigValueType, i as ConfigDirectorLogMessageDecorator, n as ConfigDirectorClientOptions, o as ConfigDirectorLoggingLevel, r as ConfigDirectorContext, s as ConfigDirectorMetaContext, t as ConfigDirectorClient } from "./types-
|
|
1
|
+
import { a as ConfigDirectorLogger, c as ConfigValueType, i as ConfigDirectorLogMessageDecorator, n as ConfigDirectorClientOptions, o as ConfigDirectorLoggingLevel, r as ConfigDirectorContext, s as ConfigDirectorMetaContext, t as ConfigDirectorClient } from "./types-BvNBpCHC.mjs";
|
|
2
2
|
|
|
3
3
|
//#region ../shared/src/logger.d.ts
|
|
4
4
|
declare class DefaultConsoleLogger implements ConfigDirectorLogger {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{n as e,t}from"./DefaultConfigDirectorClient-
|
|
1
|
+
import{n as e,t}from"./DefaultConfigDirectorClient-CJqto-ZO.mjs";const n=(e,n)=>new t(e,{sdkName:`js-server-sdk`,sdkVersion:`1.10.0`},n),r=(t,n)=>e(t,n);export{n as createClient,r as createConsoleLogger};
|
|
2
2
|
//# sourceMappingURL=configdirector-server.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configdirector-server.mjs","names":[],"sources":["../src/api.ts"],"sourcesContent":["import type { ConfigDirectorLoggingLevel, ConfigDirectorLogMessageDecorator } from \"@shared/types\";\nimport { DefaultConfigDirectorClient } from \"./DefaultConfigDirectorClient\";\nimport type { ConfigDirectorClient, ConfigDirectorClientOptions } from \"./types\";\nimport { createDefaultLogger } from \"./logger\";\n\n/**\n * Instantiates a ConfigDirector client to be used in a server environment. This function returns an\n * uninitialized client and does not make any network calls. You must call {@link ConfigDirectorClient.initialize}\n * before the client is ready to use:\n *\n * @param serverSdkKey string - The ConfigDirector server SDK key. This is a secret value, do not commit it\n * in your source code.\n * @param clientOptions {@link ConfigDirectorClientOptions} - Configuration options for the client (optional).\n * It is recommended that you include the {@link ConfigDirectorClientOptions.metadata} option including your `appName` and `appVersion` in order\n * to use those values in targeting rules.\n * @returns An uninitialized {@link ConfigDirectorClient} instance\n *\n * @example\n *\n * ```\n * import { createClient } from \"@configdirector/server-sdk\";\n *\n * const client = createClient(\"YOUR-SERVER-SDK-KEY\", {\n * metadata: { appName: \"my-awesome-app\", appVersion: \"1.0.0\" }\n * });\n *\n * await client.initialize();\n * ```\n *\n */\nexport const createClient = (\n serverSdkKey: string,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n return new DefaultConfigDirectorClient(\n serverSdkKey,\n { sdkName: \"js-server-sdk\", sdkVersion: \"__VERSION__\" },\n clientOptions,\n );\n};\n\nexport const createConsoleLogger = (\n level: ConfigDirectorLoggingLevel,\n messageDecorator?: ConfigDirectorLogMessageDecorator,\n) => {\n return createDefaultLogger(level, messageDecorator);\n};\n"],"mappings":"iEA8BA,MAAa,GACX,EACA,IAEO,IAAI,EACT,EACA,CAAE,QAAS,gBAAiB,WAAY,
|
|
1
|
+
{"version":3,"file":"configdirector-server.mjs","names":[],"sources":["../src/api.ts"],"sourcesContent":["import type { ConfigDirectorLoggingLevel, ConfigDirectorLogMessageDecorator } from \"@shared/types\";\nimport { DefaultConfigDirectorClient } from \"./DefaultConfigDirectorClient\";\nimport type { ConfigDirectorClient, ConfigDirectorClientOptions } from \"./types\";\nimport { createDefaultLogger } from \"./logger\";\n\n/**\n * Instantiates a ConfigDirector client to be used in a server environment. This function returns an\n * uninitialized client and does not make any network calls. You must call {@link ConfigDirectorClient.initialize}\n * before the client is ready to use:\n *\n * @param serverSdkKey string - The ConfigDirector server SDK key. This is a secret value, do not commit it\n * in your source code.\n * @param clientOptions {@link ConfigDirectorClientOptions} - Configuration options for the client (optional).\n * It is recommended that you include the {@link ConfigDirectorClientOptions.metadata} option including your `appName` and `appVersion` in order\n * to use those values in targeting rules.\n * @returns An uninitialized {@link ConfigDirectorClient} instance\n *\n * @example\n *\n * ```\n * import { createClient } from \"@configdirector/server-sdk\";\n *\n * const client = createClient(\"YOUR-SERVER-SDK-KEY\", {\n * metadata: { appName: \"my-awesome-app\", appVersion: \"1.0.0\" }\n * });\n *\n * await client.initialize();\n * ```\n *\n */\nexport const createClient = (\n serverSdkKey: string,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n return new DefaultConfigDirectorClient(\n serverSdkKey,\n { sdkName: \"js-server-sdk\", sdkVersion: \"__VERSION__\" },\n clientOptions,\n );\n};\n\nexport const createConsoleLogger = (\n level: ConfigDirectorLoggingLevel,\n messageDecorator?: ConfigDirectorLogMessageDecorator,\n) => {\n return createDefaultLogger(level, messageDecorator);\n};\n"],"mappings":"iEA8BA,MAAa,GACX,EACA,IAEO,IAAI,EACT,EACA,CAAE,QAAS,gBAAiB,WAAY,SAAe,CACvD,EACD,CAGU,GACX,EACA,IAEO,EAAoB,EAAO,EAAiB"}
|
|
@@ -32,27 +32,40 @@ type ConfigEvaluation = {
|
|
|
32
32
|
context?: ConfigDirectorContext;
|
|
33
33
|
};
|
|
34
34
|
/**
|
|
35
|
-
* The
|
|
36
|
-
*
|
|
35
|
+
* The context to be sent to ConfigDirector: the user or other entity, such as a device or an
|
|
36
|
+
* organization, that configs are evaluated for. This context will be used for targeting rules
|
|
37
|
+
* evaluation.
|
|
37
38
|
*/
|
|
38
39
|
type ConfigDirectorContext = {
|
|
39
40
|
/**
|
|
40
|
-
* The
|
|
41
|
-
*
|
|
41
|
+
* The context's identifier. This should be a value that uniquely identifies the user or other
|
|
42
|
+
* entity among contexts of the same {@link kind}.
|
|
42
43
|
* In the case of anonymous users, you could generate a UUID or alternatively not provide
|
|
43
44
|
* the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
|
|
44
|
-
* value is used for segmenting
|
|
45
|
-
* could result in the
|
|
45
|
+
* value is used for segmenting contexts in percentage rollouts, and changes to the {@link id}
|
|
46
|
+
* could result in the context being assigned to a different percentile.
|
|
46
47
|
*/
|
|
47
48
|
id?: string;
|
|
48
49
|
/**
|
|
49
|
-
* The
|
|
50
|
+
* The kind of entity this context represents, such as `user`, `device`, `organization`,
|
|
51
|
+
* `tenant` or `listing`. You can use any other kind that fits your application. A kind has 1
|
|
52
|
+
* to 64 characters, using only lowercase letters (`a`-`z`), digits, `-` and `_`. It is used
|
|
53
|
+
* exactly as given, without trimming or changing its case.
|
|
54
|
+
*
|
|
55
|
+
* A context with an invalid kind is ignored as a whole: the SDK logs an error and evaluates
|
|
56
|
+
* as if no context had been provided.
|
|
57
|
+
*
|
|
58
|
+
* @default "user"
|
|
59
|
+
*/
|
|
60
|
+
kind?: string;
|
|
61
|
+
/**
|
|
62
|
+
* The context's display name. This will be shown in the ConfigDirector dashboard and may be
|
|
50
63
|
* used for targeting rules.
|
|
51
64
|
*/
|
|
52
65
|
name?: string;
|
|
53
66
|
/**
|
|
54
|
-
* Any arbitrary traits for the
|
|
55
|
-
*
|
|
67
|
+
* Any arbitrary traits for the context. They will be shown in the ConfigDirector dashboard
|
|
68
|
+
* and may be used for targeting rules.
|
|
56
69
|
*/
|
|
57
70
|
traits?: {
|
|
58
71
|
[key: string]: unknown;
|
|
@@ -289,4 +302,4 @@ interface ConfigDirectorClient {
|
|
|
289
302
|
}
|
|
290
303
|
//#endregion
|
|
291
304
|
export { ConfigDirectorLogger as a, ConfigValueType as c, ConfigDirectorLogMessageDecorator as i, ConfigDirectorClientOptions as n, ConfigDirectorLoggingLevel as o, ConfigDirectorContext as r, ConfigDirectorMetaContext as s, ConfigDirectorClient as t };
|
|
292
|
-
//# sourceMappingURL=types-
|
|
305
|
+
//# sourceMappingURL=types-BvNBpCHC.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-BvNBpCHC.d.mts","names":[],"sources":["../../shared/src/types.ts","../src/types.ts"],"mappings":";cAAa,cAAA;AAAA,KAUD,UAAA,WAAqB,cAAA;AAAA,KAErB,kBAAA;EAAA,CAAwB,GAAA;AAAA;AAAA,KAExB,eAAA,wCAAuD,kBAAA;AAAA,KAEvD,WAAA;EACV,EAAA;EACA,GAAA;EACA,IAAA,EAAM,UAAA;EACN,KAAA;EACA,OAAA;AAAA;AAAA,KAQU,0BAAA;AAAA,UAEK,oBAAA;EACf,KAAA,CAAM,OAAA,aAAoB,IAAA;EAE1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,KAAA,CAAM,OAAA,aAAoB,IAAA;AAAA;AAAA,UAGX,iCAAA;EACf,eAAA,CAAgB,OAAA;AAAA;AAAA,KAGN,gBAAA;AAAA,KAUA,gBAAA;EACV,GAAA;EACA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A,CAAa,MAAA;AAAA,KAExE,YAAA,WAAuB,eAAA,KAAoB,OAAA,EAAS,CAAA;;;;;;;UAQ/C,oBAAA;EAxBO;;;;;;;;;;;EAoCtB,UAAA,IAAc,OAAA;EAhCY;;;AAG5B;;;EAH4B,IAwCtB,OAAA;EApCuC;;;;;;;;;;EAgD3C,QAAA,WAAmB,eAAA,EAAiB,SAAA,UAAmB,YAAA,EAAc,CAAA,EAAG,OAAA,GAAU,qBAAA,GAAwB,CAAA;EAhD/D;;;;;;;;;;;;EA8D3C,KAAA,WAAgB,eAAA,EACd,SAAA,UACA,YAAA,EAAc,CAAA,EACd,QAAA,EAAU,YAAA,CAAa,CAAA,GACvB,OAAA,GAAU,qBAAA;EA5DS;;;;;;;;EAuErB,OAAA,WAAkB,eAAA,EAAiB,SAAA,UAAmB,QAAA,GAAW,YAAA,CAAa,CAAA;EAvET;;;EA4ErE,UAAA;EA5EyF;AAE3F;;;;;;EAmFE,aAAA,CAAc,OAAA;IACZ,OAAA,GAAU,qBAAA;IACV,UAAA;EAAA,IACE,MAAA,SAAe,WAAA;EAEnB,EAAA,iBAAmB,YAAA,EAAc,SAAA,EAAW,CAAA,EAAG,OAAA,GAAU,IAAA,EAAM,YAAA,CAAa,CAAA;EAE5E,GAAA,iBAAoB,YAAA,EAAc,SAAA,EAAW,CAAA,EAAG,OAAA,IAAW,IAAA,EAAM,YAAA,CAAa,CAAA;EAlF3C;;;;;;EA0FnC,OAAA;AAAA"}
|
|
@@ -32,27 +32,40 @@ type ConfigEvaluation = {
|
|
|
32
32
|
context?: ConfigDirectorContext;
|
|
33
33
|
};
|
|
34
34
|
/**
|
|
35
|
-
* The
|
|
36
|
-
*
|
|
35
|
+
* The context to be sent to ConfigDirector: the user or other entity, such as a device or an
|
|
36
|
+
* organization, that configs are evaluated for. This context will be used for targeting rules
|
|
37
|
+
* evaluation.
|
|
37
38
|
*/
|
|
38
39
|
type ConfigDirectorContext = {
|
|
39
40
|
/**
|
|
40
|
-
* The
|
|
41
|
-
*
|
|
41
|
+
* The context's identifier. This should be a value that uniquely identifies the user or other
|
|
42
|
+
* entity among contexts of the same {@link kind}.
|
|
42
43
|
* In the case of anonymous users, you could generate a UUID or alternatively not provide
|
|
43
44
|
* the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
|
|
44
|
-
* value is used for segmenting
|
|
45
|
-
* could result in the
|
|
45
|
+
* value is used for segmenting contexts in percentage rollouts, and changes to the {@link id}
|
|
46
|
+
* could result in the context being assigned to a different percentile.
|
|
46
47
|
*/
|
|
47
48
|
id?: string;
|
|
48
49
|
/**
|
|
49
|
-
* The
|
|
50
|
+
* The kind of entity this context represents, such as `user`, `device`, `organization`,
|
|
51
|
+
* `tenant` or `listing`. You can use any other kind that fits your application. A kind has 1
|
|
52
|
+
* to 64 characters, using only lowercase letters (`a`-`z`), digits, `-` and `_`. It is used
|
|
53
|
+
* exactly as given, without trimming or changing its case.
|
|
54
|
+
*
|
|
55
|
+
* A context with an invalid kind is ignored as a whole: the SDK logs an error and evaluates
|
|
56
|
+
* as if no context had been provided.
|
|
57
|
+
*
|
|
58
|
+
* @default "user"
|
|
59
|
+
*/
|
|
60
|
+
kind?: string;
|
|
61
|
+
/**
|
|
62
|
+
* The context's display name. This will be shown in the ConfigDirector dashboard and may be
|
|
50
63
|
* used for targeting rules.
|
|
51
64
|
*/
|
|
52
65
|
name?: string;
|
|
53
66
|
/**
|
|
54
|
-
* Any arbitrary traits for the
|
|
55
|
-
*
|
|
67
|
+
* Any arbitrary traits for the context. They will be shown in the ConfigDirector dashboard
|
|
68
|
+
* and may be used for targeting rules.
|
|
56
69
|
*/
|
|
57
70
|
traits?: {
|
|
58
71
|
[key: string]: unknown;
|
|
@@ -289,4 +302,4 @@ interface ConfigDirectorClient {
|
|
|
289
302
|
}
|
|
290
303
|
//#endregion
|
|
291
304
|
export { ConfigDirectorLogger as a, ConfigValueType as c, ConfigDirectorLogMessageDecorator as i, ConfigDirectorClientOptions as n, ConfigDirectorLoggingLevel as o, ConfigDirectorContext as r, ConfigDirectorMetaContext as s, ConfigDirectorClient as t };
|
|
292
|
-
//# sourceMappingURL=types-
|
|
305
|
+
//# sourceMappingURL=types-KjDfmG_p.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types-KjDfmG_p.d.cts","names":[],"sources":["../../shared/src/types.ts","../src/types.ts"],"mappings":";cAAa,cAAA;AAAA,KAUD,UAAA,WAAqB,cAAA;AAAA,KAErB,kBAAA;EAAA,CAAwB,GAAA;AAAA;AAAA,KAExB,eAAA,wCAAuD,kBAAA;AAAA,KAEvD,WAAA;EACV,EAAA;EACA,GAAA;EACA,IAAA,EAAM,UAAA;EACN,KAAA;EACA,OAAA;AAAA;AAAA,KAQU,0BAAA;AAAA,UAEK,oBAAA;EACf,KAAA,CAAM,OAAA,aAAoB,IAAA;EAE1B,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,IAAA,CAAK,OAAA,aAAoB,IAAA;EAEzB,KAAA,CAAM,OAAA,aAAoB,IAAA;AAAA;AAAA,UAGX,iCAAA;EACf,eAAA,CAAgB,OAAA;AAAA;AAAA,KAGN,gBAAA;AAAA,KAUA,gBAAA;EACV,GAAA;EACA,KAAA,EAAO,eAAA;EACP,OAAA;EACA,cAAA;EACA,MAAA,EAAQ,gBAAA;EACR,OAAA,GAAU,qBAAA;AAAA;;;AA9BZ;;;KAqCY,qBAAA;EApCV;;;;;;;;EA6CA,EAAA;EAvCA;;;;;AAGF;;;;;AAIA;EA6CE,IAAA;;;;AAnCF;EAyCE,IAAA;;;;;EAMA,MAAA;IAAA,CAAY,GAAA;EAAA;EA7CZ;;;;;;;EAsDA,SAAA;AAAA;;AA3CF;;;KAkDY,yBAAA;EACV,UAAA;EACA,OAAA;AAAA;AAAA,KAGU,cAAA;;;;;AAjHZ;KCkBY,2BAAA;;;;EAIV,QAAA,GAAW,yBAAA;EDpBiB;;;ECwB5B,UAAA;IDtBU;;;;;AAEZ;;;;IC8BI,IA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kB,eAAA,EAAiB,SAAA,UAAmB,QAAA,GAAW,YAAA,CAAa,CAAA;EAvET;;;EA4ErE,UAAA;EA5EyF;AAE3F;;;;;;EAmFE,aAAA,CAAc,OAAA;IACZ,OAAA,GAAU,qBAAA;IACV,UAAA;EAAA,IACE,MAAA,SAAe,WAAA;EAEnB,EAAA,iBAAmB,YAAA,EAAc,SAAA,EAAW,CAAA,EAAG,OAAA,GAAU,IAAA,EAAM,YAAA,CAAa,CAAA;EAE5E,GAAA,iBAAoB,YAAA,EAAc,SAAA,EAAW,CAAA,EAAG,OAAA,IAAW,IAAA,EAAM,YAAA,CAAa,CAAA;EAlF3C;;;;;;EA0FnC,OAAA;AAAA"}
|
package/package.json
CHANGED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`node:events`);c=s(c);let l=require(`node:crypto`),u=require(`luxon`),d=require(`semver`);d=s(d);let ee=require(`rapidhash-js`);var f=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},p=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},m=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},h=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},g=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},_=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},v=class{constructor(e){this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=e.onEvent??(()=>{}),this.onRetry=e.onRetry,this.onComment=e.onComment}parse(e){let t=e;this.isFirstChunk&&(this.isFirstChunk=!1,t.startsWith(``)?t=t.slice(1):t.startsWith(``)&&(t=t.slice(3)));let n=this.scanLines(this.bufferedInput+t);for(let e of n)this.dispatchLine(e)}finish(){this.bufferedInput=``}scanLines(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];i===`\r`||i===`
|
|
2
|
-
`?(t.push(e.slice(n,r)),i===`\r`&&e[r+1]===`
|
|
3
|
-
`&&r++,r++,n=r):r++}return this.bufferedInput=e.slice(n),t}dispatchLine(e){if(e.startsWith(`:`)){this.onComment?.(this.extractValue(e,1));return}if(e===``){this.emitEvent();return}this.applyField(this.parseField(e))}emitEvent(){let e=this.currentEvent.data.endsWith(`
|
|
4
|
-
`)?this.currentEvent.data.slice(0,-1):this.currentEvent.data;e!==``&&this.onEvent({...this.currentEvent,id:this.lastEventId,data:e}),this.currentEvent={data:``}}applyField(e){switch(e.field){case`event`:this.currentEvent.type=e.value;break;case`data`:this.currentEvent.data+=e.value+`
|
|
5
|
-
`;break;case`id`:e.value.includes(`\0`)||(this.lastEventId=e.value);break;case`retry`:/^\d+$/.test(e.value)&&this.onRetry?.(Number.parseInt(e.value,10));break;default:break}}parseField(e){let t=e.indexOf(`:`);return t===-1?{field:e,value:``}:{field:e.slice(0,t),value:this.extractValue(e,t+1)}}extractValue(e,t){return e[t]===` `?e.slice(t+1):e.slice(t)}};let y=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var b=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=y.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers={Accept:`text/event-stream`,...e.headers};let t=e.body;this.body=typeof t==`function`?t:()=>t,this.requestOptions={method:e.method??`GET`,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=e.fetch??((e,t)=>fetch(e,t)),this._onError=this.resolveCallback(e.onError,()=>{},`onError`),this._onConnect=this.resolveCallback(e.onConnect,()=>{},`onConnect`),this._onDisconnect=this.resolveCallback(e.onDisconnect,()=>{},`onDisconnect`),this._onMessage=this.resolveCallback(e.onMessage,()=>{},`onMessage`),this._onComment=this.resolveCallback(e.onComment,()=>{},`onComment`),this._shouldReconnect=this.resolveCallback(e.shouldReconnect,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`),this._calculateReconnectDelay=this.resolveCallback(e.calculateReconnectDelay,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`calculateReconnectDelay`)}set onError(e){this._onError=this.resolveCallback(e,()=>{},`onError`)}set onMessage(e){this._onMessage=this.resolveCallback(e,()=>{},`onMessage`)}set onComment(e){this._onComment=this.resolveCallback(e,()=>{},`onComment`)}set onConnect(e){this._onConnect=this.resolveCallback(e,()=>{},`onConnect`)}set onDisconnect(e){this._onDisconnect=this.resolveCallback(e,()=>{},`onDisconnect`)}set shouldReconnect(e){this._shouldReconnect=this.resolveCallback(e,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`)}set calculateReconnectDelay(e){this._calculateReconnectDelay=this.resolveCallback(e,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`shouldReconnect`)}get readyState(){return this._readyState}connect(){this._readyState===y.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=y.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=y.CONNECTING,this._fetch(this.url,{...this.requestOptions,body:this.body(),headers:this.buildRequestHeaders(),signal:this.abortController.signal,cache:`no-store`}).then(e=>this.handleFetchResponse(e)).catch(e=>{if(e.name===`AbortError`||this.abortController.signal.aborted){this.close();return}this._onError(e),this.scheduleReconnect({error:e})})}async handleFetchResponse(e){let{body:t,status:n}=e;if(n===204){this.disconnected();return}if(n>=400){this.scheduleReconnect({status:n});return}if(!t)throw new h(`The server response did not have a body`);this._readyState=y.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new v({onEvent:e=>{typeof e.id==`string`&&(this.lastEventId=e.id),this._onMessage(e)},onComment:e=>this._onComment(e),onRetry:e=>this.serverReconnectionTime=e});await this.readResponseStream(t,r),this.scheduleReconnect({status:n,error:new m(`The server response stream was closed`)})}async readResponseStream(e,t){let n=e.getReader(),r=new TextDecoder,i=!1;for(;!i;){let e=await n.read();e.value&&t.parse(r.decode(e.value,{stream:!0})),i=e.done}t.finish()}disconnected(){clearTimeout(this.reconnectTimeout),this._readyState=y.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return{...this.headers,...e}}scheduleReconnect(e){if(this.abortController.signal.aborted)return;clearTimeout(this.reconnectTimeout),this.reconnectAttempt+=1;let t={attempt:this.reconnectAttempt,status:e.status,error:e.error,serverReconnectionTime:this.serverReconnectionTime};if(!this._shouldReconnect(t)){this.disconnected();return}this._readyState=y.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new _(`The calculated reconnect delay is out of range: ${n}. Defaulting to ${this.serverReconnectionTime}`)),n=this.serverReconnectionTime),this.reconnectTimeout=setTimeout(()=>this.initiateConnection(),n)}resolveCallback(e,t,n){if(e==null)return t;if(typeof e!=`function`)throw new g(`${n} must be a function`);return e}};const x=e=>new b(e),S=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}},C=9e4;var te=class{constructor(e){this.options=e,this.eventEmitter=new c.EventEmitter,this.options=e,this.logger=e.logger,this.url=new URL(`server/sse/v1`,e.baseUrl),this.heartbeatUrl=new URL(`server/heartbeat/v1`,e.baseUrl)}async connect(e){this.eventSource&&this.close();let t=new Promise((e,t)=>{this.eventSource=x({url:this.url,method:`POST`,headers:{"Content-Type":`application/json`},body:()=>this.buildRequestBody(),onMessage:({data:e})=>{this.dispatchMessage(e)},onConnect:()=>{this.logger.debug(`[StreamingTransport] Connected`),e(this)},shouldReconnect:e=>{let n=!this.isStatusFatal(e.status);if(!n){this.stopHeartbeat();let n=this.prepareFatalError(e.status,e.error);this.eventEmitter.emit(`connectionError`,n),t(n)}return n},calculateReconnectDelay:e=>{let t=2**Math.min(e.attempt,9)*1e3,n=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?this.logger.info(n):this.logger.warn(n),t},onDisconnect:()=>{this.logger.debug(`[StreamingTransport] Disconnected`)}}),this.eventSource.connect()});this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),C);let n;try{return await Promise.race([t,new Promise(t=>{n=setTimeout(()=>t(this),e)})])}finally{clearTimeout(n)}}get sessionId(){return this._sessionId}sendHeartbeat(){!this.isConnected||!this._sessionId||S(C,this.heartbeatUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({serverSdkKey:this.options.serverSdkKey,sessionId:this._sessionId})},this.logger).then(e=>{e.ok||this.logger.debug(`[StreamingTransport] Heartbeat failed with status: ${e.status}`)}).catch(e=>{this.logger.debug(`[StreamingTransport] Heartbeat failed: `,e)})}buildRequestBody(){return this._sessionId=(0,l.randomUUID)(),JSON.stringify({metaContext:this.options.metaContext,serverSdkKey:this.options.serverSdkKey,sessionId:this._sessionId})}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configBundleReceived`,t)}catch(e){this.logger.error(`[StreamingTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,t){let n=e??0;return new f(`${`Connection failed with status: ${e??`unknown`}.`}${t?` Error: ${t}.`:``} This is an unrecoverable error, will not attempt to reconnect.`,n)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}get isConnected(){return this.eventSource?.readyState==`open`}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}clear(){this.eventEmitter.removeAllListeners()}stopHeartbeat(){clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0}close(){this.stopHeartbeat(),this.eventSource?.close()}dispose(){this.close(),this.clear()}},ne=class{constructor(){this.fatalError=!1}clearPollingInterval(){clearInterval(this.pollingInterval)}schedulePollingInterval(e){clearInterval(this.pollingInterval),!(this.pollingIntervalSeconds<=0)&&(this.pollingInterval=setInterval(e,this.pollingIntervalSeconds*1e3))}async handleNonOkResponse(e){if(!e.ok)throw this.isStatusFatal(e.status)?(this.fatalError=!0,this.close(),this.prepareFatalResponseStatusError(e.status,await e.text())):new f(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new f(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new f(`Failed to parse the response from the server: ${e}`):new f(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){let n=e??0;return new f(`${`Connection failed with status: ${e??`unknown`}`}${(t?.trim()?.length??0)>0?` (${t})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,n)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}isFetchErrorFatal(e){return e?.name===`NotAllowedError`}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}},w=class extends ne{constructor(e){super(),this.options=e,this.eventEmitter=new c.EventEmitter,this._sessionId=(0,l.randomUUID)(),this.options=e,this.logger=e.logger,this.url=new URL(`server/polling/v1`,e.baseUrl),this.pollingIntervalSeconds=e.pollingInterval??300}async connect(e){this.clearPollingInterval();try{await this.fetchConfigs(e)}finally{this.fatalError||this.schedulePollingInterval(()=>{this.fetchConfigs(e).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})})}return this}get sessionId(){return this._sessionId}async fetchConfigs(e){if(this.fatalError){this.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let t=await S(e,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({metaContext:this.options.metaContext,serverSdkKey:this.options.serverSdkKey,lastUpdateTimestamp:this.lastUpdateTimestamp,sessionId:this._sessionId})},this.logger);if(await this.handleNonOkResponse(t),t.status===200){let e=JSON.parse(await t.text());this.lastUpdateTimestamp=e.timestamp,this.eventEmitter.emit(`configBundleReceived`,e)}}catch(e){try{this.handleFetchError(e)}catch(e){throw this.fatalError&&this.eventEmitter.emit(`connectionError`,e),e}}}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}clear(){this.eventEmitter.removeAllListeners()}};const T=/^(?:0|[1-9][0-9]*)$/,E=/~(?![01])/,D=Object.prototype.propertyIsEnumerable,re=e=>{if(!E.test(e))return e.replace(/~1/g,`/`).replace(/~0/g,`~`)},ie=(e,t)=>{if(Array.isArray(e))return T.test(t)&&D.call(e,t)?e[Number(t)]:void 0;if(typeof e==`object`&&e)return D.call(e,t)?e[t]:void 0},ae=(e,t)=>{if(e===``)return t;if(!e.startsWith(`/`))return;let n=t;for(let t of e.slice(1).split(`/`)){let e=re(t);if(e===void 0||(n=ie(n,e),n===void 0))return}return n},oe=(e,t,n)=>{let r=n[0];switch(t.toLowerCase()){case`=`:case`equals`:return r!==void 0&&e===r;case`!=`:case`does not equal`:return r!==void 0&&e!==r;case`is one of`:return n.includes(e);case`is not one of`:return!n.includes(e);case`starts with any of`:return n.some(t=>e.startsWith(t));case`does not start with any of`:return!n.some(t=>e.startsWith(t));case`ends with any of`:return n.some(t=>e.endsWith(t));case`does not end with any of`:return!n.some(t=>e.endsWith(t));default:return!1}},se=(e,t,n)=>{let r=t.toLowerCase(),i=O(e);if(i===void 0)return r===`!=`||r===`does not equal`;let a=n[0];if(a===void 0)return!1;let o=O(a);if(o===void 0)return!1;switch(r){case`=`:case`equals`:return i===o;case`!=`:case`does not equal`:return i!==o;case`<`:return i<o;case`<=`:return i<=o;case`>`:return i>o;case`>=`:return i>=o;default:return!1}},O=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(typeof e!=`string`||e.length===0||!ce(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0},ce=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},le=(e,t,n)=>{let r=n[0];if(r===void 0)return!1;let i=k(e),a=k(r);if(i===void 0||a===void 0)return!1;switch(t){case`is after`:return i>a;case`is before`:return i<a;default:return!1}},k=e=>{let t=u.DateTime.fromISO(e,{zone:`utc`});return t.isValid?t.toMillis():void 0},A=(e,t,n)=>{let r=t.toLowerCase();if(e.trim().length===0)return r===`is not one of`;let i=d.coerce(e),a=n.map(e=>d.coerce(e)),o=a[0]??null;switch(r){case`=`:return j(i,o);case`<`:return M(i,o,d.lt);case`<=`:return M(i,o,d.lte);case`>`:return M(i,o,d.gt);case`>=`:return M(i,o,d.gte);case`is one of`:return a.some(e=>j(i,e));case`is not one of`:return!a.some(e=>j(i,e));default:return!1}},j=(e,t)=>e!==null&&t!==null&&d.eq(e,t),M=(e,t,n)=>e!==null&&t!==null&&n(e,t),N=Symbol(`absent`),P=Symbol(`unknown-attribute`),F=e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`,I=e=>e===N||e==null?``:F(e)?L(e):``,L=e=>typeof e==`string`?e:String(e),R=e=>e===N?void 0:e,z=e=>e===P?`unknown-attribute`:e===N?`absent`:F(e)?`scalar`:Array.isArray(e)?`array`:`object`,B=(e,t,n)=>{let r=t.toLowerCase();if(!Array.isArray(e))return r===`does not contain any of`;let i=e.filter(F).map(L);switch(r){case`contains any of`:return i.some(e=>n.includes(e));case`does not contain any of`:return!i.some(e=>n.includes(e));default:return!1}};var V=class{evaluate(e,t){return this.explain(e,t).matched}explain(e,t){let n=this.resolve(e,t),r=z(n),i=n===N||n===P?void 0:n;return n===P?{matched:!1,resolvedValue:i,resolvedType:r}:{matched:this.compare(e,n),resolvedValue:i,resolvedType:r}}compare(e,t){let n=e.targetValues??[];switch(e.targetType){case`text`:return oe(I(t),e.operator,n);case`number`:return se(R(t),e.operator,n);case`datetime`:return le(I(t),e.operator,n);case`semver`:return A(I(t),e.operator,n);case`array`:return B(R(t),e.operator,n)}return!1}resolve(e,t){switch(e.attribute){case`identifier`:return H(t?.context?.id);case`name`:return H(t?.context?.name);case`appName`:return H(t?.metadata?.appName);case`appVersion`:return H(t?.metadata?.appVersion);case`traits`:return e.trait?H(ae(e.trait,t?.context?.traits)):N;default:return P}}};const H=e=>e??N;var U=class{constructor(e){this.conditionEvaluator=e}explain(e,t,n){let r=t?.[e.segmentId];if(r===void 0||!W(r))return{matched:!1,segmentFound:!1,matchedGroupIndex:void 0};let i=this.matchingGroupIndex(r,n),a=i!==void 0;return{matched:this.operatorHolds(e,a),segmentFound:!0,matchedGroupIndex:i}}operatorHolds(e,t){switch(e.operator.toLowerCase()){case`in`:return t;case`not in`:return!t;default:return!1}}matchingGroupIndex(e,t){let n=(e.groups??[]).findIndex(e=>(e??[]).every(e=>this.conditionEvaluator.evaluate(e,t)));return n===-1?void 0:n}};const W=e=>(e.groups??[]).every(e=>(e??[]).every(e=>e.kind===void 0||e.kind===`attribute`)),ue=e=>{let t=`${e.contextIdentifier}-${e.configId}`;return Number((0,ee.rapidhash)(t,{seed:15426857351n})%1000n)/10};var de=class{constructor(e){if(this.logger=e,this.conditionEvaluator=new V,this.segmentEvaluator=new U(this.conditionEvaluator),!e||!e.warn||!e.error||!e.info)throw TypeError(`The provided logger is not a valid 'ConfigDirectorLogger'`);this.logger=e}evaluate(e,t,n){return{id:e.id,key:e.key,type:e.type,value:this.explain(e,t,n).value}}explain(e,t,n){let r=[...e.target?.rules??[]].sort((e,t)=>(e.order??2**53-1)-(t.order??2**53-1)),i=[],a;for(let o of r){if(a){i.push({ruleId:o.id,outcome:`not-evaluated`,conditions:[],bucket:void 0});continue}let r=this.explainRule(o,e,t,n);i.push(r.explanation),r.value!==void 0&&(a={ruleId:o.id,value:r.value})}return{value:a?.value??e.target?.defaultValue,servedBy:a?{kind:`rule`,ruleId:a.ruleId}:{kind:`default`},rules:i}}explainRule(e,t,n,r){let i={ruleId:e.id,outcome:`not-matched`,conditions:[],bucket:void 0};try{let a;return e.type==`percentage`?a=this.explainPercentage(e.percentages??[],t,n,i):e.type==`conditional`&&(a=this.explainConditionalRule(e,t,n,r,i)),a!==void 0&&(i.outcome=`matched`),{explanation:i,value:a}}catch(n){return this.logger.warn(`There was an error while evaluating a targeting rule '${e?.id}' for '${t?.key}'. The rule will be disregarded.`,{error:n,configKey:t?.key,ruleId:e?.id}),{explanation:{ruleId:e.id,outcome:`errored`,conditions:[],bucket:void 0},value:void 0}}}explainPercentage(e,t,n,r){let i=n?.context?.id??void 0,a=i===void 0?0:ue({configId:t.id,contextIdentifier:i}),o=[],s=0,c;for(let t of e){let e=s+t.percentage;o.push({percentageId:t.id,from:s,to:e,value:t.value?.toString()}),c===void 0&&a<e&&(c=t),s=e}return r.bucket={identifier:i,defaultedToPredefinedBucket:i===void 0,assignedPercentage:a,shares:o,selectedPercentageId:c?.id},c?.value==null?void 0:c.value.toString()}explainConditionalRule(e,t,n,r,i){let a=!1;for(let t of e.conditions??[]){if(a){i.conditions.push({conditionId:t.id,outcome:`not-evaluated`});continue}let e=this.explainCondition(t,n,r);i.conditions.push(e),a=e.outcome!==`matched`}if(!a){if(e.target==`value`)return e.value==null?void 0:e.value.toString();if(e.target==`percentage`)return this.explainPercentage(e.percentages??[],t,n,i)}}explainCondition(e,t,n){if(e.kind===`segment`){let r=this.segmentEvaluator.explain(e,n,t);return{conditionId:e.id,kind:`segment`,outcome:r.matched?`matched`:`not-matched`,segmentId:e.segmentId,segmentFound:r.segmentFound,matchedGroupIndex:r.matchedGroupIndex}}let r=this.conditionEvaluator.explain(e,t);return{conditionId:e.id,kind:`attribute`,outcome:r.matched?`matched`:`not-matched`,resolvedValue:r.resolvedValue,resolvedType:r.resolvedType}}};const G=e=>{let t=typeof e;if(t===`object`)try{return e.constructor?.name??t}catch{return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch{return t}return t},K=e=>e===`number`||e===`bigint`,q=new Set([`boolean`,`integer`,`float`]),fe=(e,t)=>{let n=e.value,r=G(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return _e(n,t,r,e.valueId);if(typeof t==`string`)return q.has(e.type)?{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}:{parsedValue:n,parsedValueId:e.valueId,requestedType:r,usedDefault:!1,reason:`found-match`};if(typeof t==`boolean`&&(e.type===`boolean`||e.type===`string`||e.type===`enum`)){let i=pe(n),a=typeof i==`boolean`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-boolean`}}if(K(typeof t)&&e.type===`integer`){let i=me(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}if(K(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=he(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}},pe=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},me=e=>{let t=J(e);return t==null?void 0:Math.trunc(t)},he=e=>J(e),J=e=>{if(!e||!ge(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},ge=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},_e=(e,t,n,r)=>{if(typeof t==`string`)return{parsedValue:e,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`};try{let i=JSON.parse(e);return ve(i,t)?{parsedValue:i,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`}:{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`type-mismatch`}}catch{return{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`invalid-json`}}},ve=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},Y={off:-1,error:0,warn:1,info:2,debug:3},ye=()=>{let e={year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,timeZoneName:`short`};try{return new Intl.DateTimeFormat(void 0,{...e,fractionalSecondDigits:3})}catch{return new Intl.DateTimeFormat(void 0,e)}};var be=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=ye()}debug(e,...t){this.log(console.debug,`debug`,e,...t)}info(e,...t){this.log(console.info,`info`,e,...t)}warn(e,...t){this.log(console.warn,`warn`,e,...t)}error(e,...t){this.log(console.error,`error`,e,...t)}log(e,t,n,...r){Y[this.level]>=Y[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},xe=class{decorateMessage(e){return`[ConfigDirector:js-server-sdk] ${e}`}};const X=(e,t)=>new be(e??`warn`,t??new xe),Se=(e,t)=>new URL(e,t?.toString()),Ce=(e,t)=>e===void 0?{seconds:t.defaultSeconds,warning:void 0}:e>=t.minimumSeconds?{seconds:e,warning:void 0}:{seconds:t.minimumSeconds,warning:`pollingInterval of ${e} seconds is below the minimum of ${t.minimumSeconds} seconds. Using ${t.minimumSeconds} seconds.`},Z=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,Q=e=>{if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch{return{value:e.value.toString(),type:`json`}}}let t=e.value?.toString();return t&&t.length<=500?{value:t}:e.valueId?{valueId:e.valueId}:{value:t}},$=e=>{let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]?.length??0)>0)return!1;return!0},we=e=>{if(!e)return!0;let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]??0)>0)return!1;return!0};var Te=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.sdkIdentity=e.sdkIdentity,this.logger=e.logger,this.metaContext=e.metaContext,this.url=new URL(`server/telemetry/v1`,e.baseUrl.toString())}async report({discreteEvents:e,aggregatedEvents:t,droppedEvents:n}){if(!this.executeRequests)return{success:!1,fatalError:!0};let r={serverSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},discreteEvents:e,aggregatedEvents:t,droppedEvents:n};if(this.isReportEmpty(r))return{success:!0,fatalError:!1};let i=await this.sendReport(r);return i.fatalError&&(this.executeRequests=!1),i}isReportEmpty(e){return $(e.discreteEvents)&&$(e.aggregatedEvents)&&we(e.droppedEvents)}async sendReport(e){try{let t=await S(5e3,this.url,{method:`POST`,body:JSON.stringify(e)},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:!1}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},Ee=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},De=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||=new Date;let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},Oe=class{constructor(e){this.aggregator=new Ee,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new De(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},ke=class extends Map{constructor(e,t){super(t),this._droppedCount=0,this.limit=e,this.enforceLimit()}set(e,t){return super.set(e,t),this.enforceLimit(),this}get droppedCount(){return this._droppedCount}clearAndReset(){this.clear(),this._droppedCount=0}enforceLimit(){for(;this.size>this.limit;){let e=this.keys().next().value;e!==void 0&&(this.delete(e),this._droppedCount+=1)}}},Ae=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(e){let t=await Promise.all(e.events.map(async e=>({...e,defaultValue:await Z(e.defaultValue,this.valueIdGenerator),evaluatedValue:await Z(e.evaluatedValue,this.valueIdGenerator)})));return{...e,events:t}}},je=class extends Oe{constructor(e){super(e),this.reporter=new Te(e),this.contexts=new ke(e.contextLimit??1e3),this.evaluationEventSnapshotPreprocessor=new Ae(e.valueIdGenerator)}evaluatedConfig(e){if(!this.collectEvents)return;e.context?.id&&!e.context.anonymous&&this.contexts.set(e.context.id,e.context);let t={...e.evaluation,contextId:e.context?.anonymous?void 0:e.context?.id};this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(t))}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:Q({value:e.defaultValue,type:e.type}),evaluatedValue:Q({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}snapshotContexts(){let e=Array.from(this.contexts.values()),t=this.contexts.droppedCount;return this.contexts.clearAndReset(),{contexts:e,droppedCount:t}}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot()),t=this.snapshotContexts();return await this.reporter?.report({context:this._context,discreteEvents:{capturedContexts:t.contexts},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount,capturedContexts:t.droppedCount}})}};const Me=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},Ne=Math.ceil(128/Math.log2(62)),Pe=async e=>Me((0,l.createHash)(`sha256`).update(e?.toString()??``).digest().subarray(0,16),Ne),Fe=new URL(`https://server-sdk-api.configdirector.com`),Ie=(e,t)=>(e.target?.rules??[]).some(e=>e.type===`conditional`&&(e.conditions??[]).some(e=>e.kind===`segment`&&t.has(e.segmentId)));var Le=class{constructor(e,t,n,r){this.handlersMap=new Map,this.eventEmitter=new c.default,this.ready=!1,this.logger=n?.logger??X(),this.timeout=n?.connection?.timeout??3e3,this.metaContext=n?.metadata??{},this.validateSdkKeyPresence(e),this.configEvaluator=new de(this.logger);let i=this.parseUrl(n?.connection?.url)??Fe;this.connectionMode=n?.connection?.mode??`streaming`,this.usageEventCollector=r?.telemetry??this.buildTelemetryCollector(e,t,i,n),this.transport=r?.transport??this.buildTransport(e,t,i,n),this.transport.on(`configBundleReceived`,e=>{this.readyResolve?.(!1);let t=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:(this.configSet.configs={...this.configSet.configs,...e.configs},this.configSet.segments={...this.configSet.segments,...e.segments});let n=this.findKeysUpdatedBy(e);this.eventEmitter.emit(`configsUpdated`,{keys:n,removedKeys:t}),this.updateWatchers([...n,...t]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server with ${n.length} key(s) and ${t.length} removed key(s)`,{keys:n,removedKeys:t})}),this.transport.on(`connectionError`,e=>{this.logger.error(`[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.`,e),this.eventEmitter.emit(`connectionError`,{error:e})}),this.registerHandler(`clientReady`,n?.hooks?.clientReady),this.registerHandler(`configEvaluated`,n?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,n?.hooks?.configsUpdated),this.registerHandler(`connectionError`,n?.hooks?.connectionError)}registerHandler(e,t){if(!t)return;let n=Array.isArray(t)?t:[t];for(let t of n)typeof t==`function`&&this.on(e,t)}async initialize(){try{this.ready=!1,this.readyPromise=new Promise(e=>{this.readyResolve=e}).then(e=>{e||(this.ready=!0,this.eventEmitter.emit(`clientReady`),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))}),this.usageEventCollector.start();let e=new Date().getTime();await this.transport.connect(this.timeout);let t=new Date().getTime()-e,n=this.timeout-t;if(n>0&&(await Promise.race([this.readyPromise,new Promise(e=>{this.readyTimer=setTimeout(()=>e(),n)})]),this.clearReadyTimer()),!this.ready){let e=this.connectionMode===`streaming`?`The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`:`Since the client was configured without streaming, configs may not update and always return the default value.`;this.logger.warn(`[ConfigDirectorClient] Timed out waiting for initialization after ${this.timeout}ms. ${e}`)}}catch(e){this.logger.error(`[ConfigDirectorClient] An error occurred during initialization: `,e)}}resolvePollingIntervalForMode(e){if(this.connectionMode!==`polling`)return;let t=Ce(e,{defaultSeconds:300,minimumSeconds:60});return t.warning&&this.logger.warn(`[ConfigDirectorClient] ${t.warning}`),t.seconds}buildTelemetryCollector(e,t,n,r){let i=r?.telemetry?.eventQueueLimit??5e3;return new je({sdkKey:e,sdkIdentity:t,metaContext:r?.metadata??{},logger:this.logger,baseUrl:n,flushIntervalDelay:r?.telemetry?.flushInterval??3e4,evaluationQueueLimit:Math.ceil(i*.7),contextLimit:Math.floor(i*.3),urlFactory:Se,valueIdGenerator:Pe})}buildTransport(e,t,n,r){return new(this.getTransportConstructor(this.connectionMode))({serverSdkKey:e,baseUrl:n,metaContext:{...r?.metadata,sdkName:t.sdkName,sdkVersion:t.sdkVersion},logger:this.logger,pollingInterval:this.resolvePollingIntervalForMode(r?.connection?.pollingInterval)})}getTransportConstructor(e){switch(e){case`polling`:return w;default:return te}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}findKeysUpdatedBy(e){let t=new Set(Object.keys(e.segments??{})),n=Object.entries(this.configSet?.configs??{}).filter(([,e])=>Ie(e,t)).map(([e])=>e);return[...new Set([...Object.keys(e.configs),...n])]}updateWatchers(e){e.forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){let t=this.configSet?.configs[e];this.handlersMap.get(e)?.forEach(n=>{let r=this.getValueFromConfigDefinition(e,t,n.defaultValue,n.context);n.handler(r)})}watch(e,t,n,r){this.validateDefaultValue(t);let i=this.handlersMap.get(e),a={handler:n,defaultValue:t,requestedType:typeof t,context:r};return i?i.push(a):this.handlersMap.set(e,[a]),()=>this.unwatch(e,n)}unwatch(e,t){let n=this.handlersMap.get(e);if(n)if(t){let e=n.findIndex(e=>e.handler==t);e>=0&&n?.splice(e,1)}else n.splice(0)}getValue(e,t,n){this.validateDefaultValue(t);let r=this.configSet?.configs[e];return this.getValueFromConfigDefinition(e,r,t,n)}getValueFromConfigDefinition(e,t,n,r){if(t){let i=this.configEvaluator.evaluate(t,{context:r,metadata:this.metaContext},this.configSet?.segments),a=fe(i,n);return this.usageEventCollector.evaluatedConfig({context:r,evaluation:{key:e,type:i.type,defaultValue:n,requestedType:a.requestedType,evaluatedValue:a.parsedValue,evaluatedValueId:a.parsedValueId,usedDefault:a.usedDefault,evaluationReason:a.reason}}),this.dispatchEvaluationEvent({key:e,value:a.parsedValue,valueId:a.parsedValueId??void 0,isDefaultValue:a.usedDefault,reason:a.reason,context:r}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${a.parsedValue}'`),a.parsedValue}else{this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`);let t=this.isReady?`config-state-missing`:`client-not-ready`;return this.usageEventCollector.evaluatedConfig({context:r,evaluation:{key:e,defaultValue:n,requestedType:G(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:r}),n}}dispatchEvaluationEvent(e){setTimeout(()=>this.eventEmitter.emit(`configEvaluated`,{evaluation:e}),0)}parseUrl(e){if(e)try{return new URL(e)}catch(t){throw new p(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateSdkKeyPresence(e){if(!e||e.trim().length==0)throw new p(`No server SDK key was provided, the client cannot be instantiated without a valid server SDK key`)}validateDefaultValue(e){if(e==null)throw new p(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new p(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}removeAllObservers(){this.logger.debug(`[ConfigDirectorClient] removeAllObservers() has been called, removing all observers`),this.eventEmitter.removeAllListeners(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}getAllConfigs(e){if(!this.configSet)return{};let t=Object.entries(this.configSet.configs),n=e?.configKeys?t.filter(([t])=>e.configKeys?.includes(t)):t;return Object.fromEntries(n.map(([t,n])=>[t,this.configEvaluator.evaluate(n,{context:e?.context,metadata:this.metaContext},this.configSet?.segments)]))}closeConnection(){this.logger.debug(`[ConfigDirectorClient] closeConnection() has been called, closing connection to server`),this.transport.close(),this.ready=!1}clearReadyTimer(){clearTimeout(this.readyTimer),this.readyTimer=void 0}dispose(){this.removeAllObservers(),this.closeConnection(),this.readyResolve?.(!0),this.clearReadyTimer(),this.usageEventCollector.close().catch(e=>{this.logger.warn(`[ConfigDirectorClient] Error flushing telemetry while disposing the client: `,e)})}};Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return Le}});
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import e,{EventEmitter as t}from"node:events";import{createHash as n,randomUUID as r}from"node:crypto";import{DateTime as i}from"luxon";import*as a from"semver";import{rapidhash as o}from"rapidhash-js";var s=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},c=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},ee=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},l=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},u=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},d=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}},te=class{constructor(e){this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=e.onEvent??(()=>{}),this.onRetry=e.onRetry,this.onComment=e.onComment}parse(e){let t=e;this.isFirstChunk&&(this.isFirstChunk=!1,t.startsWith(``)?t=t.slice(1):t.startsWith(``)&&(t=t.slice(3)));let n=this.scanLines(this.bufferedInput+t);for(let e of n)this.dispatchLine(e)}finish(){this.bufferedInput=``}scanLines(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];i===`\r`||i===`
|
|
2
|
-
`?(t.push(e.slice(n,r)),i===`\r`&&e[r+1]===`
|
|
3
|
-
`&&r++,r++,n=r):r++}return this.bufferedInput=e.slice(n),t}dispatchLine(e){if(e.startsWith(`:`)){this.onComment?.(this.extractValue(e,1));return}if(e===``){this.emitEvent();return}this.applyField(this.parseField(e))}emitEvent(){let e=this.currentEvent.data.endsWith(`
|
|
4
|
-
`)?this.currentEvent.data.slice(0,-1):this.currentEvent.data;e!==``&&this.onEvent({...this.currentEvent,id:this.lastEventId,data:e}),this.currentEvent={data:``}}applyField(e){switch(e.field){case`event`:this.currentEvent.type=e.value;break;case`data`:this.currentEvent.data+=e.value+`
|
|
5
|
-
`;break;case`id`:e.value.includes(`\0`)||(this.lastEventId=e.value);break;case`retry`:/^\d+$/.test(e.value)&&this.onRetry?.(Number.parseInt(e.value,10));break;default:break}}parseField(e){let t=e.indexOf(`:`);return t===-1?{field:e,value:``}:{field:e.slice(0,t),value:this.extractValue(e,t+1)}}extractValue(e,t){return e[t]===` `?e.slice(t+1):e.slice(t)}};let f=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var p=class{constructor(e){this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=f.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers={Accept:`text/event-stream`,...e.headers};let t=e.body;this.body=typeof t==`function`?t:()=>t,this.requestOptions={method:e.method??`GET`,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=e.fetch??((e,t)=>fetch(e,t)),this._onError=this.resolveCallback(e.onError,()=>{},`onError`),this._onConnect=this.resolveCallback(e.onConnect,()=>{},`onConnect`),this._onDisconnect=this.resolveCallback(e.onDisconnect,()=>{},`onDisconnect`),this._onMessage=this.resolveCallback(e.onMessage,()=>{},`onMessage`),this._onComment=this.resolveCallback(e.onComment,()=>{},`onComment`),this._shouldReconnect=this.resolveCallback(e.shouldReconnect,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`),this._calculateReconnectDelay=this.resolveCallback(e.calculateReconnectDelay,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`calculateReconnectDelay`)}set onError(e){this._onError=this.resolveCallback(e,()=>{},`onError`)}set onMessage(e){this._onMessage=this.resolveCallback(e,()=>{},`onMessage`)}set onComment(e){this._onComment=this.resolveCallback(e,()=>{},`onComment`)}set onConnect(e){this._onConnect=this.resolveCallback(e,()=>{},`onConnect`)}set onDisconnect(e){this._onDisconnect=this.resolveCallback(e,()=>{},`onDisconnect`)}set shouldReconnect(e){this._shouldReconnect=this.resolveCallback(e,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`)}set calculateReconnectDelay(e){this._calculateReconnectDelay=this.resolveCallback(e,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`shouldReconnect`)}get readyState(){return this._readyState}connect(){this._readyState===f.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=f.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=f.CONNECTING,this._fetch(this.url,{...this.requestOptions,body:this.body(),headers:this.buildRequestHeaders(),signal:this.abortController.signal,cache:`no-store`}).then(e=>this.handleFetchResponse(e)).catch(e=>{if(e.name===`AbortError`||this.abortController.signal.aborted){this.close();return}this._onError(e),this.scheduleReconnect({error:e})})}async handleFetchResponse(e){let{body:t,status:n}=e;if(n===204){this.disconnected();return}if(n>=400){this.scheduleReconnect({status:n});return}if(!t)throw new l(`The server response did not have a body`);this._readyState=f.OPEN,this._onConnect(),this.reconnectAttempt=0;let r=new te({onEvent:e=>{typeof e.id==`string`&&(this.lastEventId=e.id),this._onMessage(e)},onComment:e=>this._onComment(e),onRetry:e=>this.serverReconnectionTime=e});await this.readResponseStream(t,r),this.scheduleReconnect({status:n,error:new ee(`The server response stream was closed`)})}async readResponseStream(e,t){let n=e.getReader(),r=new TextDecoder,i=!1;for(;!i;){let e=await n.read();e.value&&t.parse(r.decode(e.value,{stream:!0})),i=e.done}t.finish()}disconnected(){clearTimeout(this.reconnectTimeout),this._readyState=f.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return{...this.headers,...e}}scheduleReconnect(e){if(this.abortController.signal.aborted)return;clearTimeout(this.reconnectTimeout),this.reconnectAttempt+=1;let t={attempt:this.reconnectAttempt,status:e.status,error:e.error,serverReconnectionTime:this.serverReconnectionTime};if(!this._shouldReconnect(t)){this.disconnected();return}this._readyState=f.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new d(`The calculated reconnect delay is out of range: ${n}. Defaulting to ${this.serverReconnectionTime}`)),n=this.serverReconnectionTime),this.reconnectTimeout=setTimeout(()=>this.initiateConnection(),n)}resolveCallback(e,t,n){if(e==null)return t;if(typeof e!=`function`)throw new u(`${n} must be a function`);return e}};const m=e=>new p(e),h=async(e,t,n,r)=>{let i=new AbortController,a=setTimeout(()=>{r.debug(`[fetchWithTimeout] Reached timeout, aborting request`),i.abort()},e);try{let e=await fetch(typeof t==`string`||t instanceof Request?t:t.toString(),{...n,signal:i.signal});return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}},g=9e4;var _=class{constructor(e){this.options=e,this.eventEmitter=new t,this.options=e,this.logger=e.logger,this.url=new URL(`server/sse/v1`,e.baseUrl),this.heartbeatUrl=new URL(`server/heartbeat/v1`,e.baseUrl)}async connect(e){this.eventSource&&this.close();let t=new Promise((e,t)=>{this.eventSource=m({url:this.url,method:`POST`,headers:{"Content-Type":`application/json`},body:()=>this.buildRequestBody(),onMessage:({data:e})=>{this.dispatchMessage(e)},onConnect:()=>{this.logger.debug(`[StreamingTransport] Connected`),e(this)},shouldReconnect:e=>{let n=!this.isStatusFatal(e.status);if(!n){this.stopHeartbeat();let n=this.prepareFatalError(e.status,e.error);this.eventEmitter.emit(`connectionError`,n),t(n)}return n},calculateReconnectDelay:e=>{let t=2**Math.min(e.attempt,9)*1e3,n=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?this.logger.info(n):this.logger.warn(n),t},onDisconnect:()=>{this.logger.debug(`[StreamingTransport] Disconnected`)}}),this.eventSource.connect()});this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),g);let n;try{return await Promise.race([t,new Promise(t=>{n=setTimeout(()=>t(this),e)})])}finally{clearTimeout(n)}}get sessionId(){return this._sessionId}sendHeartbeat(){!this.isConnected||!this._sessionId||h(g,this.heartbeatUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({serverSdkKey:this.options.serverSdkKey,sessionId:this._sessionId})},this.logger).then(e=>{e.ok||this.logger.debug(`[StreamingTransport] Heartbeat failed with status: ${e.status}`)}).catch(e=>{this.logger.debug(`[StreamingTransport] Heartbeat failed: `,e)})}buildRequestBody(){return this._sessionId=r(),JSON.stringify({metaContext:this.options.metaContext,serverSdkKey:this.options.serverSdkKey,sessionId:this._sessionId})}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configBundleReceived`,t)}catch(e){this.logger.error(`[StreamingTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,t){let n=e??0;return new s(`${`Connection failed with status: ${e??`unknown`}.`}${t?` Error: ${t}.`:``} This is an unrecoverable error, will not attempt to reconnect.`,n)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}get isConnected(){return this.eventSource?.readyState==`open`}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}clear(){this.eventEmitter.removeAllListeners()}stopHeartbeat(){clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0}close(){this.stopHeartbeat(),this.eventSource?.close()}dispose(){this.close(),this.clear()}},v=class{constructor(){this.fatalError=!1}clearPollingInterval(){clearInterval(this.pollingInterval)}schedulePollingInterval(e){clearInterval(this.pollingInterval),!(this.pollingIntervalSeconds<=0)&&(this.pollingInterval=setInterval(e,this.pollingIntervalSeconds*1e3))}async handleNonOkResponse(e){if(!e.ok)throw this.isStatusFatal(e.status)?(this.fatalError=!0,this.close(),this.prepareFatalResponseStatusError(e.status,await e.text())):new s(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new s(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new s(`Failed to parse the response from the server: ${e}`):new s(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,t){let n=e??0;return new s(`${`Connection failed with status: ${e??`unknown`}`}${(t?.trim()?.length??0)>0?` (${t})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,n)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}isFetchErrorFatal(e){return e?.name===`NotAllowedError`}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}},y=class extends v{constructor(e){super(),this.options=e,this.eventEmitter=new t,this._sessionId=r(),this.options=e,this.logger=e.logger,this.url=new URL(`server/polling/v1`,e.baseUrl),this.pollingIntervalSeconds=e.pollingInterval??300}async connect(e){this.clearPollingInterval();try{await this.fetchConfigs(e)}finally{this.fatalError||this.schedulePollingInterval(()=>{this.fetchConfigs(e).catch(e=>{this.logger.error(`[PollingTransport] Error during polling:`,e)})})}return this}get sessionId(){return this._sessionId}async fetchConfigs(e){if(this.fatalError){this.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let t=await h(e,this.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({metaContext:this.options.metaContext,serverSdkKey:this.options.serverSdkKey,lastUpdateTimestamp:this.lastUpdateTimestamp,sessionId:this._sessionId})},this.logger);if(await this.handleNonOkResponse(t),t.status===200){let e=JSON.parse(await t.text());this.lastUpdateTimestamp=e.timestamp,this.eventEmitter.emit(`configBundleReceived`,e)}}catch(e){try{this.handleFetchError(e)}catch(e){throw this.fatalError&&this.eventEmitter.emit(`connectionError`,e),e}}}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}clear(){this.eventEmitter.removeAllListeners()}};const b=/^(?:0|[1-9][0-9]*)$/,x=/~(?![01])/,S=Object.prototype.propertyIsEnumerable,C=e=>{if(!x.test(e))return e.replace(/~1/g,`/`).replace(/~0/g,`~`)},ne=(e,t)=>{if(Array.isArray(e))return b.test(t)&&S.call(e,t)?e[Number(t)]:void 0;if(typeof e==`object`&&e)return S.call(e,t)?e[t]:void 0},re=(e,t)=>{if(e===``)return t;if(!e.startsWith(`/`))return;let n=t;for(let t of e.slice(1).split(`/`)){let e=C(t);if(e===void 0||(n=ne(n,e),n===void 0))return}return n},ie=(e,t,n)=>{let r=n[0];switch(t.toLowerCase()){case`=`:case`equals`:return r!==void 0&&e===r;case`!=`:case`does not equal`:return r!==void 0&&e!==r;case`is one of`:return n.includes(e);case`is not one of`:return!n.includes(e);case`starts with any of`:return n.some(t=>e.startsWith(t));case`does not start with any of`:return!n.some(t=>e.startsWith(t));case`ends with any of`:return n.some(t=>e.endsWith(t));case`does not end with any of`:return!n.some(t=>e.endsWith(t));default:return!1}},ae=(e,t,n)=>{let r=t.toLowerCase(),i=w(e);if(i===void 0)return r===`!=`||r===`does not equal`;let a=n[0];if(a===void 0)return!1;let o=w(a);if(o===void 0)return!1;switch(r){case`=`:case`equals`:return i===o;case`!=`:case`does not equal`:return i!==o;case`<`:return i<o;case`<=`:return i<=o;case`>`:return i>o;case`>=`:return i>=o;default:return!1}},w=e=>{if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(typeof e!=`string`||e.length===0||!oe(e))return;let t=Number(e);return Number.isFinite(t)?t:void 0},oe=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},se=(e,t,n)=>{let r=n[0];if(r===void 0)return!1;let i=T(e),a=T(r);if(i===void 0||a===void 0)return!1;switch(t){case`is after`:return i>a;case`is before`:return i<a;default:return!1}},T=e=>{let t=i.fromISO(e,{zone:`utc`});return t.isValid?t.toMillis():void 0},E=(e,t,n)=>{let r=t.toLowerCase();if(e.trim().length===0)return r===`is not one of`;let i=a.coerce(e),o=n.map(e=>a.coerce(e)),s=o[0]??null;switch(r){case`=`:return D(i,s);case`<`:return O(i,s,a.lt);case`<=`:return O(i,s,a.lte);case`>`:return O(i,s,a.gt);case`>=`:return O(i,s,a.gte);case`is one of`:return o.some(e=>D(i,e));case`is not one of`:return!o.some(e=>D(i,e));default:return!1}},D=(e,t)=>e!==null&&t!==null&&a.eq(e,t),O=(e,t,n)=>e!==null&&t!==null&&n(e,t),k=Symbol(`absent`),A=Symbol(`unknown-attribute`),j=e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`,M=e=>e===k||e==null?``:j(e)?N(e):``,N=e=>typeof e==`string`?e:String(e),P=e=>e===k?void 0:e,F=e=>e===A?`unknown-attribute`:e===k?`absent`:j(e)?`scalar`:Array.isArray(e)?`array`:`object`,I=(e,t,n)=>{let r=t.toLowerCase();if(!Array.isArray(e))return r===`does not contain any of`;let i=e.filter(j).map(N);switch(r){case`contains any of`:return i.some(e=>n.includes(e));case`does not contain any of`:return!i.some(e=>n.includes(e));default:return!1}};var L=class{evaluate(e,t){return this.explain(e,t).matched}explain(e,t){let n=this.resolve(e,t),r=F(n),i=n===k||n===A?void 0:n;return n===A?{matched:!1,resolvedValue:i,resolvedType:r}:{matched:this.compare(e,n),resolvedValue:i,resolvedType:r}}compare(e,t){let n=e.targetValues??[];switch(e.targetType){case`text`:return ie(M(t),e.operator,n);case`number`:return ae(P(t),e.operator,n);case`datetime`:return se(M(t),e.operator,n);case`semver`:return E(M(t),e.operator,n);case`array`:return I(P(t),e.operator,n)}return!1}resolve(e,t){switch(e.attribute){case`identifier`:return R(t?.context?.id);case`name`:return R(t?.context?.name);case`appName`:return R(t?.metadata?.appName);case`appVersion`:return R(t?.metadata?.appVersion);case`traits`:return e.trait?R(re(e.trait,t?.context?.traits)):k;default:return A}}};const R=e=>e??k;var z=class{constructor(e){this.conditionEvaluator=e}explain(e,t,n){let r=t?.[e.segmentId];if(r===void 0||!B(r))return{matched:!1,segmentFound:!1,matchedGroupIndex:void 0};let i=this.matchingGroupIndex(r,n),a=i!==void 0;return{matched:this.operatorHolds(e,a),segmentFound:!0,matchedGroupIndex:i}}operatorHolds(e,t){switch(e.operator.toLowerCase()){case`in`:return t;case`not in`:return!t;default:return!1}}matchingGroupIndex(e,t){let n=(e.groups??[]).findIndex(e=>(e??[]).every(e=>this.conditionEvaluator.evaluate(e,t)));return n===-1?void 0:n}};const B=e=>(e.groups??[]).every(e=>(e??[]).every(e=>e.kind===void 0||e.kind===`attribute`)),V=e=>{let t=`${e.contextIdentifier}-${e.configId}`;return Number(o(t,{seed:15426857351n})%1000n)/10};var H=class{constructor(e){if(this.logger=e,this.conditionEvaluator=new L,this.segmentEvaluator=new z(this.conditionEvaluator),!e||!e.warn||!e.error||!e.info)throw TypeError(`The provided logger is not a valid 'ConfigDirectorLogger'`);this.logger=e}evaluate(e,t,n){return{id:e.id,key:e.key,type:e.type,value:this.explain(e,t,n).value}}explain(e,t,n){let r=[...e.target?.rules??[]].sort((e,t)=>(e.order??2**53-1)-(t.order??2**53-1)),i=[],a;for(let o of r){if(a){i.push({ruleId:o.id,outcome:`not-evaluated`,conditions:[],bucket:void 0});continue}let r=this.explainRule(o,e,t,n);i.push(r.explanation),r.value!==void 0&&(a={ruleId:o.id,value:r.value})}return{value:a?.value??e.target?.defaultValue,servedBy:a?{kind:`rule`,ruleId:a.ruleId}:{kind:`default`},rules:i}}explainRule(e,t,n,r){let i={ruleId:e.id,outcome:`not-matched`,conditions:[],bucket:void 0};try{let a;return e.type==`percentage`?a=this.explainPercentage(e.percentages??[],t,n,i):e.type==`conditional`&&(a=this.explainConditionalRule(e,t,n,r,i)),a!==void 0&&(i.outcome=`matched`),{explanation:i,value:a}}catch(n){return this.logger.warn(`There was an error while evaluating a targeting rule '${e?.id}' for '${t?.key}'. The rule will be disregarded.`,{error:n,configKey:t?.key,ruleId:e?.id}),{explanation:{ruleId:e.id,outcome:`errored`,conditions:[],bucket:void 0},value:void 0}}}explainPercentage(e,t,n,r){let i=n?.context?.id??void 0,a=i===void 0?0:V({configId:t.id,contextIdentifier:i}),o=[],s=0,c;for(let t of e){let e=s+t.percentage;o.push({percentageId:t.id,from:s,to:e,value:t.value?.toString()}),c===void 0&&a<e&&(c=t),s=e}return r.bucket={identifier:i,defaultedToPredefinedBucket:i===void 0,assignedPercentage:a,shares:o,selectedPercentageId:c?.id},c?.value==null?void 0:c.value.toString()}explainConditionalRule(e,t,n,r,i){let a=!1;for(let t of e.conditions??[]){if(a){i.conditions.push({conditionId:t.id,outcome:`not-evaluated`});continue}let e=this.explainCondition(t,n,r);i.conditions.push(e),a=e.outcome!==`matched`}if(!a){if(e.target==`value`)return e.value==null?void 0:e.value.toString();if(e.target==`percentage`)return this.explainPercentage(e.percentages??[],t,n,i)}}explainCondition(e,t,n){if(e.kind===`segment`){let r=this.segmentEvaluator.explain(e,n,t);return{conditionId:e.id,kind:`segment`,outcome:r.matched?`matched`:`not-matched`,segmentId:e.segmentId,segmentFound:r.segmentFound,matchedGroupIndex:r.matchedGroupIndex}}let r=this.conditionEvaluator.explain(e,t);return{conditionId:e.id,kind:`attribute`,outcome:r.matched?`matched`:`not-matched`,resolvedValue:r.resolvedValue,resolvedType:r.resolvedType}}};const U=e=>{let t=typeof e;if(t===`object`)try{return e.constructor?.name??t}catch{return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch{return t}return t},W=e=>e===`number`||e===`bigint`,G=new Set([`boolean`,`integer`,`float`]),K=(e,t)=>{let n=e.value,r=U(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return fe(n,t,r,e.valueId);if(typeof t==`string`)return G.has(e.type)?{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}:{parsedValue:n,parsedValueId:e.valueId,requestedType:r,usedDefault:!1,reason:`found-match`};if(typeof t==`boolean`&&(e.type===`boolean`||e.type===`string`||e.type===`enum`)){let i=ce(n),a=typeof i==`boolean`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-boolean`}}if(W(typeof t)&&e.type===`integer`){let i=le(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}if(W(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=ue(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}},ce=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},le=e=>{let t=q(e);return t==null?void 0:Math.trunc(t)},ue=e=>q(e),q=e=>{if(!e||!de(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},de=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},fe=(e,t,n,r)=>{if(typeof t==`string`)return{parsedValue:e,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`};try{let i=JSON.parse(e);return pe(i,t)?{parsedValue:i,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`}:{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`type-mismatch`}}catch{return{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`invalid-json`}}},pe=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},J={off:-1,error:0,warn:1,info:2,debug:3},me=()=>{let e={year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,timeZoneName:`short`};try{return new Intl.DateTimeFormat(void 0,{...e,fractionalSecondDigits:3})}catch{return new Intl.DateTimeFormat(void 0,e)}};var he=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=me()}debug(e,...t){this.log(console.debug,`debug`,e,...t)}info(e,...t){this.log(console.info,`info`,e,...t)}warn(e,...t){this.log(console.warn,`warn`,e,...t)}error(e,...t){this.log(console.error,`error`,e,...t)}log(e,t,n,...r){J[this.level]>=J[t]&&e(`[${this.dateFormatter.format(new Date)}] ${this.decorator?.decorateMessage(n)}`,...r)}},ge=class{decorateMessage(e){return`[ConfigDirector:js-server-sdk] ${e}`}};const Y=(e,t)=>new he(e??`warn`,t??new ge),_e=(e,t)=>new URL(e,t?.toString()),ve=(e,t)=>e===void 0?{seconds:t.defaultSeconds,warning:void 0}:e>=t.minimumSeconds?{seconds:e,warning:void 0}:{seconds:t.minimumSeconds,warning:`pollingInterval of ${e} seconds is below the minimum of ${t.minimumSeconds} seconds. Using ${t.minimumSeconds} seconds.`},X=async(e,t)=>e.valueId?{valueId:e.valueId}:e.value?e.value.length<=500&&e.type!=`json`?{value:e.value}:{valueId:await t(e.value)}:e,Z=e=>{if(e.type===`json`||e.type==null&&typeof e.value==`object`){if(e.valueId)return{valueId:e.valueId,type:`json`};try{return{value:JSON.stringify(e.value),type:`json`}}catch{return{value:e.value.toString(),type:`json`}}}let t=e.value?.toString();return t&&t.length<=500?{value:t}:e.valueId?{valueId:e.valueId}:{value:t}},Q=e=>{let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]?.length??0)>0)return!1;return!0},ye=e=>{if(!e)return!0;let t=Object.keys(e);if(t.length==0)return!0;for(let n of t)if((e[n]??0)>0)return!1;return!0};var be=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.sdkIdentity=e.sdkIdentity,this.logger=e.logger,this.metaContext=e.metaContext,this.url=new URL(`server/telemetry/v1`,e.baseUrl.toString())}async report({discreteEvents:e,aggregatedEvents:t,droppedEvents:n}){if(!this.executeRequests)return{success:!1,fatalError:!0};let r={serverSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},discreteEvents:e,aggregatedEvents:t,droppedEvents:n};if(this.isReportEmpty(r))return{success:!0,fatalError:!1};let i=await this.sendReport(r);return i.fatalError&&(this.executeRequests=!1),i}isReportEmpty(e){return Q(e.discreteEvents)&&Q(e.aggregatedEvents)&&ye(e.droppedEvents)}async sendReport(e){try{let t=await h(5e3,this.url,{method:`POST`,body:JSON.stringify(e)},this.logger),n=this.isStatusFatal(t.status);return n&&this.logger.warn(`[EventReporter] Received a fatal status response (${t.status}) from the telemetry endpoint. No more telemetry data will be sent.`),{success:t.ok,fatalError:n}}catch(e){return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:!1}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},xe=class{aggregate(e){if(e.events.length==0)return[];let t=new Map;for(let n of e.events){let e=JSON.stringify(n),r=t.get(e)?.count||0;t.set(e,{event:n,count:r+1})}return Array.from(t).map(([,t])=>({startTime:e.startTime,endTime:e.endTime,count:t.count,event:t.event}))}},Se=class{constructor(e){this._events=[],this._droppedEventCount=0,this.limit=e??1e3}get events(){return this._events}get reachedLimit(){return this._events.length>=this.limit}get droppedEventCount(){return this._droppedEventCount}push(...e){this.startTime||(this.startTime=new Date);let t=Math.max(0,e.length-this.limit),n=e.slice(t,e.length);if(this._droppedEventCount+=t,this._events.length+n.length>this.limit){let e=this._events.length+n.length-this.limit;this._events.splice(0,e),this._droppedEventCount+=e}return this._events.push(...n)}takeSnapshot(){let e=new Date,t=this.startTime??e,n=this._events.splice(0),r=this._droppedEventCount;return this.startTime=void 0,this._droppedEventCount=0,{startTime:t,endTime:e,events:n,droppedCount:r}}clear(){this._events=[],this.startTime=void 0,this._droppedEventCount=0}},Ce=class{constructor(e){this.aggregator=new xe,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new Se(e.evaluationQueueLimit??1e3),this.flushIntervalDelay=e.flushIntervalDelay??3e4,this.initialFlushIntervalDelay=e.initialFlushIntervalDelay??5e3}start(){this.started||!this.collectEvents||(this.started=!0,this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.initialFlushIntervalDelay))}async flushAndScheduleNext(){if(!this.collectEvents)return;let e;try{e=await this.flush()}catch(t){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events: `,t),e={success:!1,fatalError:!1}}e.fatalError?(this.collectEvents=!1,this.close(),this.logger.warn(`[TelemetryEventCollector] Received a fatal error from telemetry collection. No longer collecting events.`)):this.collectEvents&&(this.cancelScheduledFlush(),this.flushTimeout=setTimeout(()=>this.flushAndScheduleNext(),this.flushIntervalDelay))}cancelScheduledFlush(){clearTimeout(this.flushTimeout)}async close(){this.collectEvents=!1,clearTimeout(this.flushTimeout);try{await this.flush()}catch(e){this.logger.warn(`[TelemetryEventCollector] Error flushing telemetry events during close: `,e)}this.evaluationEventQueue.clear()}dispose(){this.close()}},$=class extends Map{constructor(e,t){super(t),this._droppedCount=0,this.limit=e,this.enforceLimit()}set(e,t){return super.set(e,t),this.enforceLimit(),this}get droppedCount(){return this._droppedCount}clearAndReset(){this.clear(),this._droppedCount=0}enforceLimit(){for(;this.size>this.limit;){let e=this.keys().next().value;e!==void 0&&(this.delete(e),this._droppedCount+=1)}}},we=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(e){let t=await Promise.all(e.events.map(async e=>({...e,defaultValue:await X(e.defaultValue,this.valueIdGenerator),evaluatedValue:await X(e.evaluatedValue,this.valueIdGenerator)})));return{...e,events:t}}},Te=class extends Ce{constructor(e){super(e),this.reporter=new be(e),this.contexts=new $(e.contextLimit??1e3),this.evaluationEventSnapshotPreprocessor=new we(e.valueIdGenerator)}evaluatedConfig(e){if(!this.collectEvents)return;e.context?.id&&!e.context.anonymous&&this.contexts.set(e.context.id,e.context);let t={...e.evaluation,contextId:e.context?.anonymous?void 0:e.context?.id};this.evaluationEventQueue.push(this.sanitizeEvaluatedConfigEvent(t))}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:Z({value:e.defaultValue,type:e.type}),evaluatedValue:Z({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}snapshotContexts(){let e=Array.from(this.contexts.values()),t=this.contexts.droppedCount;return this.contexts.clearAndReset(),{contexts:e,droppedCount:t}}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot()),t=this.snapshotContexts();return await this.reporter?.report({context:this._context,discreteEvents:{capturedContexts:t.contexts},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e)},droppedEvents:{evaluatedConfig:e.droppedCount,capturedContexts:t.droppedCount}})}};const Ee=(e,t)=>{let n=BigInt(0),r=BigInt(62),i=Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``),a=BigInt(`0x`+i),o=``;for(;a>n;)o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`[Number(a%r)]+o,a/=r;return o.padStart(t,`0`)},De=Math.ceil(128/Math.log2(62)),Oe=async e=>Ee(n(`sha256`).update(e?.toString()??``).digest().subarray(0,16),De),ke=new URL(`https://server-sdk-api.configdirector.com`),Ae=(e,t)=>(e.target?.rules??[]).some(e=>e.type===`conditional`&&(e.conditions??[]).some(e=>e.kind===`segment`&&t.has(e.segmentId)));var je=class{constructor(t,n,r,i){this.handlersMap=new Map,this.eventEmitter=new e,this.ready=!1,this.logger=r?.logger??Y(),this.timeout=r?.connection?.timeout??3e3,this.metaContext=r?.metadata??{},this.validateSdkKeyPresence(t),this.configEvaluator=new H(this.logger);let a=this.parseUrl(r?.connection?.url)??ke;this.connectionMode=r?.connection?.mode??`streaming`,this.usageEventCollector=i?.telemetry??this.buildTelemetryCollector(t,n,a,r),this.transport=i?.transport??this.buildTransport(t,n,a,r),this.transport.on(`configBundleReceived`,e=>{this.readyResolve?.(!1);let t=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:(this.configSet.configs={...this.configSet.configs,...e.configs},this.configSet.segments={...this.configSet.segments,...e.segments});let n=this.findKeysUpdatedBy(e);this.eventEmitter.emit(`configsUpdated`,{keys:n,removedKeys:t}),this.updateWatchers([...n,...t]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server with ${n.length} key(s) and ${t.length} removed key(s)`,{keys:n,removedKeys:t})}),this.transport.on(`connectionError`,e=>{this.logger.error(`[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.`,e),this.eventEmitter.emit(`connectionError`,{error:e})}),this.registerHandler(`clientReady`,r?.hooks?.clientReady),this.registerHandler(`configEvaluated`,r?.hooks?.configEvaluated),this.registerHandler(`configsUpdated`,r?.hooks?.configsUpdated),this.registerHandler(`connectionError`,r?.hooks?.connectionError)}registerHandler(e,t){if(!t)return;let n=Array.isArray(t)?t:[t];for(let t of n)typeof t==`function`&&this.on(e,t)}async initialize(){try{this.ready=!1,this.readyPromise=new Promise(e=>{this.readyResolve=e}).then(e=>{e||(this.ready=!0,this.eventEmitter.emit(`clientReady`),this.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))}),this.usageEventCollector.start();let e=new Date().getTime();await this.transport.connect(this.timeout);let t=new Date().getTime()-e,n=this.timeout-t;if(n>0&&(await Promise.race([this.readyPromise,new Promise(e=>{this.readyTimer=setTimeout(()=>e(),n)})]),this.clearReadyTimer()),!this.ready){let e=this.connectionMode===`streaming`?`The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`:`Since the client was configured without streaming, configs may not update and always return the default value.`;this.logger.warn(`[ConfigDirectorClient] Timed out waiting for initialization after ${this.timeout}ms. ${e}`)}}catch(e){this.logger.error(`[ConfigDirectorClient] An error occurred during initialization: `,e)}}resolvePollingIntervalForMode(e){if(this.connectionMode!==`polling`)return;let t=ve(e,{defaultSeconds:300,minimumSeconds:60});return t.warning&&this.logger.warn(`[ConfigDirectorClient] ${t.warning}`),t.seconds}buildTelemetryCollector(e,t,n,r){let i=r?.telemetry?.eventQueueLimit??5e3;return new Te({sdkKey:e,sdkIdentity:t,metaContext:r?.metadata??{},logger:this.logger,baseUrl:n,flushIntervalDelay:r?.telemetry?.flushInterval??3e4,evaluationQueueLimit:Math.ceil(i*.7),contextLimit:Math.floor(i*.3),urlFactory:_e,valueIdGenerator:Oe})}buildTransport(e,t,n,r){return new(this.getTransportConstructor(this.connectionMode))({serverSdkKey:e,baseUrl:n,metaContext:{...r?.metadata,sdkName:t.sdkName,sdkVersion:t.sdkVersion},logger:this.logger,pollingInterval:this.resolvePollingIntervalForMode(r?.connection?.pollingInterval)})}getTransportConstructor(e){switch(e){case`polling`:return y;default:return _}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}findKeysUpdatedBy(e){let t=new Set(Object.keys(e.segments??{})),n=Object.entries(this.configSet?.configs??{}).filter(([,e])=>Ae(e,t)).map(([e])=>e);return[...new Set([...Object.keys(e.configs),...n])]}updateWatchers(e){e.forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){let t=this.configSet?.configs[e];this.handlersMap.get(e)?.forEach(n=>{let r=this.getValueFromConfigDefinition(e,t,n.defaultValue,n.context);n.handler(r)})}watch(e,t,n,r){this.validateDefaultValue(t);let i=this.handlersMap.get(e),a={handler:n,defaultValue:t,requestedType:typeof t,context:r};return i?i.push(a):this.handlersMap.set(e,[a]),()=>this.unwatch(e,n)}unwatch(e,t){let n=this.handlersMap.get(e);if(n)if(t){let e=n.findIndex(e=>e.handler==t);e>=0&&n?.splice(e,1)}else n.splice(0)}getValue(e,t,n){this.validateDefaultValue(t);let r=this.configSet?.configs[e];return this.getValueFromConfigDefinition(e,r,t,n)}getValueFromConfigDefinition(e,t,n,r){if(t){let i=this.configEvaluator.evaluate(t,{context:r,metadata:this.metaContext},this.configSet?.segments),a=K(i,n);return this.usageEventCollector.evaluatedConfig({context:r,evaluation:{key:e,type:i.type,defaultValue:n,requestedType:a.requestedType,evaluatedValue:a.parsedValue,evaluatedValueId:a.parsedValueId,usedDefault:a.usedDefault,evaluationReason:a.reason}}),this.dispatchEvaluationEvent({key:e,value:a.parsedValue,valueId:a.parsedValueId??void 0,isDefaultValue:a.usedDefault,reason:a.reason,context:r}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${a.parsedValue}'`),a.parsedValue}else{this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`);let t=this.isReady?`config-state-missing`:`client-not-ready`;return this.usageEventCollector.evaluatedConfig({context:r,evaluation:{key:e,defaultValue:n,requestedType:U(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:r}),n}}dispatchEvaluationEvent(e){setTimeout(()=>this.eventEmitter.emit(`configEvaluated`,{evaluation:e}),0)}parseUrl(e){if(e)try{return new URL(e)}catch(t){throw new c(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateSdkKeyPresence(e){if(!e||e.trim().length==0)throw new c(`No server SDK key was provided, the client cannot be instantiated without a valid server SDK key`)}validateDefaultValue(e){if(e==null)throw new c(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new c(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}on(e,t){this.eventEmitter.on(e,t)}off(e,t){t?this.eventEmitter.off(e,t):this.eventEmitter.removeAllListeners(e)}removeAllObservers(){this.logger.debug(`[ConfigDirectorClient] removeAllObservers() has been called, removing all observers`),this.eventEmitter.removeAllListeners(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}getAllConfigs(e){if(!this.configSet)return{};let t=Object.entries(this.configSet.configs),n=e?.configKeys?t.filter(([t])=>e.configKeys?.includes(t)):t;return Object.fromEntries(n.map(([t,n])=>[t,this.configEvaluator.evaluate(n,{context:e?.context,metadata:this.metaContext},this.configSet?.segments)]))}closeConnection(){this.logger.debug(`[ConfigDirectorClient] closeConnection() has been called, closing connection to server`),this.transport.close(),this.ready=!1}clearReadyTimer(){clearTimeout(this.readyTimer),this.readyTimer=void 0}dispose(){this.removeAllObservers(),this.closeConnection(),this.readyResolve?.(!0),this.clearReadyTimer(),this.usageEventCollector.close().catch(e=>{this.logger.warn(`[ConfigDirectorClient] Error flushing telemetry while disposing the client: `,e)})}};export{c as i,Y as n,s as r,je as t};
|
|
6
|
-
//# sourceMappingURL=DefaultConfigDirectorClient-BH0eGfm_.mjs.map
|