@configdirector/react-web-sdk 1.8.0 → 1.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/configdirector-react-client-testing.cjs +1 -1
- package/dist/configdirector-react-client-testing.d.cts +1 -1
- package/dist/configdirector-react-client-testing.d.mts +1 -1
- package/dist/configdirector-react-client-testing.mjs +1 -1
- package/dist/configdirector-react-client.cjs +1 -1
- package/dist/configdirector-react-client.d.cts +8 -2
- package/dist/configdirector-react-client.d.cts.map +1 -1
- package/dist/configdirector-react-client.d.mts +8 -2
- package/dist/configdirector-react-client.d.mts.map +1 -1
- package/dist/configdirector-react-client.mjs +1 -1
- package/dist/configdirector-react-client.mjs.map +1 -1
- package/dist/installedTestClient-BY0SbL31.mjs +6 -0
- package/dist/installedTestClient-BY0SbL31.mjs.map +1 -0
- package/dist/installedTestClient-DjPcNYN5.cjs +5 -0
- package/dist/{types-DJSy0ELn.d.cts → types-CFBLmqUM.d.cts} +49 -6
- package/dist/types-CFBLmqUM.d.cts.map +1 -0
- package/dist/{types-BfakBTXM.d.mts → types-CrgXfAWw.d.mts} +49 -6
- package/dist/types-CrgXfAWw.d.mts.map +1 -0
- package/package.json +3 -3
- package/dist/installedTestClient-BXUl11xD.cjs +0 -5
- package/dist/installedTestClient-CqDdos7F.mjs +0 -6
- package/dist/installedTestClient-CqDdos7F.mjs.map +0 -1
- package/dist/types-BfakBTXM.d.mts.map +0 -1
- package/dist/types-DJSy0ELn.d.cts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./installedTestClient-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./installedTestClient-DjPcNYN5.cjs`),t={environmentId:`test-environment`,projectId:`test-project`},n=e=>{switch(e){case`initialization`:return`initialize`;case`context update`:return`updateContext`;default:return}};var r=class{constructor(t,n){this.logger=t,this.emitter=new e.p,this.configs=new Map,this.recordedContexts=[],this.pendingDeliveries=[],this.armed={initialize:`nothing`,updateContext:`nothing`},this.connected=!1,this.delivering=!1,this.revision=0,this.attemptGeneration=0,this.on=(e,t)=>this.emitter.on(e,t),this.off=(e,t)=>this.emitter.off(e,t),this.store(n)}get contextUpdates(){return[...this.recordedContexts]}setValue(e,n){let r=this.encode(e,n);this.configs.set(e,r),this.deliverIfConnected({...t,kind:`delta`,configs:{[e]:r}})}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.initialize=`nothing`,this.armed.updateContext=`nothing`,this.deliverIfConnected(this.fullUpdate())}hold(e){this.armed[e]=`hold`}complete(e){this.pendingHold?.attempt===e?this.pendingHold.complete():this.armed[e]===`hold`&&(this.armed[e]=`nothing`)}fail(e){this.pendingHold?.attempt===e?this.pendingHold.fail():this.armed[e]=`failure`}connect(e,t,r){this.endAttempt();let i=n(r);if(!i)return this.connectNow();this.recordedContexts.push(e);let a=this.armed[i];switch(this.armed[i]=`nothing`,a){case`failure`:return this.failNow(r);case`hold`:return this.holdNow(i,r,t);default:return this.connectNow()}}clear(){this.emitter.clear()}close(){this.endAttempt()}dispose(){this.close(),this.clear()}endAttempt(){this.attemptGeneration++,this.connected=!1,this.pendingHold?.end()}connectNow(){let e=Promise.resolve(this);return this.scheduleFirstDelivery(),e}holdNow(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>this.pendingHold?.end(),n),o=()=>{clearTimeout(a),this.pendingHold=void 0};this.pendingHold={attempt:e,end:()=>{o(),r(this)},complete:()=>{o(),r(this),this.scheduleFirstDelivery()},fail:()=>{o();let e=this.fatalError(t);this.emitter.emit(`connectionError`,e),i(e)}}})}failNow(e){let t=this.fatalError(e);return this.emitter.emit(`connectionError`,t),Promise.reject(t)}fatalError(t){return new e.d(`Connection failed with status: 401. Error: the test client failed this ${t}. This is an unrecoverable error, will not attempt to reconnect.`,401)}scheduleFirstDelivery(){let e=this.attemptGeneration;Promise.resolve().then(()=>{}).then(()=>{e===this.attemptGeneration&&(this.connected=!0,this.deliver(this.fullUpdate()))})}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(`configSetReceived`,e)}catch(e){this.logger.error(`[InMemoryConnection] Error dispatching a config update from the test client: `,e)}}fullUpdate(){return{...t,kind:`full`,configs:Object.fromEntries(this.configs)}}store(e){this.encodeAll(e).forEach((e,t)=>this.configs.set(t,e))}encodeAll(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,this.encode(n,r));return t}encode(t,n){return e.u(`test-config:${t}`,t,n,`test-value:${t}:${++this.revision}`)}},i=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(`initialize`)}completeInitialization(){this.connection.complete(`initialize`)}failInitialization(){this.connection.fail(`initialize`)}holdContextUpdate(){this.connection.hold(`updateContext`)}completeContextUpdate(){this.connection.complete(`updateContext`)}failContextUpdate(){this.connection.fail(`updateContext`)}get contextUpdates(){return this.connection.contextUpdates}};const a=(t,n)=>{let a=n?.logger??e.l(),o=new r(a,n?.values??{});return new i(new e.r(()=>e.c,`test-client`,t,{logger:a,connection:{timeout:n?.timeout}},{transport:o}),o)},o=t=>{let n=globalThis,r=n[e.t];return n[e.t]=t.client,()=>{n[e.t]=r}},s=e=>a({sdkName:`react-web-sdk`,sdkVersion:`1.9.1`},e);exports.ConfigDirectorConnectionError=e.d,exports.ConfigDirectorValidationError=e.f,exports.createTestClient=s,exports.installTestClient=o;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { c as NativeValue, d as ConfigDirectorLogger, i as ConfigDirectorClient, l as NativeValues, s as NativeJsonValue, u as ConfigDirectorContext } from "./types-CFBLmqUM.cjs";
|
|
2
2
|
|
|
3
3
|
//#region ../shared/src/errors.d.ts
|
|
4
4
|
declare class ConfigDirectorConnectionError extends Error {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { c as NativeValue, d as ConfigDirectorLogger, i as ConfigDirectorClient, l as NativeValues, s as NativeJsonValue, u as ConfigDirectorContext } from "./types-CrgXfAWw.mjs";
|
|
2
2
|
|
|
3
3
|
//#region ../shared/src/errors.d.ts
|
|
4
4
|
declare class ConfigDirectorConnectionError extends Error {
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{c as e,d as t,f as n,l as r,m as i,p as a,r as o,t as s,u as c}from"./installedTestClient-BY0SbL31.mjs";const l={environmentId:`test-environment`,projectId:`test-project`},u=e=>{switch(e){case`initialization`:return`initialize`;case`context update`:return`updateContext`;default:return}};var d=class{constructor(e,t){this.logger=e,this.emitter=new a,this.configs=new Map,this.recordedContexts=[],this.pendingDeliveries=[],this.armed={initialize:`nothing`,updateContext:`nothing`},this.connected=!1,this.delivering=!1,this.revision=0,this.attemptGeneration=0,this.on=(e,t)=>this.emitter.on(e,t),this.off=(e,t)=>this.emitter.off(e,t),this.store(t)}get contextUpdates(){return[...this.recordedContexts]}setValue(e,t){let n=this.encode(e,t);this.configs.set(e,n),this.deliverIfConnected(i(i({},l),{},{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.initialize=`nothing`,this.armed.updateContext=`nothing`,this.deliverIfConnected(this.fullUpdate())}hold(e){this.armed[e]=`hold`}complete(e){var t;((t=this.pendingHold)==null?void 0:t.attempt)===e?this.pendingHold.complete():this.armed[e]===`hold`&&(this.armed[e]=`nothing`)}fail(e){var t;((t=this.pendingHold)==null?void 0:t.attempt)===e?this.pendingHold.fail():this.armed[e]=`failure`}connect(e,t,n){this.endAttempt();let r=u(n);if(!r)return this.connectNow();this.recordedContexts.push(e);let i=this.armed[r];switch(this.armed[r]=`nothing`,i){case`failure`:return this.failNow(n);case`hold`:return this.holdNow(r,n,t);default:return this.connectNow()}}clear(){this.emitter.clear()}close(){this.endAttempt()}dispose(){this.close(),this.clear()}endAttempt(){var e;this.attemptGeneration++,this.connected=!1,(e=this.pendingHold)==null||e.end()}connectNow(){let e=Promise.resolve(this);return this.scheduleFirstDelivery(),e}holdNow(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>{var e;return(e=this.pendingHold)==null?void 0:e.end()},n),o=()=>{clearTimeout(a),this.pendingHold=void 0};this.pendingHold={attempt:e,end:()=>{o(),r(this)},complete:()=>{o(),r(this),this.scheduleFirstDelivery()},fail:()=>{o();let e=this.fatalError(t);this.emitter.emit(`connectionError`,e),i(e)}}})}failNow(e){let t=this.fatalError(e);return this.emitter.emit(`connectionError`,t),Promise.reject(t)}fatalError(e){return new t(`Connection failed with status: 401. Error: the test client failed this ${e}. This is an unrecoverable error, will not attempt to reconnect.`,401)}scheduleFirstDelivery(){let e=this.attemptGeneration;Promise.resolve().then(()=>{}).then(()=>{e===this.attemptGeneration&&(this.connected=!0,this.deliver(this.fullUpdate()))})}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(`configSetReceived`,e)}catch(e){this.logger.error(`[InMemoryConnection] Error dispatching a config update from the test client: `,e)}}fullUpdate(){return i(i({},l),{},{kind:`full`,configs:Object.fromEntries(this.configs)})}store(e){this.encodeAll(e).forEach((e,t)=>this.configs.set(t,e))}encodeAll(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n,this.encode(n,r));return t}encode(e,t){return c(`test-config:${e}`,e,t,`test-value:${e}:${++this.revision}`)}},f=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(`initialize`)}completeInitialization(){this.connection.complete(`initialize`)}failInitialization(){this.connection.fail(`initialize`)}holdContextUpdate(){this.connection.hold(`updateContext`)}completeContextUpdate(){this.connection.complete(`updateContext`)}failContextUpdate(){this.connection.fail(`updateContext`)}get contextUpdates(){return this.connection.contextUpdates}};const p=(t,n)=>{var i,a;let s=(i=n==null?void 0:n.logger)==null?r():i,c=new d(s,(a=n==null?void 0:n.values)==null?{}:a);return new f(new o(()=>e,`test-client`,t,{logger:s,connection:{timeout:n==null?void 0:n.timeout}},{transport:c}),c)},m=e=>{let t=globalThis,n=t[s];return t[s]=e.client,()=>{t[s]=n}},h=e=>p({sdkName:`react-web-sdk`,sdkVersion:`1.9.1`},e);export{t as ConfigDirectorConnectionError,n as ConfigDirectorValidationError,h as createTestClient,m as installTestClient};
|
|
2
2
|
//# sourceMappingURL=configdirector-react-client-testing.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});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));const c=require(`./installedTestClient-BXUl11xD.cjs`);let l=require(`react`);l=s(l);let u=require(`react/jsx-runtime`);const d=l.default.createContext({status:`loading`}),f=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}};var p=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},m=class{constructor(e){this.turnedOff=!1,this.pendingEvaluations=[],this.pendingInvalidContextSubmissions=new p,this.logger=e.logger,this.workerCloseTimeout=e.workerCloseTimeout??6e3,this.pendingEvaluationLimit=e.evaluationQueueLimit??1e3,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:e.initialFlushIntervalDelay??5e3,flushIntervalDelay:e.flushIntervalDelay??3e4}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}createWorkerOrTurnOff(){if(typeof Worker>`u`){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.`);return}try{return new Worker(URL.createObjectURL(new Blob(["(function(){let e=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,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},n=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},r=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}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError;var a=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl)}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let i={clientSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(i))return{success:!0,fatalError:!1};let a=await this.sendReport(i);return a.fatalError&&(this.executeRequests=!1),a}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},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){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=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}))}},s=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}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new s(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()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},d=class extends c{constructor(e){super(e),this.invalidContextSubmissions=new u,this.reporter=new a(e),this.evaluationEventSnapshotPreprocessor=new l(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}recordInvalidContext(e){this.invalidContextSubmissions.record(e)}absorbInvalidContextSubmissions(e){this.invalidContextSubmissions.absorb(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e),invalidContext:this.invalidContextSubmissions.takeSnapshot()},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let f=(e,t)=>new URL(e,t?.toString()),p=(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`)},m=Math.ceil(128/Math.log2(62)),h=new TextEncoder,g=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,h.encode(e?.toString()??``));return p(new Uint8Array(t,0,16),m)},_,v=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),y=e=>{try{self.postMessage(e)}catch{self.postMessage(v(e.payload.level,e.payload.message))}},b={debug:function(e,...t){y(v(`debug`,e,t))},info:function(e,...t){y(v(`info`,e,t))},warn:function(e,...t){y(v(`warn`,e,t))},error:function(e,...t){y(v(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!_){b.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(b.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(_){b.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}_=new d({...t.payload,baseUrl:f(t.payload.baseUrl),urlFactory:f,valueIdGenerator:g,logger:b}),_.start();break;case`EvaluatedConfigEvent`:_?.evaluatedConfig(t.payload);break;case`InvalidContextSubmissions`:_?.absorbInvalidContextSubmissions(t.payload.entries);break;case`UpdateContext`:_?.updateContext(t.payload.context);break;case`Flush`:_?.forceFlush();break;case`Close`:(_?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();"],{type:`application/javascript`})))}catch(e){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: `,e);return}}turnOff(e,...t){this.turnedOff=!0,this.pendingEvaluations.length=0,this.logger.warn(e,...t)}startWorker(){if(this.worker||this.turnedOff)return this.worker;let e=this.createWorkerOrTurnOff();if(e){e.onmessage=e=>{this.handleWorkerEvent(e.data)},e.postMessage(this.initializeMessage),this.worker=e;try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}for(let t of this.pendingEvaluations)e.postMessage(t);return this.pendingEvaluations.length=0,this.forwardInvalidContextSubmissions(e),e}}forwardInvalidContextSubmissions(e){if(!e)return;let t=this.pendingInvalidContextSubmissions.takeSnapshot();if(t.length===0)return;let n={type:`InvalidContextSubmissions`,payload:{entries:t}};e.postMessage(n)}async updateContext(e){if(this.closePromise)return;let t={type:`UpdateContext`,payload:{context:e}};this.startWorker()?.postMessage(t)}evaluatedConfig(e){if(this.turnedOff)return;let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};if(this.worker){this.worker.postMessage(t);return}this.pendingEvaluations.length>=this.pendingEvaluationLimit&&this.pendingEvaluations.shift(),this.pendingEvaluations.push(t)}recordInvalidContext(e){this.pendingInvalidContextSubmissions.record(e),this.forwardInvalidContextSubmissions(this.worker)}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:f({value:e.defaultValue,type:e.type}),evaluatedValue:f({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}handleWorkerEvent(e){if(e.type===`Closed`){this.finishClose();return}if(!e.payload?.level||!e.payload?.message)return;let{level:t,message:n,args:r}=e.payload;switch(t){case`debug`:this.logger.debug(n,...r);break;case`info`:this.logger.info(n,...r);break;case`warn`:this.logger.warn(n,...r);break;case`error`:this.logger.error(n,...r);break}}flush(){this.worker?.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){clearTimeout(this.closeTimer),this.closeTimer=void 0,this.worker?.terminate(),this.closeResolve?.()}};const h=(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`)},g=Math.ceil(128/Math.log2(62)),_=new TextEncoder,v=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,_.encode(e?.toString()??``));return h(new Uint8Array(t,0,16),g)},y=(e,t,n)=>c.r.from(({clientSdkKey:e,baseUrl:n,logger:r,metadata:i})=>new m({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:i?.appName,appVersion:i?.appVersion},logger:r,baseUrl:n,urlFactory:c.i,valueIdGenerator:v}),e,t,n);var b=class{decorateMessage(e){return`[ConfigDirector:react-web-sdk] ${e}`}};const x=e=>c.o(e,new b),S=(e,t)=>{if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t))return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>S(e,t[n]));if(!C(e)||!C(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&S(e[n],t[n]))},C=e=>{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},w=(e,t)=>e.isInitializing?`none`:e.isReady?t!==void 0&&!S(t,e.context)?`updateContext`:`none`:`initialize`,T=(e,t)=>y(e,{sdkName:`react-web-sdk`,sdkVersion:`1.8.0`},t),E=e=>T(e.sdkKey,{connection:{url:e.url,timeout:e.timeout,mode:e.mode,pollingInterval:e.pollingInterval,values:e.values},metadata:{appName:e.appName,appVersion:e.appVersion},logger:e.logger??x(`warn`),hooks:e.hooks}),D=e=>`client`in e&&e.client!==void 0,O=e=>{if(D(e))return{client:e.client,owned:!1};let t=c.n();return t?{client:t,owned:!1}:{client:E(e),owned:!0}},k=async e=>{let t=c.n()??E({...e,logger:e.logger??x(`debug`)});switch(w(t,e.context)){case`initialize`:await t.initialize(e.context);break;case`updateContext`:await t.updateContext(e.context);break;case`none`:break}return({children:e})=>{let[n,r]=(0,l.useState)(()=>({client:t,status:t.isReady?`ready`:`default`}));return(0,l.useEffect)(()=>{let e=()=>{r(e=>({...e,updatedAt:new Date}))},n=()=>{r(e=>e.status===`ready`?e:{...e,status:`ready`})};return t.on(`configsUpdated`,e),t.on(`clientReady`,n),t.isReady&&n(),()=>{t.off(`configsUpdated`,e),t.off(`clientReady`,n)}},[]),(0,u.jsx)(d.Provider,{value:n,children:e})}};var A=class{constructor(e){this.client=e,this.registrations=[]}on(e,t){this.client.on(e,t),this.registrations.push({event:e,handler:t})}registerHooks(e){for(let[t,n]of Object.entries(e??{})){let e=Array.isArray(n)?n:[n];for(let n of e)typeof n==`function`&&this.on(t,n)}}removeAll(){for(let{event:e,handler:t}of this.registrations)this.client.off(e,t);this.registrations=[]}};const j=e=>e?.isReady?`ready`:`default`;var M=class extends l.Component{constructor(e){super(e),this.disposedOwnClient=!1;let t=O(e);this.ownsClient=t.owned,this.state={client:t.client,status:t.client.isReady?`ready`:`loading`}}async componentDidMount(){let e=this.state.client;this.ownsClient&&this.disposedOwnClient&&(e=E(this.props),this.disposedOwnClient=!1,this.setState({client:e,status:`loading`})),this.handlers=new A(e),this.handlers.on(`configsUpdated`,()=>{this.setState({updatedAt:new Date})}),this.handlers.on(`clientReady`,()=>{this.setState({status:`ready`})}),this.ownsClient||this.handlers.registerHooks(this.props.hooks),await this.connect(e,this.props.context)}async connect(e,t){switch(w(e,t)){case`initialize`:await e.initialize(t);break;case`updateContext`:this.setState({status:`loading`}),await e.updateContext(t);break;case`none`:return}this.setState({status:j(e)})}async componentDidUpdate(e){D(e)&&D(this.props)&&e.client!==this.props.client&&x(`warn`).warn(`The client prop of ConfigDirectorProvider changed after it mounted and is ignored. Remount the provider, for example with a new key, to use another client.`),S(e.context,this.props.context)||(this.setState({status:`loading`}),await this.state.client?.updateContext(this.props.context??{}),this.setState({status:j(this.state.client)}))}componentWillUnmount(){this.handlers?.removeAll(),this.handlers=void 0,this.ownsClient&&(this.state.client?.dispose(),this.disposedOwnClient=!0)}render(){return(0,u.jsx)(d.Provider,{value:this.state,children:this.props.children})}},N=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorReactContextError`,Object.setPrototypeOf(this,e.prototype)}};const P=()=>new N(`The ConfigDirector client was not found in the React context. Please make sure the component using this hook is inside the context of a ConfigDirectorProvider.`),F=(e,t)=>{let n=(0,l.useContext)(d);if(!n?.client)throw P();return{value:n.client.getValue(e,t),readyStatus:n.status,loading:n.status===`loading`}},I=()=>{let e=(0,l.useContext)(d);if(!e?.client)throw P();return{updateContext:async t=>{await e.client?.updateContext(t)}}},L=()=>{let e=(0,l.useContext)(d);if(!e?.client)throw P();return{client:e.client}};exports.ConfigDirectorProvider=M,exports.createConsoleLogger=x,exports.useClient=L,exports.useConfigValue=F,exports.useContext=I,exports.withProvider=k;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});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));const c=require(`./installedTestClient-DjPcNYN5.cjs`);let l=require(`react`);l=s(l);let u=require(`react/jsx-runtime`);const d=l.default.createContext({status:`loading`}),f=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}};var p=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},m=class{constructor(e){this.turnedOff=!1,this.pendingEvaluations=[],this.pendingInvalidContextSubmissions=new p,this.logger=e.logger,this.workerCloseTimeout=e.workerCloseTimeout??6e3,this.pendingEvaluationLimit=e.evaluationQueueLimit??1e3,this.clientSession=e.clientSession,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:e.initialFlushIntervalDelay??5e3,flushIntervalDelay:e.flushIntervalDelay??3e4}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}createWorkerOrTurnOff(){if(typeof Worker>`u`){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.`);return}try{return new Worker(URL.createObjectURL(new Blob(["(function(){let e=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,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},n=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},r=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}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError;var a=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl),this.clientSession=e.clientSession}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let{instanceId:i}=await this.clientSession,a={clientSdkKey:this.sdkKey,instanceId:i,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(a))return{success:!0,fatalError:!1};let o=await this.sendReport(a);return o.fatalError&&(this.executeRequests=!1),o}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},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){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=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}))}},s=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}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new s(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()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},d=class extends c{constructor(e){super(e),this.invalidContextSubmissions=new u,this.reporter=new a(e),this.evaluationEventSnapshotPreprocessor=new l(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}recordInvalidContext(e){this.invalidContextSubmissions.record(e)}absorbInvalidContextSubmissions(e){this.invalidContextSubmissions.absorb(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e),invalidContext:this.invalidContextSubmissions.takeSnapshot()},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let f=(e,t)=>new URL(e,t?.toString()),p=(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`)},m=Math.ceil(128/Math.log2(62)),h=new TextEncoder,g=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,h.encode(e?.toString()??``));return p(new Uint8Array(t,0,16),m)},_,v,y=new Promise(e=>{v=e}),b=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),x=e=>{try{self.postMessage(e)}catch{self.postMessage(b(e.payload.level,e.payload.message))}},S={debug:function(e,...t){x(b(`debug`,e,t))},info:function(e,...t){x(b(`info`,e,t))},warn:function(e,...t){x(b(`warn`,e,t))},error:function(e,...t){x(b(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!_){S.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(S.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(_){S.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}_=new d({...t.payload,baseUrl:f(t.payload.baseUrl),urlFactory:f,valueIdGenerator:g,logger:S,clientSession:y}),_.start();break;case`ClientSession`:v(t.payload);break;case`EvaluatedConfigEvent`:_?.evaluatedConfig(t.payload);break;case`InvalidContextSubmissions`:_?.absorbInvalidContextSubmissions(t.payload.entries);break;case`UpdateContext`:_?.updateContext(t.payload.context);break;case`Flush`:_?.forceFlush();break;case`Close`:(_?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();"],{type:`application/javascript`})))}catch(e){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: `,e);return}}turnOff(e,...t){this.turnedOff=!0,this.pendingEvaluations.length=0,this.logger.warn(e,...t)}startWorker(){if(this.worker||this.turnedOff)return this.worker;let e=this.createWorkerOrTurnOff();if(e){e.onmessage=e=>{this.handleWorkerEvent(e.data)},e.postMessage(this.initializeMessage),this.forwardClientSession(e),this.worker=e;try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}for(let t of this.pendingEvaluations)e.postMessage(t);return this.pendingEvaluations.length=0,this.forwardInvalidContextSubmissions(e),e}}forwardClientSession(e){this.clientSession.then(t=>{let n={type:`ClientSession`,payload:t};e.postMessage(n)})}forwardInvalidContextSubmissions(e){if(!e)return;let t=this.pendingInvalidContextSubmissions.takeSnapshot();if(t.length===0)return;let n={type:`InvalidContextSubmissions`,payload:{entries:t}};e.postMessage(n)}async updateContext(e){if(this.closePromise)return;let t={type:`UpdateContext`,payload:{context:e}};this.startWorker()?.postMessage(t)}evaluatedConfig(e){if(this.turnedOff)return;let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};if(this.worker){this.worker.postMessage(t);return}this.pendingEvaluations.length>=this.pendingEvaluationLimit&&this.pendingEvaluations.shift(),this.pendingEvaluations.push(t)}recordInvalidContext(e){this.pendingInvalidContextSubmissions.record(e),this.forwardInvalidContextSubmissions(this.worker)}sanitizeEvaluatedConfigEvent(e){return{...e,defaultValue:f({value:e.defaultValue,type:e.type}),evaluatedValue:f({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})}}handleWorkerEvent(e){if(e.type===`Closed`){this.finishClose();return}if(!e.payload?.level||!e.payload?.message)return;let{level:t,message:n,args:r}=e.payload;switch(t){case`debug`:this.logger.debug(n,...r);break;case`info`:this.logger.info(n,...r);break;case`warn`:this.logger.warn(n,...r);break;case`error`:this.logger.error(n,...r);break}}flush(){this.worker?.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){clearTimeout(this.closeTimer),this.closeTimer=void 0,this.worker?.terminate(),this.closeResolve?.()}};const h=(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`)},g=Math.ceil(128/Math.log2(62)),_=new TextEncoder,v=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,_.encode(e?.toString()??``));return h(new Uint8Array(t,0,16),g)},y=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``),b=async e=>{let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return c.i+y(new Uint8Array(t))},x=()=>typeof crypto<`u`&&crypto.subtle!=null,S=e=>{let t=c.o();if(!t||!x())return;let n=b(e);return{read:async()=>t.getItem(await n),write:async e=>t.setItem(await n,e),remove:async()=>t.removeItem(await n),sizeLimit:()=>c.a}},C=(e,t,n)=>c.r.from(({clientSdkKey:e,baseUrl:n,logger:r,metadata:i,clientSession:a})=>new m({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:i?.appName,appVersion:i?.appVersion},logger:r,baseUrl:n,urlFactory:c.s,valueIdGenerator:v,clientSession:a}),e,t,n,{platformCachingProvider:S});var w=class{decorateMessage(e){return`[ConfigDirector:react-web-sdk] ${e}`}};const T=e=>c.l(e,new w),E=(e,t)=>{if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t))return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>E(e,t[n]));if(!D(e)||!D(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&E(e[n],t[n]))},D=e=>{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},O=(e,t)=>e.isInitializing?`none`:e.isReady?t!==void 0&&!E(t,e.context)?`updateContext`:`none`:`initialize`,k=(e,t)=>C(e,{sdkName:`react-web-sdk`,sdkVersion:`1.9.1`},t),A=e=>k(e.sdkKey,{connection:{url:e.url,timeout:e.timeout,mode:e.mode,pollingInterval:e.pollingInterval,values:e.values},metadata:{appName:e.appName,appVersion:e.appVersion},logger:e.logger??T(`warn`),hooks:e.hooks,caching:e.caching}),j=e=>`client`in e&&e.client!==void 0,M=e=>{if(j(e))return{client:e.client,owned:!1};let t=c.n();return t?{client:t,owned:!1}:{client:A(e),owned:!0}},N=async e=>{let t=c.n()??A({...e,logger:e.logger??T(`debug`)});switch(O(t,e.context)){case`initialize`:await t.initialize(e.context);break;case`updateContext`:await t.updateContext(e.context);break;case`none`:break}return({children:e})=>{let[n,r]=(0,l.useState)(()=>({client:t,status:t.isReady?`ready`:`default`}));return(0,l.useEffect)(()=>{let e=()=>{r(e=>({...e,updatedAt:new Date}))},n=()=>{r(e=>e.status===`ready`?e:{...e,status:`ready`})};return t.on(`configsUpdated`,e),t.on(`clientReady`,n),t.isReady&&n(),()=>{t.off(`configsUpdated`,e),t.off(`clientReady`,n)}},[]),(0,u.jsx)(d.Provider,{value:n,children:e})}};var P=class{constructor(e){this.client=e,this.registrations=[]}on(e,t){this.client.on(e,t),this.registrations.push({event:e,handler:t})}registerHooks(e){for(let[t,n]of Object.entries(e??{})){let e=Array.isArray(n)?n:[n];for(let n of e)typeof n==`function`&&this.on(t,n)}}removeAll(){for(let{event:e,handler:t}of this.registrations)this.client.off(e,t);this.registrations=[]}};const F=e=>e?.isReady?`ready`:`default`;var I=class extends l.Component{constructor(e){super(e),this.disposedOwnClient=!1;let t=M(e);this.ownsClient=t.owned,this.state={client:t.client,status:t.client.isReady?`ready`:`loading`}}async componentDidMount(){let e=this.state.client;this.ownsClient&&this.disposedOwnClient&&(e=A(this.props),this.disposedOwnClient=!1,this.setState({client:e,status:`loading`})),this.handlers=new P(e),this.handlers.on(`configsUpdated`,()=>{this.setState({updatedAt:new Date})}),this.handlers.on(`clientReady`,()=>{this.setState({status:`ready`})}),this.ownsClient||this.handlers.registerHooks(this.props.hooks),await this.connect(e,this.props.context)}async connect(e,t){switch(O(e,t)){case`initialize`:await e.initialize(t);break;case`updateContext`:this.setState({status:`loading`}),await e.updateContext(t);break;case`none`:return}this.setState({status:F(e)})}async componentDidUpdate(e){j(e)&&j(this.props)&&e.client!==this.props.client&&T(`warn`).warn(`The client prop of ConfigDirectorProvider changed after it mounted and is ignored. Remount the provider, for example with a new key, to use another client.`),E(e.context,this.props.context)||(this.setState({status:`loading`}),await this.state.client?.updateContext(this.props.context??{}),this.setState({status:F(this.state.client)}))}componentWillUnmount(){this.handlers?.removeAll(),this.handlers=void 0,this.ownsClient&&(this.state.client?.dispose(),this.disposedOwnClient=!0)}render(){return(0,u.jsx)(d.Provider,{value:this.state,children:this.props.children})}},L=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorReactContextError`,Object.setPrototypeOf(this,e.prototype)}};const R=()=>new L(`The ConfigDirector client was not found in the React context. Please make sure the component using this hook is inside the context of a ConfigDirectorProvider.`),z=(e,t)=>{let n=(0,l.useContext)(d);if(!n?.client)throw R();return{value:n.client.getValue(e,t),readyStatus:n.status,loading:n.status===`loading`}},B=()=>{let e=(0,l.useContext)(d);if(!e?.client)throw R();return{updateContext:async t=>{await e.client?.updateContext(t)}}},V=()=>{let e=(0,l.useContext)(d);if(!e?.client)throw R();return{client:e.client}};exports.ConfigDirectorProvider=I,exports.createConsoleLogger=T,exports.useClient=V,exports.useConfigValue=z,exports.useContext=B,exports.withProvider=N;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as OfflineValue, d as ConfigDirectorLogger, f as ConfigDirectorLoggingLevel, i as ConfigDirectorClient, m as ConnectionMode, n as CachingProvider, o as OfflineValues, p as ConfigValueType, r as ClientHooks, t as CachingOptions, u as ConfigDirectorContext } from "./types-CFBLmqUM.cjs";
|
|
2
2
|
import * as _$react_jsx_runtime0 from "react/jsx-runtime";
|
|
3
3
|
import { Component, PropsWithChildren, ReactNode } from "react";
|
|
4
4
|
|
|
@@ -46,6 +46,12 @@ type ConfigDirectorProviderOptions = {
|
|
|
46
46
|
context?: ConfigDirectorContext;
|
|
47
47
|
logger?: ConfigDirectorLogger;
|
|
48
48
|
hooks?: ClientHooks;
|
|
49
|
+
/**
|
|
50
|
+
* Options for the values the client keeps on the device between launches. The last values received
|
|
51
|
+
* are kept by default and served, with the evaluation reason `cached`, on the next launch of the same
|
|
52
|
+
* context until live values arrive.
|
|
53
|
+
*/
|
|
54
|
+
caching?: CachingOptions;
|
|
49
55
|
};
|
|
50
56
|
/**
|
|
51
57
|
* Props of a `ConfigDirectorProvider` given an existing client instead of the options to build one,
|
|
@@ -107,5 +113,5 @@ declare const useClient: () => {
|
|
|
107
113
|
//#region src/logger.d.ts
|
|
108
114
|
declare const createConsoleLogger: (level: ConfigDirectorLoggingLevel) => ConfigDirectorLogger;
|
|
109
115
|
//#endregion
|
|
110
|
-
export { type ClientStatus, type ConfigDirectorClient, type ConfigDirectorContext, ConfigDirectorProvider, type ConfigDirectorProviderClientProps, type ConfigDirectorProviderOptions, type ConfigDirectorProviderProps, type ConnectionMode, type OfflineValue, type OfflineValues, createConsoleLogger, useClient, useConfigValue, useContext, withProvider };
|
|
116
|
+
export { type CachingOptions, type CachingProvider, type ClientStatus, type ConfigDirectorClient, type ConfigDirectorContext, ConfigDirectorProvider, type ConfigDirectorProviderClientProps, type ConfigDirectorProviderOptions, type ConfigDirectorProviderProps, type ConnectionMode, type OfflineValue, type OfflineValues, createConsoleLogger, useClient, useConfigValue, useContext, withProvider };
|
|
111
117
|
//# sourceMappingURL=configdirector-react-client.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configdirector-react-client.d.cts","names":[],"sources":["../src/types.ts","../src/withProvider.tsx","../src/provider.tsx","../src/hooks.tsx","../src/logger.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"configdirector-react-client.d.cts","names":[],"sources":["../src/types.ts","../src/withProvider.tsx","../src/provider.tsx","../src/hooks.tsx","../src/logger.ts"],"mappings":";;;;;KAaY,YAAA;AAAA,UAEK,yBAAA;EACf,MAAA,GAAS,oBAAA;EACT,SAAA,GAAY,IAAA;EACZ,MAAA,EAAQ,YAAA;AAAA;AAAA,KAGE,2BAAA,GAA8B,yBAAA;AAAA,KAE9B,6BAAA;EARK;;;EAYf,MAAA;EACA,OAAA;EACA,UAAA;EACA,GAAA;EACA,OAAA;EAfA;;;;;;;;AAKF;EAoBE,IAAA,GAAO,cAAA;;;;AAlBT;;;EAyBE,MAAA,GAAS,aAAA;EAAA;;;;;;EAOT,eAAA;EACA,OAAA,GAAU,qBAAA;EACV,MAAA,GAAS,oBAAA;EACT,KAAA,GAAQ,WAAA;EA5BR;;;;;EAkCA,OAAA,GAAU,cAAA;AAAA;;;;;KAOA,iCAAA;EAbF;;;;;AAaV;EAOE,MAAA,EAAQ,oBAAA;EACR,OAAA,GAAU,qBAAA;EADF;;;;EAMR,KAAA,GAAQ,WAAA;AAAA;;;;KAME,2BAAA,GAA8B,6BAAA,GAAgC,iCAAA;;;cCjF7D,YAAA,GAAsB,OAAA,EAAS,6BAAA,KAA6B,OAAA;EAAA;AAAA;EAcvB,QAAA,EAAU,SAAA;AAAA,MAAW,oBAAA,CAAA,GAAA,CAAA,OAAA;;;cCL1D,sBAAA,SAA+B,SAAA,CAC1C,iBAAA,CAAkB,2BAAA,GAClB,2BAAA;EAAA,iBAEiB,UAAA;EAAA,QACT,iBAAA;EAAA,QACA,QAAA;cAEI,KAAA,EAAO,2BAAA;EAOJ,iBAAA,CAAA,GAAqB,OAAA;EAAA,QAoBtB,OAAA;EAeC,kBAAA,CAAmB,SAAA,EAAW,iBAAA,CAAkB,2BAAA,IAA+B,OAAA;EAarF,oBAAA,CAAA;EASA,MAAA,CAAA,GAAM,oBAAA,CAAA,GAAA,CAAA,OAAA;AAAA;;;cC3EX,cAAA,aAA4B,eAAA,EAChC,GAAA,UACA,YAAA,EAAc,CAAA;EAEd,KAAA,EAAO,CAAA;EACP,WAAA,EAAa,YAAA;EACb,OAAA;AAAA;AAAA,cAYI,UAAA;2BAMkC,qBAAA,KAAqB,OAAA;AAAA;AAAA,cAOvD,SAAA;UAOL,oBAAA;AAAA;;;cCvCY,mBAAA,GAAuB,KAAA,EAAO,0BAAA,KAA6B,oBAAA"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as OfflineValue, d as ConfigDirectorLogger, f as ConfigDirectorLoggingLevel, i as ConfigDirectorClient, m as ConnectionMode, n as CachingProvider, o as OfflineValues, p as ConfigValueType, r as ClientHooks, t as CachingOptions, u as ConfigDirectorContext } from "./types-CrgXfAWw.mjs";
|
|
2
2
|
import { Component, PropsWithChildren, ReactNode } from "react";
|
|
3
3
|
import * as _$react_jsx_runtime0 from "react/jsx-runtime";
|
|
4
4
|
|
|
@@ -46,6 +46,12 @@ type ConfigDirectorProviderOptions = {
|
|
|
46
46
|
context?: ConfigDirectorContext;
|
|
47
47
|
logger?: ConfigDirectorLogger;
|
|
48
48
|
hooks?: ClientHooks;
|
|
49
|
+
/**
|
|
50
|
+
* Options for the values the client keeps on the device between launches. The last values received
|
|
51
|
+
* are kept by default and served, with the evaluation reason `cached`, on the next launch of the same
|
|
52
|
+
* context until live values arrive.
|
|
53
|
+
*/
|
|
54
|
+
caching?: CachingOptions;
|
|
49
55
|
};
|
|
50
56
|
/**
|
|
51
57
|
* Props of a `ConfigDirectorProvider` given an existing client instead of the options to build one,
|
|
@@ -107,5 +113,5 @@ declare const useClient: () => {
|
|
|
107
113
|
//#region src/logger.d.ts
|
|
108
114
|
declare const createConsoleLogger: (level: ConfigDirectorLoggingLevel) => ConfigDirectorLogger;
|
|
109
115
|
//#endregion
|
|
110
|
-
export { type ClientStatus, type ConfigDirectorClient, type ConfigDirectorContext, ConfigDirectorProvider, type ConfigDirectorProviderClientProps, type ConfigDirectorProviderOptions, type ConfigDirectorProviderProps, type ConnectionMode, type OfflineValue, type OfflineValues, createConsoleLogger, useClient, useConfigValue, useContext, withProvider };
|
|
116
|
+
export { type CachingOptions, type CachingProvider, type ClientStatus, type ConfigDirectorClient, type ConfigDirectorContext, ConfigDirectorProvider, type ConfigDirectorProviderClientProps, type ConfigDirectorProviderOptions, type ConfigDirectorProviderProps, type ConnectionMode, type OfflineValue, type OfflineValues, createConsoleLogger, useClient, useConfigValue, useContext, withProvider };
|
|
111
117
|
//# sourceMappingURL=configdirector-react-client.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configdirector-react-client.d.mts","names":[],"sources":["../src/types.ts","../src/withProvider.tsx","../src/provider.tsx","../src/hooks.tsx","../src/logger.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"configdirector-react-client.d.mts","names":[],"sources":["../src/types.ts","../src/withProvider.tsx","../src/provider.tsx","../src/hooks.tsx","../src/logger.ts"],"mappings":";;;;;KAaY,YAAA;AAAA,UAEK,yBAAA;EACf,MAAA,GAAS,oBAAA;EACT,SAAA,GAAY,IAAA;EACZ,MAAA,EAAQ,YAAA;AAAA;AAAA,KAGE,2BAAA,GAA8B,yBAAA;AAAA,KAE9B,6BAAA;EARK;;;EAYf,MAAA;EACA,OAAA;EACA,UAAA;EACA,GAAA;EACA,OAAA;EAfA;;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qDdos7F.mjs";import a,{Component as o,useContext as s,useEffect as c,useState as l}from"react";import{jsx as u}from"react/jsx-runtime";const d=a.createContext({status:`loading`}),f=e=>{var t;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(t){return{value:e.value.toString(),type:`json`}}}let n=(t=e.value)==null?void 0:t.toString();return n&&n.length<=500?{value:n}:e.valueId?{valueId:e.valueId}:{value:n}};var p=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime!=null||(this.startTime=new Date),this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){var e;let t=new Date,n=(e=this.startTime)==null?t:e,r=(e,r)=>({startTime:n,endTime:t,count:e,event:{reason:`invalid-context-kind`,kindSample:r}}),i=Array.from(this.countsByKindSample,([e,t])=>r(t,e)),a=this.countBeyondSampleLimit>0?[...i,r(this.countBeyondSampleLimit)]:i;return this.clear(),a}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},m=class{constructor(e){var t,n,r,i;this.turnedOff=!1,this.pendingEvaluations=[],this.pendingInvalidContextSubmissions=new p,this.logger=e.logger,this.workerCloseTimeout=(t=e.workerCloseTimeout)==null?6e3:t,this.pendingEvaluationLimit=(n=e.evaluationQueueLimit)==null?1e3:n,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:(r=e.initialFlushIntervalDelay)==null?5e3:r,flushIntervalDelay:(i=e.flushIntervalDelay)==null?3e4:i}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}createWorkerOrTurnOff(){if(typeof Worker>`u`){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.`);return}try{return new Worker(URL.createObjectURL(new Blob(["(function(){let e=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,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},n=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},r=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}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError;var a=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl)}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let i={clientSdkKey:this.sdkKey,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(i))return{success:!0,fatalError:!1};let a=await this.sendReport(i);return a.fatalError&&(this.executeRequests=!1),a}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},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){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=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}))}},s=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}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new s(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()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},d=class extends c{constructor(e){super(e),this.invalidContextSubmissions=new u,this.reporter=new a(e),this.evaluationEventSnapshotPreprocessor=new l(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}recordInvalidContext(e){this.invalidContextSubmissions.record(e)}absorbInvalidContextSubmissions(e){this.invalidContextSubmissions.absorb(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e),invalidContext:this.invalidContextSubmissions.takeSnapshot()},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let f=(e,t)=>new URL(e,t?.toString()),p=(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`)},m=Math.ceil(128/Math.log2(62)),h=new TextEncoder,g=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,h.encode(e?.toString()??``));return p(new Uint8Array(t,0,16),m)},_,v=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),y=e=>{try{self.postMessage(e)}catch{self.postMessage(v(e.payload.level,e.payload.message))}},b={debug:function(e,...t){y(v(`debug`,e,t))},info:function(e,...t){y(v(`info`,e,t))},warn:function(e,...t){y(v(`warn`,e,t))},error:function(e,...t){y(v(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!_){b.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(b.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(_){b.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}_=new d({...t.payload,baseUrl:f(t.payload.baseUrl),urlFactory:f,valueIdGenerator:g,logger:b}),_.start();break;case`EvaluatedConfigEvent`:_?.evaluatedConfig(t.payload);break;case`InvalidContextSubmissions`:_?.absorbInvalidContextSubmissions(t.payload.entries);break;case`UpdateContext`:_?.updateContext(t.payload.context);break;case`Flush`:_?.forceFlush();break;case`Close`:(_?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();"],{type:`application/javascript`})))}catch(e){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: `,e);return}}turnOff(e,...t){this.turnedOff=!0,this.pendingEvaluations.length=0,this.logger.warn(e,...t)}startWorker(){if(this.worker||this.turnedOff)return this.worker;let e=this.createWorkerOrTurnOff();if(e){e.onmessage=e=>{this.handleWorkerEvent(e.data)},e.postMessage(this.initializeMessage),this.worker=e;try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}for(let t of this.pendingEvaluations)e.postMessage(t);return this.pendingEvaluations.length=0,this.forwardInvalidContextSubmissions(e),e}}forwardInvalidContextSubmissions(e){if(!e)return;let t=this.pendingInvalidContextSubmissions.takeSnapshot();if(t.length===0)return;let n={type:`InvalidContextSubmissions`,payload:{entries:t}};e.postMessage(n)}async updateContext(e){var t=this,n;if(t.closePromise)return;let r={type:`UpdateContext`,payload:{context:e}};(n=t.startWorker())==null||n.postMessage(r)}evaluatedConfig(e){if(this.turnedOff)return;let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};if(this.worker){this.worker.postMessage(t);return}this.pendingEvaluations.length>=this.pendingEvaluationLimit&&this.pendingEvaluations.shift(),this.pendingEvaluations.push(t)}recordInvalidContext(e){this.pendingInvalidContextSubmissions.record(e),this.forwardInvalidContextSubmissions(this.worker)}sanitizeEvaluatedConfigEvent(t){return e(e({},t),{},{defaultValue:f({value:t.defaultValue,type:t.type}),evaluatedValue:f({value:t.evaluatedValue,valueId:t.evaluatedValueId,type:t.type})})}handleWorkerEvent(e){var t,n;if(e.type===`Closed`){this.finishClose();return}if(!((t=e.payload)!=null&&t.level)||!((n=e.payload)!=null&&n.message))return;let{level:r,message:i,args:a}=e.payload;switch(r){case`debug`:this.logger.debug(i,...a);break;case`info`:this.logger.info(i,...a);break;case`warn`:this.logger.warn(i,...a);break;case`error`:this.logger.error(i,...a);break}}flush(){var e;(e=this.worker)==null||e.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){var e,t;clearTimeout(this.closeTimer),this.closeTimer=void 0,(e=this.worker)==null||e.terminate(),(t=this.closeResolve)==null||t.call(this)}};const h=(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`)},g=Math.ceil(128/Math.log2(62)),_=new TextEncoder,v=async e=>{var t;if(typeof crypto>`u`||crypto.subtle==null)return;let n=await crypto.subtle.digest(`SHA-256`,_.encode((t=e==null?void 0:e.toString())==null?``:t));return h(new Uint8Array(n,0,16),g)},y=(e,n,r)=>i.from(({clientSdkKey:e,baseUrl:r,logger:i,metadata:a})=>new m({sdkKey:e,sdkIdentity:{sdkName:n.sdkName,sdkVersion:n.sdkVersion},metaContext:{appName:a==null?void 0:a.appName,appVersion:a==null?void 0:a.appVersion},logger:i,baseUrl:r,urlFactory:t,valueIdGenerator:v}),e,n,r);var b=class{decorateMessage(e){return`[ConfigDirector:react-web-sdk] ${e}`}};const x=e=>r(e,new b),S=(e,t)=>{if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t))return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>S(e,t[n]));if(!C(e)||!C(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&S(e[n],t[n]))},C=e=>{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},w=(e,t)=>e.isInitializing?`none`:e.isReady?t!==void 0&&!S(t,e.context)?`updateContext`:`none`:`initialize`,T=(e,t)=>y(e,{sdkName:`react-web-sdk`,sdkVersion:`1.8.0`},t),E=e=>{var t;return T(e.sdkKey,{connection:{url:e.url,timeout:e.timeout,mode:e.mode,pollingInterval:e.pollingInterval,values:e.values},metadata:{appName:e.appName,appVersion:e.appVersion},logger:(t=e.logger)==null?x(`warn`):t,hooks:e.hooks})},D=e=>`client`in e&&e.client!==void 0,O=e=>{if(D(e))return{client:e.client,owned:!1};let t=n();return t?{client:t,owned:!1}:{client:E(e),owned:!0}},k=async t=>{var r,i;let a=(r=n())==null?E(e(e({},t),{},{logger:(i=t.logger)==null?x(`debug`):i})):r;switch(w(a,t.context)){case`initialize`:await a.initialize(t.context);break;case`updateContext`:await a.updateContext(t.context);break;case`none`:break}return({children:t})=>{let[n,r]=l(()=>({client:a,status:a.isReady?`ready`:`default`}));return c(()=>{let t=()=>{r(t=>e(e({},t),{},{updatedAt:new Date}))},n=()=>{r(t=>t.status===`ready`?t:e(e({},t),{},{status:`ready`}))};return a.on(`configsUpdated`,t),a.on(`clientReady`,n),a.isReady&&n(),()=>{a.off(`configsUpdated`,t),a.off(`clientReady`,n)}},[]),u(d.Provider,{value:n,children:t})}};var A=class{constructor(e){this.client=e,this.registrations=[]}on(e,t){this.client.on(e,t),this.registrations.push({event:e,handler:t})}registerHooks(e){for(let[t,n]of Object.entries(e==null?{}:e)){let e=Array.isArray(n)?n:[n];for(let n of e)typeof n==`function`&&this.on(t,n)}}removeAll(){for(let{event:e,handler:t}of this.registrations)this.client.off(e,t);this.registrations=[]}};const j=e=>e!=null&&e.isReady?`ready`:`default`;var M=class extends o{constructor(e){super(e),this.disposedOwnClient=!1;let t=O(e);this.ownsClient=t.owned,this.state={client:t.client,status:t.client.isReady?`ready`:`loading`}}async componentDidMount(){var e=this;let t=e.state.client;e.ownsClient&&e.disposedOwnClient&&(t=E(e.props),e.disposedOwnClient=!1,e.setState({client:t,status:`loading`})),e.handlers=new A(t),e.handlers.on(`configsUpdated`,()=>{e.setState({updatedAt:new Date})}),e.handlers.on(`clientReady`,()=>{e.setState({status:`ready`})}),e.ownsClient||e.handlers.registerHooks(e.props.hooks),await e.connect(t,e.props.context)}async connect(e,t){var n=this;switch(w(e,t)){case`initialize`:await e.initialize(t);break;case`updateContext`:n.setState({status:`loading`}),await e.updateContext(t);break;case`none`:return}n.setState({status:j(e)})}async componentDidUpdate(e){var t=this;if(D(e)&&D(t.props)&&e.client!==t.props.client&&x(`warn`).warn(`The client prop of ConfigDirectorProvider changed after it mounted and is ignored. Remount the provider, for example with a new key, to use another client.`),!S(e.context,t.props.context)){var n,r;t.setState({status:`loading`}),await((n=t.state.client)==null?void 0:n.updateContext((r=t.props.context)==null?{}:r)),t.setState({status:j(t.state.client)})}}componentWillUnmount(){var e;if((e=this.handlers)==null||e.removeAll(),this.handlers=void 0,this.ownsClient){var t;(t=this.state.client)==null||t.dispose(),this.disposedOwnClient=!0}}render(){return u(d.Provider,{value:this.state,children:this.props.children})}},N=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorReactContextError`,Object.setPrototypeOf(this,e.prototype)}};const P=()=>new N(`The ConfigDirector client was not found in the React context. Please make sure the component using this hook is inside the context of a ConfigDirectorProvider.`),F=(e,t)=>{let n=s(d);if(!(n!=null&&n.client))throw P();return{value:n.client.getValue(e,t),readyStatus:n.status,loading:n.status===`loading`}},I=()=>{let e=s(d);if(!(e!=null&&e.client))throw P();return{updateContext:async t=>{var n;await((n=e.client)==null?void 0:n.updateContext(t))}}},L=()=>{let e=s(d);if(!(e!=null&&e.client))throw P();return{client:e.client}};export{M as ConfigDirectorProvider,x as createConsoleLogger,L as useClient,F as useConfigValue,I as useContext,k as withProvider};
|
|
1
|
+
import{a as e,i as t,l as n,m as r,n as i,o as a,r as o,s}from"./installedTestClient-BY0SbL31.mjs";import c,{Component as l,useContext as u,useEffect as d,useState as f}from"react";import{jsx as p}from"react/jsx-runtime";const m=c.createContext({status:`loading`}),h=e=>{var t;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(t){return{value:e.value.toString(),type:`json`}}}let n=(t=e.value)==null?void 0:t.toString();return n&&n.length<=500?{value:n}:e.valueId?{valueId:e.valueId}:{value:n}};var g=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime!=null||(this.startTime=new Date),this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){var e;let t=new Date,n=(e=this.startTime)==null?t:e,r=(e,r)=>({startTime:n,endTime:t,count:e,event:{reason:`invalid-context-kind`,kindSample:r}}),i=Array.from(this.countsByKindSample,([e,t])=>r(t,e)),a=this.countBeyondSampleLimit>0?[...i,r(this.countBeyondSampleLimit)]:i;return this.clear(),a}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},_=class{constructor(e){var t,n,r,i;this.turnedOff=!1,this.pendingEvaluations=[],this.pendingInvalidContextSubmissions=new g,this.logger=e.logger,this.workerCloseTimeout=(t=e.workerCloseTimeout)==null?6e3:t,this.pendingEvaluationLimit=(n=e.evaluationQueueLimit)==null?1e3:n,this.clientSession=e.clientSession,this.initializeMessage={type:`Initialize`,payload:{sdkKey:e.sdkKey,sdkIdentity:e.sdkIdentity,metaContext:e.metaContext,baseUrl:e.baseUrl.toString(),evaluationQueueLimit:this.pendingEvaluationLimit,initialFlushIntervalDelay:(r=e.initialFlushIntervalDelay)==null?5e3:r,flushIntervalDelay:(i=e.flushIntervalDelay)==null?3e4:i}},this.visibilityHandler=()=>{document.visibilityState===`hidden`&&this.flush()}}createWorkerOrTurnOff(){if(typeof Worker>`u`){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.`);return}try{return new Worker(URL.createObjectURL(new Blob(["(function(){let e=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,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},n=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},r=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}},i=e=>e?.name===`NotAllowedError`?!0:e instanceof TypeError;var a=class{constructor(e){this.executeRequests=!0,this.sdkKey=e.sdkKey,this.logger=e.logger,this.sdkIdentity=e.sdkIdentity,this.metaContext=e.metaContext,this.url=e.urlFactory(`client/telemetry/v1`,e.baseUrl),this.clientSession=e.clientSession}async report({context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r}){if(!this.executeRequests)return{success:!1,fatalError:!0};let{instanceId:i}=await this.clientSession,a={clientSdkKey:this.sdkKey,instanceId:i,metaContext:{sdkName:this.sdkIdentity.sdkName,sdkVersion:this.sdkIdentity.sdkVersion,appName:this.metaContext.appName,appVersion:this.metaContext.appVersion},context:e,discreteEvents:t,aggregatedEvents:n,droppedEvents:r};if(this.isReportEmpty(a))return{success:!0,fatalError:!1};let o=await this.sendReport(a);return o.fatalError&&(this.executeRequests=!1),o}isReportEmpty(e){return t(e.discreteEvents)&&t(e.aggregatedEvents)&&n(e.droppedEvents)}async sendReport(e){try{let t=await r(5e3,this.url,{method:`POST`,body:JSON.stringify(e),keepalive:!0},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){let t=i(e);return this.logger.warn(`[EventReporter] Error attempting to send telemetry data: ${e}`,{error:e}),{success:!1,fatalError:t}}}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}},o=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}))}},s=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}},c=class{constructor(e){this.aggregator=new o,this.collectEvents=!0,this.started=!1,this.logger=e.logger,this.evaluationEventQueue=new s(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()}},l=class{constructor(e){this.valueIdGenerator=e,this.valueIdGenerator=e}async process(t){let n=await Promise.all(t.events.map(async t=>({...t,defaultValue:await e(t.defaultValue,this.valueIdGenerator),evaluatedValue:await e(t.evaluatedValue,this.valueIdGenerator)})));return{...t,events:n}}},u=class{constructor(){this.countsByKindSample=new Map,this.countBeyondSampleLimit=0}record(e){return this.startTime??=new Date,this.add(e,1)}absorb(e){for(let t of e)(this.startTime===void 0||t.startTime<this.startTime)&&(this.startTime=t.startTime),this.add(t.event.kindSample,t.count)}add(e,t){if(e!==void 0){let n=this.countsByKindSample.get(e);if(n!==void 0)return this.countsByKindSample.set(e,n+t),`known-kind-sample`;if(this.countsByKindSample.size<20)return this.countsByKindSample.set(e,t),`new-kind-sample`}let n=this.countBeyondSampleLimit===0;return this.countBeyondSampleLimit+=t,n?`first-beyond-sample-limit`:`beyond-sample-limit`}takeSnapshot(){let e=new Date,t=this.startTime??e,n=(n,r)=>({startTime:t,endTime:e,count:n,event:{reason:`invalid-context-kind`,kindSample:r}}),r=Array.from(this.countsByKindSample,([e,t])=>n(t,e)),i=this.countBeyondSampleLimit>0?[...r,n(this.countBeyondSampleLimit)]:r;return this.clear(),i}clear(){this.countsByKindSample.clear(),this.countBeyondSampleLimit=0,this.startTime=void 0}},d=class extends c{constructor(e){super(e),this.invalidContextSubmissions=new u,this.reporter=new a(e),this.evaluationEventSnapshotPreprocessor=new l(e.valueIdGenerator)}async updateContext(e){this.cancelScheduledFlush(),await this.flush(),this._context=e,await this.flushAndScheduleNext()}evaluatedConfig(e){this.collectEvents&&this.evaluationEventQueue.push(e)}recordInvalidContext(e){this.invalidContextSubmissions.record(e)}absorbInvalidContextSubmissions(e){this.invalidContextSubmissions.absorb(e)}async forceFlush(){this.cancelScheduledFlush(),await this.flushAndScheduleNext()}async flush(){if(!this.reporter)return{success:!1,fatalError:!1};let e=await this.evaluationEventSnapshotPreprocessor.process(this.evaluationEventQueue.takeSnapshot());return await this.reporter?.report({context:this._context,discreteEvents:{},aggregatedEvents:{evaluatedConfig:this.aggregator.aggregate(e),invalidContext:this.invalidContextSubmissions.takeSnapshot()},droppedEvents:{evaluatedConfig:e.droppedCount}})}};let f=(e,t)=>new URL(e,t?.toString()),p=(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`)},m=Math.ceil(128/Math.log2(62)),h=new TextEncoder,g=async e=>{if(typeof crypto>`u`||crypto.subtle==null)return;let t=await crypto.subtle.digest(`SHA-256`,h.encode(e?.toString()??``));return p(new Uint8Array(t,0,16),m)},_,v,y=new Promise(e=>{v=e}),b=(e,t,...n)=>({type:`Log`,payload:{level:e,message:t,args:n}}),x=e=>{try{self.postMessage(e)}catch{self.postMessage(b(e.payload.level,e.payload.message))}},S={debug:function(e,...t){x(b(`debug`,e,t))},info:function(e,...t){x(b(`info`,e,t))},warn:function(e,...t){x(b(`warn`,e,t))},error:function(e,...t){x(b(`error`,e,t))}};addEventListener(`message`,e=>{let t=e.data;if(t.type!=`Initialize`&&!_){S.info(`[TelemetryWorker] Ignoring ${t.type} because no collector is configured`);return}switch(S.debug(`[TelemetryWorker] Received '${t.type}' event:`,t),t.type){case`Initialize`:if(_){S.warn(`[TelemetryWorker] Received a duplicate Initialize event, ignoring it`);break}_=new d({...t.payload,baseUrl:f(t.payload.baseUrl),urlFactory:f,valueIdGenerator:g,logger:S,clientSession:y}),_.start();break;case`ClientSession`:v(t.payload);break;case`EvaluatedConfigEvent`:_?.evaluatedConfig(t.payload);break;case`InvalidContextSubmissions`:_?.absorbInvalidContextSubmissions(t.payload.entries);break;case`UpdateContext`:_?.updateContext(t.payload.context);break;case`Flush`:_?.forceFlush();break;case`Close`:(_?.close()??Promise.resolve()).then(()=>{self.postMessage({type:`Closed`}),self.close()});break}})})();"],{type:`application/javascript`})))}catch(e){this.turnOff(`[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: `,e);return}}turnOff(e,...t){this.turnedOff=!0,this.pendingEvaluations.length=0,this.logger.warn(e,...t)}startWorker(){if(this.worker||this.turnedOff)return this.worker;let e=this.createWorkerOrTurnOff();if(e){e.onmessage=e=>{this.handleWorkerEvent(e.data)},e.postMessage(this.initializeMessage),this.forwardClientSession(e),this.worker=e;try{document.addEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[TelemetryEventCollector] Could not configure 'visibilitychange' listener: `,e)}for(let t of this.pendingEvaluations)e.postMessage(t);return this.pendingEvaluations.length=0,this.forwardInvalidContextSubmissions(e),e}}forwardClientSession(e){this.clientSession.then(t=>{let n={type:`ClientSession`,payload:t};e.postMessage(n)})}forwardInvalidContextSubmissions(e){if(!e)return;let t=this.pendingInvalidContextSubmissions.takeSnapshot();if(t.length===0)return;let n={type:`InvalidContextSubmissions`,payload:{entries:t}};e.postMessage(n)}async updateContext(e){var t=this,n;if(t.closePromise)return;let r={type:`UpdateContext`,payload:{context:e}};(n=t.startWorker())==null||n.postMessage(r)}evaluatedConfig(e){if(this.turnedOff)return;let t={type:`EvaluatedConfigEvent`,payload:this.sanitizeEvaluatedConfigEvent(e)};if(this.worker){this.worker.postMessage(t);return}this.pendingEvaluations.length>=this.pendingEvaluationLimit&&this.pendingEvaluations.shift(),this.pendingEvaluations.push(t)}recordInvalidContext(e){this.pendingInvalidContextSubmissions.record(e),this.forwardInvalidContextSubmissions(this.worker)}sanitizeEvaluatedConfigEvent(e){return r(r({},e),{},{defaultValue:h({value:e.defaultValue,type:e.type}),evaluatedValue:h({value:e.evaluatedValue,valueId:e.evaluatedValueId,type:e.type})})}handleWorkerEvent(e){var t,n;if(e.type===`Closed`){this.finishClose();return}if(!((t=e.payload)!=null&&t.level)||!((n=e.payload)!=null&&n.message))return;let{level:r,message:i,args:a}=e.payload;switch(r){case`debug`:this.logger.debug(i,...a);break;case`info`:this.logger.info(i,...a);break;case`warn`:this.logger.warn(i,...a);break;case`error`:this.logger.error(i,...a);break}}flush(){var e;(e=this.worker)==null||e.postMessage({type:`Flush`})}close(){return this.closePromise?this.closePromise:this.performClose()}performClose(){let e=this.worker;if(!e)return this.pendingEvaluations.length=0,this.closePromise=Promise.resolve(),this.closePromise;try{document.removeEventListener(`visibilitychange`,this.visibilityHandler)}catch(e){this.logger.warn(`[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: `,e)}return this.closePromise=new Promise(t=>{this.closeResolve=t,this.closeTimer=setTimeout(()=>{this.logger.warn(`[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.`),this.finishClose()},this.workerCloseTimeout),e.postMessage({type:`Close`})}),this.closePromise}finishClose(){var e,t;clearTimeout(this.closeTimer),this.closeTimer=void 0,(e=this.worker)==null||e.terminate(),(t=this.closeResolve)==null||t.call(this)}};const v=(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`)},y=Math.ceil(128/Math.log2(62)),b=new TextEncoder,x=async e=>{var t;if(typeof crypto>`u`||crypto.subtle==null)return;let n=await crypto.subtle.digest(`SHA-256`,b.encode((t=e==null?void 0:e.toString())==null?``:t));return v(new Uint8Array(n,0,16),y)},S=e=>Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``),C=async e=>{let n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return t+S(new Uint8Array(n))},w=()=>typeof crypto<`u`&&crypto.subtle!=null,T=t=>{let n=a();if(!n||!w())return;let r=C(t);return{read:async()=>n.getItem(await r),write:async e=>n.setItem(await r,e),remove:async()=>n.removeItem(await r),sizeLimit:()=>e}},E=(e,t,n)=>o.from(({clientSdkKey:e,baseUrl:n,logger:r,metadata:i,clientSession:a})=>new _({sdkKey:e,sdkIdentity:{sdkName:t.sdkName,sdkVersion:t.sdkVersion},metaContext:{appName:i==null?void 0:i.appName,appVersion:i==null?void 0:i.appVersion},logger:r,baseUrl:n,urlFactory:s,valueIdGenerator:x,clientSession:a}),e,t,n,{platformCachingProvider:T});var D=class{decorateMessage(e){return`[ConfigDirector:react-web-sdk] ${e}`}};const O=e=>n(e,new D),k=(e,t)=>{if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t))return!1;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>k(e,t[n]));if(!A(e)||!A(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&k(e[n],t[n]))},A=e=>{let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},j=(e,t)=>e.isInitializing?`none`:e.isReady?t!==void 0&&!k(t,e.context)?`updateContext`:`none`:`initialize`,M=(e,t)=>E(e,{sdkName:`react-web-sdk`,sdkVersion:`1.9.1`},t),N=e=>{var t;return M(e.sdkKey,{connection:{url:e.url,timeout:e.timeout,mode:e.mode,pollingInterval:e.pollingInterval,values:e.values},metadata:{appName:e.appName,appVersion:e.appVersion},logger:(t=e.logger)==null?O(`warn`):t,hooks:e.hooks,caching:e.caching})},P=e=>`client`in e&&e.client!==void 0,F=e=>{if(P(e))return{client:e.client,owned:!1};let t=i();return t?{client:t,owned:!1}:{client:N(e),owned:!0}},I=async e=>{var t,n;let a=(t=i())==null?N(r(r({},e),{},{logger:(n=e.logger)==null?O(`debug`):n})):t;switch(j(a,e.context)){case`initialize`:await a.initialize(e.context);break;case`updateContext`:await a.updateContext(e.context);break;case`none`:break}return({children:e})=>{let[t,n]=f(()=>({client:a,status:a.isReady?`ready`:`default`}));return d(()=>{let e=()=>{n(e=>r(r({},e),{},{updatedAt:new Date}))},t=()=>{n(e=>e.status===`ready`?e:r(r({},e),{},{status:`ready`}))};return a.on(`configsUpdated`,e),a.on(`clientReady`,t),a.isReady&&t(),()=>{a.off(`configsUpdated`,e),a.off(`clientReady`,t)}},[]),p(m.Provider,{value:t,children:e})}};var L=class{constructor(e){this.client=e,this.registrations=[]}on(e,t){this.client.on(e,t),this.registrations.push({event:e,handler:t})}registerHooks(e){for(let[t,n]of Object.entries(e==null?{}:e)){let e=Array.isArray(n)?n:[n];for(let n of e)typeof n==`function`&&this.on(t,n)}}removeAll(){for(let{event:e,handler:t}of this.registrations)this.client.off(e,t);this.registrations=[]}};const R=e=>e!=null&&e.isReady?`ready`:`default`;var z=class extends l{constructor(e){super(e),this.disposedOwnClient=!1;let t=F(e);this.ownsClient=t.owned,this.state={client:t.client,status:t.client.isReady?`ready`:`loading`}}async componentDidMount(){var e=this;let t=e.state.client;e.ownsClient&&e.disposedOwnClient&&(t=N(e.props),e.disposedOwnClient=!1,e.setState({client:t,status:`loading`})),e.handlers=new L(t),e.handlers.on(`configsUpdated`,()=>{e.setState({updatedAt:new Date})}),e.handlers.on(`clientReady`,()=>{e.setState({status:`ready`})}),e.ownsClient||e.handlers.registerHooks(e.props.hooks),await e.connect(t,e.props.context)}async connect(e,t){var n=this;switch(j(e,t)){case`initialize`:await e.initialize(t);break;case`updateContext`:n.setState({status:`loading`}),await e.updateContext(t);break;case`none`:return}n.setState({status:R(e)})}async componentDidUpdate(e){var t=this;if(P(e)&&P(t.props)&&e.client!==t.props.client&&O(`warn`).warn(`The client prop of ConfigDirectorProvider changed after it mounted and is ignored. Remount the provider, for example with a new key, to use another client.`),!k(e.context,t.props.context)){var n,r;t.setState({status:`loading`}),await((n=t.state.client)==null?void 0:n.updateContext((r=t.props.context)==null?{}:r)),t.setState({status:R(t.state.client)})}}componentWillUnmount(){var e;if((e=this.handlers)==null||e.removeAll(),this.handlers=void 0,this.ownsClient){var t;(t=this.state.client)==null||t.dispose(),this.disposedOwnClient=!0}}render(){return p(m.Provider,{value:this.state,children:this.props.children})}},B=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorReactContextError`,Object.setPrototypeOf(this,e.prototype)}};const V=()=>new B(`The ConfigDirector client was not found in the React context. Please make sure the component using this hook is inside the context of a ConfigDirectorProvider.`),H=(e,t)=>{let n=u(m);if(!(n!=null&&n.client))throw V();return{value:n.client.getValue(e,t),readyStatus:n.status,loading:n.status===`loading`}},U=()=>{let e=u(m);if(!(e!=null&&e.client))throw V();return{updateContext:async t=>{var n;await((n=e.client)==null?void 0:n.updateContext(t))}}},W=()=>{let e=u(m);if(!(e!=null&&e.client))throw V();return{client:e.client}};export{z as ConfigDirectorProvider,O as createConsoleLogger,W as useClient,H as useConfigValue,U as useContext,I as withProvider};
|
|
2
2
|
//# sourceMappingURL=configdirector-react-client.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configdirector-react-client.mjs","names":["createJsSdkLogger","this","useReactContext"],"sources":["../src/context.tsx","../../shared/src/telemetry/utils.ts","../../shared/src/telemetry/InvalidContextSubmissions.ts","../../js-browser-client/src/telemetry/WebWorkerTelemetryClient.ts","../../shared/src/base62-encoder.ts","../../shared/src/value-id.ts","../../js-browser-client/src/telemetry/value-id-generator.ts","../../js-browser-client/src/BrowserConfigDirectorClient.ts","../src/logger.ts","../../shared/src/deepEqual.ts","../../js-client-core/src/mountAction.ts","../src/client.ts","../src/clientSource.ts","../src/withProvider.tsx","../../js-client-core/src/clientHandlers.ts","../src/provider.tsx","../src/errors.ts","../src/hooks.tsx"],"sourcesContent":["import React from \"react\";\nimport type { ConfigDirectorContextData } from \"./types\";\n\nconst createReactContext = () => React.createContext<ConfigDirectorContextData>({status: \"loading\"});\nexport const reactContext = createReactContext();\n","import type { ConfigType, ConfigValueType } from \"../types\";\nimport type { ValueIdGenerator, DroppedEvents } from \"./types\";\n\nconst CONFIG_VALUE_MAX_LENGTH = 500;\n\nexport type TelemetryValue = {\n value?: string;\n valueId?: string;\n type?: ConfigType;\n};\n\nexport type TelemetryEvaluationValue<TV extends ConfigValueType> = {\n value: TV;\n valueId?: string | null | undefined;\n type?: ConfigType;\n};\n\nexport const compactTelemetryValue = async (\n tv: TelemetryValue,\n valueIdGenerator: ValueIdGenerator,\n): Promise<TelemetryValue> => {\n if (tv.valueId) {\n return { valueId: tv.valueId };\n }\n if (tv.value) {\n if (tv.value.length <= CONFIG_VALUE_MAX_LENGTH && tv.type != \"json\") {\n return { value: tv.value };\n }\n\n return { valueId: await valueIdGenerator(tv.value) };\n }\n\n return tv;\n};\n\nexport const mapToTelemetryValue = <TV extends ConfigValueType>(\n ev: TelemetryEvaluationValue<TV>,\n): TelemetryValue => {\n if (ev.type === \"json\" || (ev.type == null && typeof ev.value === \"object\")) {\n if (ev.valueId) {\n return { valueId: ev.valueId, type: \"json\" };\n }\n try {\n const json = JSON.stringify(ev.value);\n return { value: json, type: \"json\" };\n } catch {\n return { value: ev.value.toString(), type: \"json\" };\n }\n }\n\n const stringValue = ev.value?.toString();\n if (stringValue && stringValue.length <= CONFIG_VALUE_MAX_LENGTH) {\n return { value: stringValue };\n }\n\n return ev.valueId ? { valueId: ev.valueId } : { value: stringValue };\n};\n\nexport const djb2Hash = (data: string): string => {\n const hash = djb2(new TextEncoder().encode(data));\n return hash.toString(16).padStart(8, \"0\");\n};\n\nconst djb2 = (bytes: Uint8Array): number => {\n let hash = 5381;\n for (let i = 0; i < bytes.length; i++) {\n hash = (hash << 5) + hash + (bytes[i] ?? 0);\n hash = hash >>> 0;\n }\n return hash;\n};\n\nexport const isEventListEmpty = <T extends Record<string | symbol, any[]>>(eventList: T): boolean => {\n const keys = Object.keys(eventList);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((eventList[key]?.length ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n\nexport const isDroppedEventsEmpty = (droppedEvents?: DroppedEvents): boolean => {\n if (!droppedEvents) {\n return true;\n }\n const keys = Object.keys(droppedEvents);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((droppedEvents[key] ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n","import type { InvalidContextEvent } from \"./telemetry-events\";\nimport type { AggregatedEvent } from \"./types\";\n\nexport const DISTINCT_KIND_SAMPLE_LIMIT = 20;\n\nexport type InvalidContextRecording =\n | \"new-kind-sample\"\n | \"known-kind-sample\"\n | \"first-beyond-sample-limit\"\n | \"beyond-sample-limit\";\n\nexport class InvalidContextSubmissions {\n private readonly countsByKindSample = new Map<string, number>();\n private countBeyondSampleLimit = 0;\n private startTime: Date | undefined;\n\n public record(kindSample: string): InvalidContextRecording {\n this.startTime ??= new Date();\n return this.add(kindSample, 1);\n }\n\n public absorb(entries: AggregatedEvent<InvalidContextEvent>[]): void {\n for (const entry of entries) {\n if (this.startTime === undefined || entry.startTime < this.startTime) {\n this.startTime = entry.startTime;\n }\n this.add(entry.event.kindSample, entry.count);\n }\n }\n\n private add(kindSample: string | undefined, count: number): InvalidContextRecording {\n if (kindSample !== undefined) {\n const knownCount = this.countsByKindSample.get(kindSample);\n if (knownCount !== undefined) {\n this.countsByKindSample.set(kindSample, knownCount + count);\n return \"known-kind-sample\";\n }\n if (this.countsByKindSample.size < DISTINCT_KIND_SAMPLE_LIMIT) {\n this.countsByKindSample.set(kindSample, count);\n return \"new-kind-sample\";\n }\n }\n const firstBeyondSampleLimit = this.countBeyondSampleLimit === 0;\n this.countBeyondSampleLimit += count;\n return firstBeyondSampleLimit ? \"first-beyond-sample-limit\" : \"beyond-sample-limit\";\n }\n\n public takeSnapshot(): AggregatedEvent<InvalidContextEvent>[] {\n const endTime = new Date();\n const startTime = this.startTime ?? endTime;\n const entryOf = (count: number, kindSample?: string): AggregatedEvent<InvalidContextEvent> => ({\n startTime,\n endTime,\n count,\n event: { reason: \"invalid-context-kind\", kindSample },\n });\n const sampledEntries = Array.from(this.countsByKindSample, ([kindSample, count]) =>\n entryOf(count, kindSample),\n );\n const entries =\n this.countBeyondSampleLimit > 0\n ? [...sampledEntries, entryOf(this.countBeyondSampleLimit)]\n : sampledEntries;\n this.clear();\n return entries;\n }\n\n private clear() {\n this.countsByKindSample.clear();\n this.countBeyondSampleLimit = 0;\n this.startTime = undefined;\n }\n}\n","import { type TelemetryEventCollectorOptions } from \"@shared/telemetry/TelemetryEventCollector\";\nimport type { ConfigDirectorContext, ConfigDirectorLogger, ConfigValueType } from \"@js-client-core/types\";\nimport type { TelemetryClient, EvaluatedConfigEvent } from \"@js-client-core/telemetry\";\nimport type {\n TelemetryCloseEvent,\n TelemetryEvaluatedConfigEvent,\n TelemetryFlushEvent,\n TelemetryInitializeEvent,\n TelemetryInvalidContextSubmissionsEvent,\n TelemetryUpdateContextEvent,\n TelemetryWorkerResponseEvent,\n} from \"./types\";\nimport type { TelemetryValue } from \"@shared/telemetry/utils\";\nimport { mapToTelemetryValue } from \"@shared/telemetry/utils\";\nimport { InvalidContextSubmissions } from \"@shared/telemetry/InvalidContextSubmissions\";\n\nconst DEFAULT_WORKER_CLOSE_TIMEOUT = 6_000;\n\nexport type WebWorkerTelemetryClientOptions = TelemetryEventCollectorOptions & {\n workerCloseTimeout?: number;\n};\n\nexport class WebWorkerTelemetryClient implements TelemetryClient {\n private readonly logger: ConfigDirectorLogger;\n private readonly initializeMessage: TelemetryInitializeEvent;\n private worker: Worker | undefined;\n private turnedOff = false;\n private readonly pendingEvaluations: TelemetryEvaluatedConfigEvent[] = [];\n private readonly pendingEvaluationLimit: number;\n private readonly pendingInvalidContextSubmissions = new InvalidContextSubmissions();\n private closePromise: Promise<void> | undefined;\n private closeResolve: (() => void) | undefined;\n private closeTimer: ReturnType<typeof setTimeout> | undefined;\n private readonly workerCloseTimeout: number;\n private readonly visibilityHandler: () => void;\n\n constructor(options: WebWorkerTelemetryClientOptions) {\n this.logger = options.logger;\n this.workerCloseTimeout = options.workerCloseTimeout ?? DEFAULT_WORKER_CLOSE_TIMEOUT;\n this.pendingEvaluationLimit = options.evaluationQueueLimit ?? 1_000;\n\n this.initializeMessage = {\n type: \"Initialize\",\n payload: {\n sdkKey: options.sdkKey,\n sdkIdentity: options.sdkIdentity,\n metaContext: options.metaContext,\n baseUrl: options.baseUrl.toString(),\n evaluationQueueLimit: this.pendingEvaluationLimit,\n initialFlushIntervalDelay: options.initialFlushIntervalDelay ?? 5_000,\n flushIntervalDelay: options.flushIntervalDelay ?? 30_000,\n },\n };\n\n this.visibilityHandler = () => {\n if (document.visibilityState === \"hidden\") {\n this.flush();\n }\n };\n }\n\n private createWorkerOrTurnOff(): Worker | undefined {\n if (typeof Worker === \"undefined\") {\n this.turnOff(\n \"[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.\",\n );\n return undefined;\n }\n try {\n return new Worker(new URL(\"./worker.ts\", import.meta.url), { type: \"module\" });\n } catch (error) {\n this.turnOff(\n \"[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: \",\n error,\n );\n return undefined;\n }\n }\n\n private turnOff(warning: string, ...details: unknown[]) {\n this.turnedOff = true;\n this.pendingEvaluations.length = 0;\n this.logger.warn(warning, ...details);\n }\n\n private startWorker(): Worker | undefined {\n if (this.worker || this.turnedOff) {\n return this.worker;\n }\n const worker = this.createWorkerOrTurnOff();\n if (!worker) {\n return undefined;\n }\n worker.onmessage = (message: MessageEvent<TelemetryWorkerResponseEvent>) => {\n this.handleWorkerEvent(message.data);\n };\n worker.postMessage(this.initializeMessage);\n this.worker = worker;\n\n try {\n document.addEventListener(\"visibilitychange\", this.visibilityHandler);\n } catch (error) {\n this.logger.warn(\"[TelemetryEventCollector] Could not configure 'visibilitychange' listener: \", error);\n }\n\n for (const evaluation of this.pendingEvaluations) {\n worker.postMessage(evaluation);\n }\n this.pendingEvaluations.length = 0;\n this.forwardInvalidContextSubmissions(worker);\n return worker;\n }\n\n private forwardInvalidContextSubmissions(worker: Worker | undefined) {\n if (!worker) {\n return;\n }\n const entries = this.pendingInvalidContextSubmissions.takeSnapshot();\n if (entries.length === 0) {\n return;\n }\n const submissionsMessage: TelemetryInvalidContextSubmissionsEvent = {\n type: \"InvalidContextSubmissions\",\n payload: { entries },\n };\n worker.postMessage(submissionsMessage);\n }\n\n public async updateContext(value: ConfigDirectorContext | undefined) {\n if (this.closePromise) {\n return;\n }\n const updateContextMessage: TelemetryUpdateContextEvent = {\n type: \"UpdateContext\",\n payload: {\n context: value,\n },\n };\n this.startWorker()?.postMessage(updateContextMessage);\n }\n\n public evaluatedConfig<T extends ConfigValueType>(event: EvaluatedConfigEvent<T>): void {\n if (this.turnedOff) {\n return;\n }\n const evaluatedConfigMessage: TelemetryEvaluatedConfigEvent = {\n type: \"EvaluatedConfigEvent\",\n payload: this.sanitizeEvaluatedConfigEvent(event),\n };\n if (this.worker) {\n this.worker.postMessage(evaluatedConfigMessage);\n return;\n }\n if (this.pendingEvaluations.length >= this.pendingEvaluationLimit) {\n this.pendingEvaluations.shift();\n }\n this.pendingEvaluations.push(evaluatedConfigMessage);\n }\n\n public recordInvalidContext(kindSample: string): void {\n this.pendingInvalidContextSubmissions.record(kindSample);\n this.forwardInvalidContextSubmissions(this.worker);\n }\n\n private sanitizeEvaluatedConfigEvent<T extends ConfigValueType>(\n event: EvaluatedConfigEvent<T>,\n ): EvaluatedConfigEvent<TelemetryValue> {\n return {\n ...event,\n defaultValue: mapToTelemetryValue({ value: event.defaultValue, type: event.type }),\n evaluatedValue: mapToTelemetryValue({\n value: event.evaluatedValue,\n valueId: event.evaluatedValueId,\n type: event.type,\n }),\n };\n }\n\n private handleWorkerEvent(event: TelemetryWorkerResponseEvent) {\n if (event.type === \"Closed\") {\n this.finishClose();\n return;\n }\n if (!event.payload?.level || !event.payload?.message) {\n return;\n }\n const { level, message, args } = event.payload;\n\n switch (level) {\n case \"debug\":\n this.logger.debug(message, ...args);\n break;\n case \"info\":\n this.logger.info(message, ...args);\n break;\n case \"warn\":\n this.logger.warn(message, ...args);\n break;\n case \"error\":\n this.logger.error(message, ...args);\n break;\n }\n }\n\n private flush() {\n const flushMessage: TelemetryFlushEvent = {\n type: \"Flush\",\n };\n this.worker?.postMessage(flushMessage);\n }\n\n public close(): Promise<void> {\n if (this.closePromise) {\n return this.closePromise;\n }\n\n return this.performClose();\n }\n\n private performClose(): Promise<void> {\n const worker = this.worker;\n if (!worker) {\n this.pendingEvaluations.length = 0;\n this.closePromise = Promise.resolve();\n return this.closePromise;\n }\n try {\n document.removeEventListener(\"visibilitychange\", this.visibilityHandler);\n } catch (error) {\n this.logger.warn(\"[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: \", error);\n }\n this.closePromise = new Promise<void>((resolve) => {\n this.closeResolve = resolve;\n this.closeTimer = setTimeout(() => {\n this.logger.warn(\n \"[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.\",\n );\n this.finishClose();\n }, this.workerCloseTimeout);\n const closeMessage: TelemetryCloseEvent = { type: \"Close\" };\n worker.postMessage(closeMessage);\n });\n return this.closePromise;\n }\n\n private finishClose() {\n clearTimeout(this.closeTimer);\n this.closeTimer = undefined;\n this.worker?.terminate();\n this.closeResolve?.();\n }\n}\n","const BASE62 = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\nexport const toBase62 = (buf: Uint8Array, length: number): string => {\n const ZERO = BigInt(0);\n const BASE = BigInt(62);\n const hex = Array.from(buf)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n let n = BigInt(\"0x\" + hex);\n let result = \"\";\n while (n > ZERO) {\n result = BASE62[Number(n % BASE)] + result;\n n /= BASE;\n }\n return result.padStart(length, \"0\");\n};\n","export const DIGEST_BYTES = 16;\nexport const BASE62_LENGTH = Math.ceil((DIGEST_BYTES * 8) / Math.log2(62));\n","import { toBase62 } from \"@shared/base62-encoder\";\nimport { DIGEST_BYTES, BASE62_LENGTH } from \"@shared/value-id\";\n\nconst encoder = new TextEncoder();\n\nexport const generateValueId = async (\n v: string | number | boolean | null | undefined,\n): Promise<string | undefined> => {\n if (typeof crypto === \"undefined\" || crypto.subtle == null) {\n return undefined;\n }\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encoder.encode(v?.toString() ?? \"\"));\n return toBase62(new Uint8Array(hashBuffer, 0, DIGEST_BYTES), BASE62_LENGTH);\n};\n","import {\n type ConfigDirectorClientOptions,\n type ConfigDirectorClient,\n type IdentifyingSdkOptions,\n type OfflineClientOptions,\n} from \"@js-client-core/index\";\nimport { WebWorkerTelemetryClient } from \"./telemetry/WebWorkerTelemetryClient\";\nimport { DefaultConfigDirectorClient } from \"@js-client-core/DefaultConfigDirectorClient\";\nimport { defaultUrlFactory } from \"@shared/url\";\nimport { generateValueId } from \"./telemetry/value-id-generator\";\n\n/**\n * Creates a browser client. With a client SDK key it connects to ConfigDirector; with\n * {@link OfflineClientOptions} alone it runs in `offline` mode and serves `connection.values`. An\n * absent key with `clientOptions` is the same as the options alone when their mode is `offline`,\n * and fails like a missing key otherwise.\n */\nexport const createBrowserClient = (\n clientSdkKeyOrOptions: string | OfflineClientOptions | undefined,\n sdkOptions: IdentifyingSdkOptions,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n return DefaultConfigDirectorClient.from(\n ({ clientSdkKey, baseUrl, logger, metadata }) =>\n new WebWorkerTelemetryClient({\n sdkKey: clientSdkKey,\n sdkIdentity: {\n sdkName: sdkOptions.sdkName,\n sdkVersion: sdkOptions.sdkVersion,\n },\n metaContext: {\n appName: metadata?.appName,\n appVersion: metadata?.appVersion,\n },\n logger,\n baseUrl,\n urlFactory: defaultUrlFactory,\n valueIdGenerator: generateValueId,\n }),\n clientSdkKeyOrOptions,\n sdkOptions,\n clientOptions,\n );\n};\n","import type {\n ConfigDirectorLogMessageDecorator,\n ConfigDirectorLogger} from \"@js-browser-client/index\";\nimport {\n type ConfigDirectorLoggingLevel,\n createDefaultLogger as createJsSdkLogger,\n} from \"@js-browser-client/index\";\n\nclass MessageDecorator implements ConfigDirectorLogMessageDecorator {\n decorateMessage(message: string): string {\n return `[ConfigDirector:react-web-sdk] ${message}`;\n }\n}\n\nexport const createConsoleLogger = (level: ConfigDirectorLoggingLevel): ConfigDirectorLogger => {\n return createJsSdkLogger(level, new MessageDecorator());\n};\n","export const deepEqual = (left: unknown, right: unknown): boolean => {\n if (Object.is(left, right)) {\n return true;\n }\n if (typeof left !== \"object\" || typeof right !== \"object\" || left === null || right === null) {\n return false;\n }\n if (Object.getPrototypeOf(left) !== Object.getPrototypeOf(right)) {\n return false;\n }\n if (left instanceof Date && right instanceof Date) {\n return left.getTime() === right.getTime();\n }\n if (Array.isArray(left) && Array.isArray(right)) {\n return left.length === right.length && left.every((item, index) => deepEqual(item, right[index]));\n }\n if (!isPlainObject(left) || !isPlainObject(right)) {\n return false;\n }\n const leftKeys = Object.keys(left);\n const rightKeys = Object.keys(right);\n return (\n leftKeys.length === rightKeys.length &&\n leftKeys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && deepEqual(left[key], right[key]))\n );\n};\n\nconst isPlainObject = (value: object): value is Record<string, unknown> => {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n};\n","import type { ConfigDirectorClient, ConfigDirectorContext } from \"./types\";\nimport { deepEqual } from \"@shared/deepEqual\";\n\nexport type MountAction = \"initialize\" | \"updateContext\" | \"none\";\n\nexport const decideMountAction = (\n client: ConfigDirectorClient,\n context: ConfigDirectorContext | undefined,\n): MountAction => {\n if (client.isInitializing) {\n return \"none\";\n }\n if (!client.isReady) {\n return \"initialize\";\n }\n if (context !== undefined && !deepEqual(context, client.context)) {\n return \"updateContext\";\n }\n return \"none\";\n};\n","import type {\n ConfigDirectorClient,\n ConfigDirectorClientOptions} from \"@js-browser-client/index\";\nimport {\n createBrowserClient,\n} from \"@js-browser-client/index\";\n\nexport const createClient = (\n clientSdkKey: string | undefined,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n return createBrowserClient(\n clientSdkKey,\n { sdkName: \"react-web-sdk\", sdkVersion: \"__VERSION__\" },\n clientOptions,\n );\n};\n\n","import type { ConfigDirectorClient } from \"@js-browser-client/index\";\nimport { readInstalledTestClient } from \"@js-client-core/installedTestClient\";\nimport { createClient } from \"./client\";\nimport { createConsoleLogger } from \"./logger\";\nimport type { ConfigDirectorProviderOptions, ConfigDirectorProviderProps } from \"./types\";\n\nexport type ClientSource = { client: ConfigDirectorClient; owned: boolean };\n\nexport const buildClient = (options: ConfigDirectorProviderOptions): ConfigDirectorClient =>\n createClient(options.sdkKey, {\n connection: {\n url: options.url,\n timeout: options.timeout,\n mode: options.mode,\n pollingInterval: options.pollingInterval,\n values: options.values,\n },\n metadata: { appName: options.appName, appVersion: options.appVersion },\n logger: options.logger ?? createConsoleLogger(\"warn\"),\n hooks: options.hooks,\n });\n\nexport const hasGivenClient = (props: ConfigDirectorProviderProps): props is { client: ConfigDirectorClient } =>\n \"client\" in props && props.client !== undefined;\n\nexport const resolveClientSource = (props: ConfigDirectorProviderProps): ClientSource => {\n if (hasGivenClient(props)) {\n return { client: props.client, owned: false };\n }\n const installed = readInstalledTestClient();\n if (installed) {\n return { client: installed, owned: false };\n }\n return { client: buildClient(props), owned: true };\n};\n","import { useEffect, useState, type ReactNode } from \"react\";\nimport { reactContext } from \"./context\";\nimport { createConsoleLogger } from \"./logger\";\nimport { readInstalledTestClient } from \"@js-client-core/installedTestClient\";\nimport { decideMountAction } from \"@js-client-core/mountAction\";\nimport type { ConfigDirectorContext } from \"@js-browser-client/index\";\nimport { buildClient } from \"./clientSource\";\nimport type { ConfigDirectorProviderOptions, ConfigDirectorProviderState } from \"./types\";\n\nexport const withProvider = async (options: ConfigDirectorProviderOptions) => {\n const client =\n readInstalledTestClient() ?? buildClient({ ...options, logger: options.logger ?? createConsoleLogger(\"debug\") });\n switch (decideMountAction(client, options.context)) {\n case \"initialize\":\n await client.initialize(options.context);\n break;\n case \"updateContext\":\n await client.updateContext(options.context as ConfigDirectorContext);\n break;\n case \"none\":\n break;\n }\n\n const ConfigDirectorProvider = ({ children }: { children: ReactNode }) => {\n const [data, setData] = useState<ConfigDirectorProviderState>(() => ({\n client,\n status: client.isReady ? \"ready\" : \"default\",\n }));\n\n useEffect(() => {\n const onConfigsUpdated = () => {\n setData((prevState) => ({ ...prevState, updatedAt: new Date() }));\n };\n const onClientReady = () => {\n setData((prevState) => (prevState.status === \"ready\" ? prevState : { ...prevState, status: \"ready\" }));\n };\n client.on(\"configsUpdated\", onConfigsUpdated);\n client.on(\"clientReady\", onClientReady);\n if (client.isReady) {\n onClientReady();\n }\n return () => {\n client.off(\"configsUpdated\", onConfigsUpdated);\n client.off(\"clientReady\", onClientReady);\n };\n }, []);\n\n return <reactContext.Provider value={data}>{children}</reactContext.Provider>;\n };\n\n return ConfigDirectorProvider;\n};\n","import type { ClientEvents, ClientHooks, ConfigDirectorClient } from \"./types\";\n\ntype Registration = { event: keyof ClientEvents; handler: (payload: any) => void };\n\nexport class ClientHandlers {\n private registrations: Registration[] = [];\n\n constructor(private readonly client: ConfigDirectorClient) {}\n\n public on<T extends keyof ClientEvents>(event: T, handler: (payload: ClientEvents[T]) => void) {\n this.client.on(event, handler);\n this.registrations.push({ event, handler });\n }\n\n public registerHooks(hooks: ClientHooks | undefined) {\n for (const [event, handlerOrHandlers] of Object.entries(hooks ?? {})) {\n const handlers = Array.isArray(handlerOrHandlers) ? handlerOrHandlers : [handlerOrHandlers];\n for (const handler of handlers) {\n if (typeof handler === \"function\") {\n this.on(event as keyof ClientEvents, handler as (payload: unknown) => void);\n }\n }\n }\n }\n\n public removeAll() {\n for (const { event, handler } of this.registrations) {\n this.client.off(event, handler);\n }\n this.registrations = [];\n }\n}\n","import { reactContext } from \"./context\";\nimport { createConsoleLogger } from \"./logger\";\nimport { Component, type PropsWithChildren } from \"react\";\nimport type { ConfigDirectorClient, ConfigDirectorContext } from \"@js-browser-client/index\";\nimport { decideMountAction } from \"@js-client-core/mountAction\";\nimport { deepEqual } from \"@shared/deepEqual\";\nimport { buildClient, hasGivenClient, resolveClientSource } from \"./clientSource\";\nimport { ClientHandlers } from \"@js-client-core/clientHandlers\";\nimport type {\n ClientStatus,\n ConfigDirectorProviderOptions,\n ConfigDirectorProviderProps,\n ConfigDirectorProviderState,\n} from \"./types\";\n\nconst settledStatusOf = (client: ConfigDirectorClient | undefined): ClientStatus =>\n client?.isReady ? \"ready\" : \"default\";\n\nexport class ConfigDirectorProvider extends Component<\n PropsWithChildren<ConfigDirectorProviderProps>,\n ConfigDirectorProviderState\n> {\n private readonly ownsClient: boolean;\n private disposedOwnClient = false;\n private handlers: ClientHandlers | undefined;\n\n constructor(props: ConfigDirectorProviderProps) {\n super(props);\n const source = resolveClientSource(props);\n this.ownsClient = source.owned;\n this.state = { client: source.client, status: source.client.isReady ? \"ready\" : \"loading\" };\n }\n\n override async componentDidMount(): Promise<void> {\n let client = this.state.client as ConfigDirectorClient;\n if (this.ownsClient && this.disposedOwnClient) {\n client = buildClient(this.props as ConfigDirectorProviderOptions);\n this.disposedOwnClient = false;\n this.setState({ client, status: \"loading\" });\n }\n this.handlers = new ClientHandlers(client);\n this.handlers.on(\"configsUpdated\", () => {\n this.setState({ updatedAt: new Date() });\n });\n this.handlers.on(\"clientReady\", () => {\n this.setState({ status: \"ready\" });\n });\n if (!this.ownsClient) {\n this.handlers.registerHooks(this.props.hooks);\n }\n await this.connect(client, this.props.context);\n }\n\n private async connect(client: ConfigDirectorClient, context: ConfigDirectorContext | undefined): Promise<void> {\n switch (decideMountAction(client, context)) {\n case \"initialize\":\n await client.initialize(context);\n break;\n case \"updateContext\":\n this.setState({ status: \"loading\" });\n await client.updateContext(context as ConfigDirectorContext);\n break;\n case \"none\":\n return;\n }\n this.setState({ status: settledStatusOf(client) });\n }\n\n override async componentDidUpdate(prevProps: PropsWithChildren<ConfigDirectorProviderProps>): Promise<void> {\n if (hasGivenClient(prevProps) && hasGivenClient(this.props) && prevProps.client !== this.props.client) {\n createConsoleLogger(\"warn\").warn(\n \"The client prop of ConfigDirectorProvider changed after it mounted and is ignored. Remount the provider, for example with a new key, to use another client.\",\n );\n }\n if (!deepEqual(prevProps.context, this.props.context)) {\n this.setState({ status: \"loading\" });\n await this.state.client?.updateContext(this.props.context ?? {});\n this.setState({ status: settledStatusOf(this.state.client) });\n }\n }\n\n override componentWillUnmount(): void {\n this.handlers?.removeAll();\n this.handlers = undefined;\n if (this.ownsClient) {\n this.state.client?.dispose();\n this.disposedOwnClient = true;\n }\n }\n\n override render() {\n return <reactContext.Provider value={this.state}>{this.props.children}</reactContext.Provider>;\n }\n}\n","export class ConfigDirectorReactContextError extends Error {\n public override readonly name: string = \"ConfigDirectorReactContextError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, ConfigDirectorReactContextError.prototype);\n }\n}\n","\"use client\";\n\nimport { useContext as useReactContext } from \"react\";\nimport { reactContext } from \"./context\";\nimport type {\n ConfigDirectorContext,\n ConfigValueType,\n} from \"@js-browser-client/index\";\nimport { ConfigDirectorReactContextError } from \"./errors\";\nimport type { ClientStatus } from \"./types\";\n\nconst noContextError = () => {\n return new ConfigDirectorReactContextError(\"The ConfigDirector client was not found in the React context. Please make sure the component using this hook is inside the context of a ConfigDirectorProvider.\");\n};\n\nconst useConfigValue = <T extends ConfigValueType>(\n key: string,\n defaultValue: T,\n): {\n value: T;\n readyStatus: ClientStatus;\n loading: boolean;\n} => {\n const configDirectorReactContext = useReactContext(reactContext);\n if (!configDirectorReactContext?.client) {\n throw noContextError();\n }\n\n const value = configDirectorReactContext.client.getValue(key, defaultValue);\n\n return { value, readyStatus: configDirectorReactContext.status, loading: configDirectorReactContext.status === \"loading\" };\n};\n\nconst useContext = () => {\n const configDirectorReactContext = useReactContext(reactContext);\n if (!configDirectorReactContext?.client) {\n throw noContextError();\n }\n\n const updateContext = async (context: ConfigDirectorContext) => {\n await configDirectorReactContext.client?.updateContext(context);\n };\n\n return { updateContext };\n};\n\nconst useClient = () => {\n const configDirectorReactContext = useReactContext(reactContext);\n if (!configDirectorReactContext?.client) {\n throw noContextError();\n }\n\n return { client: configDirectorReactContext.client };\n};\n\nexport { useConfigValue, use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AK,MAAM,OAAO,CAAE,CAAC,EAIjE,sBAAsC,OAGpC,IAFA,EAAA,KAAK,WAAA,MAAA,EAAU,WAAW,CAC1B,KAAK,SAAW,IAAA,GACZ,KAAK,WAAY,QACnB,EAAA,KAAK,MAAM,SAAA,MAAA,EAAQ,SAAS,CAC5B,KAAK,kBAAoB,IAI7B,QAAkB,CAChB,OAAO,EAAC,EAAa,SAAd,CAAuB,MAAO,KAAK,eAAQ,KAAK,MAAM,SAAiC,CAAA,GC3FrF,EAAb,MAAa,UAAwC,KAAM,CAGzD,YAAY,EAAiB,CAC3B,MAAM,EAAQ,CAHhB,KAAyB,KAAe,kCAKtC,OAAO,eAAe,KAAM,EAAgC,UAAU,GCK1E,MAAM,MACG,IAAI,EAAgC,kKAAkK,CAGzM,GACJ,EACA,IAKG,CACH,IAAM,EAA6BC,EAAgB,EAAa,CAChE,GAAI,EAAA,GAAA,MAAC,EAA4B,QAC/B,MAAM,GAAgB,CAKxB,MAAO,CAAE,MAFK,EAA2B,OAAO,SAAS,EAAK,EAAa,CAE3D,YAAa,EAA2B,OAAQ,QAAS,EAA2B,SAAW,UAAW,EAGtH,MAAmB,CACvB,IAAM,EAA6BA,EAAgB,EAAa,CAChE,GAAI,EAAA,GAAA,MAAC,EAA4B,QAC/B,MAAM,GAAgB,CAOxB,MAAO,CAAE,cAJa,KAAO,IAAmC,OAC9D,OAAA,EAAM,EAA2B,SAAA,KAAA,IAAA,GAAA,EAAQ,cAAc,EAAQ,GAGzC,EAGpB,MAAkB,CACtB,IAAM,EAA6BA,EAAgB,EAAa,CAChE,GAAI,EAAA,GAAA,MAAC,EAA4B,QAC/B,MAAM,GAAgB,CAGxB,MAAO,CAAE,OAAQ,EAA2B,OAAQ"}
|
|
1
|
+
{"version":3,"file":"configdirector-react-client.mjs","names":["createJsSdkLogger","this","useReactContext"],"sources":["../src/context.tsx","../../shared/src/telemetry/utils.ts","../../shared/src/telemetry/InvalidContextSubmissions.ts","../../js-browser-client/src/telemetry/WebWorkerTelemetryClient.ts","../../shared/src/base62-encoder.ts","../../shared/src/value-id.ts","../../js-browser-client/src/telemetry/value-id-generator.ts","../../js-browser-client/src/local-storage-caching-provider.ts","../../js-browser-client/src/BrowserConfigDirectorClient.ts","../src/logger.ts","../../shared/src/deepEqual.ts","../../js-client-core/src/mountAction.ts","../src/client.ts","../src/clientSource.ts","../src/withProvider.tsx","../../js-client-core/src/clientHandlers.ts","../src/provider.tsx","../src/errors.ts","../src/hooks.tsx"],"sourcesContent":["import React from \"react\";\nimport type { ConfigDirectorContextData } from \"./types\";\n\nconst createReactContext = () => React.createContext<ConfigDirectorContextData>({status: \"loading\"});\nexport const reactContext = createReactContext();\n","import type { ConfigType, ConfigValueType } from \"../types\";\nimport type { ValueIdGenerator, DroppedEvents } from \"./types\";\n\nconst CONFIG_VALUE_MAX_LENGTH = 500;\n\nexport type TelemetryValue = {\n value?: string;\n valueId?: string;\n type?: ConfigType;\n};\n\nexport type TelemetryEvaluationValue<TV extends ConfigValueType> = {\n value: TV;\n valueId?: string | null | undefined;\n type?: ConfigType;\n};\n\nexport const compactTelemetryValue = async (\n tv: TelemetryValue,\n valueIdGenerator: ValueIdGenerator,\n): Promise<TelemetryValue> => {\n if (tv.valueId) {\n return { valueId: tv.valueId };\n }\n if (tv.value) {\n if (tv.value.length <= CONFIG_VALUE_MAX_LENGTH && tv.type != \"json\") {\n return { value: tv.value };\n }\n\n return { valueId: await valueIdGenerator(tv.value) };\n }\n\n return tv;\n};\n\nexport const mapToTelemetryValue = <TV extends ConfigValueType>(\n ev: TelemetryEvaluationValue<TV>,\n): TelemetryValue => {\n if (ev.type === \"json\" || (ev.type == null && typeof ev.value === \"object\")) {\n if (ev.valueId) {\n return { valueId: ev.valueId, type: \"json\" };\n }\n try {\n const json = JSON.stringify(ev.value);\n return { value: json, type: \"json\" };\n } catch {\n return { value: ev.value.toString(), type: \"json\" };\n }\n }\n\n const stringValue = ev.value?.toString();\n if (stringValue && stringValue.length <= CONFIG_VALUE_MAX_LENGTH) {\n return { value: stringValue };\n }\n\n return ev.valueId ? { valueId: ev.valueId } : { value: stringValue };\n};\n\nexport const djb2Hash = (data: string): string => {\n const hash = djb2(new TextEncoder().encode(data));\n return hash.toString(16).padStart(8, \"0\");\n};\n\nconst djb2 = (bytes: Uint8Array): number => {\n let hash = 5381;\n for (let i = 0; i < bytes.length; i++) {\n hash = (hash << 5) + hash + (bytes[i] ?? 0);\n hash = hash >>> 0;\n }\n return hash;\n};\n\nexport const isEventListEmpty = <T extends Record<string | symbol, any[]>>(eventList: T): boolean => {\n const keys = Object.keys(eventList);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((eventList[key]?.length ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n\nexport const isDroppedEventsEmpty = (droppedEvents?: DroppedEvents): boolean => {\n if (!droppedEvents) {\n return true;\n }\n const keys = Object.keys(droppedEvents);\n if (keys.length == 0) {\n return true;\n }\n\n for (const key of keys) {\n if ((droppedEvents[key] ?? 0) > 0) {\n return false;\n }\n }\n\n return true;\n};\n","import type { InvalidContextEvent } from \"./telemetry-events\";\nimport type { AggregatedEvent } from \"./types\";\n\nexport const DISTINCT_KIND_SAMPLE_LIMIT = 20;\n\nexport type InvalidContextRecording =\n | \"new-kind-sample\"\n | \"known-kind-sample\"\n | \"first-beyond-sample-limit\"\n | \"beyond-sample-limit\";\n\nexport class InvalidContextSubmissions {\n private readonly countsByKindSample = new Map<string, number>();\n private countBeyondSampleLimit = 0;\n private startTime: Date | undefined;\n\n public record(kindSample: string): InvalidContextRecording {\n this.startTime ??= new Date();\n return this.add(kindSample, 1);\n }\n\n public absorb(entries: AggregatedEvent<InvalidContextEvent>[]): void {\n for (const entry of entries) {\n if (this.startTime === undefined || entry.startTime < this.startTime) {\n this.startTime = entry.startTime;\n }\n this.add(entry.event.kindSample, entry.count);\n }\n }\n\n private add(kindSample: string | undefined, count: number): InvalidContextRecording {\n if (kindSample !== undefined) {\n const knownCount = this.countsByKindSample.get(kindSample);\n if (knownCount !== undefined) {\n this.countsByKindSample.set(kindSample, knownCount + count);\n return \"known-kind-sample\";\n }\n if (this.countsByKindSample.size < DISTINCT_KIND_SAMPLE_LIMIT) {\n this.countsByKindSample.set(kindSample, count);\n return \"new-kind-sample\";\n }\n }\n const firstBeyondSampleLimit = this.countBeyondSampleLimit === 0;\n this.countBeyondSampleLimit += count;\n return firstBeyondSampleLimit ? \"first-beyond-sample-limit\" : \"beyond-sample-limit\";\n }\n\n public takeSnapshot(): AggregatedEvent<InvalidContextEvent>[] {\n const endTime = new Date();\n const startTime = this.startTime ?? endTime;\n const entryOf = (count: number, kindSample?: string): AggregatedEvent<InvalidContextEvent> => ({\n startTime,\n endTime,\n count,\n event: { reason: \"invalid-context-kind\", kindSample },\n });\n const sampledEntries = Array.from(this.countsByKindSample, ([kindSample, count]) =>\n entryOf(count, kindSample),\n );\n const entries =\n this.countBeyondSampleLimit > 0\n ? [...sampledEntries, entryOf(this.countBeyondSampleLimit)]\n : sampledEntries;\n this.clear();\n return entries;\n }\n\n private clear() {\n this.countsByKindSample.clear();\n this.countBeyondSampleLimit = 0;\n this.startTime = undefined;\n }\n}\n","import type {\n ClientSession,\n ConfigDirectorContext,\n ConfigDirectorLogger,\n ConfigValueType,\n} from \"@js-client-core/types\";\nimport type {\n ClientTelemetryEventCollectorOptions,\n TelemetryClient,\n EvaluatedConfigEvent,\n} from \"@js-client-core/telemetry\";\nimport type {\n TelemetryClientSessionEvent,\n TelemetryCloseEvent,\n TelemetryEvaluatedConfigEvent,\n TelemetryFlushEvent,\n TelemetryInitializeEvent,\n TelemetryInvalidContextSubmissionsEvent,\n TelemetryUpdateContextEvent,\n TelemetryWorkerResponseEvent,\n} from \"./types\";\nimport type { TelemetryValue } from \"@shared/telemetry/utils\";\nimport { mapToTelemetryValue } from \"@shared/telemetry/utils\";\nimport { InvalidContextSubmissions } from \"@shared/telemetry/InvalidContextSubmissions\";\n\nconst DEFAULT_WORKER_CLOSE_TIMEOUT = 6_000;\n\nexport type WebWorkerTelemetryClientOptions = ClientTelemetryEventCollectorOptions & {\n workerCloseTimeout?: number;\n};\n\nexport class WebWorkerTelemetryClient implements TelemetryClient {\n private readonly logger: ConfigDirectorLogger;\n private readonly initializeMessage: TelemetryInitializeEvent;\n private readonly clientSession: Promise<ClientSession>;\n private worker: Worker | undefined;\n private turnedOff = false;\n private readonly pendingEvaluations: TelemetryEvaluatedConfigEvent[] = [];\n private readonly pendingEvaluationLimit: number;\n private readonly pendingInvalidContextSubmissions = new InvalidContextSubmissions();\n private closePromise: Promise<void> | undefined;\n private closeResolve: (() => void) | undefined;\n private closeTimer: ReturnType<typeof setTimeout> | undefined;\n private readonly workerCloseTimeout: number;\n private readonly visibilityHandler: () => void;\n\n constructor(options: WebWorkerTelemetryClientOptions) {\n this.logger = options.logger;\n this.workerCloseTimeout = options.workerCloseTimeout ?? DEFAULT_WORKER_CLOSE_TIMEOUT;\n this.pendingEvaluationLimit = options.evaluationQueueLimit ?? 1_000;\n this.clientSession = options.clientSession;\n\n this.initializeMessage = {\n type: \"Initialize\",\n payload: {\n sdkKey: options.sdkKey,\n sdkIdentity: options.sdkIdentity,\n metaContext: options.metaContext,\n baseUrl: options.baseUrl.toString(),\n evaluationQueueLimit: this.pendingEvaluationLimit,\n initialFlushIntervalDelay: options.initialFlushIntervalDelay ?? 5_000,\n flushIntervalDelay: options.flushIntervalDelay ?? 30_000,\n },\n };\n\n this.visibilityHandler = () => {\n if (document.visibilityState === \"hidden\") {\n this.flush();\n }\n };\n }\n\n private createWorkerOrTurnOff(): Worker | undefined {\n if (typeof Worker === \"undefined\") {\n this.turnOff(\n \"[WebWorkerTelemetryClient] Telemetry is off because Web Workers are not available in this environment.\",\n );\n return undefined;\n }\n try {\n return new Worker(new URL(\"./worker.ts\", import.meta.url), { type: \"module\" });\n } catch (error) {\n this.turnOff(\n \"[WebWorkerTelemetryClient] Telemetry is off because the telemetry Web Worker could not be created: \",\n error,\n );\n return undefined;\n }\n }\n\n private turnOff(warning: string, ...details: unknown[]) {\n this.turnedOff = true;\n this.pendingEvaluations.length = 0;\n this.logger.warn(warning, ...details);\n }\n\n private startWorker(): Worker | undefined {\n if (this.worker || this.turnedOff) {\n return this.worker;\n }\n const worker = this.createWorkerOrTurnOff();\n if (!worker) {\n return undefined;\n }\n worker.onmessage = (message: MessageEvent<TelemetryWorkerResponseEvent>) => {\n this.handleWorkerEvent(message.data);\n };\n worker.postMessage(this.initializeMessage);\n this.forwardClientSession(worker);\n this.worker = worker;\n\n try {\n document.addEventListener(\"visibilitychange\", this.visibilityHandler);\n } catch (error) {\n this.logger.warn(\"[TelemetryEventCollector] Could not configure 'visibilitychange' listener: \", error);\n }\n\n for (const evaluation of this.pendingEvaluations) {\n worker.postMessage(evaluation);\n }\n this.pendingEvaluations.length = 0;\n this.forwardInvalidContextSubmissions(worker);\n return worker;\n }\n\n private forwardClientSession(worker: Worker) {\n void this.clientSession.then((clientSession) => {\n const clientSessionMessage: TelemetryClientSessionEvent = {\n type: \"ClientSession\",\n payload: clientSession,\n };\n worker.postMessage(clientSessionMessage);\n });\n }\n\n private forwardInvalidContextSubmissions(worker: Worker | undefined) {\n if (!worker) {\n return;\n }\n const entries = this.pendingInvalidContextSubmissions.takeSnapshot();\n if (entries.length === 0) {\n return;\n }\n const submissionsMessage: TelemetryInvalidContextSubmissionsEvent = {\n type: \"InvalidContextSubmissions\",\n payload: { entries },\n };\n worker.postMessage(submissionsMessage);\n }\n\n public async updateContext(value: ConfigDirectorContext | undefined) {\n if (this.closePromise) {\n return;\n }\n const updateContextMessage: TelemetryUpdateContextEvent = {\n type: \"UpdateContext\",\n payload: {\n context: value,\n },\n };\n this.startWorker()?.postMessage(updateContextMessage);\n }\n\n public evaluatedConfig<T extends ConfigValueType>(event: EvaluatedConfigEvent<T>): void {\n if (this.turnedOff) {\n return;\n }\n const evaluatedConfigMessage: TelemetryEvaluatedConfigEvent = {\n type: \"EvaluatedConfigEvent\",\n payload: this.sanitizeEvaluatedConfigEvent(event),\n };\n if (this.worker) {\n this.worker.postMessage(evaluatedConfigMessage);\n return;\n }\n if (this.pendingEvaluations.length >= this.pendingEvaluationLimit) {\n this.pendingEvaluations.shift();\n }\n this.pendingEvaluations.push(evaluatedConfigMessage);\n }\n\n public recordInvalidContext(kindSample: string): void {\n this.pendingInvalidContextSubmissions.record(kindSample);\n this.forwardInvalidContextSubmissions(this.worker);\n }\n\n private sanitizeEvaluatedConfigEvent<T extends ConfigValueType>(\n event: EvaluatedConfigEvent<T>,\n ): EvaluatedConfigEvent<TelemetryValue> {\n return {\n ...event,\n defaultValue: mapToTelemetryValue({ value: event.defaultValue, type: event.type }),\n evaluatedValue: mapToTelemetryValue({\n value: event.evaluatedValue,\n valueId: event.evaluatedValueId,\n type: event.type,\n }),\n };\n }\n\n private handleWorkerEvent(event: TelemetryWorkerResponseEvent) {\n if (event.type === \"Closed\") {\n this.finishClose();\n return;\n }\n if (!event.payload?.level || !event.payload?.message) {\n return;\n }\n const { level, message, args } = event.payload;\n\n switch (level) {\n case \"debug\":\n this.logger.debug(message, ...args);\n break;\n case \"info\":\n this.logger.info(message, ...args);\n break;\n case \"warn\":\n this.logger.warn(message, ...args);\n break;\n case \"error\":\n this.logger.error(message, ...args);\n break;\n }\n }\n\n private flush() {\n const flushMessage: TelemetryFlushEvent = {\n type: \"Flush\",\n };\n this.worker?.postMessage(flushMessage);\n }\n\n public close(): Promise<void> {\n if (this.closePromise) {\n return this.closePromise;\n }\n\n return this.performClose();\n }\n\n private performClose(): Promise<void> {\n const worker = this.worker;\n if (!worker) {\n this.pendingEvaluations.length = 0;\n this.closePromise = Promise.resolve();\n return this.closePromise;\n }\n try {\n document.removeEventListener(\"visibilitychange\", this.visibilityHandler);\n } catch (error) {\n this.logger.warn(\"[WebWorkerTelemetryClient] Could not remove 'visibilitychange' listener: \", error);\n }\n this.closePromise = new Promise<void>((resolve) => {\n this.closeResolve = resolve;\n this.closeTimer = setTimeout(() => {\n this.logger.warn(\n \"[WebWorkerTelemetryClient] Timed out waiting for the telemetry worker to close. Terminating the worker.\",\n );\n this.finishClose();\n }, this.workerCloseTimeout);\n const closeMessage: TelemetryCloseEvent = { type: \"Close\" };\n worker.postMessage(closeMessage);\n });\n return this.closePromise;\n }\n\n private finishClose() {\n clearTimeout(this.closeTimer);\n this.closeTimer = undefined;\n this.worker?.terminate();\n this.closeResolve?.();\n }\n}\n","const BASE62 = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\nexport const toBase62 = (buf: Uint8Array, length: number): string => {\n const ZERO = BigInt(0);\n const BASE = BigInt(62);\n const hex = Array.from(buf)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n let n = BigInt(\"0x\" + hex);\n let result = \"\";\n while (n > ZERO) {\n result = BASE62[Number(n % BASE)] + result;\n n /= BASE;\n }\n return result.padStart(length, \"0\");\n};\n","export const DIGEST_BYTES = 16;\nexport const BASE62_LENGTH = Math.ceil((DIGEST_BYTES * 8) / Math.log2(62));\n","import { toBase62 } from \"@shared/base62-encoder\";\nimport { DIGEST_BYTES, BASE62_LENGTH } from \"@shared/value-id\";\n\nconst encoder = new TextEncoder();\n\nexport const generateValueId = async (\n v: string | number | boolean | null | undefined,\n): Promise<string | undefined> => {\n if (typeof crypto === \"undefined\" || crypto.subtle == null) {\n return undefined;\n }\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", encoder.encode(v?.toString() ?? \"\"));\n return toBase62(new Uint8Array(hashBuffer, 0, DIGEST_BYTES), BASE62_LENGTH);\n};\n","import type { CachingProvider } from \"@js-client-core/index\";\nimport { CACHED_VALUES_STORAGE_KEY_PREFIX, DEFAULT_CACHING_SIZE_LIMIT_BYTES } from \"@js-client-core/cached-values\";\nimport { localStorageIfAvailable } from \"@js-client-core/browser-globals\";\n\nconst toHex = (bytes: Uint8Array): string =>\n Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\nconst storageKeyFor = async (clientSdkKey: string): Promise<string> => {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(clientSdkKey));\n return CACHED_VALUES_STORAGE_KEY_PREFIX + toHex(new Uint8Array(digest));\n};\n\nconst subtleCryptoAvailable = (): boolean => typeof crypto !== \"undefined\" && crypto.subtle != null;\n\nexport const localStorageCachingProvider = (clientSdkKey: string): CachingProvider | undefined => {\n const storage = localStorageIfAvailable();\n if (!storage || !subtleCryptoAvailable()) {\n return undefined;\n }\n const storageKey = storageKeyFor(clientSdkKey);\n return {\n read: async () => storage.getItem(await storageKey),\n write: async (value) => storage.setItem(await storageKey, value),\n remove: async () => storage.removeItem(await storageKey),\n sizeLimit: () => DEFAULT_CACHING_SIZE_LIMIT_BYTES,\n };\n};\n","import {\n type ConfigDirectorClientOptions,\n type ConfigDirectorClient,\n type IdentifyingSdkOptions,\n type OfflineClientOptions,\n} from \"@js-client-core/index\";\nimport { WebWorkerTelemetryClient } from \"./telemetry/WebWorkerTelemetryClient\";\nimport { DefaultConfigDirectorClient } from \"@js-client-core/DefaultConfigDirectorClient\";\nimport { defaultUrlFactory } from \"@shared/url\";\nimport { generateValueId } from \"./telemetry/value-id-generator\";\nimport { localStorageCachingProvider } from \"./local-storage-caching-provider\";\n\n/**\n * Creates a browser client. With a client SDK key it connects to ConfigDirector; with\n * {@link OfflineClientOptions} alone it runs in `offline` mode and serves `connection.values`. An\n * absent key with `clientOptions` is the same as the options alone when their mode is `offline`,\n * and fails like a missing key otherwise.\n */\nexport const createBrowserClient = (\n clientSdkKeyOrOptions: string | OfflineClientOptions | undefined,\n sdkOptions: IdentifyingSdkOptions,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n return DefaultConfigDirectorClient.from(\n ({ clientSdkKey, baseUrl, logger, metadata, clientSession }) =>\n new WebWorkerTelemetryClient({\n sdkKey: clientSdkKey,\n sdkIdentity: {\n sdkName: sdkOptions.sdkName,\n sdkVersion: sdkOptions.sdkVersion,\n },\n metaContext: {\n appName: metadata?.appName,\n appVersion: metadata?.appVersion,\n },\n logger,\n baseUrl,\n urlFactory: defaultUrlFactory,\n valueIdGenerator: generateValueId,\n clientSession,\n }),\n clientSdkKeyOrOptions,\n sdkOptions,\n clientOptions,\n { platformCachingProvider: localStorageCachingProvider },\n );\n};\n","import type {\n ConfigDirectorLogMessageDecorator,\n ConfigDirectorLogger} from \"@js-browser-client/index\";\nimport {\n type ConfigDirectorLoggingLevel,\n createDefaultLogger as createJsSdkLogger,\n} from \"@js-browser-client/index\";\n\nclass MessageDecorator implements ConfigDirectorLogMessageDecorator {\n decorateMessage(message: string): string {\n return `[ConfigDirector:react-web-sdk] ${message}`;\n }\n}\n\nexport const createConsoleLogger = (level: ConfigDirectorLoggingLevel): ConfigDirectorLogger => {\n return createJsSdkLogger(level, new MessageDecorator());\n};\n","export const deepEqual = (left: unknown, right: unknown): boolean => {\n if (Object.is(left, right)) {\n return true;\n }\n if (typeof left !== \"object\" || typeof right !== \"object\" || left === null || right === null) {\n return false;\n }\n if (Object.getPrototypeOf(left) !== Object.getPrototypeOf(right)) {\n return false;\n }\n if (left instanceof Date && right instanceof Date) {\n return left.getTime() === right.getTime();\n }\n if (Array.isArray(left) && Array.isArray(right)) {\n return left.length === right.length && left.every((item, index) => deepEqual(item, right[index]));\n }\n if (!isPlainObject(left) || !isPlainObject(right)) {\n return false;\n }\n const leftKeys = Object.keys(left);\n const rightKeys = Object.keys(right);\n return (\n leftKeys.length === rightKeys.length &&\n leftKeys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && deepEqual(left[key], right[key]))\n );\n};\n\nconst isPlainObject = (value: object): value is Record<string, unknown> => {\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n};\n","import type { ConfigDirectorClient, ConfigDirectorContext } from \"./types\";\nimport { deepEqual } from \"@shared/deepEqual\";\n\nexport type MountAction = \"initialize\" | \"updateContext\" | \"none\";\n\nexport const decideMountAction = (\n client: ConfigDirectorClient,\n context: ConfigDirectorContext | undefined,\n): MountAction => {\n if (client.isInitializing) {\n return \"none\";\n }\n if (!client.isReady) {\n return \"initialize\";\n }\n if (context !== undefined && !deepEqual(context, client.context)) {\n return \"updateContext\";\n }\n return \"none\";\n};\n","import type {\n ConfigDirectorClient,\n ConfigDirectorClientOptions} from \"@js-browser-client/index\";\nimport {\n createBrowserClient,\n} from \"@js-browser-client/index\";\n\nexport const createClient = (\n clientSdkKey: string | undefined,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n return createBrowserClient(\n clientSdkKey,\n { sdkName: \"react-web-sdk\", sdkVersion: \"__VERSION__\" },\n clientOptions,\n );\n};\n\n","import type { ConfigDirectorClient } from \"@js-browser-client/index\";\nimport { readInstalledTestClient } from \"@js-client-core/installedTestClient\";\nimport { createClient } from \"./client\";\nimport { createConsoleLogger } from \"./logger\";\nimport type { ConfigDirectorProviderOptions, ConfigDirectorProviderProps } from \"./types\";\n\nexport type ClientSource = { client: ConfigDirectorClient; owned: boolean };\n\nexport const buildClient = (options: ConfigDirectorProviderOptions): ConfigDirectorClient =>\n createClient(options.sdkKey, {\n connection: {\n url: options.url,\n timeout: options.timeout,\n mode: options.mode,\n pollingInterval: options.pollingInterval,\n values: options.values,\n },\n metadata: { appName: options.appName, appVersion: options.appVersion },\n logger: options.logger ?? createConsoleLogger(\"warn\"),\n hooks: options.hooks,\n caching: options.caching,\n });\n\nexport const hasGivenClient = (props: ConfigDirectorProviderProps): props is { client: ConfigDirectorClient } =>\n \"client\" in props && props.client !== undefined;\n\nexport const resolveClientSource = (props: ConfigDirectorProviderProps): ClientSource => {\n if (hasGivenClient(props)) {\n return { client: props.client, owned: false };\n }\n const installed = readInstalledTestClient();\n if (installed) {\n return { client: installed, owned: false };\n }\n return { client: buildClient(props), owned: true };\n};\n","import { useEffect, useState, type ReactNode } from \"react\";\nimport { reactContext } from \"./context\";\nimport { createConsoleLogger } from \"./logger\";\nimport { readInstalledTestClient } from \"@js-client-core/installedTestClient\";\nimport { decideMountAction } from \"@js-client-core/mountAction\";\nimport type { ConfigDirectorContext } from \"@js-browser-client/index\";\nimport { buildClient } from \"./clientSource\";\nimport type { ConfigDirectorProviderOptions, ConfigDirectorProviderState } from \"./types\";\n\nexport const withProvider = async (options: ConfigDirectorProviderOptions) => {\n const client =\n readInstalledTestClient() ?? buildClient({ ...options, logger: options.logger ?? createConsoleLogger(\"debug\") });\n switch (decideMountAction(client, options.context)) {\n case \"initialize\":\n await client.initialize(options.context);\n break;\n case \"updateContext\":\n await client.updateContext(options.context as ConfigDirectorContext);\n break;\n case \"none\":\n break;\n }\n\n const ConfigDirectorProvider = ({ children }: { children: ReactNode }) => {\n const [data, setData] = useState<ConfigDirectorProviderState>(() => ({\n client,\n status: client.isReady ? \"ready\" : \"default\",\n }));\n\n useEffect(() => {\n const onConfigsUpdated = () => {\n setData((prevState) => ({ ...prevState, updatedAt: new Date() }));\n };\n const onClientReady = () => {\n setData((prevState) => (prevState.status === \"ready\" ? prevState : { ...prevState, status: \"ready\" }));\n };\n client.on(\"configsUpdated\", onConfigsUpdated);\n client.on(\"clientReady\", onClientReady);\n if (client.isReady) {\n onClientReady();\n }\n return () => {\n client.off(\"configsUpdated\", onConfigsUpdated);\n client.off(\"clientReady\", onClientReady);\n };\n }, []);\n\n return <reactContext.Provider value={data}>{children}</reactContext.Provider>;\n };\n\n return ConfigDirectorProvider;\n};\n","import type { ClientEvents, ClientHooks, ConfigDirectorClient } from \"./types\";\n\ntype Registration = { event: keyof ClientEvents; handler: (payload: any) => void };\n\nexport class ClientHandlers {\n private registrations: Registration[] = [];\n\n constructor(private readonly client: ConfigDirectorClient) {}\n\n public on<T extends keyof ClientEvents>(event: T, handler: (payload: ClientEvents[T]) => void) {\n this.client.on(event, handler);\n this.registrations.push({ event, handler });\n }\n\n public registerHooks(hooks: ClientHooks | undefined) {\n for (const [event, handlerOrHandlers] of Object.entries(hooks ?? {})) {\n const handlers = Array.isArray(handlerOrHandlers) ? handlerOrHandlers : [handlerOrHandlers];\n for (const handler of handlers) {\n if (typeof handler === \"function\") {\n this.on(event as keyof ClientEvents, handler as (payload: unknown) => void);\n }\n }\n }\n }\n\n public removeAll() {\n for (const { event, handler } of this.registrations) {\n this.client.off(event, handler);\n }\n this.registrations = [];\n }\n}\n","import { reactContext } from \"./context\";\nimport { createConsoleLogger } from \"./logger\";\nimport { Component, type PropsWithChildren } from \"react\";\nimport type { ConfigDirectorClient, ConfigDirectorContext } from \"@js-browser-client/index\";\nimport { decideMountAction } from \"@js-client-core/mountAction\";\nimport { deepEqual } from \"@shared/deepEqual\";\nimport { buildClient, hasGivenClient, resolveClientSource } from \"./clientSource\";\nimport { ClientHandlers } from \"@js-client-core/clientHandlers\";\nimport type {\n ClientStatus,\n ConfigDirectorProviderOptions,\n ConfigDirectorProviderProps,\n ConfigDirectorProviderState,\n} from \"./types\";\n\nconst settledStatusOf = (client: ConfigDirectorClient | undefined): ClientStatus =>\n client?.isReady ? \"ready\" : \"default\";\n\nexport class ConfigDirectorProvider extends Component<\n PropsWithChildren<ConfigDirectorProviderProps>,\n ConfigDirectorProviderState\n> {\n private readonly ownsClient: boolean;\n private disposedOwnClient = false;\n private handlers: ClientHandlers | undefined;\n\n constructor(props: ConfigDirectorProviderProps) {\n super(props);\n const source = resolveClientSource(props);\n this.ownsClient = source.owned;\n this.state = { client: source.client, status: source.client.isReady ? \"ready\" : \"loading\" };\n }\n\n override async componentDidMount(): Promise<void> {\n let client = this.state.client as ConfigDirectorClient;\n if (this.ownsClient && this.disposedOwnClient) {\n client = buildClient(this.props as ConfigDirectorProviderOptions);\n this.disposedOwnClient = false;\n this.setState({ client, status: \"loading\" });\n }\n this.handlers = new ClientHandlers(client);\n this.handlers.on(\"configsUpdated\", () => {\n this.setState({ updatedAt: new Date() });\n });\n this.handlers.on(\"clientReady\", () => {\n this.setState({ status: \"ready\" });\n });\n if (!this.ownsClient) {\n this.handlers.registerHooks(this.props.hooks);\n }\n await this.connect(client, this.props.context);\n }\n\n private async connect(client: ConfigDirectorClient, context: ConfigDirectorContext | undefined): Promise<void> {\n switch (decideMountAction(client, context)) {\n case \"initialize\":\n await client.initialize(context);\n break;\n case \"updateContext\":\n this.setState({ status: \"loading\" });\n await client.updateContext(context as ConfigDirectorContext);\n break;\n case \"none\":\n return;\n }\n this.setState({ status: settledStatusOf(client) });\n }\n\n override async componentDidUpdate(prevProps: PropsWithChildren<ConfigDirectorProviderProps>): Promise<void> {\n if (hasGivenClient(prevProps) && hasGivenClient(this.props) && prevProps.client !== this.props.client) {\n createConsoleLogger(\"warn\").warn(\n \"The client prop of ConfigDirectorProvider changed after it mounted and is ignored. Remount the provider, for example with a new key, to use another client.\",\n );\n }\n if (!deepEqual(prevProps.context, this.props.context)) {\n this.setState({ status: \"loading\" });\n await this.state.client?.updateContext(this.props.context ?? {});\n this.setState({ status: settledStatusOf(this.state.client) });\n }\n }\n\n override componentWillUnmount(): void {\n this.handlers?.removeAll();\n this.handlers = undefined;\n if (this.ownsClient) {\n this.state.client?.dispose();\n this.disposedOwnClient = true;\n }\n }\n\n override render() {\n return <reactContext.Provider value={this.state}>{this.props.children}</reactContext.Provider>;\n }\n}\n","export class ConfigDirectorReactContextError extends Error {\n public override readonly name: string = \"ConfigDirectorReactContextError\";\n\n constructor(message: string) {\n super(message);\n\n Object.setPrototypeOf(this, ConfigDirectorReactContextError.prototype);\n }\n}\n","\"use client\";\n\nimport { useContext as useReactContext } from \"react\";\nimport { reactContext } from \"./context\";\nimport type {\n ConfigDirectorContext,\n ConfigValueType,\n} from \"@js-browser-client/index\";\nimport { ConfigDirectorReactContextError } from \"./errors\";\nimport type { ClientStatus } from \"./types\";\n\nconst noContextError = () => {\n return new ConfigDirectorReactContextError(\"The ConfigDirector client was not found in the React context. Please make sure the component using this hook is inside the context of a ConfigDirectorProvider.\");\n};\n\nconst useConfigValue = <T extends ConfigValueType>(\n key: string,\n defaultValue: T,\n): {\n value: T;\n readyStatus: ClientStatus;\n loading: boolean;\n} => {\n const configDirectorReactContext = useReactContext(reactContext);\n if (!configDirectorReactContext?.client) {\n throw noContextError();\n }\n\n const value = configDirectorReactContext.client.getValue(key, defaultValue);\n\n return { value, readyStatus: configDirectorReactContext.status, loading: configDirectorReactContext.status === \"loading\" };\n};\n\nconst useContext = () => {\n const configDirectorReactContext = useReactContext(reactContext);\n if (!configDirectorReactContext?.client) {\n throw noContextError();\n }\n\n const updateContext = async (context: ConfigDirectorContext) => {\n await configDirectorReactContext.client?.updateContext(context);\n };\n\n return { updateContext };\n};\n\nconst useClient = () => {\n const configDirectorReactContext = useReactContext(reactContext);\n if (!configDirectorReactContext?.client) {\n throw noContextError();\n }\n\n return { client: configDirectorReactContext.client };\n};\n\nexport { useConfigValue, useContext, useClient };\n"],"mappings":"6NAIA,MAAa,EADoB,EAAM,cAAyC,CAAC,OAAQ,UAAU,CAAC,CCgCvF,EACX,GACmB,OACnB,GAAI,EAAG,OAAS,QAAW,EAAG,MAAQ,MAAQ,OAAO,EAAG,OAAU,SAAW,CAC3E,GAAI,EAAG,QACL,MAAO,CAAE,QAAS,EAAG,QAAS,KAAM,OAAQ,CAE9C,GAAI,CAEF,MAAO,CAAE,MADI,KAAK,UAAU,EAAG,MAAM,CACf,KAAM,OAAQ,SAC9B,CACN,MAAO,CAAE,MAAO,EAAG,MAAM,UAAU,CAAE,KAAM,OAAQ,EAIvD,IAAM,GAAA,EAAc,EAAG,QAAA,KAAA,IAAA,GAAA,EAAO,UAAU,CAKxC,OAJI,GAAe,EAAY,QAAU,IAChC,CAAE,MAAO,EAAa,CAGxB,EAAG,QAAU,CAAE,QAAS,EAAG,QAAS,CAAG,CAAE,MAAO,EAAa,EC5CtE,IAAa,EAAb,KAAuC,eACrC,KAAiB,mBAAqB,IAAI,IAC1C,KAAQ,uBAAyB,EAGjC,OAAc,EAA6C,CAEzD,OADA,KAAK,WAAA,OAAA,KAAA,UAAc,IAAI,MAChB,KAAK,IAAI,EAAY,EAAE,CAGhC,OAAc,EAAuD,CACnE,IAAK,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