@configdirector/vue-sdk 1.6.1 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/dist/DefaultConfigDirectorClient-D7S6zs2D.cjs +5 -0
  2. package/dist/DefaultConfigDirectorClient-zODkltqb.mjs +6 -0
  3. package/dist/DefaultConfigDirectorClient-zODkltqb.mjs.map +1 -0
  4. package/dist/configdirector-vue-client-testing.cjs +1 -1
  5. package/dist/configdirector-vue-client-testing.d.cts +7 -15
  6. package/dist/configdirector-vue-client-testing.d.cts.map +1 -1
  7. package/dist/configdirector-vue-client-testing.d.mts +7 -15
  8. package/dist/configdirector-vue-client-testing.d.mts.map +1 -1
  9. package/dist/configdirector-vue-client-testing.mjs +1 -1
  10. package/dist/configdirector-vue-client-testing.mjs.map +1 -1
  11. package/dist/configdirector-vue-client.cjs +1 -1
  12. package/dist/configdirector-vue-client.d.cts +18 -6
  13. package/dist/configdirector-vue-client.d.cts.map +1 -1
  14. package/dist/configdirector-vue-client.d.mts +18 -6
  15. package/dist/configdirector-vue-client.d.mts.map +1 -1
  16. package/dist/configdirector-vue-client.mjs +1 -1
  17. package/dist/configdirector-vue-client.mjs.map +1 -1
  18. package/dist/{types-CU9VmelO.d.mts → types-BfakBTXM.d.mts} +57 -16
  19. package/dist/types-BfakBTXM.d.mts.map +1 -0
  20. package/dist/{types-3Pw7bIUn.d.cts → types-DJSy0ELn.d.cts} +57 -16
  21. package/dist/types-DJSy0ELn.d.cts.map +1 -0
  22. package/package.json +1 -1
  23. package/dist/DefaultConfigDirectorClient-Ci14OJI0.mjs +0 -6
  24. package/dist/DefaultConfigDirectorClient-Ci14OJI0.mjs.map +0 -1
  25. package/dist/DefaultConfigDirectorClient-DJLwj6p6.cjs +0 -5
  26. package/dist/types-3Pw7bIUn.d.cts.map +0 -1
  27. package/dist/types-CU9VmelO.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"configdirector-vue-client.mjs","names":["createJsSdkLogger"],"sources":["../../shared/src/telemetry/utils.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","../src/client.ts","../src/plugin.ts","../src/composables/util.ts","../src/composables/useClient.ts","../src/composables/useClientStatus.ts","../src/composables/useConfigValue.ts","../src/composables/useContext.ts"],"sourcesContent":["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 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 TelemetryUpdateContextEvent,\n TelemetryWorkerResponseEvent,\n} from \"./types\";\nimport type { TelemetryValue } from \"@shared/telemetry/utils\";\nimport { mapToTelemetryValue } from \"@shared/telemetry/utils\";\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 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 return worker;\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 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 createDefaultLogger,\n} from \"@js-client-core/index\";\nimport { WebWorkerTelemetryClient } from \"./telemetry/WebWorkerTelemetryClient\";\nimport { DefaultConfigDirectorClient } from \"@js-client-core/DefaultConfigDirectorClient\";\nimport { defaultUrlFactory, parseUrl } from \"@shared/url\";\nimport { CLIENT_BASE_URL } from \"@shared/constants\";\nimport { generateValueId } from \"./telemetry/value-id-generator\";\n\nexport const createBrowserClient = (\n clientSdkKey: string,\n sdkOptions: IdentifyingSdkOptions,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n const logger = clientOptions?.logger ?? createDefaultLogger();\n const baseUrl = parseUrl(clientOptions?.connection?.url) ?? CLIENT_BASE_URL;\n const telemetryClient = new WebWorkerTelemetryClient({\n sdkKey: clientSdkKey,\n sdkIdentity: {\n sdkName: sdkOptions.sdkName,\n sdkVersion: sdkOptions.sdkVersion,\n },\n metaContext: {\n appName: clientOptions?.metadata?.appName,\n appVersion: clientOptions?.metadata?.appVersion,\n },\n logger: logger,\n baseUrl,\n urlFactory: defaultUrlFactory,\n valueIdGenerator: generateValueId,\n });\n\n return new DefaultConfigDirectorClient(telemetryClient, clientSdkKey, sdkOptions, {\n ...clientOptions,\n logger,\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:vue-sdk] ${message}`;\n }\n}\n\nexport const createConsoleLogger = (level: ConfigDirectorLoggingLevel): ConfigDirectorLogger => {\n return createJsSdkLogger(level, new MessageDecorator());\n};\n","import type { ConfigDirectorClient, ConfigDirectorClientOptions } from \"@js-browser-client/index\";\nimport { createBrowserClient } from \"@js-browser-client/index\";\nimport type { ConfigDirectorPluginOptions } from \"./types\";\nimport { createConsoleLogger } from \"./logger\";\n\nexport const createClient = (\n clientSdkKey: string,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n return createBrowserClient(clientSdkKey, { sdkName: \"vue-sdk\", sdkVersion: \"__VERSION__\" }, clientOptions);\n};\n\nexport const createClientFromPluginOptions = (options: ConfigDirectorPluginOptions): ConfigDirectorClient => {\n return createClient(options.sdkKey, {\n connection: {\n url: options.url,\n timeout: options.timeout,\n mode: options.mode,\n pollingInterval: options.pollingInterval,\n },\n metadata: { appName: options.appName, appVersion: options.appVersion },\n logger: options.logger ?? createConsoleLogger(\"warn\"),\n hooks: options.hooks,\n });\n};\n\nexport const initializeClient = async (\n options: ConfigDirectorPluginOptions,\n): Promise<ConfigDirectorClient> => {\n const client = createClientFromPluginOptions(options);\n await client.initialize(options.context);\n return client;\n};\n","import { readonly, ref, type InjectionKey, type Ref, type App } from \"vue\";\nimport type { ClientStatus, ConfigDirectorPluginOptions } from \"./types\";\nimport { createClientFromPluginOptions } from \"./client\";\nimport type { ConfigDirectorClient, ConfigDirectorContext } from \"@js-client-core/types\";\nimport { ConfigDirectorInitializationError } from \"@shared/errors\";\n\nexport const ConfigDirectorClientKey: InjectionKey<ConfigDirectorClient> = Symbol(\"ConfigDirector.Client\");\nexport const ConfigDirectorStatusKey: InjectionKey<Readonly<Ref<ClientStatus>>> = Symbol(\n \"ConfigDirector.ClientStatus\",\n);\nexport const ConfigDirectorContextKey: InjectionKey<Readonly<Ref<ConfigDirectorContext | undefined>>> =\n Symbol(\"ConfigDirector.Context\");\n\nexport const ConfigDirectorPlugin = {\n install: (app: App, optionsOrClient: ConfigDirectorPluginOptions | ConfigDirectorClient) => {\n const getClient = () => {\n if (isClientObject(optionsOrClient)) {\n return optionsOrClient as ConfigDirectorClient;\n } else if (isOptionsObject(optionsOrClient)) {\n return createClientFromPluginOptions(optionsOrClient as ConfigDirectorPluginOptions);\n } else {\n throw new ConfigDirectorInitializationError(\n \"The plugin options must be either an initialized ConfigDirectorClient, or a ConfigDirectorPluginOptions object with a valid client 'sdkKey'\",\n );\n }\n };\n\n const client = getClient();\n\n const status = ref<ClientStatus>(client.isReady ? \"ready\" : \"loading\");\n const readonlyStatus = readonly(status);\n client.on(\"clientReady\", () => (status.value = \"ready\"));\n\n const context = ref<ConfigDirectorContext | undefined>(optionsOrClient.context);\n const readonlyContext = readonly(context);\n client.on(\"contextUpdated\", ({ context: newContext }) => (context.value = newContext));\n\n if (!client.isReady && !client.isInitializing) {\n client.initialize(optionsOrClient.context).then(() => {\n if (!client.isReady) {\n // The client timed-out initialization and it is serving default values\n status.value = \"default\";\n }\n });\n }\n\n app.provide(ConfigDirectorClientKey, client);\n app.provide(ConfigDirectorStatusKey, readonlyStatus);\n app.provide(ConfigDirectorContextKey, readonlyContext);\n },\n};\n\nconst isClientObject = (options: ConfigDirectorPluginOptions | ConfigDirectorClient): options is ConfigDirectorClient => {\n const candidate = options as Partial<ConfigDirectorClient>;\n return (\n typeof candidate.initialize === \"function\" &&\n typeof candidate.getValue === \"function\" &&\n typeof candidate.watch === \"function\" &&\n typeof candidate.on === \"function\"\n );\n};\n\nconst isOptionsObject = (options: ConfigDirectorPluginOptions | ConfigDirectorClient) => {\n return typeof (options as ConfigDirectorPluginOptions).sdkKey === \"string\";\n};\n","import type { InjectionKey } from \"vue\";\nimport { inject } from \"vue\";\nimport { ConfigDirectorInitializationError } from \"@shared/errors\";\n\nexport const injectOrThrow = <T>(key: InjectionKey<T>): T => {\n const injected = inject(key);\n if (injected === undefined) {\n throw new ConfigDirectorInitializationError(\n `Could not inject ${key.description} from ConfigDirectorPlugin. Make sure the ConfigDirectorPlugin is installed.`,\n );\n }\n return injected;\n};\n","import type { ConfigDirectorClient } from \"@js-browser-client/index\";\nimport { ConfigDirectorClientKey } from \"../plugin\";\nimport { injectOrThrow } from \"./util\";\n\nexport const useClient = (): { client: ConfigDirectorClient } => {\n const client = injectOrThrow(ConfigDirectorClientKey);\n return { client };\n};\n","import type { Ref } from \"vue\";\nimport { computed } from \"vue\";\nimport type { ClientStatus } from \"../types\";\nimport { injectOrThrow } from \"./util\";\nimport { ConfigDirectorStatusKey } from \"../plugin\";\n\nexport const useClientStatus = (): {\n readyStatus: Readonly<Ref<ClientStatus>>;\n loading: Readonly<Ref<boolean>>;\n} => {\n const readyStatus = injectOrThrow(ConfigDirectorStatusKey);\n const loading = computed(() => readyStatus.value === \"loading\");\n return { readyStatus, loading };\n};\n","import { shallowRef, onBeforeUnmount } from \"vue\";\nimport type { Ref, ShallowRef } from \"vue\";\nimport type { ConfigValueType } from \"@js-client-core/types\";\nimport type { ClientStatus } from \"../types\";\nimport { useClient } from \"./useClient\";\nimport { useClientStatus } from \"./useClientStatus\";\n\nexport const useConfigValue = <T extends ConfigValueType>(\n configKey: string,\n defaultValue: T,\n): { value: ShallowRef<T>; readyStatus: Readonly<Ref<ClientStatus>>; loading: Readonly<Ref<boolean>> } => {\n const { client } = useClient();\n const { readyStatus, loading } = useClientStatus();\n const configValue = shallowRef(client.getValue<T>(configKey, defaultValue)) as ShallowRef<T>;\n\n const watcher = (newValue: T) => (configValue.value = newValue);\n client.watch(configKey, defaultValue, watcher);\n\n onBeforeUnmount(() => client.unwatch(configKey, watcher));\n\n return { value: configValue, readyStatus, loading };\n};\n","import type { ConfigDirectorContext } from \"@js-browser-client/index\";\nimport { toRaw } from \"vue\";\nimport { ConfigDirectorContextKey } from \"../plugin\";\nimport { useClient } from \"./useClient\";\nimport { injectOrThrow } from \"./util\";\n\nexport const useContext = () => {\n const { client } = useClient();\n const currentContext = injectOrThrow(ConfigDirectorContextKey);\n\n const updateContext = async (context: ConfigDirectorContext) => {\n const rawContext = toRaw(context);\n const oldContextJson = JSON.stringify(client.context);\n const newContextJson = JSON.stringify(rawContext);\n if (oldContextJson != newContextJson) {\n await client.updateContext(rawContext);\n }\n };\n\n return {\n context: currentContext,\n updateContext,\n };\n};\n"],"mappings":"2NAGA,MAgCa,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,ECnCtE,IAAa,EAAb,KAAiE,CAa/D,YAAY,EAA0C,aATtD,KAAQ,UAAY,GACpB,KAAiB,mBAAsD,EAAE,CASvE,KAAK,OAAS,EAAQ,OACtB,KAAK,oBAAA,EAAqB,EAAQ,qBAAA,KAAsB,IAAtB,EAClC,KAAK,wBAAA,EAAyB,EAAQ,uBAAA,KAAwB,IAAxB,EAEtC,KAAK,kBAAoB,CACvB,KAAM,aACN,QAAS,CACP,OAAQ,EAAQ,OAChB,YAAa,EAAQ,YACrB,YAAa,EAAQ,YACrB,QAAS,EAAQ,QAAQ,UAAU,CACnC,qBAAsB,KAAK,uBAC3B,2BAAA,EAA2B,EAAQ,4BAAA,KAA6B,IAA7B,EACnC,oBAAA,EAAoB,EAAQ,qBAAA,KAAsB,IAAtB,EAC7B,CACF,CAED,KAAK,sBAA0B,CACzB,SAAS,kBAAoB,UAC/B,KAAK,OAAO,EAKlB,uBAAoD,CAClD,GAAI,OAAO,OAAW,IAAa,CACjC,K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EAAM,EAAQ,CACV,KAAK,UAAU,EAAO,QAAQ,EAC9B,KAAK,UAAU,EAAW,EAE/C,MAAM,EAAO,cAAc,EAAW,EAOzC"}
1
+ {"version":3,"file":"configdirector-vue-client.mjs","names":["createJsSdkLogger"],"sources":["../../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","../src/client.ts","../src/plugin.ts","../src/composables/util.ts","../src/composables/useClient.ts","../src/composables/useClientStatus.ts","../src/composables/useConfigValue.ts","../src/composables/useContext.ts"],"sourcesContent":["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:vue-sdk] ${message}`;\n }\n}\n\nexport const createConsoleLogger = (level: ConfigDirectorLoggingLevel): ConfigDirectorLogger => {\n return createJsSdkLogger(level, new MessageDecorator());\n};\n","import type { ConfigDirectorClient, ConfigDirectorClientOptions } from \"@js-browser-client/index\";\nimport { createBrowserClient } from \"@js-browser-client/index\";\nimport type { ConfigDirectorPluginOptions } from \"./types\";\nimport { createConsoleLogger } from \"./logger\";\n\nconst createClient = (\n clientSdkKey: string | undefined,\n clientOptions?: ConfigDirectorClientOptions,\n): ConfigDirectorClient => {\n return createBrowserClient(clientSdkKey, { sdkName: \"vue-sdk\", sdkVersion: \"__VERSION__\" }, clientOptions);\n};\n\nexport const createClientFromPluginOptions = (options: ConfigDirectorPluginOptions): ConfigDirectorClient => {\n return 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};\n\nexport const initializeClient = async (\n options: ConfigDirectorPluginOptions,\n): Promise<ConfigDirectorClient> => {\n const client = createClientFromPluginOptions(options);\n await client.initialize(options.context);\n return client;\n};\n","import { readonly, ref, type InjectionKey, type Ref, type App } from \"vue\";\nimport type { ClientStatus, ConfigDirectorPluginOptions } from \"./types\";\nimport { createClientFromPluginOptions } from \"./client\";\nimport type { ConfigDirectorClient, ConfigDirectorContext } from \"@js-client-core/types\";\n\nexport const ConfigDirectorClientKey: InjectionKey<ConfigDirectorClient> = Symbol(\"ConfigDirector.Client\");\nexport const ConfigDirectorStatusKey: InjectionKey<Readonly<Ref<ClientStatus>>> = Symbol(\n \"ConfigDirector.ClientStatus\",\n);\nexport const ConfigDirectorContextKey: InjectionKey<Readonly<Ref<ConfigDirectorContext | undefined>>> =\n Symbol(\"ConfigDirector.Context\");\n\nexport const ConfigDirectorPlugin = {\n install: (app: App, optionsOrClient: ConfigDirectorPluginOptions | ConfigDirectorClient) => {\n const client = isClientObject(optionsOrClient)\n ? optionsOrClient\n : createClientFromPluginOptions(optionsOrClient);\n\n const status = ref<ClientStatus>(client.isReady ? \"ready\" : \"loading\");\n const readonlyStatus = readonly(status);\n client.on(\"clientReady\", () => (status.value = \"ready\"));\n\n const context = ref<ConfigDirectorContext | undefined>(optionsOrClient.context);\n const readonlyContext = readonly(context);\n client.on(\"contextUpdated\", ({ context: newContext }) => (context.value = newContext));\n\n if (!client.isReady && !client.isInitializing) {\n client.initialize(optionsOrClient.context).then(() => {\n if (!client.isReady) {\n // The client timed-out initialization and it is serving default values\n status.value = \"default\";\n }\n });\n }\n\n app.provide(ConfigDirectorClientKey, client);\n app.provide(ConfigDirectorStatusKey, readonlyStatus);\n app.provide(ConfigDirectorContextKey, readonlyContext);\n },\n};\n\nconst isClientObject = (options: ConfigDirectorPluginOptions | ConfigDirectorClient): options is ConfigDirectorClient => {\n const candidate = options as Partial<ConfigDirectorClient>;\n return (\n typeof candidate.initialize === \"function\" &&\n typeof candidate.getValue === \"function\" &&\n typeof candidate.watch === \"function\" &&\n typeof candidate.on === \"function\"\n );\n};\n","import type { InjectionKey } from \"vue\";\nimport { inject } from \"vue\";\nimport { ConfigDirectorInitializationError } from \"@shared/errors\";\n\nexport const injectOrThrow = <T>(key: InjectionKey<T>): T => {\n const injected = inject(key);\n if (injected === undefined) {\n throw new ConfigDirectorInitializationError(\n `Could not inject ${key.description} from ConfigDirectorPlugin. Make sure the ConfigDirectorPlugin is installed.`,\n );\n }\n return injected;\n};\n","import type { ConfigDirectorClient } from \"@js-browser-client/index\";\nimport { ConfigDirectorClientKey } from \"../plugin\";\nimport { injectOrThrow } from \"./util\";\n\nexport const useClient = (): { client: ConfigDirectorClient } => {\n const client = injectOrThrow(ConfigDirectorClientKey);\n return { client };\n};\n","import type { Ref } from \"vue\";\nimport { computed } from \"vue\";\nimport type { ClientStatus } from \"../types\";\nimport { injectOrThrow } from \"./util\";\nimport { ConfigDirectorStatusKey } from \"../plugin\";\n\nexport const useClientStatus = (): {\n readyStatus: Readonly<Ref<ClientStatus>>;\n loading: Readonly<Ref<boolean>>;\n} => {\n const readyStatus = injectOrThrow(ConfigDirectorStatusKey);\n const loading = computed(() => readyStatus.value === \"loading\");\n return { readyStatus, loading };\n};\n","import { shallowRef, onBeforeUnmount } from \"vue\";\nimport type { Ref, ShallowRef } from \"vue\";\nimport type { ConfigValueType } from \"@js-client-core/types\";\nimport type { ClientStatus } from \"../types\";\nimport { useClient } from \"./useClient\";\nimport { useClientStatus } from \"./useClientStatus\";\n\nexport const useConfigValue = <T extends ConfigValueType>(\n configKey: string,\n defaultValue: T,\n): { value: ShallowRef<T>; readyStatus: Readonly<Ref<ClientStatus>>; loading: Readonly<Ref<boolean>> } => {\n const { client } = useClient();\n const { readyStatus, loading } = useClientStatus();\n const configValue = shallowRef(client.getValue<T>(configKey, defaultValue)) as ShallowRef<T>;\n\n const watcher = (newValue: T) => (configValue.value = newValue);\n client.watch(configKey, defaultValue, watcher);\n\n onBeforeUnmount(() => client.unwatch(configKey, watcher));\n\n return { value: configValue, readyStatus, loading };\n};\n","import type { ConfigDirectorContext } from \"@js-browser-client/index\";\nimport { toRaw } from \"vue\";\nimport { ConfigDirectorContextKey } from \"../plugin\";\nimport { useClient } from \"./useClient\";\nimport { injectOrThrow } from \"./util\";\n\nexport const useContext = () => {\n const { client } = useClient();\n const currentContext = injectOrThrow(ConfigDirectorContextKey);\n\n const updateContext = async (context: ConfigDirectorContext) => {\n const rawContext = toRaw(context);\n const oldContextJson = JSON.stringify(client.context);\n const newContextJson = JSON.stringify(rawContext);\n if (oldContextJson != newContextJson) {\n await client.updateContext(rawContext);\n }\n };\n\n return {\n context: currentContext,\n updateContext,\n };\n};\n"],"mappings":"6MAGA,MAgCa,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,C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B,EAAY,MAAQ,EAKtD,OAJA,EAAO,MAAM,EAAW,EAAc,EAAQ,CAE9C,MAAsB,EAAO,QAAQ,EAAW,EAAQ,CAAC,CAElD,CAAE,MAAO,EAAa,cAAa,UAAS,ECdxC,MAAmB,CAC9B,GAAM,CAAE,UAAW,GAAW,CAY9B,MAAO,CACL,QAZqB,EAAc,EAAyB,CAa5D,cAXoB,KAAO,IAAmC,CAC9D,IAAM,EAAa,EAAM,EAAQ,CACV,KAAK,UAAU,EAAO,QAAQ,EAC9B,KAAK,UAAU,EAAW,EAE/C,MAAM,EAAO,cAAc,EAAW,EAOzC"}
@@ -30,27 +30,40 @@ type ConfigEvaluation = {
30
30
  context?: ConfigDirectorContext;
31
31
  };
32
32
  /**
33
- * The user's context to be sent to ConfigDirector. This context will be used for targeting
34
- * rules evaluation.
33
+ * The context to be sent to ConfigDirector: the user or other entity, such as a device or an
34
+ * organization, that configs are evaluated for. This context will be used for targeting rules
35
+ * evaluation.
35
36
  */
36
37
  type ConfigDirectorContext = {
37
38
  /**
38
- * The user's identifier. This should be a value that uniquely identifies an application
39
- * user.
39
+ * The context's identifier. This should be a value that uniquely identifies the user or other
40
+ * entity among contexts of the same {@link kind}.
40
41
  * In the case of anonymous users, you could generate a UUID or alternatively not provide
41
42
  * the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
42
- * value is used for segmenting users in percentage rollouts, and changes to the {@link id}
43
- * could result in the user being assigned to a different percentile.
43
+ * value is used for segmenting contexts in percentage rollouts, and changes to the {@link id}
44
+ * could result in the context being assigned to a different percentile.
44
45
  */
45
46
  id?: string;
46
47
  /**
47
- * The user's display name. This will be shown in the ConfigDirector dashboard and may be
48
+ * The kind of entity this context represents, such as `user`, `device`, `organization`,
49
+ * `tenant` or `listing`. You can use any other kind that fits your application. A kind has 1
50
+ * to 64 characters, using only lowercase letters (`a`-`z`), digits, `-` and `_`. It is used
51
+ * exactly as given, without trimming or changing its case.
52
+ *
53
+ * A context with an invalid kind is ignored as a whole: the SDK logs an error and evaluates
54
+ * as if no context had been provided.
55
+ *
56
+ * @default "user"
57
+ */
58
+ kind?: string;
59
+ /**
60
+ * The context's display name. This will be shown in the ConfigDirector dashboard and may be
48
61
  * used for targeting rules.
49
62
  */
50
63
  name?: string;
51
64
  /**
52
- * Any arbitrary traits for the current user. They will be shown in the ConfigDirector
53
- * dashboard and may be used for targeting rules.
65
+ * Any arbitrary traits for the context. They will be shown in the ConfigDirector dashboard
66
+ * and may be used for targeting rules.
54
67
  */
55
68
  traits?: {
56
69
  [key: string]: unknown;
@@ -64,9 +77,29 @@ type ConfigDirectorContext = {
64
77
  */
65
78
  anonymous?: boolean;
66
79
  };
67
- type ConnectionMode = "streaming" | "polling";
80
+ type ConnectionMode = "streaming" | "polling" | "offline";
81
+ //#endregion
82
+ //#region ../shared/src/native-values.d.ts
83
+ type NativeJsonValue = boolean | number | string | null | NativeJsonValue[] | {
84
+ [key: string]: NativeJsonValue;
85
+ };
86
+ type NativeValue = boolean | number | string | NativeJsonValue[] | {
87
+ [key: string]: NativeJsonValue;
88
+ };
89
+ type NativeValues = Record<string, NativeValue>;
68
90
  //#endregion
69
91
  //#region ../js-client-core/src/types.d.ts
92
+ /**
93
+ * One value an offline client serves for a config key. The config type follows from the value: a
94
+ * boolean, an integral number (`integer`), any other number (`float`), a string, or a plain object
95
+ * or array (`json`).
96
+ */
97
+ type OfflineValue = NativeValue;
98
+ /**
99
+ * The values an offline client serves, keyed by config key. See {@link OfflineValue} for how each
100
+ * value's config type is decided. Every context receives the same value.
101
+ */
102
+ type OfflineValues = NativeValues;
70
103
  type ClientHooks = {
71
104
  clientReady?: HookHandler<"clientReady"> | HookHandler<"clientReady">[];
72
105
  configsUpdated?: HookHandler<"configsUpdated"> | HookHandler<"configsUpdated">[];
@@ -116,17 +149,25 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
116
149
  * not attempt to re-connect and an error will be logged to the console or the provided
117
150
  * logger.
118
151
  *
119
- * @param context The current user's context to be used for evaluating targeting rules (optional).
152
+ * A context whose {@link ConfigDirectorContext.kind} is invalid is ignored as a whole: an error is
153
+ * logged, and the client connects as if no context had been provided.
154
+ *
155
+ * @param context The current context to be used for evaluating targeting rules (optional).
120
156
  */
121
157
  initialize(context?: ConfigDirectorContext): Promise<void>;
122
158
  /**
123
- * Updates the user's context and re-evaluates all config and flag values based on the new context.
159
+ * Updates the context and re-evaluates all config and flag values based on the new context.
160
+ *
161
+ * A context whose {@link ConfigDirectorContext.kind} is invalid is ignored as a whole: an error is
162
+ * logged, the previous context is no longer used, and the client connects as if no context had been
163
+ * provided.
124
164
  *
125
- * @param context The current user's context to be used for evaluating targeting rules (required).
165
+ * @param context The current context to be used for evaluating targeting rules (required).
126
166
  */
127
167
  updateContext(context: ConfigDirectorContext): Promise<void>;
128
168
  /**
129
- * Returns the current context the client is configured with, or undefined if there is no context.
169
+ * Returns the current context the client is configured with, or undefined if there is no context,
170
+ * including after a context with an invalid kind was ignored.
130
171
  *
131
172
  * Note that the value returned does not updated immediately after calling {@link updateContext}. Only
132
173
  * once the underlying connection was successful or timed out, the current context is updated. This is
@@ -206,5 +247,5 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
206
247
  dispose(): void;
207
248
  }
208
249
  //#endregion
209
- export { ConfigDirectorLoggingLevel as a, ConfigDirectorLogger as i, ConfigDirectorClient as n, ConfigValueType as o, ConfigDirectorContext as r, ConnectionMode as s, ClientHooks as t };
210
- //# sourceMappingURL=types-CU9VmelO.d.mts.map
250
+ export { NativeJsonValue as a, ConfigDirectorContext as c, ConfigValueType as d, ConnectionMode as f, OfflineValues as i, ConfigDirectorLogger as l, ConfigDirectorClient as n, NativeValue as o, OfflineValue as r, NativeValues as s, ClientHooks as t, ConfigDirectorLoggingLevel as u };
251
+ //# sourceMappingURL=types-BfakBTXM.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-BfakBTXM.d.mts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/types.ts","../../sh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A,EAAU,YAAA,CAAa,CAAA;EA/FzE;;;;;;;AAIrB;EAqGE,OAAA,WAAkB,eAAA,EAAiB,SAAA,UAAmB,QAAA,GAAW,YAAA,CAAa,CAAA;EArGxD;;;EA0GtB,UAAA;EA1G8D;;;;AAWhE;;;EAwGE,YAAA;EAvFqB;;;;EA6FrB,aAAA,IAAiB,OAAA;EA3CE;;;;;;EAmDnB,OAAA;AAAA"}
@@ -30,27 +30,40 @@ type ConfigEvaluation = {
30
30
  context?: ConfigDirectorContext;
31
31
  };
32
32
  /**
33
- * The user's context to be sent to ConfigDirector. This context will be used for targeting
34
- * rules evaluation.
33
+ * The context to be sent to ConfigDirector: the user or other entity, such as a device or an
34
+ * organization, that configs are evaluated for. This context will be used for targeting rules
35
+ * evaluation.
35
36
  */
36
37
  type ConfigDirectorContext = {
37
38
  /**
38
- * The user's identifier. This should be a value that uniquely identifies an application
39
- * user.
39
+ * The context's identifier. This should be a value that uniquely identifies the user or other
40
+ * entity among contexts of the same {@link kind}.
40
41
  * In the case of anonymous users, you could generate a UUID or alternatively not provide
41
42
  * the {@link id} and the SDK will generate a random UUID. However, keep in mind that this
42
- * value is used for segmenting users in percentage rollouts, and changes to the {@link id}
43
- * could result in the user being assigned to a different percentile.
43
+ * value is used for segmenting contexts in percentage rollouts, and changes to the {@link id}
44
+ * could result in the context being assigned to a different percentile.
44
45
  */
45
46
  id?: string;
46
47
  /**
47
- * The user's display name. This will be shown in the ConfigDirector dashboard and may be
48
+ * The kind of entity this context represents, such as `user`, `device`, `organization`,
49
+ * `tenant` or `listing`. You can use any other kind that fits your application. A kind has 1
50
+ * to 64 characters, using only lowercase letters (`a`-`z`), digits, `-` and `_`. It is used
51
+ * exactly as given, without trimming or changing its case.
52
+ *
53
+ * A context with an invalid kind is ignored as a whole: the SDK logs an error and evaluates
54
+ * as if no context had been provided.
55
+ *
56
+ * @default "user"
57
+ */
58
+ kind?: string;
59
+ /**
60
+ * The context's display name. This will be shown in the ConfigDirector dashboard and may be
48
61
  * used for targeting rules.
49
62
  */
50
63
  name?: string;
51
64
  /**
52
- * Any arbitrary traits for the current user. They will be shown in the ConfigDirector
53
- * dashboard and may be used for targeting rules.
65
+ * Any arbitrary traits for the context. They will be shown in the ConfigDirector dashboard
66
+ * and may be used for targeting rules.
54
67
  */
55
68
  traits?: {
56
69
  [key: string]: unknown;
@@ -64,9 +77,29 @@ type ConfigDirectorContext = {
64
77
  */
65
78
  anonymous?: boolean;
66
79
  };
67
- type ConnectionMode = "streaming" | "polling";
80
+ type ConnectionMode = "streaming" | "polling" | "offline";
81
+ //#endregion
82
+ //#region ../shared/src/native-values.d.ts
83
+ type NativeJsonValue = boolean | number | string | null | NativeJsonValue[] | {
84
+ [key: string]: NativeJsonValue;
85
+ };
86
+ type NativeValue = boolean | number | string | NativeJsonValue[] | {
87
+ [key: string]: NativeJsonValue;
88
+ };
89
+ type NativeValues = Record<string, NativeValue>;
68
90
  //#endregion
69
91
  //#region ../js-client-core/src/types.d.ts
92
+ /**
93
+ * One value an offline client serves for a config key. The config type follows from the value: a
94
+ * boolean, an integral number (`integer`), any other number (`float`), a string, or a plain object
95
+ * or array (`json`).
96
+ */
97
+ type OfflineValue = NativeValue;
98
+ /**
99
+ * The values an offline client serves, keyed by config key. See {@link OfflineValue} for how each
100
+ * value's config type is decided. Every context receives the same value.
101
+ */
102
+ type OfflineValues = NativeValues;
70
103
  type ClientHooks = {
71
104
  clientReady?: HookHandler<"clientReady"> | HookHandler<"clientReady">[];
72
105
  configsUpdated?: HookHandler<"configsUpdated"> | HookHandler<"configsUpdated">[];
@@ -116,17 +149,25 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
116
149
  * not attempt to re-connect and an error will be logged to the console or the provided
117
150
  * logger.
118
151
  *
119
- * @param context The current user's context to be used for evaluating targeting rules (optional).
152
+ * A context whose {@link ConfigDirectorContext.kind} is invalid is ignored as a whole: an error is
153
+ * logged, and the client connects as if no context had been provided.
154
+ *
155
+ * @param context The current context to be used for evaluating targeting rules (optional).
120
156
  */
121
157
  initialize(context?: ConfigDirectorContext): Promise<void>;
122
158
  /**
123
- * Updates the user's context and re-evaluates all config and flag values based on the new context.
159
+ * Updates the context and re-evaluates all config and flag values based on the new context.
160
+ *
161
+ * A context whose {@link ConfigDirectorContext.kind} is invalid is ignored as a whole: an error is
162
+ * logged, the previous context is no longer used, and the client connects as if no context had been
163
+ * provided.
124
164
  *
125
- * @param context The current user's context to be used for evaluating targeting rules (required).
165
+ * @param context The current context to be used for evaluating targeting rules (required).
126
166
  */
127
167
  updateContext(context: ConfigDirectorContext): Promise<void>;
128
168
  /**
129
- * Returns the current context the client is configured with, or undefined if there is no context.
169
+ * Returns the current context the client is configured with, or undefined if there is no context,
170
+ * including after a context with an invalid kind was ignored.
130
171
  *
131
172
  * Note that the value returned does not updated immediately after calling {@link updateContext}. Only
132
173
  * once the underlying connection was successful or timed out, the current context is updated. This is
@@ -206,5 +247,5 @@ interface ConfigDirectorClient extends EventProvider<ClientEvents> {
206
247
  dispose(): void;
207
248
  }
208
249
  //#endregion
209
- export { ConfigDirectorLoggingLevel as a, ConfigDirectorLogger as i, ConfigDirectorClient as n, ConfigValueType as o, ConfigDirectorContext as r, ConnectionMode as s, ClientHooks as t };
210
- //# sourceMappingURL=types-3Pw7bIUn.d.cts.map
250
+ export { NativeJsonValue as a, ConfigDirectorContext as c, ConfigValueType as d, ConnectionMode as f, OfflineValues as i, ConfigDirectorLogger as l, ConfigDirectorClient as n, NativeValue as o, OfflineValue as r, NativeValues as s, ClientHooks as t, ConfigDirectorLoggingLevel as u };
251
+ //# sourceMappingURL=types-DJSy0ELn.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-DJSy0ELn.d.cts","names":[],"sources":["../../js-client-core/src/Emitter.ts","../../shared/src/types.ts","../../shared/src/native-values.ts","../../js-client-core/src/types.ts"],"mappings":";KAAK,SAAA;AAAA,KACA,YAAA,GAAe,MAAA,CAAO,SAAA;AAAA,KAEtB,OAAA,uBAA8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a,CAAA;EArGxD;;;EA0GtB,UAAA;EA1G8D;;;;AAWhE;;;EAwGE,YAAA;EAvFqB;;;;EA6FrB,aAAA,IAAiB,OAAA;EA3CE;;;;;;EAmDnB,OAAA;AAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@configdirector/vue-sdk",
3
- "version": "1.6.1",
3
+ "version": "1.8.0",
4
4
  "description": "Vue client SDK for ConfigDirector. ConfigDirector is a remote configuration and feature flag service.",
5
5
  "license": "MIT",
6
6
  "author": "ConfigDirector",
@@ -1,6 +0,0 @@
1
- var e=class{constructor(){this.handlerMap=new Map}on(e,t){let n=this.handlerMap.get(e);n?n.push(t):this.handlerMap.set(e,[t])}once(e,t){let n=this;function r(i){n.off(e,r),t.apply(n,i)}this.on(e,r)}off(e,t){let n=this.handlerMap.get(e);if(n)if(t){let e=n.indexOf(t);e>=0&&n.splice(e,1)}else this.handlerMap.set(e,[])}clear(){this.handlerMap.clear()}emit(e,t){let n=this.handlerMap.get(e);n&&n.slice().map(e=>e(t))}},t=class e extends Error{constructor(t,n){super(t),this.name=`ConfigDirectorConnectionError`,this.status=n,Object.setPrototypeOf(this,e.prototype)}},n=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorValidationError`,Object.setPrototypeOf(this,e.prototype)}},r=class e extends Error{constructor(t){super(t),this.name=`ConfigDirectorInitializationError`,Object.setPrototypeOf(this,e.prototype)}},i=class e extends Error{constructor(t){super(t),this.name=`StreamClosedError`,Object.setPrototypeOf(this,e.prototype)}},a=class e extends Error{constructor(t){super(t),this.name=`MissingResponseBodyError`,Object.setPrototypeOf(this,e.prototype)}},o=class e extends Error{constructor(t){super(t),this.name=`InvalidOptionError`,Object.setPrototypeOf(this,e.prototype)}},s=class e extends Error{constructor(t){super(t),this.name=`ValueOutOfRangeError`,Object.setPrototypeOf(this,e.prototype)}};function c(e){"@babel/helpers - typeof";return c=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},c(e)}function l(e,t){if(c(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(c(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function u(e){var t=l(e,`string`);return c(t)==`symbol`?t:t+``}function d(e,t,n){return(t=u(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function f(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function p(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?f(Object(n),!0).forEach(function(t){d(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):f(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var m=class{constructor(e){var t;this.isFirstChunk=!0,this.bufferedInput=``,this.currentEvent={data:``},this.currentEvent={data:``},this.onEvent=(t=e.onEvent)==null?(()=>{}):t,this.onRetry=e.onRetry,this.onComment=e.onComment}parse(e){let t=e;this.isFirstChunk&&(this.isFirstChunk=!1,t.startsWith(``)?t=t.slice(1):t.startsWith(``)&&(t=t.slice(3)));let n=this.scanLines(this.bufferedInput+t);for(let e of n)this.dispatchLine(e)}finish(){this.bufferedInput=``}scanLines(e){let t=[],n=0,r=0;for(;r<e.length;){let i=e[r];i===`\r`||i===`
2
- `?(t.push(e.slice(n,r)),i===`\r`&&e[r+1]===`
3
- `&&r++,r++,n=r):r++}return this.bufferedInput=e.slice(n),t}dispatchLine(e){if(e.startsWith(`:`)){var t;(t=this.onComment)==null||t.call(this,this.extractValue(e,1));return}if(e===``){this.emitEvent();return}this.applyField(this.parseField(e))}emitEvent(){let e=this.currentEvent.data.endsWith(`
4
- `)?this.currentEvent.data.slice(0,-1):this.currentEvent.data;e!==``&&this.onEvent(p(p({},this.currentEvent),{},{id:this.lastEventId,data:e})),this.currentEvent={data:``}}applyField(e){switch(e.field){case`event`:this.currentEvent.type=e.value;break;case`data`:this.currentEvent.data+=e.value+`
5
- `;break;case`id`:e.value.includes(`\0`)||(this.lastEventId=e.value);break;case`retry`:if(/^\d+$/.test(e.value)){var t;(t=this.onRetry)==null||t.call(this,Number.parseInt(e.value,10))}break;default:break}}parseField(e){let t=e.indexOf(`:`);return t===-1?{field:e,value:``}:{field:e.slice(0,t),value:this.extractValue(e,t+1)}}extractValue(e,t){return e[t]===` `?e.slice(t+1):e.slice(t)}};let h=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CONNECTING=`connecting`,e}({});var g=class{constructor(e){var t,n;this.DEFAULT_SHOULD_RECONNECT=()=>!0,this.DEFAULT_CALCULATE_RECONNECT_DELAY=()=>this.serverReconnectionTime,this.reconnectAttempt=0,this.abortController=new AbortController,this._readyState=h.CLOSED,this.serverReconnectionTime=2e3,this.url=e.url.toString(),this.lastEventId=e.lastEventId,this.headers=p({Accept:`text/event-stream`},e.headers);let r=e.body;this.body=typeof r==`function`?r:()=>r,this.requestOptions={method:(t=e.method)==null?`GET`:t,mode:e.mode,credentials:e.credentials,redirect:e.redirect,referrer:e.referrer,referrerPolicy:e.referrerPolicy},this._fetch=(n=e.fetch)==null?((e,t)=>fetch(e,t)):n,this._onError=this.resolveCallback(e.onError,()=>{},`onError`),this._onConnect=this.resolveCallback(e.onConnect,()=>{},`onConnect`),this._onDisconnect=this.resolveCallback(e.onDisconnect,()=>{},`onDisconnect`),this._onMessage=this.resolveCallback(e.onMessage,()=>{},`onMessage`),this._onComment=this.resolveCallback(e.onComment,()=>{},`onComment`),this._shouldReconnect=this.resolveCallback(e.shouldReconnect,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`),this._calculateReconnectDelay=this.resolveCallback(e.calculateReconnectDelay,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`calculateReconnectDelay`)}set onError(e){this._onError=this.resolveCallback(e,()=>{},`onError`)}set onMessage(e){this._onMessage=this.resolveCallback(e,()=>{},`onMessage`)}set onComment(e){this._onComment=this.resolveCallback(e,()=>{},`onComment`)}set onConnect(e){this._onConnect=this.resolveCallback(e,()=>{},`onConnect`)}set onDisconnect(e){this._onDisconnect=this.resolveCallback(e,()=>{},`onDisconnect`)}set shouldReconnect(e){this._shouldReconnect=this.resolveCallback(e,this.DEFAULT_SHOULD_RECONNECT,`shouldReconnect`)}set calculateReconnectDelay(e){this._calculateReconnectDelay=this.resolveCallback(e,this.DEFAULT_CALCULATE_RECONNECT_DELAY,`shouldReconnect`)}get readyState(){return this._readyState}connect(){this._readyState===h.CLOSED&&(this.reconnectAttempt=0,this.initiateConnection())}close(){clearTimeout(this.reconnectTimeout),this._readyState=h.CLOSED,this.abortController.abort()}initiateConnection(){this.abortController=new AbortController,this._readyState=h.CONNECTING,this._fetch(this.url,p(p({},this.requestOptions),{},{body:this.body(),headers:this.buildRequestHeaders(),signal:this.abortController.signal,cache:`no-store`})).then(e=>this.handleFetchResponse(e)).catch(e=>{if(e.name===`AbortError`||this.abortController.signal.aborted){this.close();return}this._onError(e),this.scheduleReconnect({error:e})})}async handleFetchResponse(e){var t=this;let{body:n,status:r}=e;if(r===204){t.disconnected();return}if(r>=400){t.scheduleReconnect({status:r});return}if(!n)throw new a(`The server response did not have a body`);t._readyState=h.OPEN,t._onConnect(),t.reconnectAttempt=0;let o=new m({onEvent:e=>{typeof e.id==`string`&&(t.lastEventId=e.id),t._onMessage(e)},onComment:e=>t._onComment(e),onRetry:e=>t.serverReconnectionTime=e});await t.readResponseStream(n,o),t.scheduleReconnect({status:r,error:new i(`The server response stream was closed`)})}async readResponseStream(e,t){let n=e.getReader(),r=new TextDecoder,i=!1;for(;!i;){let e=await n.read();e.value&&t.parse(r.decode(e.value,{stream:!0})),i=e.done}t.finish()}disconnected(){clearTimeout(this.reconnectTimeout),this._readyState=h.CLOSED,this._onDisconnect()}buildRequestHeaders(){let e=this.lastEventId?{"Last-Event-ID":this.lastEventId}:void 0;return p(p({},this.headers),e)}scheduleReconnect(e){if(this.abortController.signal.aborted)return;clearTimeout(this.reconnectTimeout),this.reconnectAttempt+=1;let t={attempt:this.reconnectAttempt,status:e.status,error:e.error,serverReconnectionTime:this.serverReconnectionTime};if(!this._shouldReconnect(t)){this.disconnected();return}this._readyState=h.CONNECTING;let n=this._calculateReconnectDelay(t);(!Number.isFinite(n)||n<1||n>1e3*60*60)&&(this._onError(new s(`The calculated reconnect delay is out of range: ${n}. Defaulting to ${this.serverReconnectionTime}`)),n=this.serverReconnectionTime),this.reconnectTimeout=setTimeout(()=>this.initiateConnection(),n)}resolveCallback(e,t,n){if(e==null)return t;if(typeof e!=`function`)throw new o(`${n} must be a function`);return e}};const _=e=>new g(e);var v=class{constructor(t){this.options=t,this.eventEmitter=new e,this.options=t,this.logger=t.logger,this.url=t.resolveUrl(`client/sse/v1`,t.baseUrl)}async connect(e,t){var n=this;n.eventSource&&n.close();let r=new Promise((t,r)=>{n.eventSource=_({url:n.url,method:`POST`,headers:{"Content-Type":`application/json`},fetch:n.options.fetch,body:JSON.stringify({givenContext:e,metaContext:n.options.metaContext,clientSdkKey:n.options.clientSdkKey,instanceId:n.options.instanceId}),onMessage:({data:e})=>{n.dispatchMessage(e)},onConnect:()=>{n.logger.debug(`[StreamingTransport] Connected`),t(n)},shouldReconnect:e=>{let t=!n.isStatusFatal(e.status);if(!t){let t=n.prepareFatalError(e.status,e.error);n.eventEmitter.emit(`connectionError`,t),r(t)}return t},calculateReconnectDelay:e=>{let t=n.options.connectionRetryDelay(e.attempt),r=`[StreamingTransport] Scheduling reconnect attempt #${e.attempt} in ${t}ms.`;return e.attempt<=5?n.logger.info(r):n.logger.warn(r),t},onError:e=>{n.logger.debug(`[StreamingTransport] Error: `,e)},onDisconnect:()=>{n.logger.debug(`[StreamingTransport] Disconnected`)}}),n.eventSource.connect()});return clearTimeout(n.timeoutTimer),n.timeoutTimer=void 0,Promise.race([r,new Promise(e=>{n.timeoutTimer=setTimeout(()=>e(n),t)})]).finally(()=>clearTimeout(n.timeoutTimer))}dispatchMessage(e){try{let t=JSON.parse(e);this.eventEmitter.emit(`configSetReceived`,t)}catch(e){this.logger.error(`[StreamingTransport] Error parsing and dispatching config data update: `,e)}}prepareFatalError(e,n){let r=e==null?0:e;return new t(`${`Connection failed with status: ${e==null?`unknown`:e}.`}${n?` Error: ${n}`:``}. This is an unrecoverable error, will not attempt to reconnect.`,r)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}close(){var e;(e=this.eventSource)==null||e.close(),clearTimeout(this.timeoutTimer)}dispose(){this.close(),this.clear()}};const y=e=>{let t=typeof e;if(t===`object`)try{var n,r;return(n=(r=e.constructor)==null?void 0:r.name)==null?t:n}catch(e){return t}else if(t===`function`)try{let n=e.name;return n?`function: ${n}`:t}catch(e){return t}return t},b=e=>e===`number`||e===`bigint`,x=new Set([`boolean`,`integer`,`float`]),S=(e,t)=>{let n=e.value,r=y(t);if(n==null||n===``)return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`value-missing`};if(e.type===`json`)return O(n,t,r,e.valueId);if(typeof t==`string`)return x.has(e.type)?{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}:{parsedValue:n,parsedValueId:e.valueId,requestedType:r,usedDefault:!1,reason:`found-match`};if(typeof t==`boolean`&&(e.type===`boolean`||e.type===`string`||e.type===`enum`)){let i=C(n),a=typeof i==`boolean`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-boolean`}}if(b(typeof t)&&e.type===`integer`){let i=w(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}if(b(typeof t)&&(e.type===`float`||e.type===`enum`||e.type===`string`)){let i=T(n),a=typeof i==`number`;return{parsedValue:a?i:t,parsedValueId:a?e.valueId:void 0,requestedType:r,usedDefault:!a,reason:a?`found-match`:`invalid-number`}}return{parsedValue:t,parsedValueId:void 0,requestedType:r,usedDefault:!0,reason:`type-mismatch`}},C=e=>{if(!e)return;let t=e.toLowerCase();if(!(t!=`true`&&t!=`false`))return t===`true`},w=e=>{let t=E(e);return t==null?void 0:Math.trunc(t)},T=e=>E(e),E=e=>{if(!e||!D(e))return;let t=Number(e);if(!(isNaN(t)||!isFinite(t)))return t},D=e=>{for(let t of e)if(!(t>=`0`&&t<=`9`)&&!`+-.eE`.includes(t))return!1;return!0},O=(e,t,n,r)=>{if(typeof t==`string`)return{parsedValue:e,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`};try{let i=JSON.parse(e);return k(i,t)?{parsedValue:i,parsedValueId:r,requestedType:n,usedDefault:!1,reason:`found-match`}:{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`type-mismatch`}}catch(e){return{parsedValue:t,parsedValueId:void 0,requestedType:n,usedDefault:!0,reason:`invalid-json`}}},k=(e,t)=>{if(e===null)return!1;let n=typeof t;return n===`bigint`?typeof e==`number`:typeof e===n},A={off:-1,error:0,warn:1,info:2,debug:3},j=()=>{let e={year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,timeZoneName:`short`};try{return new Intl.DateTimeFormat(void 0,p(p({},e),{},{fractionalSecondDigits:3}))}catch(t){return new Intl.DateTimeFormat(void 0,e)}};var M=class{constructor(e,t){this.level=e,this.decorator=t,this.level=e,this.decorator=t,this.dateFormatter=j()}debug(e,...t){this.log(console.debug,`debug`,e,...t)}info(e,...t){this.log(console.info,`info`,e,...t)}warn(e,...t){this.log(console.warn,`warn`,e,...t)}error(e,...t){this.log(console.error,`error`,e,...t)}log(e,t,n,...r){if(A[this.level]>=A[t]){var i;e(`[${this.dateFormatter.format(new Date)}] ${(i=this.decorator)==null?void 0:i.decorateMessage(n)}`,...r)}}},N=class{decorateMessage(e){return`[ConfigDirector:js-client-sdk] ${e}`}};const P=(e,t)=>new M(e==null?`warn`:e,t==null?new N:t),F=(e,t)=>new URL(e,t==null?void 0:t.toString()),I=e=>{if(e)try{return new URL(e)}catch(t){throw new n(`Invalid URL '${e}'. Parsing failed: ${t}`)}},L=`https://client-sdk-api.configdirector.com`,R=(e,t)=>e===void 0?{seconds:t.defaultSeconds,warning:void 0}:e>=t.minimumSeconds?{seconds:e,warning:void 0}:{seconds:t.minimumSeconds,warning:`pollingInterval of ${e} seconds is below the minimum of ${t.minimumSeconds} seconds. Using ${t.minimumSeconds} seconds.`},z=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)}),B=`configdirector-sdk:instance-id`,V=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,H=(e,t)=>{let n=t;for(let t=0;t<e.length;t++)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return n>>>0},U=(e,t)=>{let n=`configdirector.instanceId.v1|${e}|${t}`,r=H(n,2166136261);return H(`${r}|${n}`,16777619).toString(16).padStart(8,`0`)+r.toString(16).padStart(8,`0`)},W=()=>{try{var e;return(e=globalThis.localStorage)==null?void 0:e}catch(e){return}},G=e=>{if(!e||typeof e!=`object`)return!1;let{v:t,id:n,createdAt:r,checksum:i}=e;return t!==1||typeof n!=`string`||typeof i!=`string`||typeof r!=`number`||!Number.isInteger(r)||r<=0||!V.test(n)?!1:i===U(n,r)},K=(e,t)=>{let n;try{n=e.getItem(B)}catch(e){t==null||t.debug(`[ConfigDirectorClient] Could not read the stored instance id, generating a new one`,e);return}if(!n)return;let r;try{r=JSON.parse(n)}catch(e){t==null||t.debug(`[ConfigDirectorClient] The stored instance id is not valid JSON, generating a new one`);return}if(!G(r)){t==null||t.debug(`[ConfigDirectorClient] The stored instance id failed validation, generating a new one`);return}let i=Date.now()-r.createdAt;if(i<0||i>=216e5){t==null||t.debug(`[ConfigDirectorClient] The stored instance id has expired, generating a new one`);return}return r.id},q=(e,t,n)=>{let r=Date.now(),i={v:1,id:t,createdAt:r,checksum:U(t,r)};try{e.setItem(B,JSON.stringify(i))}catch(e){n==null||n.debug(`[ConfigDirectorClient] Could not persist the instance id`,e)}},J=e=>{let t=W();if(!t)return z();let n=K(t,e);if(n)return n;let r=z();return q(t,r,e),r};var Y=class{constructor(){this.fatalError=!1}clearPollingInterval(){clearInterval(this.pollingInterval)}schedulePollingInterval(e){clearInterval(this.pollingInterval),!(this.pollingIntervalSeconds<=0)&&(this.pollingInterval=setInterval(e,this.pollingIntervalSeconds*1e3))}async handleNonOkResponse(e){var n=this;if(!e.ok)throw n.isStatusFatal(e.status)?(n.fatalError=!0,n.close(),n.prepareFatalResponseStatusError(e.status,await e.text())):new t(`Connection failed with status: ${e.status}`,e.status)}handleFetchError(e){throw this.isFetchErrorFatal(e)?(this.fatalError=!0,this.close(),new t(`Connection failed with fatal error: ${e}. This is an unrecoverable error, retry attempts will be ignored.`)):e instanceof SyntaxError?new t(`Failed to parse the response from the server: ${e}`):new t(`Connection failed with error: ${e}.`)}prepareFatalResponseStatusError(e,n){var r,i;let a=e==null?0:e;return new t(`${`Connection failed with status: ${e==null?`unknown`:e}`}${((r=n==null||(i=n.trim())==null?void 0:i.length)==null?0:r)>0?` (${n})`:``}. This is an unrecoverable error, retry attempts will be ignored.`,a)}isStatusFatal(e){return!!e&&e>=400&&e<500&&e!=429}isFetchErrorFatal(e){return(e==null?void 0:e.name)===`NotAllowedError`}get isConnected(){return this.pollingInterval!==void 0}close(){clearInterval(this.pollingInterval),this.pollingInterval=void 0}dispose(){this.close(),this.clear()}};const X=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(),p(p({},n),{},{signal:i.signal}));return clearTimeout(a),e}catch(e){throw r.warn(`[fetchWithTimeout] Fetch error: `,e),clearTimeout(a),e}};var Z=class extends Y{constructor(t){var n;super(),this.options=t,this.eventEmitter=new e,this.options=t,this.logger=t.logger,this.url=t.resolveUrl(`client/polling/v1`,t.baseUrl),this.pollingIntervalSeconds=(n=t.pollingInterval)==null?60:n}async connect(e,t){var n=this;n.clearPollingInterval();try{await n.fetchConfigs(e,t)}finally{n.fatalError||n.schedulePollingInterval(()=>{n.fetchConfigs(e,t).catch(e=>{n.logger.error(`[PollingTransport] Error during polling:`,e)})})}return n}async fetchConfigs(e,t){var n=this;if(n.fatalError){n.logger.warn(`[PollingTransport] There was a prior unrecoverable error. Ignoring attempt to reconnect.`);return}try{let r=await X(t,n.url,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({givenContext:e,metaContext:n.options.metaContext,clientSdkKey:n.options.clientSdkKey,instanceId:n.options.instanceId,lastUpdateTimestamp:n.lastUpdateTimestamp})},n.logger);if(await n.handleNonOkResponse(r),r.status==200){let e=JSON.parse(await r.text());n.lastUpdateTimestamp=e.timestamp,n.eventEmitter.emit(`configSetReceived`,e)}}catch(e){try{n.handleFetchError(e)}catch(e){throw n.fatalError&&n.eventEmitter.emit(`connectionError`,e),e}}}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.eventEmitter.clear()}};const Q=e=>{try{return e(globalThis)}catch(e){return}},$=()=>Q(e=>{var t;return(t=e.navigator)==null?void 0:t.userAgent}),ee=()=>Q(e=>{var t;return(t=e.location)==null?void 0:t.host});var te=class{constructor(t,n,r,i,a){var o,s,c,l,u,d,f,m,h,g,_,v,y,b;this.handlersMap=new Map,this.eventEmitter=new e,this.ready=!1,this.initializing=!1,this.hasReceivedConfigSet=!1,this.logger=(o=i==null?void 0:i.logger)==null?P():o,this.instanceId=J(this.logger),this.timeout=(s=i==null||(c=i.connection)==null?void 0:c.timeout)==null?3e3:s,this.validateSdkKeyPresence(n);let x=(l=a==null?void 0:a.urlFactory)==null?F:l,S=(u=this.parseUrl(i==null||(d=i.connection)==null?void 0:d.url,x))==null?L:u;this.connectionMode=(f=i==null||(m=i.connection)==null?void 0:m.mode)==null?`streaming`:f,this.telemetryClient=t,this.transport=(h=a==null?void 0:a.transport)==null?this.buildTransport(n,r,S,x,i,a):h,this.transport.on(`configSetReceived`,e=>{var t;this.hasReceivedConfigSet=!0,(t=this.readyResolve)==null||t.call(this);let n=this.findKeysRemovedBy(e);!this.configSet||e.kind==`full`?this.configSet=e:this.configSet.configs=p(p({},this.configSet.configs),e.configs);let r=Object.keys(e.configs);this.emit(`configsUpdated`,{keys:r,removedKeys:n}),this.updateWatchers([...r,...n]),this.logger.debug(`[ConfigDirectorClient] ConfigSet updated from server:`,{keys:r,removedKeys:n})}),this.transport.on(`connectionError`,e=>{this.initializing=!1,this.logger.error(`[ConfigDirectorClient] The connection encountered an unrecoverable error and will not be retried. Configs will no longer receive updates.`,e),this.emit(`connectionError`,{error:e})}),this.registerHandler(`clientReady`,i==null||(g=i.hooks)==null?void 0:g.clientReady),this.registerHandler(`configEvaluated`,i==null||(_=i.hooks)==null?void 0:_.configEvaluated),this.registerHandler(`configsUpdated`,i==null||(v=i.hooks)==null?void 0:v.configsUpdated),this.registerHandler(`contextUpdated`,i==null||(y=i.hooks)==null?void 0:y.contextUpdated),this.registerHandler(`connectionError`,i==null||(b=i.hooks)==null?void 0:b.connectionError)}registerHandler(e,t){if(!t)return;let n=Array.isArray(t)?t:[t];for(let t of n)typeof t==`function`&&this.on(e,t)}resolvePollingIntervalForMode(e){if(this.connectionMode!==`polling`)return;let t=R(e,{defaultSeconds:60,minimumSeconds:30});return t.warning&&this.logger.warn(`[ConfigDirectorClient] ${t.warning}`),t.seconds}buildTransport(e,t,n,r,i,a){var o,s;return new(this.getTransportConstructor(this.connectionMode))({instanceId:this.instanceId,clientSdkKey:e,baseUrl:n,resolveUrl:r,metaContext:p(p({},i==null?void 0:i.metadata),{},{sdkName:t.sdkName,sdkVersion:t.sdkVersion,userAgent:$(),host:ee()}),logger:this.logger,fetch:a==null?void 0:a.fetch,connectionRetryDelay:(o=a==null?void 0:a.connectionRetryDelay)==null?(e=>2**Math.min(e,9)*1e3):o,pollingInterval:this.resolvePollingIntervalForMode(i==null||(s=i.connection)==null?void 0:s.pollingInterval)})}getTransportConstructor(e){switch(e){case`polling`:return Z;default:return v}}async initialize(e){var t=this;t.hasReceivedConfigSet||(t.initializing=!0),await t.connectToTransport(e,`initialization`)}async updateContext(e){await this.connectToTransport(e,`context update`)}get context(){return this.currentContext}async connectToTransport(e,t){var n=this;try{n.ready=!1,n.readyPromise=new Promise(e=>{n.readyResolve=e}).then(e=>{e||(n.ready=!0,n.initializing=!1,n.emit(`clientReady`,{action:t}),n.logger.debug(`[ConfigDirectorClient] Received initial payload from the server, client is ready`))});let r=new Date().getTime();await n.transport.connect(e==null?{}:e,n.timeout,t),n.currentContext=e,n.telemetryClient.updateContext(e).catch(e=>n.logger.warn(`[ConfigDirectorClient] Telemetry could not update the context: `,e)),n.emit(`contextUpdated`,{context:e});let i=new Date().getTime()-r,a=n.timeout-i;clearTimeout(n.timeoutTimer),n.timeoutTimer=void 0,a>0&&await Promise.race([n.readyPromise,new Promise(e=>{n.timeoutTimer=setTimeout(()=>e(),a)})]).finally(()=>clearTimeout(n.timeoutTimer)),n.ready||n.logger.warn(`[ConfigDirectorClient] Timed out waiting for ${t} after ${n.timeout}ms. The client will continue to retry since there were no fatal errors detected. Configs will return the default value until the connection succeeds.`)}catch(e){n.logger.error(`[ConfigDirectorClient] An error occurred during ${t}: `,e)}}findKeysRemovedBy(e){return!this.configSet||e.kind!=`full`?[]:Object.keys(this.configSet.configs).filter(t=>!Object.prototype.hasOwnProperty.call(e.configs,t))}updateWatchers(e){e.forEach(e=>this.updateWatchersForConfig(e))}updateWatchersForConfig(e){var t,n;let r=(t=this.configSet)==null?void 0:t.configs[e];(n=this.handlersMap.get(e))==null||n.forEach(t=>{let n=this.getValueFromConfigState(e,r,t.defaultValue);t.handler(n)})}watch(e,t,n){this.validateDefaultValue(t);let r=this.handlersMap.get(e),i={handler:n,defaultValue:t,requestedType:typeof t};return r?r.push(i):this.handlersMap.set(e,[i]),()=>this.unwatch(e,n)}unwatch(e,t){let n=this.handlersMap.get(e);if(n)if(t){let e=n.findIndex(e=>e.handler==t);e>=0&&(n==null||n.splice(e,1))}else n.splice(0)}getValue(e,t){var n;this.validateDefaultValue(t);let r=(n=this.configSet)==null?void 0:n.configs[e];return this.getValueFromConfigState(e,r,t)}getValueFromConfigState(e,t,n){var r,i;if(!t){var a;this.logger.debug(`[ConfigDirectorClient] No config state found for '${e}', returning default value '${n}'`);let t=this.isReady?`config-state-missing`:`client-not-ready`;return this.telemetryClient.evaluatedConfig({contextId:(a=this.currentContext)==null?void 0:a.id,key:e,defaultValue:n,requestedType:y(n),evaluatedValue:n,usedDefault:!0,evaluationReason:t}),this.dispatchEvaluationEvent({key:e,value:n,isDefaultValue:!0,reason:t,context:this.context}),n}let o=S(t,n);return this.telemetryClient.evaluatedConfig({contextId:(r=this.currentContext)==null?void 0:r.id,type:t.type,key:e,defaultValue:n,requestedType:o.requestedType,evaluatedValue:o.parsedValue,evaluatedValueId:o.parsedValueId,usedDefault:o.usedDefault,evaluationReason:o.reason}),this.dispatchEvaluationEvent({key:e,value:o.parsedValue,valueId:(i=o.parsedValueId)==null?void 0:i,isDefaultValue:o.usedDefault,reason:o.reason,context:this.context}),this.logger.debug(`[ConfigDirectorClient] Evaluated '${e}' to '${o.parsedValue}'`),o.parsedValue}dispatchEvaluationEvent(e){setTimeout(()=>this.emit(`configEvaluated`,{evaluation:e}),0)}emit(e,t){try{this.eventEmitter.emit(e,t)}catch(t){this.logger.error(`[ConfigDirectorClient] Error executing event handlers for '${e}'`,t)}}parseUrl(e,t){if(e)try{return t(e)}catch(t){throw new n(`Invalid base URL '${e}'. Parsing failed: ${t}`)}}validateSdkKeyPresence(e){if(!e||e.trim().length==0)throw new n(`No client SDK key was provided, the client cannot be instantiated without a valid client SDK key`)}validateDefaultValue(e){if(e==null)throw new n(`Invalid default value. The default value for a config must be defined and non-null.`);if(typeof e==`function`)throw new n(`Invalid default value. The default value for a config cannot be a function.`)}get isReady(){return this.ready}get isInitializing(){return this.initializing}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}clear(){this.logger.debug(`[ConfigDirectorClient] clear() has been called, removing all observers`),this.eventEmitter.clear(),this.handlersMap.clear()}unwatchAll(){this.handlersMap.clear()}pauseNetwork(){this.logger.debug(`[ConfigDirectorClient] pauseNetwork() called, pausing transport connection`),clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0,this.transport.close(),this.ready=!1}async resumeNetwork(){var e=this;await e.connectToTransport(e.currentContext,`network resume`)}async close(){var e=this,t;e.logger.debug(`[ConfigDirectorClient] close() has been called, closing connection to server`),clearTimeout(e.timeoutTimer),(t=e.readyResolve)==null||t.call(e,!0),e.telemetryClient.close().catch(t=>e.logger.warn(`[ConfigDirectorClient] Telemetry could not close: `,t)),e.transport.close(),e.ready=!1,e.initializing=!1}dispose(){this.clear(),this.close()}};export{P as a,r as c,I as i,n as l,L as n,p as o,F as r,t as s,te as t,e as u};
6
- //# sourceMappingURL=DefaultConfigDirectorClient-Ci14OJI0.mjs.map