@launchdarkly/cloudflare-server-sdk 2.7.11 → 2.7.13

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../shared/sdk-server/dist/BigSegmentStatusProviderImpl.js","../../../../shared/common/dist/cjs/index.cjs","../../../../shared/sdk-server/dist/api/data/LDFlagsStateOptions.js","../../../../shared/sdk-server/dist/api/data/LDFlagsState.js","../../../../shared/sdk-server/dist/api/data/LDMigrationStage.js","../../../../shared/sdk-server/dist/api/data/LDMigrationOpEvent.js","../../../../shared/sdk-server/dist/api/data/LDMigrationVariation.js","../../../../shared/sdk-server/dist/api/data/index.js","../../../../shared/sdk-server/dist/api/options/LDBigSegmentsOptions.js","../../../../shared/sdk-server/dist/api/options/LDOptions.js","../../../../shared/sdk-server/dist/api/options/LDProxyOptions.js","../../../../shared/sdk-server/dist/api/options/LDTLSOptions.js","../../../../shared/sdk-server/dist/api/options/LDMigrationOptions.js","../../../../shared/sdk-server/dist/api/options/LDDataSystemOptions.js","../../../../shared/sdk-server/dist/api/options/index.js","../../../../shared/sdk-server/dist/api/LDClient.js","../../../../shared/sdk-server/dist/api/LDMigration.js","../../../../shared/sdk-server/dist/api/interfaces/DataKind.js","../../../../shared/sdk-server/dist/api/subsystems/LDFeatureStore.js","../../../../shared/sdk-server/dist/api/subsystems/LDTransactionalFeatureStore.js","../../../../shared/sdk-server/dist/api/LDWaitForInitializationOptions.js","../../../../shared/sdk-server/dist/api/integrations/FileDataSourceOptions.js","../../../../shared/sdk-server/dist/api/integrations/Hook.js","../../../../shared/sdk-server/dist/api/integrations/index.js","../../../../shared/sdk-server/dist/api/interfaces/BigSegmentStore.js","../../../../shared/sdk-server/dist/api/interfaces/BigSegmentStoreMembership.js","../../../../shared/sdk-server/dist/api/interfaces/BigSegmentStoreMetadata.js","../../../../shared/sdk-server/dist/api/interfaces/BigSegmentStoreStatus.js","../../../../shared/sdk-server/dist/api/interfaces/DataCollection.js","../../../../shared/sdk-server/dist/api/interfaces/FullDataSet.js","../../../../shared/sdk-server/dist/api/interfaces/KeyedItems.js","../../../../shared/sdk-server/dist/api/interfaces/VersionedData.js","../../../../shared/sdk-server/dist/api/interfaces/BigSegmentStoreStatusProvider.js","../../../../shared/sdk-server/dist/api/interfaces/persistent_store/index.js","../../../../shared/sdk-server/dist/api/interfaces/index.js","../../../../shared/sdk-server/dist/api/subsystems/LDDataSourceUpdates.js","../../../../shared/sdk-server/dist/api/subsystems/LDFeatureRequestor.js","../../../../shared/sdk-server/dist/api/subsystems/LDTransactionalDataSourceUpdates.js","../../../../shared/sdk-server/dist/api/subsystems/index.js","../../../../shared/sdk-server/dist/api/index.js","../../../../shared/sdk-server/dist/cache/LruCache.js","../../../../shared/sdk-server/dist/BigSegmentsManager.js","../../../../shared/sdk-server/dist/createPluginEnvironmentMetadata.js","../../../../shared/sdk-server/dist/data_sources/createPayloadListenerFDv2.js","../../../../shared/sdk-server/dist/store/VersionedDataKinds.js","../../../../shared/sdk-server/dist/store/serialization.js","../../../../shared/sdk-server/dist/data_sources/createStreamListeners.js","../../../../shared/sdk-server/dist/data_sources/NamespacedDataSet.js","../../../../shared/sdk-server/dist/data_sources/DependencyTracker.js","../../../../shared/sdk-server/dist/data_sources/DataSourceUpdates.js","../../../../shared/sdk-server/dist/data_sources/FileLoader.js","../../../../shared/sdk-server/dist/data_sources/fileDataInitilizerFDv2.js","../../../../shared/sdk-server/dist/data_sources/OneShotInitializerFDv2.js","../../../../shared/sdk-server/dist/async/promisify.js","../../../../shared/sdk-server/dist/store/AsyncStoreFacade.js","../../../../shared/sdk-server/dist/store/AsyncTransactionalStoreFacade.js","../../../../shared/sdk-server/dist/cache/TtlCache.js","../../../../shared/sdk-server/dist/store/persistentStoreKinds.js","../../../../shared/sdk-server/dist/store/sortDataSet.js","../../../../shared/sdk-server/dist/store/UpdateQueue.js","../../../../shared/sdk-server/dist/store/PersistentDataStoreWrapper.js","../../../../shared/sdk-server/dist/store/InMemoryFeatureStore.js","../../../../shared/sdk-server/dist/store/TransactionalFeatureStore.js","../../../../shared/sdk-server/dist/store/index.js","../../../../shared/sdk-server/dist/data_sources/PollingProcessor.js","../../../../shared/sdk-server/dist/data_sources/PollingProcessorFDv2.js","../../../../shared/sdk-server/dist/data_sources/Requestor.js","../../../../shared/sdk-server/dist/data_sources/StreamingProcessor.js","../../../../shared/sdk-server/dist/data_sources/StreamingProcessorFDv2.js","../../../../shared/sdk-server/dist/data_sources/TransactionalDataSourceUpdates.js","../../../../shared/sdk-server/dist/options/Configuration.js","../../../../shared/sdk-server/dist/diagnostics/createDiagnosticsInitConfig.js","../../../../shared/sdk-server/dist/evaluation/collection.js","../../../../shared/sdk-server/dist/evaluation/Reasons.js","../../../../shared/sdk-server/dist/evaluation/EvalResult.js","../../../../shared/sdk-server/dist/evaluation/Bucketer.js","../../../../shared/sdk-server/dist/evaluation/variations.js","../../../../shared/sdk-server/dist/evaluation/evalTargets.js","../../../../shared/sdk-server/dist/evaluation/makeBigSegmentRef.js","../../../../shared/sdk-server/dist/evaluation/Operations.js","../../../../shared/sdk-server/dist/evaluation/matchClause.js","../../../../shared/sdk-server/dist/evaluation/matchSegmentTargets.js","../../../../shared/sdk-server/dist/evaluation/Evaluator.js","../../../../shared/sdk-server/dist/events/ContextDeduplicator.js","../../../../shared/sdk-server/dist/events/isExperiment.js","../../../../shared/sdk-server/dist/events/EventFactory.js","../../../../shared/sdk-server/dist/FlagsStateBuilder.js","../../../../shared/sdk-server/dist/hooks/HookRunner.js","../../../../shared/sdk-server/dist/MigrationOpEventConversion.js","../../../../shared/sdk-server/dist/MigrationOpTracker.js","../../../../shared/sdk-server/dist/LDClientImpl.js","../../../../shared/sdk-server/dist/Migration.js","../../../../shared/sdk-server/dist/data_sources/FileDataSource.js","../../../../shared/sdk-server/dist/integrations/FileDataSourceFactory.js","../../../../shared/sdk-server/dist/integrations/test_data/booleanVariation.js","../../../../shared/sdk-server/dist/integrations/test_data/TestDataRuleBuilder.js","../../../../shared/sdk-server/dist/integrations/test_data/TestDataFlagBuilder.js","../../../../shared/sdk-server/dist/integrations/test_data/TestDataSource.js","../../../../shared/sdk-server/dist/integrations/test_data/TestData.js","../../../../shared/sdk-server/dist/integrations/test_data/index.js","../../../../shared/sdk-server/dist/integrations/index.js","../../../../shared/sdk-server/dist/events/NullEventSource.js","../../../../shared/sdk-server/dist/events/index.js","../../../../shared/sdk-server/dist/internal/index.js","../../../../shared/sdk-server/dist/index.js","../../../../shared/sdk-server-edge/dist/esm/src/platform/crypto/cryptoJSHasher.js","../../../../shared/sdk-server-edge/dist/esm/src/platform/crypto/cryptoJSHmac.js","../../../../shared/sdk-server-edge/dist/esm/src/platform/crypto/index.js","../../../../shared/sdk-server-edge/dist/esm/src/platform/requests.js","../../../../shared/sdk-server-edge/dist/esm/src/platform/index.js","../../../../shared/sdk-server-edge/dist/esm/src/api/createCallbacks.js","../../../../shared/sdk-server-edge/dist/esm/src/api/createOptions.js","../../../../shared/sdk-server-edge/dist/esm/src/api/LDClient.js","../../../../shared/sdk-server-edge/dist/esm/src/api/EdgeFeatureStore.js","../../../../shared/sdk-server-edge/dist/esm/src/utils/validateOptions.js","../../src/createPlatformInfo.ts","../../src/index.ts","../../../../shared/sdk-server-edge/dist/esm/src/index.js"],"sourcesContent":["\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @ignore\n */\nclass BigSegmentStoreStatusProviderImpl {\n constructor(_onRequestStatus) {\n this._onRequestStatus = _onRequestStatus;\n }\n /**\n * Gets the current status of the store, if known.\n *\n * @returns a {@link BigSegmentStoreStatus}, or `undefined` if the SDK has not yet queried the\n * Big Segment store status\n */\n getStatus() {\n return this._lastStatus;\n }\n /**\n * Gets the current status of the store, querying it if the status has not already been queried.\n *\n * @returns a Promise for the status of the store\n */\n async requireStatus() {\n if (!this._lastStatus) {\n await this._onRequestStatus();\n }\n // Status will be defined at this point.\n return this._lastStatus;\n }\n notify() {\n var _a;\n if (this._lastStatus) {\n (_a = this._listener) === null || _a === void 0 ? void 0 : _a.call(this, this._lastStatus);\n }\n }\n setListener(listener) {\n this._listener = listener;\n }\n setStatus(status) {\n this._lastStatus = status;\n }\n}\nexports.default = BigSegmentStoreStatusProviderImpl;\n//# sourceMappingURL=BigSegmentStatusProviderImpl.js.map","'use strict';\n\n/**\n * Converts a literal to a ref string.\n * @param value\n * @returns An escaped literal which can be used as a ref.\n */\nfunction toRefString(value) {\n return `/${value.replace(/~/g, '~0').replace(/\\//g, '~1')}`;\n}\n/**\n * Produce a literal from a ref component.\n * @param ref\n * @returns A literal version of the ref.\n */\nfunction unescape(ref) {\n return ref.indexOf('~') ? ref.replace(/~1/g, '/').replace(/~0/g, '~') : ref;\n}\nfunction getComponents(reference) {\n const referenceWithoutPrefix = reference.startsWith('/') ? reference.substring(1) : reference;\n return referenceWithoutPrefix.split('/').map((component) => unescape(component));\n}\nfunction isLiteral(reference) {\n return !reference.startsWith('/');\n}\nfunction validate(reference) {\n return !reference.match(/\\/\\/|(^\\/.*~[^0|^1])|~$/);\n}\nclass AttributeReference {\n /**\n * Take an attribute reference string, or literal string, and produce\n * an attribute reference.\n *\n * Legacy user objects would have been created with names not\n * references. So, in that case, we need to use them as a component\n * without escaping them.\n *\n * e.g. A user could contain a custom attribute of `/a` which would\n * become the literal `a` if treated as a reference. Which would cause\n * it to no longer be redacted.\n * @param refOrLiteral The attribute reference string or literal string.\n * @param literal it true the value should be treated as a literal.\n */\n constructor(refOrLiteral, literal = false) {\n if (!literal) {\n this.redactionName = refOrLiteral;\n if (refOrLiteral === '' || refOrLiteral === '/' || !validate(refOrLiteral)) {\n this.isValid = false;\n this._components = [];\n return;\n }\n if (isLiteral(refOrLiteral)) {\n this._components = [refOrLiteral];\n }\n else if (refOrLiteral.indexOf('/', 1) < 0) {\n this._components = [unescape(refOrLiteral.slice(1))];\n }\n else {\n this._components = getComponents(refOrLiteral);\n }\n // The items inside of '_meta' are not intended to be addressable.\n // Excluding it as a valid reference means that we can make it non-addressable\n // without having to copy all the attributes out of the context object\n // provided by the user.\n if (this._components[0] === '_meta') {\n this.isValid = false;\n }\n else {\n this.isValid = true;\n }\n }\n else {\n const literalVal = refOrLiteral;\n this._components = [literalVal];\n this.isValid = literalVal !== '';\n // Literals which start with '/' need escaped to prevent ambiguity.\n this.redactionName = literalVal.startsWith('/') ? toRefString(literalVal) : literalVal;\n }\n }\n get(target) {\n const { _components: components, isValid } = this;\n if (!isValid) {\n return undefined;\n }\n let current = target;\n // This doesn't use a range based for loops, because those use generators.\n // See `no-restricted-syntax`.\n // It also doesn't use a collection method because this logic is more\n // straightforward with a loop.\n for (let index = 0; index < components.length; index += 1) {\n const component = components[index];\n if (current !== null &&\n current !== undefined &&\n // See https://eslint.org/docs/rules/no-prototype-builtins\n Object.prototype.hasOwnProperty.call(current, component) &&\n typeof current === 'object' &&\n // We do not want to allow indexing into an array.\n !Array.isArray(current)) {\n current = current[component];\n }\n else {\n return undefined;\n }\n }\n return current;\n }\n getComponent(depth) {\n return this._components[depth];\n }\n get depth() {\n return this._components.length;\n }\n get isKind() {\n return this._components.length === 1 && this._components[0] === 'kind';\n }\n compare(other) {\n return (this.depth === other.depth &&\n this._components.every((value, index) => value === other.getComponent(index)));\n }\n get components() {\n return [...this._components];\n }\n}\n/**\n * For use as invalid references when deserializing Flag/Segment data.\n */\nAttributeReference.InvalidReference = new AttributeReference('');\n\n/* eslint-disable class-methods-use-this */\n/* eslint-disable max-classes-per-file */\n/**\n * Validate a factory or instance.\n */\nclass FactoryOrInstance {\n is(factoryOrInstance) {\n if (Array.isArray(factoryOrInstance)) {\n return false;\n }\n const anyFactory = factoryOrInstance;\n const typeOfFactory = typeof anyFactory;\n return typeOfFactory === 'function' || typeOfFactory === 'object';\n }\n getType() {\n return 'factory method or object';\n }\n}\n/**\n * Validate a basic type.\n */\nclass Type {\n constructor(typeName, example) {\n this._typeName = typeName;\n this.typeOf = typeof example;\n }\n is(u) {\n if (Array.isArray(u)) {\n return false;\n }\n return typeof u === this.typeOf;\n }\n getType() {\n return this._typeName;\n }\n}\n/**\n * Validate an array of the specified type.\n *\n * This does not validate instances of types. All class instances\n * of classes will simply objects.\n */\nclass TypeArray {\n constructor(typeName, example) {\n this._typeName = typeName;\n this.typeOf = typeof example;\n }\n is(u) {\n if (Array.isArray(u)) {\n if (u.length > 0) {\n return u.every((val) => typeof val === this.typeOf);\n }\n return true;\n }\n return false;\n }\n getType() {\n return this._typeName;\n }\n}\n/**\n * Validate a value is a number and is greater or eval than a minimum.\n */\nclass NumberWithMinimum extends Type {\n constructor(min) {\n super(`number with minimum value of ${min}`, 0);\n this.min = min;\n }\n is(u) {\n return typeof u === this.typeOf && u >= this.min;\n }\n}\n/**\n * Validate a value is a string and it matches the given expression.\n */\nclass StringMatchingRegex extends Type {\n constructor(expression) {\n super(`string matching ${expression}`, '');\n this.expression = expression;\n }\n is(u) {\n return typeof u === 'string' && !!u.match(this.expression);\n }\n}\n/**\n * Validate a value is a function.\n */\nclass Function {\n is(u) {\n // We cannot inspect the parameters and there isn't really\n // a generic function type we can instantiate.\n // So the type guard is here just to make TS comfortable\n // calling something after using this guard.\n return typeof u === 'function';\n }\n getType() {\n return 'function';\n }\n}\nclass NullableBoolean {\n is(u) {\n return typeof u === 'boolean' || typeof u === 'undefined' || u === null;\n }\n getType() {\n return 'boolean | undefined | null';\n }\n}\n// Our reference SDK, Go, parses date/time strings with the time.RFC3339Nano format.\n// This regex should match strings that are valid in that format, and no others.\n// Acceptable:\n// 2019-10-31T23:59:59Z, 2019-10-31T23:59:59.100Z,\n// 2019-10-31T23:59:59-07, 2019-10-31T23:59:59-07:00, etc.\n// Unacceptable: no \"T\", no time zone designation\nconst DATE_REGEX = /^\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(\\.\\d\\d*)?(Z|[-+]\\d\\d(:\\d\\d)?)/;\n/**\n * Validate a value is a date. Values which are numbers are treated as dates and any string\n * which if compliant with `time.RFC3339Nano` is a date.\n */\nclass DateValidator {\n is(u) {\n return typeof u === 'number' || (typeof u === 'string' && DATE_REGEX.test(u));\n }\n getType() {\n return 'date';\n }\n}\n/**\n * Validates that a string is a valid kind.\n */\nclass KindValidator extends StringMatchingRegex {\n constructor() {\n super(/^(\\w|\\.|-)+$/);\n }\n is(u) {\n return super.is(u) && u !== 'kind';\n }\n}\n/**\n * A set of standard type validators.\n */\nclass TypeValidators {\n static createTypeArray(typeName, example) {\n return new TypeArray(typeName, example);\n }\n static numberWithMin(min) {\n return new NumberWithMinimum(min);\n }\n static stringMatchingRegex(expression) {\n return new StringMatchingRegex(expression);\n }\n}\nTypeValidators.String = new Type('string', '');\nTypeValidators.Number = new Type('number', 0);\nTypeValidators.ObjectOrFactory = new FactoryOrInstance();\nTypeValidators.Object = new Type('object', {});\nTypeValidators.StringArray = new TypeArray('string[]', '');\nTypeValidators.Boolean = new Type('boolean', true);\nTypeValidators.Function = new Function();\nTypeValidators.Date = new DateValidator();\nTypeValidators.Kind = new KindValidator();\nTypeValidators.NullableBoolean = new NullableBoolean();\n\n/**\n * Check if a context is a single kind context.\n * @param context\n * @returns true if the context is a single kind context.\n */\nfunction isSingleKind(context) {\n if ('kind' in context) {\n return TypeValidators.String.is(context.kind) && context.kind !== 'multi';\n }\n return false;\n}\n/**\n * Check if a context is a multi-kind context.\n * @param context\n * @returns true if it is a multi-kind context.\n */\nfunction isMultiKind(context) {\n if ('kind' in context) {\n return TypeValidators.String.is(context.kind) && context.kind === 'multi';\n }\n return false;\n}\n/**\n * Check if a context is a legacy user context.\n * @param context\n * @returns true if it is a legacy user context.\n */\nfunction isLegacyUser(context) {\n return !('kind' in context) || context.kind === null || context.kind === undefined;\n}\n\n/**\n * Given some object to serialize product a canonicalized JSON string.\n * https://www.rfc-editor.org/rfc/rfc8785.html\n *\n * We do not support custom toJSON methods on objects. Objects should be limited to basic types.\n *\n * @param object The object to serialize.\n */\nfunction canonicalize(object, visited = []) {\n // For JavaScript the default JSON serialization will produce canonicalized output for basic types.\n if (object === null || typeof object !== 'object') {\n return JSON.stringify(object);\n }\n if (visited.includes(object)) {\n throw new Error('Cycle detected');\n }\n if (Array.isArray(object)) {\n const values = object\n .map((item) => canonicalize(item, [...visited, object]))\n .map((item) => (item === undefined ? 'null' : item));\n return `[${values.join(',')}]`;\n }\n const values = Object.keys(object)\n .sort()\n .map((key) => {\n const value = canonicalize(object[key], [...visited, object]);\n if (value !== undefined) {\n return `${JSON.stringify(key)}:${value}`;\n }\n return undefined;\n })\n .filter((item) => item !== undefined);\n return `{${values.join(',')}}`;\n}\n\n// The general strategy for the context is to transform the passed in context\n// as little as possible. We do convert the legacy users to a single kind\n// context, but we do not translate all passed contexts into a rigid structure.\n// The context will have to be copied for events, but we want to avoid any\n// copying that we can.\n// So we validate that the information we are given is correct, and then we\n// just proxy calls with a nicely typed interface.\n// This is to reduce work on the hot-path. Later, for event processing, deeper\n// cloning of the context will be done.\n// When no kind is specified, then this kind will be used.\nconst DEFAULT_KIND = 'user';\n// The API allows for calling with an `LDContext` which is\n// `LDUser | LDSingleKindContext | LDMultiKindContext`. When ingesting a context\n// first the type must be determined to allow us to put it into a consistent type.\n/**\n * The partial URL encoding is needed because : is a valid character in context keys.\n *\n * Partial encoding is the replacement of all colon (:) characters with the URL\n * encoded equivalent (%3A) and all percent (%) characters with the URL encoded\n * equivalent (%25).\n * @param key The key to encode.\n * @returns Partially URL encoded key.\n */\nfunction encodeKey(key) {\n if (key.includes('%') || key.includes(':')) {\n return key.replace(/%/g, '%25').replace(/:/g, '%3A');\n }\n return key;\n}\n/**\n * Check if the given value is a LDContextCommon.\n * @param kindOrContext\n * @returns true if it is an LDContextCommon\n *\n * Due to a limitation in the expressiveness of these highly polymorphic types any field\n * in a multi-kind context can either be a context or 'kind'. So we need to re-assure\n * the compiler that it isn't the word multi.\n *\n * Because we do not allow top level values in a multi-kind context we can validate\n * that as well.\n */\nfunction isContextCommon(kindOrContext) {\n return kindOrContext && TypeValidators.Object.is(kindOrContext);\n}\n/**\n * Validate a context kind.\n * @param kind\n * @returns true if the kind is valid.\n */\nfunction validKind(kind) {\n return TypeValidators.Kind.is(kind);\n}\n/**\n * Validate a context key.\n * @param key\n * @returns true if the key is valid.\n */\nfunction validKey(key) {\n return TypeValidators.String.is(key) && key !== '';\n}\nfunction processPrivateAttributes(privateAttributes, literals = false) {\n if (privateAttributes) {\n return privateAttributes.map((privateAttribute) => new AttributeReference(privateAttribute, literals));\n }\n return [];\n}\nfunction defined(value) {\n return value !== null && value !== undefined;\n}\n/**\n * Convert a legacy user to a single kind context.\n * @param user\n * @returns A single kind context.\n */\nfunction legacyToSingleKind(user) {\n const singleKindContext = {\n // Key was coerced to a string for eval and events, so we can do that up-front.\n ...(user.custom || []),\n kind: 'user',\n key: String(user.key),\n };\n // For legacy users we never established a difference between null\n // and undefined for inputs. Because anonymous can be used in evaluations\n // we would want it to not possibly match true/false unless defined.\n // Which is different than coercing a null/undefined anonymous as `false`.\n if (defined(user.anonymous)) {\n const anonymous = !!user.anonymous;\n delete singleKindContext.anonymous;\n singleKindContext.anonymous = anonymous;\n }\n if (user.name !== null && user.name !== undefined) {\n singleKindContext.name = user.name;\n }\n if (user.ip !== null && user.ip !== undefined) {\n singleKindContext.ip = user.ip;\n }\n if (user.firstName !== null && user.firstName !== undefined) {\n singleKindContext.firstName = user.firstName;\n }\n if (user.lastName !== null && user.lastName !== undefined) {\n singleKindContext.lastName = user.lastName;\n }\n if (user.email !== null && user.email !== undefined) {\n singleKindContext.email = user.email;\n }\n if (user.avatar !== null && user.avatar !== undefined) {\n singleKindContext.avatar = user.avatar;\n }\n if (user.country !== null && user.country !== undefined) {\n singleKindContext.country = user.country;\n }\n if (user.privateAttributeNames !== null && user.privateAttributeNames !== undefined) {\n singleKindContext._meta = {\n privateAttributes: user.privateAttributeNames,\n };\n }\n // We are not pulling private attributes over because we will serialize\n // those from attribute references for events.\n return singleKindContext;\n}\n/**\n * Container for a context/contexts. Because contexts come from external code\n * they must be thoroughly validated and then formed to comply with\n * the type system.\n */\nclass Context {\n /**\n * Contexts should be created using the static factory method {@link Context.fromLDContext}.\n * @param kind The kind of the context.\n *\n * The factory methods are static functions within the class because they access private\n * implementation details, so they cannot be free functions.\n */\n constructor(valid, kind, message) {\n this._isMulti = false;\n this._isUser = false;\n this._wasLegacy = false;\n this._contexts = {};\n this.kind = kind;\n this.valid = valid;\n this.message = message;\n }\n static _contextForError(kind, message) {\n return new Context(false, kind, message);\n }\n static _getValueFromContext(reference, context) {\n if (!context || !reference.isValid) {\n return undefined;\n }\n if (reference.depth === 1 && reference.getComponent(0) === 'anonymous') {\n return !!context?.anonymous;\n }\n return reference.get(context);\n }\n _contextForKind(kind) {\n if (this._isMulti) {\n return this._contexts[kind];\n }\n if (this.kind === kind) {\n return this._context;\n }\n return undefined;\n }\n static _fromMultiKindContext(context) {\n const kinds = Object.keys(context).filter((key) => key !== 'kind');\n const kindsValid = kinds.every(validKind);\n if (!kinds.length) {\n return Context._contextForError('multi', 'A multi-kind context must contain at least one kind');\n }\n if (!kindsValid) {\n return Context._contextForError('multi', 'Context contains invalid kinds');\n }\n const privateAttributes = {};\n let contextsAreObjects = true;\n const contexts = kinds.reduce((acc, kind) => {\n const singleContext = context[kind];\n if (isContextCommon(singleContext)) {\n acc[kind] = singleContext;\n privateAttributes[kind] = processPrivateAttributes(singleContext._meta?.privateAttributes);\n }\n else {\n // No early break isn't the most efficient, but it is an error condition.\n contextsAreObjects = false;\n }\n return acc;\n }, {});\n if (!contextsAreObjects) {\n return Context._contextForError('multi', 'Context contained contexts that were not objects');\n }\n if (!Object.values(contexts).every((part) => validKey(part.key))) {\n return Context._contextForError('multi', 'Context contained invalid keys');\n }\n // There was only a single kind in the multi-kind context.\n // So we can just translate this to a single-kind context.\n if (kinds.length === 1) {\n const kind = kinds[0];\n const created = new Context(true, kind);\n created._context = { ...contexts[kind], kind };\n created._privateAttributeReferences = privateAttributes;\n created._isUser = kind === 'user';\n return created;\n }\n const created = new Context(true, context.kind);\n created._contexts = contexts;\n created._privateAttributeReferences = privateAttributes;\n created._isMulti = true;\n return created;\n }\n static _fromSingleKindContext(context) {\n const { key, kind } = context;\n const kindValid = validKind(kind);\n const keyValid = validKey(key);\n if (!kindValid) {\n return Context._contextForError(kind ?? 'unknown', 'The kind was not valid for the context');\n }\n if (!keyValid) {\n return Context._contextForError(kind, 'The key for the context was not valid');\n }\n // The JSON interfaces uses dangling _.\n // eslint-disable-next-line no-underscore-dangle\n const privateAttributeReferences = processPrivateAttributes(context._meta?.privateAttributes);\n const created = new Context(true, kind);\n created._isUser = kind === 'user';\n created._context = context;\n created._privateAttributeReferences = {\n [kind]: privateAttributeReferences,\n };\n return created;\n }\n static _fromLegacyUser(context) {\n const keyValid = context.key !== undefined && context.key !== null;\n // For legacy users we allow empty keys.\n if (!keyValid) {\n return Context._contextForError('user', 'The key for the context was not valid');\n }\n const created = new Context(true, 'user');\n created._isUser = true;\n created._wasLegacy = true;\n created._context = legacyToSingleKind(context);\n created._privateAttributeReferences = {\n user: processPrivateAttributes(context.privateAttributeNames, true),\n };\n return created;\n }\n /**\n * Attempt to create a {@link Context} from an {@link LDContext}.\n * @param context The input context to create a Context from.\n * @returns a {@link Context}, if the context was not valid, then the returned contexts `valid`\n * property will be false.\n */\n static fromLDContext(context) {\n if (!context) {\n return Context._contextForError('unknown', 'No context specified. Returning default value');\n }\n if (isSingleKind(context)) {\n return Context._fromSingleKindContext(context);\n }\n if (isMultiKind(context)) {\n return Context._fromMultiKindContext(context);\n }\n if (isLegacyUser(context)) {\n return Context._fromLegacyUser(context);\n }\n return Context._contextForError('unknown', 'Context was not of a valid kind');\n }\n /**\n * Creates a {@link LDContext} from a {@link Context}.\n * @param context to be converted\n * @returns an {@link LDContext} if input was valid, otherwise undefined\n */\n static toLDContext(context) {\n if (!context.valid) {\n return undefined;\n }\n const contexts = context.getContexts();\n if (!context._isMulti) {\n return contexts[0][1];\n }\n const result = {\n kind: 'multi',\n };\n contexts.forEach((kindAndContext) => {\n const kind = kindAndContext[0];\n const nestedContext = kindAndContext[1];\n result[kind] = nestedContext;\n });\n return result;\n }\n /**\n * Attempt to get a value for the given context kind using the given reference.\n * @param reference The reference to the value to get.\n * @param kind The kind of the context to get the value for.\n * @returns a value or `undefined` if one is not found.\n */\n valueForKind(reference, kind = DEFAULT_KIND) {\n if (reference.isKind) {\n return this.kinds;\n }\n return Context._getValueFromContext(reference, this._contextForKind(kind));\n }\n /**\n * Attempt to get a key for the specified kind.\n * @param kind The kind to get a key for.\n * @returns The key for the specified kind, or undefined.\n */\n key(kind = DEFAULT_KIND) {\n return this._contextForKind(kind)?.key;\n }\n /**\n * True if this is a multi-kind context.\n */\n get isMultiKind() {\n return this._isMulti;\n }\n /**\n * Get the canonical key for this context.\n */\n get canonicalKey() {\n if (this._isUser) {\n return this._context.key;\n }\n if (this._isMulti) {\n return Object.keys(this._contexts)\n .sort()\n .map((key) => `${key}:${encodeKey(this._contexts[key].key)}`)\n .join(':');\n }\n return `${this.kind}:${encodeKey(this._context.key)}`;\n }\n /**\n * Get the kinds of this context.\n */\n get kinds() {\n if (this._isMulti) {\n return Object.keys(this._contexts);\n }\n return [this.kind];\n }\n /**\n * Get the kinds, and their keys, for this context.\n */\n get kindsAndKeys() {\n if (this._isMulti) {\n return Object.entries(this._contexts).reduce((acc, [kind, context]) => {\n acc[kind] = context.key;\n return acc;\n }, {});\n }\n return { [this.kind]: this._context.key };\n }\n /**\n * Get the attribute references.\n *\n * @param kind\n */\n privateAttributes(kind) {\n return this._privateAttributeReferences?.[kind] || [];\n }\n /**\n * Get the underlying context objects from this context.\n *\n * This method is intended to be used in event generation.\n *\n * The returned objects should not be modified.\n */\n getContexts() {\n if (this._isMulti) {\n return Object.entries(this._contexts);\n }\n return [[this.kind, this._context]];\n }\n get legacy() {\n return this._wasLegacy;\n }\n /**\n * Get the serialized canonical JSON for this context. This is not filtered for use in events.\n *\n * This method will cache the result.\n *\n * @returns The serialized canonical JSON or undefined if it cannot be serialized.\n */\n canonicalUnfilteredJson() {\n if (!this.valid) {\n return undefined;\n }\n if (this._cachedCanonicalJson) {\n return this._cachedCanonicalJson;\n }\n try {\n this._cachedCanonicalJson = canonicalize(Context.toLDContext(this));\n }\n catch {\n // Indicated by undefined being returned.\n }\n return this._cachedCanonicalJson;\n }\n}\nContext.UserKind = DEFAULT_KIND;\n\n// _meta is part of the specification.\n// These attributes cannot be removed via a private attribute.\nconst protectedAttributes = ['key', 'kind', '_meta', 'anonymous'].map((str) => new AttributeReference(str, true));\n// Attributes that should be stringified for legacy users.\nconst legacyTopLevelCopyAttributes = [\n 'name',\n 'ip',\n 'firstName',\n 'lastName',\n 'email',\n 'avatar',\n 'country',\n];\nfunction compare(a, b) {\n return a.depth === b.length && b.every((value, index) => value === a.getComponent(index));\n}\nfunction cloneWithRedactions(target, references) {\n const stack = [];\n const cloned = {};\n const excluded = [];\n stack.push(...Object.keys(target).map((key) => ({\n key,\n ptr: [key],\n source: target,\n parent: cloned,\n visited: [target],\n })));\n while (stack.length) {\n const item = stack.pop();\n const redactRef = references.find((ref) => compare(ref, item.ptr));\n if (!redactRef) {\n const value = item.source[item.key];\n // Handle null because it overlaps with object, which we will want to handle later.\n if (value === null) {\n item.parent[item.key] = value;\n }\n else if (Array.isArray(value)) {\n item.parent[item.key] = [...value];\n }\n else if (typeof value === 'object') {\n // Arrays and null must already be handled.\n // Prevent cycles by not visiting the same object\n // with in the same branch. Different branches\n // may contain the same object.\n //\n // Same object visited twice in different branches.\n // A -> B -> D\n // -> C -> D\n // This is fine, which is why it doesn't just check if the object\n // was visited ever.\n if (!item.visited.includes(value)) {\n item.parent[item.key] = {};\n stack.push(...Object.keys(value).map((key) => ({\n key,\n ptr: [...item.ptr, key],\n source: value,\n parent: item.parent[item.key],\n visited: [...item.visited, value],\n })));\n }\n }\n else {\n item.parent[item.key] = value;\n }\n }\n else {\n excluded.push(redactRef.redactionName);\n }\n }\n return { cloned, excluded: excluded.sort() };\n}\nclass ContextFilter {\n constructor(_allAttributesPrivate, _privateAttributes) {\n this._allAttributesPrivate = _allAttributesPrivate;\n this._privateAttributes = _privateAttributes;\n }\n filter(context, redactAnonymousAttributes = false) {\n const contexts = context.getContexts();\n if (contexts.length === 1) {\n return this._filterSingleKind(context, contexts[0][1], contexts[0][0], redactAnonymousAttributes);\n }\n const filteredMulti = {\n kind: 'multi',\n };\n contexts.forEach(([kind, single]) => {\n filteredMulti[kind] = this._filterSingleKind(context, single, kind, redactAnonymousAttributes);\n });\n return filteredMulti;\n }\n _getAttributesToFilter(context, single, kind, redactAllAttributes) {\n return (redactAllAttributes\n ? Object.keys(single).map((k) => new AttributeReference(k, true))\n : [...this._privateAttributes, ...context.privateAttributes(kind)]).filter((attr) => !protectedAttributes.some((protectedAttr) => protectedAttr.compare(attr)));\n }\n _filterSingleKind(context, single, kind, redactAnonymousAttributes) {\n const redactAllAttributes = this._allAttributesPrivate || (redactAnonymousAttributes && single.anonymous === true);\n const { cloned, excluded } = cloneWithRedactions(single, this._getAttributesToFilter(context, single, kind, redactAllAttributes));\n if (context.legacy) {\n legacyTopLevelCopyAttributes.forEach((name) => {\n if (name in cloned) {\n cloned[name] = String(cloned[name]);\n }\n });\n }\n if (excluded.length) {\n if (!cloned._meta) {\n cloned._meta = {};\n }\n cloned._meta.redactedAttributes = excluded;\n }\n if (cloned._meta) {\n delete cloned._meta.privateAttributes;\n if (Object.keys(cloned._meta).length === 0) {\n delete cloned._meta;\n }\n }\n return cloned;\n }\n}\n\nconst MAX_RETRY_DELAY = 30 * 1000; // Maximum retry delay 30 seconds.\nconst JITTER_RATIO = 0.5; // Delay should be 50%-100% of calculated time.\n/**\n * Implements exponential backoff and jitter. This class tracks successful connections and failures\n * and produces a retry delay.\n *\n * It does not start any timers or directly control a connection.\n *\n * The backoff follows an exponential backoff scheme with 50% jitter starting at\n * initialRetryDelayMillis and capping at MAX_RETRY_DELAY. If RESET_INTERVAL has elapsed after a\n * success, without an intervening faulure, then the backoff is reset to initialRetryDelayMillis.\n */\nclass DefaultBackoff {\n constructor(initialRetryDelayMillis, _retryResetIntervalMillis, _random = Math.random) {\n this._retryResetIntervalMillis = _retryResetIntervalMillis;\n this._random = _random;\n this._retryCount = 0;\n // Initial retry delay cannot be 0.\n this._initialRetryDelayMillis = Math.max(1, initialRetryDelayMillis);\n this._maxExponent = Math.ceil(Math.log2(MAX_RETRY_DELAY / this._initialRetryDelayMillis));\n }\n _backoff() {\n const exponent = Math.min(this._retryCount, this._maxExponent);\n const delay = this._initialRetryDelayMillis * 2 ** exponent;\n return Math.min(delay, MAX_RETRY_DELAY);\n }\n _jitter(computedDelayMillis) {\n return computedDelayMillis - Math.trunc(this._random() * JITTER_RATIO * computedDelayMillis);\n }\n /**\n * This function should be called when a connection attempt is successful.\n *\n * @param timeStampMs The time of the success. Used primarily for testing, when not provided\n * the current time is used.\n */\n success(timeStampMs = Date.now()) {\n this._activeSince = timeStampMs;\n }\n /**\n * This function should be called when a connection fails. It returns the a delay, in\n * milliseconds, after which a reconnection attempt should be made.\n *\n * @param timeStampMs The time of the success. Used primarily for testing, when not provided\n * the current time is used.\n * @returns The delay before the next connection attempt.\n */\n fail(timeStampMs = Date.now()) {\n // If the last successful connection was active for more than the RESET_INTERVAL, then we\n // return to the initial retry delay.\n if (this._activeSince !== undefined &&\n timeStampMs - this._activeSince > this._retryResetIntervalMillis) {\n this._retryCount = 0;\n }\n this._activeSince = undefined;\n const delay = this._jitter(this._backoff());\n this._retryCount += 1;\n return delay;\n }\n}\n\n/**\n * Handler that connects the current {@link DataSource} to the {@link CompositeDataSource}. A single\n * {@link CallbackHandler} should only be given to one {@link DataSource}. Use {@link disable()} to\n * prevent additional callback events.\n */\nclass CallbackHandler {\n constructor(_dataCallback, _statusCallback) {\n this._dataCallback = _dataCallback;\n this._statusCallback = _statusCallback;\n this._disabled = false;\n }\n disable() {\n this._disabled = true;\n }\n async dataHandler(basis, data) {\n if (this._disabled) {\n return;\n }\n this._dataCallback(basis, data);\n }\n async statusHandler(status, err) {\n if (this._disabled) {\n return;\n }\n this._statusCallback(status, err);\n }\n}\n\n// TODO: refactor client-sdk to use this enum\n/**\n * @experimental\n * This feature is not stable and not subject to any backwards compatibility guarantees or semantic\n * versioning. It is not suitable for production usage.\n */\nvar DataSourceState;\n(function (DataSourceState) {\n // Positive confirmation of connection/data receipt\n DataSourceState[DataSourceState[\"Valid\"] = 0] = \"Valid\";\n // Spinning up to make first connection attempt\n DataSourceState[DataSourceState[\"Initializing\"] = 1] = \"Initializing\";\n // Transient issue, automatic retry is expected\n DataSourceState[DataSourceState[\"Interrupted\"] = 2] = \"Interrupted\";\n // Data source was closed and will not retry automatically.\n DataSourceState[DataSourceState[\"Closed\"] = 3] = \"Closed\";\n})(DataSourceState || (DataSourceState = {}));\n\n/**\n * Helper class for {@link CompositeDataSource} to manage iterating on data sources and removing them on the fly.\n */\nclass DataSourceList {\n /**\n * @param circular whether to loop off the end of the list back to the start\n * @param initialList of content\n */\n constructor(circular, initialList) {\n this._list = initialList ? [...initialList] : [];\n this._circular = circular;\n this._pos = 0;\n }\n /**\n * Returns the current head and then iterates.\n */\n next() {\n if (this._list.length <= 0 || this._pos >= this._list.length) {\n return undefined;\n }\n const result = this._list[this._pos];\n if (this._circular) {\n this._pos = (this._pos + 1) % this._list.length;\n }\n else {\n this._pos += 1;\n }\n return result;\n }\n /**\n * Replaces all elements with the provided list and resets the position of head to the start.\n *\n * @param input that will replace existing list\n */\n replace(input) {\n this._list = [...input];\n this._pos = 0;\n }\n /**\n * Removes the provided element from the list. If the removed element was the head, head moves to next. Consider head may be undefined if list is empty after removal.\n *\n * @param element to remove\n * @returns true if element was removed\n */\n remove(element) {\n const index = this._list.indexOf(element);\n if (index < 0) {\n return false;\n }\n this._list.splice(index, 1);\n if (this._list.length > 0) {\n // if removed item was before head, adjust head\n if (index < this._pos) {\n this._pos -= 1;\n }\n if (this._circular && this._pos > this._list.length - 1) {\n this._pos = 0;\n }\n }\n return true;\n }\n /**\n * Reset the head position to the start of the list.\n */\n reset() {\n this._pos = 0;\n }\n /**\n * @returns the current head position in the list, 0 indexed.\n */\n pos() {\n return this._pos;\n }\n /**\n * @returns the current length of the list\n */\n length() {\n return this._list.length;\n }\n /**\n * Clears the list and resets head.\n */\n clear() {\n this._list = [];\n this._pos = 0;\n }\n}\n\nclass LDFileDataSourceError extends Error {\n constructor(message) {\n super(message);\n this.name = 'LaunchDarklyFileDataSourceError';\n }\n}\nclass LDPollingError extends Error {\n constructor(kind, message, status, recoverable = true) {\n super(message);\n this.kind = kind;\n this.status = status;\n this.name = 'LaunchDarklyPollingError';\n this.recoverable = recoverable;\n }\n}\nclass LDStreamingError extends Error {\n constructor(kind, message, code, recoverable = true) {\n super(message);\n this.kind = kind;\n this.code = code;\n this.name = 'LaunchDarklyStreamingError';\n this.recoverable = recoverable;\n }\n}\n/**\n * This is a short term error and will be removed once FDv2 adoption is sufficient.\n */\nclass LDFlagDeliveryFallbackError extends Error {\n constructor(kind, message, code) {\n super(message);\n this.kind = kind;\n this.code = code;\n this.name = 'LDFlagDeliveryFallbackError';\n this.recoverable = false;\n }\n}\n\nconst DEFAULT_FALLBACK_TIME_MS = 2 * 60 * 1000;\nconst DEFAULT_RECOVERY_TIME_MS = 5 * 60 * 1000;\n/**\n * The {@link CompositeDataSource} can combine a number of {@link DataSystemInitializer}s and {@link DataSystemSynchronizer}s\n * into a single {@link DataSource}, implementing fallback and recovery logic internally to choose where data is sourced from.\n */\nclass CompositeDataSource {\n /**\n * @param initializers factories to create {@link DataSystemInitializer}s, in priority order.\n * @param synchronizers factories to create {@link DataSystemSynchronizer}s, in priority order.\n * @param fdv1Synchronizers factories to fallback to if we need to fallback to FDv1.\n * @param _logger for logging\n * @param _transitionConditions to control automated transition between datasources. Typically only used for testing.\n * @param _backoff to control delay between transitions. Typically only used for testing.\n */\n constructor(initializers, synchronizers, fdv1Synchronizers, _logger, _transitionConditions = {\n [DataSourceState.Valid]: {\n durationMS: DEFAULT_RECOVERY_TIME_MS,\n transition: 'recover',\n },\n [DataSourceState.Interrupted]: {\n durationMS: DEFAULT_FALLBACK_TIME_MS,\n transition: 'fallback',\n },\n }, _backoff = new DefaultBackoff(1000, 30000)) {\n this._logger = _logger;\n this._transitionConditions = _transitionConditions;\n this._backoff = _backoff;\n this._stopped = true;\n this._cancelTokens = [];\n this._cancellableDelay = (delayMS) => {\n let timeout;\n const promise = new Promise((res, _) => {\n timeout = setTimeout(res, delayMS);\n });\n return {\n promise,\n cancel() {\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n },\n };\n };\n this._externalTransitionPromise = new Promise((resolveTransition) => {\n this._externalTransitionResolve = resolveTransition;\n });\n this._initPhaseActive = initializers.length > 0; // init phase if we have initializers\n this._initFactories = new DataSourceList(false, initializers);\n this._syncFactories = new DataSourceList(true, synchronizers);\n this._fdv1Synchronizers = new DataSourceList(true, fdv1Synchronizers);\n }\n async start(dataCallback, statusCallback, selectorGetter) {\n if (!this._stopped) {\n // don't allow multiple simultaneous runs\n this._logger?.info('CompositeDataSource already running. Ignoring call to start.');\n return;\n }\n this._stopped = false;\n this._logger?.debug(`CompositeDataSource starting with (${this._initFactories.length()} initializers, ${this._syncFactories.length()} synchronizers).`);\n // this wrapper turns status updates from underlying data sources into a valid series of status updates for the consumer of this\n // composite data source\n const sanitizedStatusCallback = this._wrapStatusCallbackWithSanitizer(statusCallback);\n sanitizedStatusCallback(DataSourceState.Initializing);\n let lastTransition;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { dataSource: currentDS, isPrimary, cullDSFactory, } = this._pickDataSource(lastTransition);\n const internalTransitionPromise = new Promise((transitionResolve) => {\n if (currentDS) {\n // these local variables are used for handling automatic transition related to data source status (ex: recovering to primary after\n // secondary has been valid for N many seconds)\n let lastState;\n let cancelScheduledTransition = () => { };\n // this callback handler can be disabled and ensures only one transition request occurs\n const callbackHandler = new CallbackHandler((basis, data) => {\n this._backoff.success();\n dataCallback(basis, data);\n if (basis && this._initPhaseActive) {\n // transition to sync if we get basis during init\n callbackHandler.disable();\n this._consumeCancelToken(cancelScheduledTransition);\n sanitizedStatusCallback(DataSourceState.Interrupted);\n transitionResolve({ transition: 'switchToSync' });\n }\n }, (state, err) => {\n // When we get a status update, we want to fallback if it is an error. We also want to schedule a transition for some\n // time in the future if this status remains for some duration (ex: Recover to primary synchronizer after the secondary\n // synchronizer has been Valid for some time). These scheduled transitions are configurable in the constructor.\n this._logger?.debug(`CompositeDataSource received state ${state} from underlying data source. Err is ${err}`);\n if (err || state === DataSourceState.Closed) {\n callbackHandler.disable();\n if (err?.recoverable === false) {\n // don't use this datasource's factory again\n this._logger?.debug(`Culling data source due to err ${err}`);\n cullDSFactory?.();\n // this error indicates we should fallback to only using FDv1 synchronizers\n if (err instanceof LDFlagDeliveryFallbackError) {\n this._logger?.debug(`Falling back to FDv1`);\n this._syncFactories = this._fdv1Synchronizers;\n }\n }\n sanitizedStatusCallback(state, err);\n this._consumeCancelToken(cancelScheduledTransition);\n transitionResolve({ transition: 'fallback', err }); // unrecoverable error has occurred, so fallback\n }\n else {\n sanitizedStatusCallback(state);\n if (state !== lastState) {\n lastState = state;\n this._consumeCancelToken(cancelScheduledTransition); // cancel previously scheduled status transition if one was scheduled\n // primary source cannot recover to itself, so exclude it\n const condition = this._lookupTransitionCondition(state, isPrimary);\n if (condition) {\n const { promise, cancel } = this._cancellableDelay(condition.durationMS);\n cancelScheduledTransition = cancel;\n this._cancelTokens.push(cancelScheduledTransition);\n promise.then(() => {\n this._consumeCancelToken(cancel);\n callbackHandler.disable();\n sanitizedStatusCallback(DataSourceState.Interrupted);\n transitionResolve({ transition: condition.transition });\n });\n }\n }\n }\n });\n currentDS.start((basis, data) => callbackHandler.dataHandler(basis, data), (status, err) => callbackHandler.statusHandler(status, err), selectorGetter);\n }\n else {\n // we don't have a data source to use!\n transitionResolve({\n transition: 'stop',\n err: {\n name: 'ExhaustedDataSources',\n message: `CompositeDataSource has exhausted all configured initializers and synchronizers.`,\n },\n });\n }\n });\n // await transition triggered by internal data source or an external stop request\n let transitionRequest = await Promise.race([\n internalTransitionPromise,\n this._externalTransitionPromise,\n ]);\n // stop the underlying datasource before transitioning to next state\n currentDS?.stop();\n if (transitionRequest.err && transitionRequest.transition !== 'stop') {\n // if the transition was due to an error we're not in the initializer phase, throttle the transition. Fallback between initializers is not throttled.\n const delay = this._initPhaseActive ? 0 : this._backoff.fail();\n const { promise, cancel: cancelDelay } = this._cancellableDelay(delay);\n this._cancelTokens.push(cancelDelay);\n const delayedTransition = promise.then(() => {\n this._consumeCancelToken(cancelDelay);\n return transitionRequest;\n });\n // race the delayed transition and external transition requests to be responsive\n transitionRequest = await Promise.race([\n delayedTransition,\n this._externalTransitionPromise,\n ]);\n // consume the delay cancel token (even if it resolved, need to stop tracking its token)\n this._consumeCancelToken(cancelDelay);\n }\n lastTransition = transitionRequest.transition;\n if (transitionRequest.transition === 'stop') {\n // exit the loop, this is intentionally not the sanitized status callback\n statusCallback(DataSourceState.Closed, transitionRequest.err);\n break;\n }\n }\n // reset so that run can be called again in the future\n this._reset();\n }\n async stop() {\n this._cancelTokens.forEach((cancel) => cancel());\n this._cancelTokens = [];\n this._externalTransitionResolve?.({ transition: 'stop' });\n }\n _reset() {\n this._stopped = true;\n this._initPhaseActive = this._initFactories.length() > 0; // init phase if we have initializers;\n this._initFactories.reset();\n this._syncFactories.reset();\n this._fdv1Synchronizers.reset();\n this._externalTransitionPromise = new Promise((tr) => {\n this._externalTransitionResolve = tr;\n });\n // intentionally not resetting the backoff to avoid a code path that could circumvent throttling\n }\n /**\n * Determines the next datasource and returns that datasource as well as a closure to cull the\n * datasource from the datasource lists. One example where the cull closure is invoked is if the\n * datasource has an unrecoverable error.\n */\n _pickDataSource(transition) {\n let factory;\n let isPrimary;\n switch (transition) {\n case 'switchToSync':\n this._initPhaseActive = false; // one way toggle to false, unless this class is reset()\n this._syncFactories.reset();\n isPrimary = this._syncFactories.pos() === 0;\n factory = this._syncFactories.next();\n break;\n case 'recover':\n if (this._initPhaseActive) {\n this._initFactories.reset();\n isPrimary = this._initFactories.pos() === 0;\n factory = this._initFactories.next();\n }\n else {\n this._syncFactories.reset();\n isPrimary = this._syncFactories.pos() === 0;\n factory = this._syncFactories.next();\n }\n break;\n case 'fallback':\n default:\n // if asked to fallback after using all init factories, switch to sync factories\n if (this._initPhaseActive && this._initFactories.pos() >= this._initFactories.length()) {\n this._initPhaseActive = false;\n this._syncFactories.reset();\n }\n if (this._initPhaseActive) {\n isPrimary = this._initFactories.pos() === 0;\n factory = this._initFactories.next();\n }\n else {\n isPrimary = this._syncFactories.pos() === 0;\n factory = this._syncFactories.next();\n }\n break;\n }\n if (!factory) {\n return { dataSource: undefined, isPrimary, cullDSFactory: undefined };\n }\n return {\n dataSource: factory(),\n isPrimary,\n cullDSFactory: () => {\n if (factory) {\n this._syncFactories.remove(factory);\n }\n },\n };\n }\n /**\n * @returns the transition condition for the provided data source state or undefined\n * if there is no transition condition\n */\n _lookupTransitionCondition(state, excludeRecover) {\n const condition = this._transitionConditions[state];\n // exclude recovery can happen for certain initializers/synchronizers (ex: the primary synchronizer shouldn't recover to itself)\n if (excludeRecover && condition?.transition === 'recover') {\n return undefined;\n }\n return condition;\n }\n _consumeCancelToken(cancel) {\n cancel();\n const index = this._cancelTokens.indexOf(cancel, 0);\n if (index > -1) {\n this._cancelTokens.splice(index, 1);\n }\n }\n /**\n * This wrapper will ensure the following:\n *\n * Don't report DataSourceState.Initializing except as first status callback.\n * Map underlying DataSourceState.Closed to interrupted.\n * Don't report the same status and error twice in a row.\n */\n _wrapStatusCallbackWithSanitizer(statusCallback) {\n let alreadyReportedInitializing = false;\n let lastStatus;\n let lastErr;\n return (status, err) => {\n let sanitized = status;\n // underlying errors, closed state, or off are masked as interrupted while we transition\n if (status === DataSourceState.Closed) {\n sanitized = DataSourceState.Interrupted;\n }\n // don't report the same combination of values twice in a row\n if (sanitized === lastStatus && err === lastErr) {\n return;\n }\n if (sanitized === DataSourceState.Initializing) {\n // don't report initializing again if that has already been reported\n if (alreadyReportedInitializing) {\n return;\n }\n alreadyReportedInitializing = true;\n }\n lastStatus = sanitized;\n lastErr = err;\n statusCallback(sanitized, err);\n };\n }\n}\n\nexports.DataSourceErrorKind = void 0;\n(function (DataSourceErrorKind) {\n /// An unexpected error, such as an uncaught exception, further\n /// described by the error message.\n DataSourceErrorKind[\"Unknown\"] = \"UNKNOWN\";\n /// An I/O error such as a dropped connection.\n DataSourceErrorKind[\"NetworkError\"] = \"NETWORK_ERROR\";\n /// The LaunchDarkly service returned an HTTP response with an error\n /// status, available in the status code.\n DataSourceErrorKind[\"ErrorResponse\"] = \"ERROR_RESPONSE\";\n /// The SDK received malformed data from the LaunchDarkly service.\n DataSourceErrorKind[\"InvalidData\"] = \"INVALID_DATA\";\n})(exports.DataSourceErrorKind || (exports.DataSourceErrorKind = {}));\n\n/* eslint-disable import/prefer-default-export */\n/**\n * Enable / disable Auto environment attributes. When enabled, the SDK will automatically\n * provide data about the mobile environment where the application is running. This data makes it simpler to target\n * your mobile customers based on application name or version, or on device characteristics including manufacturer,\n * model, operating system, locale, and so on. We recommend enabling this when you configure the SDK. To learn more,\n * read [Automatic environment attributes](https://docs.launchdarkly.com/sdk/features/environment-attributes).\n * for more documentation.\n */\nexports.AutoEnvAttributes = void 0;\n(function (AutoEnvAttributes) {\n AutoEnvAttributes[AutoEnvAttributes[\"Disabled\"] = 0] = \"Disabled\";\n AutoEnvAttributes[AutoEnvAttributes[\"Enabled\"] = 1] = \"Enabled\";\n})(exports.AutoEnvAttributes || (exports.AutoEnvAttributes = {}));\n\nvar LDEventType;\n(function (LDEventType) {\n LDEventType[LDEventType[\"AnalyticsEvents\"] = 0] = \"AnalyticsEvents\";\n LDEventType[LDEventType[\"DiagnosticEvent\"] = 1] = \"DiagnosticEvent\";\n})(LDEventType || (LDEventType = {}));\nvar LDDeliveryStatus;\n(function (LDDeliveryStatus) {\n LDDeliveryStatus[LDDeliveryStatus[\"Succeeded\"] = 0] = \"Succeeded\";\n LDDeliveryStatus[LDDeliveryStatus[\"Failed\"] = 1] = \"Failed\";\n LDDeliveryStatus[LDDeliveryStatus[\"FailedAndMustShutDown\"] = 2] = \"FailedAndMustShutDown\";\n})(LDDeliveryStatus || (LDDeliveryStatus = {}));\n\nvar index$1 = /*#__PURE__*/Object.freeze({\n __proto__: null,\n get DataSourceState () { return DataSourceState; },\n get LDDeliveryStatus () { return LDDeliveryStatus; },\n get LDEventType () { return LDEventType; }\n});\n\n/**\n * Attempt to produce a string representation of a value.\n * The format should be roughly comparable to `util.format`\n * aside from object which will be JSON versus the `util.inspect`\n * format.\n * @param val\n * @returns A string representation of the value if possible.\n */\nfunction tryStringify(val) {\n if (typeof val === 'string') {\n return val;\n }\n if (val === undefined) {\n return 'undefined';\n }\n if (val === null) {\n return 'null';\n }\n if (Object.prototype.hasOwnProperty.call(val, 'toString')) {\n try {\n return val.toString();\n }\n catch {\n /* Keep going */\n }\n }\n if (typeof val === 'bigint') {\n return `${val}n`;\n }\n try {\n return JSON.stringify(val);\n }\n catch (error) {\n if (error instanceof TypeError && error.message.indexOf('circular') >= 0) {\n return '[Circular]';\n }\n return '[Not Stringifiable]';\n }\n}\n/**\n * Attempt to produce a numeric representation.\n * BigInts have an `n` suffix.\n * @param val\n * @returns The numeric representation or 'NaN' if not numeric.\n */\nfunction toNumber(val) {\n // Symbol has to be treated special because it will\n // throw an exception if an attempt is made to convert it.\n if (typeof val === 'symbol') {\n return 'NaN';\n }\n if (typeof val === 'bigint') {\n return `${val}n`;\n }\n return String(Number(val));\n}\n/**\n * Attempt to produce an integer representation.\n * BigInts have an `n` suffix.\n * @param val\n * @returns The integer representation or 'NaN' if not numeric.\n */\nfunction toInt(val) {\n if (typeof val === 'symbol') {\n return 'NaN';\n }\n if (typeof val === 'bigint') {\n return `${val}n`;\n }\n return String(parseInt(val, 10));\n}\n/**\n * Attempt to produce a float representation.\n * BigInts have an `n` suffix.\n * @param val\n * @returns The integer representation or 'NaN' if not numeric.\n */\nfunction toFloat(val) {\n if (typeof val === 'symbol') {\n return 'NaN';\n }\n return String(parseFloat(val));\n}\n// Based on:\n// https://nodejs.org/api/util.html#utilformatformat-args\n// The result will not match node exactly, but it should get the\n// right information through.\nconst escapes = {\n s: (val) => tryStringify(val),\n d: (val) => toNumber(val),\n i: (val) => toInt(val),\n f: (val) => toFloat(val),\n j: (val) => tryStringify(val),\n o: (val) => tryStringify(val),\n // eslint-disable-next-line @typescript-eslint/naming-convention\n O: (val) => tryStringify(val),\n c: () => '',\n};\n/**\n * A basic formatted for use where `util.format` is not available.\n * This will not be as performant, but it will produce formatted\n * messages.\n *\n * @internal\n *\n * @param args\n * @returns Formatted string.\n */\nfunction format(...args) {\n const formatString = args.shift();\n if (TypeValidators.String.is(formatString)) {\n let out = '';\n let i = 0;\n while (i < formatString.length) {\n const char = formatString.charAt(i);\n if (char === '%') {\n const nextIndex = i + 1;\n if (nextIndex < formatString.length) {\n const nextChar = formatString.charAt(i + 1);\n if (nextChar in escapes && args.length) {\n const value = args.shift();\n // This rule is for math.\n // eslint-disable-next-line no-unsafe-optional-chaining\n out += escapes[nextChar]?.(value);\n }\n else if (nextChar === '%') {\n out += '%';\n }\n else {\n out += `%${nextChar}`;\n }\n i += 2;\n }\n }\n else {\n out += char;\n i += 1;\n }\n }\n // If there are any args left after we exhaust the format string\n // then just stick those on the end.\n if (args.length) {\n if (out.length) {\n out += ' ';\n }\n out += args.map(tryStringify).join(' ');\n }\n return out;\n }\n return args.map(tryStringify).join(' ');\n}\n\nvar LogPriority;\n(function (LogPriority) {\n LogPriority[LogPriority[\"debug\"] = 0] = \"debug\";\n LogPriority[LogPriority[\"info\"] = 1] = \"info\";\n LogPriority[LogPriority[\"warn\"] = 2] = \"warn\";\n LogPriority[LogPriority[\"error\"] = 3] = \"error\";\n LogPriority[LogPriority[\"none\"] = 4] = \"none\";\n})(LogPriority || (LogPriority = {}));\nconst LEVEL_NAMES = ['debug', 'info', 'warn', 'error', 'none'];\n/**\n * A basic logger which handles filtering by level.\n *\n * With the default options it will write to `console.error`\n * and it will use the formatting provided by `console.error`.\n * If the destination is overwritten, then it will use an included\n * formatter similar to `util.format`.\n *\n * If a formatter is available, then that should be overridden\n * as well for performance.\n */\nclass BasicLogger {\n /**\n * This should only be used as a default fallback and not as a convenient\n * solution. In most cases you should construct a new instance with the\n * appropriate options for your specific needs.\n */\n static get() {\n return new BasicLogger({});\n }\n constructor(options) {\n this._logLevel = LogPriority[options.level ?? 'info'] ?? LogPriority.info;\n this._name = options.name ?? 'LaunchDarkly';\n this._formatter = options.formatter;\n if (typeof options.destination === 'object') {\n this._destinations = {\n [LogPriority.debug]: options.destination.debug,\n [LogPriority.info]: options.destination.info,\n [LogPriority.warn]: options.destination.warn,\n [LogPriority.error]: options.destination.error,\n };\n }\n else if (typeof options.destination === 'function') {\n const { destination } = options;\n this._destinations = {\n [LogPriority.debug]: destination,\n [LogPriority.info]: destination,\n [LogPriority.warn]: destination,\n [LogPriority.error]: destination,\n };\n }\n }\n _tryFormat(...args) {\n try {\n if (this._formatter) {\n // In case the provided formatter fails.\n return this._formatter?.(...args);\n }\n return format(...args);\n }\n catch {\n return format(...args);\n }\n }\n _tryWrite(destination, msg) {\n try {\n destination(msg);\n }\n catch {\n // eslint-disable-next-line no-console\n console.error(msg);\n }\n }\n _log(level, args) {\n if (level >= this._logLevel) {\n const prefix = `${LEVEL_NAMES[level]}: [${this._name}]`;\n try {\n const destination = this._destinations?.[level];\n if (destination) {\n this._tryWrite(destination, `${prefix} ${this._tryFormat(...args)}`);\n }\n else {\n // `console.error` has its own formatter.\n // So we don't need to do anything.\n // eslint-disable-next-line no-console\n console.error(...args);\n }\n }\n catch {\n // If all else fails do not break.\n // eslint-disable-next-line no-console\n console.error(...args);\n }\n }\n }\n error(...args) {\n this._log(LogPriority.error, args);\n }\n warn(...args) {\n this._log(LogPriority.warn, args);\n }\n info(...args) {\n this._log(LogPriority.info, args);\n }\n debug(...args) {\n this._log(LogPriority.debug, args);\n }\n}\n\nconst loggerRequirements = {\n error: TypeValidators.Function,\n warn: TypeValidators.Function,\n info: TypeValidators.Function,\n debug: TypeValidators.Function,\n};\n/**\n * The safeLogger logic exists because we allow the application to pass in a custom logger, but\n * there is no guarantee that the logger works correctly and if it ever throws exceptions there\n * could be serious consequences (e.g. an uncaught exception within an error event handler, due\n * to the SDK trying to log the error, can terminate the application). An exception could result\n * from faulty logic in the logger implementation, or it could be that this is not a logger at\n * all but some other kind of object; the former is handled by a catch block that logs an error\n * message to the SDK's default logger, and we can at least partly guard against the latter by\n * checking for the presence of required methods at configuration time.\n */\nclass SafeLogger {\n /**\n * Construct a safe logger with the specified logger.\n * @param logger The logger to use.\n * @param fallback A fallback logger to use in case an issue is encountered using\n * the provided logger.\n */\n constructor(logger, fallback) {\n Object.entries(loggerRequirements).forEach(([level, validator]) => {\n if (!validator.is(logger[level])) {\n throw new Error(`Provided logger instance must support logger.${level}(...) method`);\n // Note that the SDK normally does not throw exceptions to the application, but that rule\n // does not apply to LDClient.init() which will throw an exception if the parameters are so\n // invalid that we cannot proceed with creating the client. An invalid logger meets those\n // criteria since the SDK calls the logger during nearly all of its operations.\n }\n });\n this._logger = logger;\n this._fallback = fallback;\n }\n _log(level, args) {\n try {\n this._logger[level](...args);\n }\n catch {\n // If all else fails do not break.\n this._fallback[level](...args);\n }\n }\n error(...args) {\n this._log('error', args);\n }\n warn(...args) {\n this._log('warn', args);\n }\n info(...args) {\n this._log('info', args);\n }\n debug(...args) {\n this._log('debug', args);\n }\n}\n\nconst createSafeLogger = (logger) => {\n const basicLogger = new BasicLogger({\n level: 'info',\n // eslint-disable-next-line no-console\n destination: console.error,\n formatter: format,\n });\n return logger ? new SafeLogger(logger, basicLogger) : basicLogger;\n};\n\n/**\n * Messages for issues which can be encountered from processing the configuration options.\n */\nclass OptionMessages {\n static deprecated(oldName, newName) {\n return `\"${oldName}\" is deprecated, please use \"${newName}\"`;\n }\n static optionBelowMinimum(name, value, min) {\n return `Config option \"${name}\" had invalid value of ${value}, using minimum of ${min} instead`;\n }\n static unknownOption(name) {\n return `Ignoring unknown config option \"${name}\"`;\n }\n static wrongOptionType(name, expectedType, actualType) {\n return `Config option \"${name}\" should be of type ${expectedType}, got ${actualType}, using default value`;\n }\n static wrongOptionTypeBoolean(name, actualType) {\n return `Config option \"${name}\" should be a boolean, got ${actualType}, converting to boolean`;\n }\n static invalidTagValue(name) {\n return `Config option \"${name}\" must only contain letters, numbers, ., _ or -.`;\n }\n static tagValueTooLong(name) {\n return `Value of \"${name}\" was longer than 64 characters and was discarded.`;\n }\n static partialEndpoint(name) {\n return `You have set custom uris without specifying the ${name} URI; connections may not work properly`;\n }\n}\n\n/**\n * Expression to validate characters that are allowed in tag keys and values.\n */\nconst allowedTagCharacters = /^(\\w|\\.|-)+$/;\nconst regexValidator = TypeValidators.stringMatchingRegex(allowedTagCharacters);\nconst tagValidator = {\n is: (u, name) => {\n if (regexValidator.is(u)) {\n if (u.length > 64) {\n return { valid: false, message: OptionMessages.tagValueTooLong(name) };\n }\n return { valid: true };\n }\n return { valid: false, message: OptionMessages.invalidTagValue(name) };\n },\n};\n/**\n * Class for managing tags.\n */\nclass ApplicationTags {\n constructor(options) {\n const tags = {};\n const application = options?.application;\n const logger = options?.logger;\n if (application) {\n Object.entries(application).forEach(([key, value]) => {\n if (value !== null && value !== undefined) {\n const { valid, message } = tagValidator.is(value, `application.${key}`);\n if (!valid) {\n logger?.warn(message);\n }\n else if (key === 'versionName') {\n tags[`application-version-name`] = [value];\n }\n else {\n tags[`application-${key}`] = [value];\n }\n }\n });\n }\n const tagKeys = Object.keys(tags);\n if (tagKeys.length) {\n this.value = tagKeys\n .sort()\n .flatMap((key) => tags[key].sort().map((value) => `${key}/${value}`))\n .join(' ');\n }\n }\n}\n\n/**\n * The client context provides basic configuration and platform support which are required\n * when building SDK components.\n */\nclass ClientContext {\n constructor(sdkKey, configuration, platform) {\n this.platform = platform;\n this.basicConfiguration = {\n tags: configuration.tags,\n logger: configuration.logger,\n offline: configuration.offline,\n serviceEndpoints: configuration.serviceEndpoints,\n sdkKey,\n };\n }\n}\n\nfunction canonicalizeUri(uri) {\n return uri.replace(/\\/+$/, '');\n}\nfunction canonicalizePath(path) {\n return path.replace(/^\\/+/, '').replace(/\\?$/, '');\n}\n/**\n * Specifies the base service URIs used by SDK components.\n */\nclass ServiceEndpoints {\n constructor(streaming, polling, events = ServiceEndpoints.DEFAULT_EVENTS, analyticsEventPath = '/bulk', diagnosticEventPath = '/diagnostic', includeAuthorizationHeader = true, payloadFilterKey) {\n this.streaming = canonicalizeUri(streaming);\n this.polling = canonicalizeUri(polling);\n this.events = canonicalizeUri(events);\n this.analyticsEventPath = analyticsEventPath;\n this.diagnosticEventPath = diagnosticEventPath;\n this.includeAuthorizationHeader = includeAuthorizationHeader;\n this.payloadFilterKey = payloadFilterKey;\n }\n}\n// eslint-disable-next-line @typescript-eslint/naming-convention\nServiceEndpoints.DEFAULT_EVENTS = 'https://events.launchdarkly.com';\nfunction getWithParams(uri, parameters = []) {\n if (parameters.length === 0) {\n return uri;\n }\n const parts = parameters.map(({ key, value }) => `${key}=${value}`);\n return `${uri}?${parts.join('&')}`;\n}\n/**\n * Get the URI for the streaming endpoint.\n *\n * @param endpoints The service endpoints.\n * @param path The path to the resource, devoid of any query parameters or hrefs.\n * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.\n */\nfunction getStreamingUri(endpoints, path, parameters) {\n const canonicalizedPath = canonicalizePath(path);\n const combinedParameters = [...parameters];\n if (endpoints.payloadFilterKey) {\n combinedParameters.push({ key: 'filter', value: endpoints.payloadFilterKey });\n }\n return getWithParams(`${endpoints.streaming}/${canonicalizedPath}`, combinedParameters);\n}\n/**\n * Get the URI for the polling endpoint.\n *\n * @param endpoints The service endpoints.\n * @param path The path to the resource, devoid of any query parameters or hrefs.\n * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.\n */\nfunction getPollingUri(endpoints, path, parameters = []) {\n const canonicalizedPath = canonicalizePath(path);\n const combinedParameters = [...parameters];\n if (endpoints.payloadFilterKey) {\n combinedParameters.push({ key: 'filter', value: endpoints.payloadFilterKey });\n }\n return getWithParams(`${endpoints.polling}/${canonicalizedPath}`, combinedParameters);\n}\n/**\n * Get the URI for the events endpoint.\n *\n * @param endpoints The service endpoints.\n * @param path The path to the resource, devoid of any query parameters or hrefs.\n * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.\n */\nfunction getEventsUri(endpoints, path, parameters = []) {\n const canonicalizedPath = canonicalizePath(path);\n return getWithParams(`${endpoints.events}/${canonicalizedPath}`, parameters);\n}\n\n// These classes are of trivial complexity. If they become\n// more complex, then they could be independent files.\n/* eslint-disable max-classes-per-file */\nclass LDUnexpectedResponseError extends Error {\n constructor(message) {\n super(message);\n this.name = 'LaunchDarklyUnexpectedResponseError';\n }\n}\nclass LDClientError extends Error {\n constructor(message) {\n super(message);\n this.name = 'LaunchDarklyClientError';\n }\n}\nclass LDTimeoutError extends Error {\n constructor(message) {\n super(message);\n this.name = 'LaunchDarklyTimeoutError';\n }\n}\n/**\n * Check if the HTTP error is recoverable. This will return false if a request\n * made with any payload could not recover. If the reason for the failure\n * is payload specific, for instance a payload that is too large, then\n * it could recover with a different payload.\n */\nfunction isHttpRecoverable(status) {\n if (status >= 400 && status < 500) {\n return status === 400 || status === 408 || status === 429;\n }\n return true;\n}\n/**\n * Returns true if the status could recover for a different payload.\n *\n * When used with event processing this indicates that we should discard\n * the payload, but that a subsequent payload may succeed. Therefore we should\n * not stop event processing.\n */\nfunction isHttpLocallyRecoverable(status) {\n if (status === 413) {\n return true;\n }\n return isHttpRecoverable(status);\n}\n\n/**\n * Returns a promise which errors after t seconds.\n *\n * @param t Timeout in seconds.\n * @param taskName Name of task being timed for logging and error reporting.\n */\nfunction cancelableTimedPromise(t, taskName) {\n let timeout;\n let resolve;\n const promise = new Promise((_res, reject) => {\n resolve = _res;\n timeout = setTimeout(() => {\n const e = `${taskName} timed out after ${t} seconds.`;\n reject(new LDTimeoutError(e));\n }, t * 1000);\n });\n return {\n promise,\n cancel: () => {\n resolve();\n clearTimeout(timeout);\n },\n };\n}\n\nfunction clone(obj) {\n if (obj === undefined || obj === null) {\n return obj;\n }\n return JSON.parse(JSON.stringify(obj));\n}\n\n// eslint-disable-next-line import/prefer-default-export\nfunction secondsToMillis(sec) {\n return Math.trunc(sec * 1000);\n}\n\n/**\n * Wait before calling the same function. Useful for expensive calls.\n * Adapted from https://amitd.co/code/typescript/debounce.\n *\n * @return The debounced function.\n *\n * @example\n *\n * ```js\n * const debouncedFunction = debounce(e => {\n * console.log(e);\n * }, 5000);\n *\n * // Console logs 'Hello world again ' after 5 seconds\n * debouncedFunction('Hello world');\n * debouncedFunction('Hello world again');\n * ```\n * @param fn The function to be debounced.\n * @param delayMs Defaults to 5 seconds.\n */\nconst debounce = (fn, delayMs = 5000) => {\n let timer;\n return (...args) => {\n clearTimeout(timer);\n timer = setTimeout(() => {\n fn(...args);\n }, delayMs);\n };\n};\n\nconst isEmptyObject = (obj) => JSON.stringify(obj) === '{}';\n\n/**\n * Strips all falsy and empty {} from a given object. Returns a new object with only truthy values.\n * Sourced from below but modified to include checks for empty object and ignoring keys.\n * https://www.w3resource.com/javascript-exercises/javascript-array-exercise-47.php\n *\n * @param obj\n * @param ignoreKeys\n */\nconst deepCompact = (obj, ignoreKeys) => {\n if (!obj) {\n return obj;\n }\n return Object.entries(obj).reduce((acc, [key, value]) => {\n if (Boolean(value) && !isEmptyObject(value) && !ignoreKeys?.includes(key)) {\n acc[key] = typeof value === 'object' ? deepCompact(value, ignoreKeys) : value;\n }\n return acc;\n }, {});\n};\n\n/* eslint-disable */\n// Ripped from https://github.com/epoberezkin/fast-deep-fastDeepEqual\n// {{? it.es6 }}\n// var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';\n// {{?}}\nfunction fastDeepEqual(a, b) {\n if (a === b)\n return true;\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor)\n return false;\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length)\n return false;\n for (i = length; i-- !== 0;)\n if (!fastDeepEqual(a[i], b[i]))\n return false;\n return true;\n }\n // {{? it.es6 }}\n if (a instanceof Map && b instanceof Map) {\n if (a.size !== b.size)\n return false;\n for (i of a.entries())\n if (!b.has(i[0]))\n return false;\n for (i of a.entries())\n if (!fastDeepEqual(i[1], b.get(i[0])))\n return false;\n return true;\n }\n if (a instanceof Set && b instanceof Set) {\n if (a.size !== b.size)\n return false;\n for (i of a.entries())\n if (!b.has(i[0]))\n return false;\n return true;\n }\n if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {\n // @ts-ignore\n length = a.length;\n // @ts-ignore\n if (length != b.length)\n return false;\n for (i = length; i-- !== 0;) {\n // @ts-ignore\n if (a[i] !== b[i])\n return false;\n }\n return true;\n }\n // {{?}}\n if (a.constructor === RegExp)\n return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf)\n return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString)\n return a.toString() === b.toString();\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length)\n return false;\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i]))\n return false;\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n // {{? it.react }}\n // if (key === '_owner' && a.$$typeof) {\n // // React-specific: avoid traversing React elements' _owner.\n // // _owner contains circular references\n // // and is not needed when comparing the actual elements (and not their owners)\n // continue;\n // }\n // {{?}}\n if (!fastDeepEqual(a[key], b[key]))\n return false;\n }\n return true;\n }\n // true if both NaN, false otherwise\n return a !== a && b !== b;\n}\n\nfunction defaultHeaders(sdkKey, info, tags, includeAuthorizationHeader = true, userAgentHeaderName = 'user-agent') {\n const { userAgentBase, version, wrapperName, wrapperVersion } = info.sdkData();\n const headers = {\n [userAgentHeaderName]: `${userAgentBase ?? 'NodeJSClient'}/${version}`,\n };\n // edge sdks sets this to false because they use the clientSideID\n // and they don't need the authorization header\n if (includeAuthorizationHeader) {\n headers.authorization = sdkKey;\n }\n if (wrapperName) {\n headers['x-launchdarkly-wrapper'] = wrapperVersion\n ? `${wrapperName}/${wrapperVersion}`\n : wrapperName;\n }\n if (tags?.value) {\n headers['x-launchdarkly-tags'] = tags.value;\n }\n return headers;\n}\nfunction httpErrorMessage(err, context, retryMessage) {\n let desc;\n if (err.status) {\n desc = `error ${err.status}${err.status === 401 ? ' (invalid SDK key)' : ''}`;\n }\n else {\n desc = `I/O error (${err.message || 'unknown error'})`;\n }\n const action = retryMessage ?? 'giving up permanently';\n return `Received ${desc} for ${context} - ${action}`;\n}\nfunction shouldRetry({ status }) {\n return status ? isHttpRecoverable(status) : true;\n}\n/**\n * In react-native use base64-js to polyfill btoa. This is safe\n * because the react-native repo uses it too. Set the global.btoa to the encode\n * function of base64-js.\n * https://github.com/beatgammit/base64-js\n * https://github.com/axios/axios/issues/2235#issuecomment-512204616\n *\n * Ripped from https://thewoods.blog/base64url/\n */\nconst base64UrlEncode = (s, encoding) => encoding.btoa(s).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n\nvar noop = () => { };\n\nconst sleep = async (delayMillis = 1000) => new Promise((resolve) => {\n setTimeout(resolve, delayMillis);\n});\n\n/**\n * Returns a promise which errors after t seconds.\n *\n * @param t Timeout in seconds.\n * @param taskName Name of task being timed for logging and error reporting.\n */\nconst timedPromise = (t, taskName) => new Promise((_res, reject) => {\n setTimeout(() => {\n const e = `${taskName} timed out after ${t} seconds.`;\n reject(new LDTimeoutError(e));\n }, t * 1000);\n});\n\nclass DiagnosticsManager {\n constructor(sdkKey, _platform, _diagnosticInitConfig) {\n this._platform = _platform;\n this._diagnosticInitConfig = _diagnosticInitConfig;\n this._streamInits = [];\n this._startTime = Date.now();\n this._dataSinceDate = this._startTime;\n this._id = {\n diagnosticId: _platform.crypto.randomUUID(),\n sdkKeySuffix: sdkKey.length > 6 ? sdkKey.substring(sdkKey.length - 6) : sdkKey,\n };\n }\n /**\n * Creates the initial event that is sent by the event processor when the SDK starts up. This will\n * not be repeated during the lifetime of the SDK client.\n */\n createInitEvent() {\n const sdkData = this._platform.info.sdkData();\n const platformData = this._platform.info.platformData();\n return {\n kind: 'diagnostic-init',\n id: this._id,\n creationDate: this._startTime,\n sdk: sdkData,\n configuration: this._diagnosticInitConfig,\n platform: {\n name: platformData.name,\n osArch: platformData.os?.arch,\n osName: platformData.os?.name,\n osVersion: platformData.os?.version,\n ...(platformData.additional || {}),\n },\n };\n }\n /**\n * Records a stream connection attempt (called by the stream processor).\n *\n * @param timestamp Time of the *beginning* of the connection attempt.\n * @param failed True if the connection failed, or we got a read timeout before receiving a \"put\".\n * @param durationMillis Elapsed time between starting timestamp and when we either gave up/lost\n * the connection or received a successful \"put\".\n */\n recordStreamInit(timestamp, failed, durationMillis) {\n const item = { timestamp, failed, durationMillis };\n this._streamInits.push(item);\n }\n /**\n * Creates a periodic event containing time-dependent stats, and resets the state of the manager\n * with regard to those stats.\n *\n * Note: the reason droppedEvents, deduplicatedUsers, and eventsInLastBatch are passed into this\n * function, instead of being properties of the DiagnosticsManager, is that the event processor is\n * the one who's calling this function and is also the one who's tracking those stats.\n */\n createStatsEventAndReset(droppedEvents, deduplicatedUsers, eventsInLastBatch) {\n const currentTime = Date.now();\n const evt = {\n kind: 'diagnostic',\n id: this._id,\n creationDate: currentTime,\n dataSinceDate: this._dataSinceDate,\n droppedEvents,\n deduplicatedUsers,\n eventsInLastBatch,\n streamInits: this._streamInits,\n };\n this._streamInits = [];\n this._dataSinceDate = currentTime;\n return evt;\n }\n}\n\n/**\n * Different kinds of error which may be encountered during evaluation.\n */\nvar ErrorKinds;\n(function (ErrorKinds) {\n ErrorKinds[\"MalformedFlag\"] = \"MALFORMED_FLAG\";\n ErrorKinds[\"UserNotSpecified\"] = \"USER_NOT_SPECIFIED\";\n ErrorKinds[\"FlagNotFound\"] = \"FLAG_NOT_FOUND\";\n ErrorKinds[\"ClientNotReady\"] = \"CLIENT_NOT_READY\";\n ErrorKinds[\"WrongType\"] = \"WRONG_TYPE\";\n})(ErrorKinds || (ErrorKinds = {}));\nvar ErrorKinds$1 = ErrorKinds;\n\n/**\n * Messages for issues which can be encountered processing client requests.\n */\nclass ClientMessages {\n static invalidMetricValue(badType) {\n return ('The track function was called with a non-numeric \"metricValue\"' +\n ` (${badType}), only numeric metric values are supported.`);\n }\n}\nClientMessages.MissingContextKeyNoEvent = 'Context was unspecified or had no key; event will not be sent';\n\nclass EventSender {\n constructor(clientContext, baseHeaders) {\n const { basicConfiguration, platform } = clientContext;\n const { serviceEndpoints: { analyticsEventPath, diagnosticEventPath }, } = basicConfiguration;\n const { crypto, requests } = platform;\n this._defaultHeaders = { ...baseHeaders };\n this._eventsUri = getEventsUri(basicConfiguration.serviceEndpoints, analyticsEventPath, []);\n this._diagnosticEventsUri = getEventsUri(basicConfiguration.serviceEndpoints, diagnosticEventPath, []);\n this._requests = requests;\n this._crypto = crypto;\n }\n async _tryPostingEvents(events, uri, payloadId, canRetry) {\n const tryRes = {\n status: LDDeliveryStatus.Succeeded,\n };\n const headers = {\n ...this._defaultHeaders,\n 'content-type': 'application/json',\n };\n if (payloadId) {\n headers['x-launchdarkly-payload-id'] = payloadId;\n headers['x-launchDarkly-event-schema'] = '4';\n }\n let error;\n try {\n const { status, headers: resHeaders } = await this._requests.fetch(uri, {\n headers,\n body: JSON.stringify(events),\n compressBodyIfPossible: true,\n method: 'POST',\n // When sending events from browser environments the request should be completed even\n // if the user is navigating away from the page.\n keepalive: true,\n });\n const serverDate = Date.parse(resHeaders.get('date') || '');\n if (serverDate) {\n tryRes.serverTime = serverDate;\n }\n if (status <= 204) {\n return tryRes;\n }\n error = new LDUnexpectedResponseError(httpErrorMessage({ status, message: 'some events were dropped' }, 'event posting'));\n if (!isHttpRecoverable(status)) {\n // If the HTTP request isn't recoverable. Meaning if we made the same request it\n // would not recover, then we check if a different request could recover.\n // If a different request could not recover, then we shutdown. If a different request could\n // recover, then we just don't retry this specific request.\n if (!isHttpLocallyRecoverable(status)) {\n tryRes.status = LDDeliveryStatus.FailedAndMustShutDown;\n }\n else {\n tryRes.status = LDDeliveryStatus.Failed;\n }\n tryRes.error = error;\n return tryRes;\n }\n }\n catch (err) {\n error = err;\n }\n // recoverable but not retrying\n if (error && !canRetry) {\n tryRes.status = LDDeliveryStatus.Failed;\n tryRes.error = error;\n return tryRes;\n }\n // wait 1 second before retrying\n await sleep();\n return this._tryPostingEvents(events, this._eventsUri, payloadId, false);\n }\n async sendEventData(type, data) {\n const payloadId = type === LDEventType.AnalyticsEvents ? this._crypto.randomUUID() : undefined;\n const uri = type === LDEventType.AnalyticsEvents ? this._eventsUri : this._diagnosticEventsUri;\n return this._tryPostingEvents(data, uri, payloadId, true);\n }\n}\n\nfunction isFeature(u) {\n return u.kind === 'feature';\n}\nfunction isIdentify(u) {\n return u.kind === 'identify';\n}\nfunction isMigration(u) {\n return u.kind === 'migration_op';\n}\n\n/**\n * @internal\n */\nclass SummaryCounter {\n constructor(count, key, value, defValue, version, variation) {\n this.count = count;\n this.key = key;\n this.value = value;\n this.version = version;\n this.variation = variation;\n this.default = defValue;\n }\n increment() {\n this.count += 1;\n }\n}\n\nfunction counterKey(event) {\n return `${event.key}:${event.variation !== null && event.variation !== undefined ? event.variation : ''}:${event.version !== null && event.version !== undefined ? event.version : ''}`;\n}\n/**\n * @internal\n */\nclass EventSummarizer {\n constructor(_singleContext = false, _contextFilter) {\n this._singleContext = _singleContext;\n this._contextFilter = _contextFilter;\n this._startDate = 0;\n this._endDate = 0;\n this._counters = {};\n this._contextKinds = {};\n }\n summarizeEvent(event) {\n if (isFeature(event) && !event.excludeFromSummaries) {\n if (!this._context) {\n this._context = event.context;\n }\n const countKey = counterKey(event);\n const counter = this._counters[countKey];\n let kinds = this._contextKinds[event.key];\n if (!kinds) {\n kinds = new Set();\n this._contextKinds[event.key] = kinds;\n }\n event.context.kinds.forEach((kind) => kinds.add(kind));\n if (counter) {\n counter.increment();\n }\n else {\n this._counters[countKey] = new SummaryCounter(1, event.key, event.value, event.default, event.version, event.variation);\n }\n if (this._startDate === 0 || event.creationDate < this._startDate) {\n this._startDate = event.creationDate;\n }\n if (event.creationDate > this._endDate) {\n this._endDate = event.creationDate;\n }\n }\n }\n getSummary() {\n const features = Object.values(this._counters).reduce((acc, counter) => {\n let flagSummary = acc[counter.key];\n if (!flagSummary) {\n flagSummary = {\n default: counter.default,\n counters: [],\n contextKinds: [...this._contextKinds[counter.key]],\n };\n acc[counter.key] = flagSummary;\n }\n const counterOut = {\n value: counter.value,\n count: counter.count,\n };\n if (counter.variation !== undefined && counter.variation !== null) {\n counterOut.variation = counter.variation;\n }\n if (counter.version !== undefined && counter.version !== null) {\n counterOut.version = counter.version;\n }\n else {\n counterOut.unknown = true;\n }\n flagSummary.counters.push(counterOut);\n return acc;\n }, {});\n const event = {\n startDate: this._startDate,\n endDate: this._endDate,\n features,\n kind: 'summary',\n context: this._context !== undefined && this._singleContext\n ? this._contextFilter?.filter(this._context)\n : undefined,\n };\n this._clearSummary();\n return event;\n }\n _clearSummary() {\n this._startDate = 0;\n this._endDate = 0;\n this._counters = {};\n this._contextKinds = {};\n }\n}\n\nclass LDInvalidSDKKeyError extends Error {\n constructor(message) {\n super(message);\n this.name = 'LaunchDarklyInvalidSDKKeyError';\n }\n}\n\nclass MultiEventSummarizer {\n constructor(_contextFilter, _logger) {\n this._contextFilter = _contextFilter;\n this._logger = _logger;\n this._summarizers = {};\n }\n summarizeEvent(event) {\n if (isFeature(event)) {\n const key = event.context.canonicalUnfilteredJson();\n if (!key) {\n if (event.context.valid) {\n // The context appeared valid, but it could not be hashed.\n // This is likely because of a cycle in the data.\n this._logger?.error('Unable to serialize context, likely the context contains a cycle.');\n }\n return;\n }\n let summarizer = this._summarizers[key];\n if (!summarizer) {\n this._summarizers[key] = new EventSummarizer(true, this._contextFilter);\n summarizer = this._summarizers[key];\n }\n summarizer.summarizeEvent(event);\n }\n }\n getSummaries() {\n const summarizersToFlush = this._summarizers;\n this._summarizers = {};\n return Object.values(summarizersToFlush).map((summarizer) => summarizer.getSummary());\n }\n}\n\n/**\n * The contents of this file are for event sampling. They are not used for\n * any purpose requiring cryptographic security.\n * */\nfunction shouldSample(ratio) {\n const truncated = Math.trunc(ratio);\n // A radio of 1 means 1 in 1. So that will always sample. No need\n // to draw a random number.\n if (truncated === 1) {\n return true;\n }\n if (truncated === 0) {\n return false;\n }\n // Math.random() * truncated) would return 0, 1, ... (ratio - 1).\n // Checking for any number in the range will have approximately a 1 in X\n // chance. So we check for 0 as it is part of any range.\n return Math.floor(Math.random() * truncated) === 0;\n}\n\nfunction isMultiEventSummarizer(summarizer) {\n return summarizer.getSummaries !== undefined;\n}\nclass EventProcessor {\n constructor(_config, clientContext, baseHeaders, _contextDeduplicator, _diagnosticsManager, start = true, summariesPerContext = false) {\n this._config = _config;\n this._contextDeduplicator = _contextDeduplicator;\n this._diagnosticsManager = _diagnosticsManager;\n this._queue = [];\n this._lastKnownPastTime = 0;\n this._droppedEvents = 0;\n this._deduplicatedUsers = 0;\n this._exceededCapacity = false;\n this._eventsInLastBatch = 0;\n this._shutdown = false;\n this._flushUsersTimer = null;\n this._capacity = _config.eventsCapacity;\n this._logger = clientContext.basicConfiguration.logger;\n this._eventSender = new EventSender(clientContext, baseHeaders);\n this._contextFilter = new ContextFilter(_config.allAttributesPrivate, _config.privateAttributes.map((ref) => new AttributeReference(ref)));\n if (summariesPerContext) {\n this._summarizer = new MultiEventSummarizer(this._contextFilter, this._logger);\n }\n else {\n this._summarizer = new EventSummarizer();\n }\n if (start) {\n this.start();\n }\n }\n start() {\n if (this._contextDeduplicator?.flushInterval !== undefined) {\n this._flushUsersTimer = setInterval(() => {\n this._contextDeduplicator?.flush();\n }, this._contextDeduplicator.flushInterval * 1000);\n }\n this._flushTimer = setInterval(async () => {\n try {\n await this.flush();\n }\n catch (e) {\n // Log errors and swallow them\n this._logger?.debug(`Flush failed: ${e}`);\n }\n }, this._config.flushInterval * 1000);\n if (this._diagnosticsManager) {\n const initEvent = this._diagnosticsManager.createInitEvent();\n this._postDiagnosticEvent(initEvent);\n this._diagnosticsTimer = setInterval(() => {\n const statsEvent = this._diagnosticsManager.createStatsEventAndReset(this._droppedEvents, this._deduplicatedUsers, this._eventsInLastBatch);\n this._droppedEvents = 0;\n this._deduplicatedUsers = 0;\n this._postDiagnosticEvent(statsEvent);\n }, this._config.diagnosticRecordingInterval * 1000);\n }\n this._logger?.debug('Started EventProcessor.');\n }\n _postDiagnosticEvent(event) {\n this._eventSender.sendEventData(LDEventType.DiagnosticEvent, event);\n }\n close() {\n clearInterval(this._flushTimer);\n if (this._flushUsersTimer) {\n clearInterval(this._flushUsersTimer);\n }\n if (this._diagnosticsTimer) {\n clearInterval(this._diagnosticsTimer);\n }\n }\n async flush() {\n if (this._shutdown) {\n throw new LDInvalidSDKKeyError('Events cannot be posted because a permanent error has been encountered. ' +\n 'This is most likely an invalid SDK key. The specific error information ' +\n 'is logged independently.');\n }\n const eventsToFlush = this._queue;\n this._queue = [];\n if (isMultiEventSummarizer(this._summarizer)) {\n const summaries = this._summarizer.getSummaries();\n summaries.forEach((summary) => {\n if (Object.keys(summary.features).length) {\n eventsToFlush.push(summary);\n }\n });\n }\n else {\n const summary = this._summarizer.getSummary();\n if (Object.keys(summary.features).length) {\n eventsToFlush.push(summary);\n }\n }\n if (!eventsToFlush.length) {\n return;\n }\n this._eventsInLastBatch = eventsToFlush.length;\n this._logger?.debug('Flushing %d events', eventsToFlush.length);\n await this._tryPostingEvents(eventsToFlush);\n }\n sendEvent(inputEvent) {\n if (this._shutdown) {\n return;\n }\n if (isMigration(inputEvent)) {\n // These conditions are not combined, because we always want to stop\n // processing at this point for a migration event. It cannot generate\n // an index event or debug event.\n if (shouldSample(inputEvent.samplingRatio)) {\n const migrationEvent = {\n ...inputEvent,\n context: inputEvent.context ? this._contextFilter.filter(inputEvent.context) : undefined,\n };\n if (migrationEvent.samplingRatio === 1) {\n delete migrationEvent.samplingRatio;\n }\n this._enqueue(migrationEvent);\n }\n return;\n }\n this._summarizer.summarizeEvent(inputEvent);\n const isFeatureEvent = isFeature(inputEvent);\n const addFullEvent = (isFeatureEvent && inputEvent.trackEvents) || !isFeatureEvent;\n const addDebugEvent = this._shouldDebugEvent(inputEvent);\n const isIdentifyEvent = isIdentify(inputEvent);\n const shouldNotDeduplicate = this._contextDeduplicator?.processContext(inputEvent.context);\n // If there is no cache, then it will never be in the cache.\n if (!shouldNotDeduplicate) {\n if (!isIdentifyEvent) {\n this._deduplicatedUsers += 1;\n }\n }\n const addIndexEvent = shouldNotDeduplicate && !isIdentifyEvent;\n if (addIndexEvent) {\n this._enqueue(this._makeOutputEvent({\n kind: 'index',\n creationDate: inputEvent.creationDate,\n context: inputEvent.context,\n samplingRatio: 1,\n }, false));\n }\n if (addFullEvent && shouldSample(inputEvent.samplingRatio)) {\n this._enqueue(this._makeOutputEvent(inputEvent, false));\n }\n if (addDebugEvent && shouldSample(inputEvent.samplingRatio)) {\n this._enqueue(this._makeOutputEvent(inputEvent, true));\n }\n }\n _makeOutputEvent(event, debug) {\n switch (event.kind) {\n case 'feature': {\n const out = {\n kind: debug ? 'debug' : 'feature',\n creationDate: event.creationDate,\n context: this._contextFilter.filter(event.context, !debug),\n key: event.key,\n value: event.value,\n default: event.default,\n };\n if (event.samplingRatio !== 1) {\n out.samplingRatio = event.samplingRatio;\n }\n if (event.prereqOf) {\n out.prereqOf = event.prereqOf;\n }\n if (event.variation !== undefined) {\n out.variation = event.variation;\n }\n if (event.version !== undefined) {\n out.version = event.version;\n }\n if (event.reason) {\n out.reason = event.reason;\n }\n return out;\n }\n case 'index': // Intentional fallthrough.\n case 'identify': {\n const out = {\n kind: event.kind,\n creationDate: event.creationDate,\n context: this._contextFilter.filter(event.context),\n };\n if (event.samplingRatio !== 1) {\n out.samplingRatio = event.samplingRatio;\n }\n return out;\n }\n case 'custom': {\n const out = {\n kind: 'custom',\n creationDate: event.creationDate,\n key: event.key,\n context: this._contextFilter.filter(event.context),\n };\n if (event.samplingRatio !== 1) {\n out.samplingRatio = event.samplingRatio;\n }\n if (event.data !== undefined) {\n out.data = event.data;\n }\n if (event.metricValue !== undefined) {\n out.metricValue = event.metricValue;\n }\n if (event.url !== undefined) {\n out.url = event.url;\n }\n return out;\n }\n case 'click': {\n const out = {\n kind: 'click',\n creationDate: event.creationDate,\n contextKeys: event.context.kindsAndKeys,\n key: event.key,\n url: event.url,\n selector: event.selector,\n };\n return out;\n }\n case 'pageview': {\n const out = {\n kind: 'pageview',\n creationDate: event.creationDate,\n contextKeys: event.context.kindsAndKeys,\n key: event.key,\n url: event.url,\n };\n return out;\n }\n default:\n // This would happen during the addition of a new event type to the SDK.\n return event;\n }\n }\n _enqueue(event) {\n if (this._queue.length < this._capacity) {\n this._queue.push(event);\n this._exceededCapacity = false;\n }\n else {\n if (!this._exceededCapacity) {\n this._exceededCapacity = true;\n this._logger?.warn('Exceeded event queue capacity. Increase capacity to avoid dropping events.');\n }\n this._droppedEvents += 1;\n }\n }\n _shouldDebugEvent(event) {\n return (isFeature(event) &&\n event.debugEventsUntilDate &&\n event.debugEventsUntilDate > this._lastKnownPastTime &&\n event.debugEventsUntilDate > Date.now());\n }\n async _tryPostingEvents(events) {\n const res = await this._eventSender.sendEventData(LDEventType.AnalyticsEvents, events);\n if (res.status === LDDeliveryStatus.FailedAndMustShutDown) {\n this._shutdown = true;\n }\n if (res.serverTime) {\n this._lastKnownPastTime = res.serverTime;\n }\n if (res.error) {\n throw res.error;\n }\n }\n}\n\nclass InputCustomEvent {\n constructor(context, key, data, metricValue, \n // Currently custom events are not sampled, but this is here to make the handling\n // code more uniform.\n samplingRatio = 1, \n // Browser SDKs can include a URL for custom events.\n url) {\n this.context = context;\n this.key = key;\n this.data = data;\n this.metricValue = metricValue;\n this.samplingRatio = samplingRatio;\n this.url = url;\n this.kind = 'custom';\n this.creationDate = Date.now();\n this.context = context;\n }\n}\n\nclass InputEvalEvent {\n constructor(withReasons, context, key, value, defValue, // default is a reserved keyword in this context.\n version, variation, trackEvents, prereqOf, reason, debugEventsUntilDate, excludeFromSummaries, samplingRatio = 1) {\n this.withReasons = withReasons;\n this.context = context;\n this.key = key;\n this.samplingRatio = samplingRatio;\n this.kind = 'feature';\n this.creationDate = Date.now();\n this.value = value;\n this.default = defValue;\n if (version !== undefined) {\n this.version = version;\n }\n if (variation !== undefined) {\n this.variation = variation;\n }\n if (trackEvents !== undefined) {\n this.trackEvents = trackEvents;\n }\n if (prereqOf !== undefined) {\n this.prereqOf = prereqOf;\n }\n if (reason !== undefined) {\n this.reason = reason;\n }\n if (debugEventsUntilDate !== undefined) {\n this.debugEventsUntilDate = debugEventsUntilDate;\n }\n if (excludeFromSummaries !== undefined) {\n this.excludeFromSummaries = excludeFromSummaries;\n }\n }\n}\n\nclass InputIdentifyEvent {\n constructor(context, samplingRatio = 1) {\n this.context = context;\n this.samplingRatio = samplingRatio;\n this.kind = 'identify';\n this.creationDate = Date.now();\n }\n}\n\nclass NullEventProcessor {\n close() { }\n async flush() {\n // empty comment to keep ts and eslint happy\n }\n sendEvent() { }\n}\n\nclass EventFactoryBase {\n constructor(_withReasons) {\n this._withReasons = _withReasons;\n }\n evalEvent(e) {\n return new InputEvalEvent(this._withReasons, e.context, e.flagKey, e.value, e.defaultVal, e.version, \n // Exclude null as a possibility.\n e.variation ?? undefined, e.trackEvents || e.addExperimentData, e.prereqOfFlagKey, this._withReasons || e.addExperimentData ? e.reason : undefined, e.debugEventsUntilDate, e.excludeFromSummaries, e.samplingRatio);\n }\n unknownFlagEvent(key, defVal, context) {\n return new InputEvalEvent(this._withReasons, context, key, defVal, defVal, \n // This isn't ideal, but the purpose of the factory is to at least\n // handle this situation.\n undefined, // version\n undefined, // variation index\n undefined, // track events\n undefined, // prereqOf\n undefined, // reason\n undefined, // debugEventsUntilDate\n undefined, // exclude from summaries\n undefined);\n }\n /* eslint-disable-next-line class-methods-use-this */\n identifyEvent(context) {\n // Currently sampling for identify events is always 1.\n return new InputIdentifyEvent(context, 1);\n }\n /* eslint-disable-next-line class-methods-use-this */\n customEvent(key, context, data, metricValue, samplingRatio = 1) {\n return new InputCustomEvent(context, key, data ?? undefined, metricValue ?? undefined, samplingRatio);\n }\n}\n\nconst PAYLOAD_ID = 'FDv1Fallback';\nfunction fdv1PayloadAdaptor(processor) {\n return {\n _processor: processor,\n _selector: '',\n useSelector(selector) {\n this._selector = selector;\n return this;\n },\n processFullTransfer(data) {\n const events = [\n {\n event: 'server-intent',\n data: {\n payloads: [\n {\n id: PAYLOAD_ID,\n target: 1,\n intentCode: 'xfer-full',\n reason: 'payload-missing',\n },\n ],\n },\n },\n ];\n Object.entries(data?.flags || []).forEach(([key, flag]) => {\n events.push({\n event: 'put-object',\n data: {\n kind: 'flag',\n key,\n version: flag.version || 1,\n object: flag,\n },\n });\n });\n Object.entries(data?.segments || []).forEach(([key, segment]) => {\n events.push({\n event: 'put-object',\n data: {\n kind: 'segment',\n key,\n version: segment.version || 1,\n object: segment,\n },\n });\n });\n events.push({\n event: 'payload-transferred',\n data: {\n // IMPORTANT: the selector MUST be empty or \"live\" data synchronizers\n // will not work as it would try to resume from a bogus state.\n state: this._selector,\n version: 1,\n id: PAYLOAD_ID,\n },\n });\n this._processor.processEvents(events);\n },\n };\n}\n\n/**\n * A FDv2 PayloadProcessor can be used to parse payloads from a stream of FDv2 events. It will send payloads\n * to the PayloadListeners as the payloads are received. Invalid series of events may be dropped silently,\n * but the payload processor will continue to operate.\n */\nclass PayloadProcessor {\n /**\n * Creates a PayloadProcessor\n *\n * @param _objProcessors defines object processors for each object kind.\n * @param _errorHandler that will be called with parsing errors as they are encountered\n * @param _logger for logging\n */\n constructor(_objProcessors, _errorHandler, _logger) {\n this._objProcessors = _objProcessors;\n this._errorHandler = _errorHandler;\n this._logger = _logger;\n this._listeners = [];\n this._tempId = undefined;\n this._tempBasis = false;\n this._tempUpdates = [];\n this._processServerIntent = (data) => {\n // clear state in prep for handling data\n this._resetAll();\n // if there's no payloads, return\n if (!data.payloads.length) {\n return;\n }\n // at the time of writing this, it was agreed upon that SDKs could assume exactly 1 element in this list. In the future, a negotiation of protocol version will be required to remove this assumption.\n const payload = data.payloads[0];\n switch (payload?.intentCode) {\n case 'xfer-full':\n this._tempBasis = true;\n break;\n case 'xfer-changes':\n this._tempBasis = false;\n break;\n case 'none':\n this._tempBasis = false;\n this._processIntentNone(payload);\n break;\n default:\n // unrecognized intent code, return\n this._logger?.warn(`Unable to process intent code '${payload?.intentCode}'.`);\n return;\n }\n this._tempId = payload?.id;\n };\n this._processPutObject = (data) => {\n // if the following properties haven't been provided by now, we should ignore the event\n if (!this._tempId || // server intent hasn't been received yet.\n !data.kind ||\n !data.key ||\n !data.version ||\n !data.object) {\n return;\n }\n const obj = this._processObj(data.kind, data.object);\n if (!obj) {\n this._logger?.warn(`Unable to process object for kind: '${data.kind}'`);\n // ignore unrecognized kinds\n return;\n }\n this._tempUpdates.push({\n kind: data.kind,\n key: data.key,\n version: data.version,\n object: obj,\n // intentionally omit deleted for this put\n });\n };\n this._processDeleteObject = (data) => {\n // if the following properties haven't been provided by now, we should ignore the event\n if (!this._tempId || !data.kind || !data.key || !data.version) {\n return;\n }\n this._tempUpdates.push({\n kind: data.kind,\n key: data.key,\n version: data.version,\n // intentionally omit object for this delete\n deleted: true,\n });\n };\n this._processIntentNone = (intent) => {\n // if the following properties aren't present ignore the event\n if (!intent.id || !intent.target) {\n return;\n }\n const payload = {\n id: intent.id,\n version: intent.target,\n basis: false,\n updates: [], // payload with no updates to hide the intent none concept from the consumer\n // note: state is absent here as that only appears in payload transferred events\n };\n this._listeners.forEach((it) => it(payload));\n this._resetAfterEmission();\n };\n this._processPayloadTransferred = (data) => {\n // if the following properties haven't been provided by now, we should reset\n if (\n // server intent hasn't been received yet.\n !this._tempId ||\n // selector can be an empty string if we are using a file data initilizer\n data.state === null ||\n data.state === undefined ||\n !data.version) {\n this._resetAll(); // a reset is best defensive action since payload transferred terminates a payload\n return;\n }\n const payload = {\n id: this._tempId,\n version: data.version,\n state: data.state,\n basis: this._tempBasis,\n updates: this._tempUpdates,\n };\n this._listeners.forEach((it) => it(payload));\n this._resetAfterEmission();\n };\n this._processGoodbye = (data) => {\n this._logger?.info(`Goodbye was received from the LaunchDarkly connection with reason: ${data.reason}.`);\n this._resetAll();\n };\n this._processError = (data) => {\n this._logger?.info(`An issue was encountered receiving updates for payload ${this._tempId} with reason: ${data.reason}.`);\n this._resetAfterError();\n };\n }\n addPayloadListener(listener) {\n this._listeners.push(listener);\n }\n removePayloadListener(listener) {\n const index = this._listeners.indexOf(listener, 0);\n if (index > -1) {\n this._listeners.splice(index, 1);\n }\n }\n /**\n * Gives the {@link PayloadProcessor} a series of events that it will statefully, incrementally process.\n * This may lead to listeners being invoked as necessary.\n * @param events to be processed (can be a single element)\n */\n processEvents(events) {\n events.forEach((event) => {\n switch (event.event) {\n case 'server-intent': {\n this._processServerIntent(event.data);\n break;\n }\n case 'put-object': {\n this._processPutObject(event.data);\n break;\n }\n case 'delete-object': {\n this._processDeleteObject(event.data);\n break;\n }\n case 'payload-transferred': {\n this._processPayloadTransferred(event.data);\n break;\n }\n case 'goodbye': {\n this._processGoodbye(event.data);\n break;\n }\n case 'error': {\n this._processError(event.data);\n break;\n }\n }\n });\n }\n _processObj(kind, jsonObj) {\n return this._objProcessors[kind]?.(jsonObj);\n }\n _resetAfterEmission() {\n this._tempBasis = false;\n this._tempUpdates = [];\n }\n _resetAfterError() {\n this._tempUpdates = [];\n }\n _resetAll() {\n this._tempId = undefined;\n this._tempBasis = false;\n this._tempUpdates = [];\n }\n}\n\n/**\n * A FDv2 PayloadStreamReader can be used to parse payloads from a stream of FDv2 events. See {@link PayloadProcessor}\n * for more details.\n */\nclass PayloadStreamReader {\n /**\n * Creates a PayloadStreamReader\n *\n * @param eventStream event stream of FDv2 events\n * @param _objProcessors defines object processors for each object kind.\n * @param _errorHandler that will be called with parsing errors as they are encountered\n * @param _logger for logging\n */\n constructor(eventStream, _objProcessors, _errorHandler, _logger) {\n this._errorHandler = _errorHandler;\n this._logger = _logger;\n this._attachHandler(eventStream, 'server-intent');\n this._attachHandler(eventStream, 'put-object');\n this._attachHandler(eventStream, 'delete-object');\n this._attachHandler(eventStream, 'payload-transferred');\n this._attachHandler(eventStream, 'goodbye');\n this._attachHandler(eventStream, 'error');\n this._payloadProcessor = new PayloadProcessor(_objProcessors, _errorHandler, _logger);\n }\n addPayloadListener(listener) {\n this._payloadProcessor.addPayloadListener(listener);\n }\n removePayloadListener(listener) {\n this._payloadProcessor.removePayloadListener(listener);\n }\n _attachHandler(stream, eventName) {\n stream.addEventListener(eventName, async (event) => {\n if (event?.data) {\n this._logger?.debug(`Received ${eventName} event. Data is ${event.data}`);\n try {\n this._payloadProcessor.processEvents([\n { event: eventName, data: JSON.parse(event.data) },\n ]);\n }\n catch {\n this._logger?.error(`Stream received data that was unable to be processed in \"${eventName}\" message`);\n this._logger?.debug(`Data follows: ${event.data}`);\n this._errorHandler?.(exports.DataSourceErrorKind.InvalidData, 'Malformed data in EventStream.');\n }\n }\n else {\n this._errorHandler?.(exports.DataSourceErrorKind.Unknown, 'Event from EventStream missing data.');\n }\n });\n }\n}\n\n/**\n * Creates an InitMetadata object from initialization headers.\n *\n * @param initHeaders Initialization headers received when establishing\n * a streaming or polling connection to LD.\n * @returns InitMetadata object, or undefined if initHeaders is undefined\n * or missing the required header values.\n */\nfunction initMetadataFromHeaders(initHeaders) {\n if (initHeaders) {\n const envIdKey = Object.keys(initHeaders).find((key) => key.toLowerCase() === 'x-ld-envid');\n if (envIdKey) {\n return { environmentId: initHeaders[envIdKey] };\n }\n }\n return undefined;\n}\n\nconst UNKNOWN_PLUGIN_NAME = 'unknown plugin';\nfunction safeGetName(logger, plugin) {\n try {\n return plugin.getMetadata().name || UNKNOWN_PLUGIN_NAME;\n }\n catch {\n logger.error(`Exception thrown getting metadata for plugin. Unable to get plugin name.`);\n return UNKNOWN_PLUGIN_NAME;\n }\n}\n\nfunction safeGetHooks(logger, environmentMetadata, plugins) {\n const hooks = [];\n plugins.forEach((plugin) => {\n try {\n const pluginHooks = plugin.getHooks?.(environmentMetadata);\n if (pluginHooks === undefined) {\n logger.error(`Plugin ${safeGetName(logger, plugin)} returned undefined from getHooks.`);\n }\n else if (pluginHooks && pluginHooks.length > 0) {\n hooks.push(...pluginHooks);\n }\n }\n catch (error) {\n logger.error(`Exception thrown getting hooks for plugin ${safeGetName(logger, plugin)}. Unable to get hooks.`);\n }\n });\n return hooks;\n}\n\nfunction safeRegisterPlugins(logger, environmentMetadata, client, plugins) {\n plugins.forEach((plugin) => {\n try {\n plugin.register(client, environmentMetadata);\n }\n catch (error) {\n logger.error(`Exception thrown registering plugin ${safeGetName(logger, plugin)}.`);\n }\n });\n}\n\nvar index = /*#__PURE__*/Object.freeze({\n __proto__: null,\n ClientMessages: ClientMessages,\n DiagnosticsManager: DiagnosticsManager,\n ErrorKinds: ErrorKinds$1,\n EventFactoryBase: EventFactoryBase,\n EventProcessor: EventProcessor,\n FDv1PayloadAdaptor: fdv1PayloadAdaptor,\n InputCustomEvent: InputCustomEvent,\n InputEvalEvent: InputEvalEvent,\n InputIdentifyEvent: InputIdentifyEvent,\n NullEventProcessor: NullEventProcessor,\n PayloadProcessor: PayloadProcessor,\n PayloadStreamReader: PayloadStreamReader,\n canonicalize: canonicalize,\n initMetadataFromHeaders: initMetadataFromHeaders,\n isLegacyUser: isLegacyUser,\n isMultiKind: isMultiKind,\n isSingleKind: isSingleKind,\n safeGetHooks: safeGetHooks,\n safeGetName: safeGetName,\n safeRegisterPlugins: safeRegisterPlugins,\n shouldSample: shouldSample\n});\n\nexports.ApplicationTags = ApplicationTags;\nexports.AttributeReference = AttributeReference;\nexports.BasicLogger = BasicLogger;\nexports.ClientContext = ClientContext;\nexports.CompositeDataSource = CompositeDataSource;\nexports.Context = Context;\nexports.ContextFilter = ContextFilter;\nexports.DateValidator = DateValidator;\nexports.DefaultBackoff = DefaultBackoff;\nexports.FactoryOrInstance = FactoryOrInstance;\nexports.Function = Function;\nexports.KindValidator = KindValidator;\nexports.LDClientError = LDClientError;\nexports.LDFileDataSourceError = LDFileDataSourceError;\nexports.LDFlagDeliveryFallbackError = LDFlagDeliveryFallbackError;\nexports.LDPollingError = LDPollingError;\nexports.LDStreamingError = LDStreamingError;\nexports.LDTimeoutError = LDTimeoutError;\nexports.LDUnexpectedResponseError = LDUnexpectedResponseError;\nexports.NullableBoolean = NullableBoolean;\nexports.NumberWithMinimum = NumberWithMinimum;\nexports.OptionMessages = OptionMessages;\nexports.SafeLogger = SafeLogger;\nexports.ServiceEndpoints = ServiceEndpoints;\nexports.StringMatchingRegex = StringMatchingRegex;\nexports.Type = Type;\nexports.TypeArray = TypeArray;\nexports.TypeValidators = TypeValidators;\nexports.base64UrlEncode = base64UrlEncode;\nexports.cancelableTimedPromise = cancelableTimedPromise;\nexports.clone = clone;\nexports.createSafeLogger = createSafeLogger;\nexports.debounce = debounce;\nexports.deepCompact = deepCompact;\nexports.defaultHeaders = defaultHeaders;\nexports.fastDeepEqual = fastDeepEqual;\nexports.getEventsUri = getEventsUri;\nexports.getPollingUri = getPollingUri;\nexports.getStreamingUri = getStreamingUri;\nexports.httpErrorMessage = httpErrorMessage;\nexports.internal = index;\nexports.isHttpLocallyRecoverable = isHttpLocallyRecoverable;\nexports.isHttpRecoverable = isHttpRecoverable;\nexports.noop = noop;\nexports.secondsToMillis = secondsToMillis;\nexports.shouldRetry = shouldRetry;\nexports.sleep = sleep;\nexports.subsystem = index$1;\nexports.timedPromise = timedPromise;\n//# sourceMappingURL=index.cjs.map\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDFlagsStateOptions.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDFlagsState.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IsMigrationStage = exports.LDMigrationStage = void 0;\n/**\n * Stage denotes one of six possible stages a technology migration could be a\n * part of, progressing through the following order.\n *\n * Off -> DualWrite -> Shadow -> Live -> RampDown -> Complete\n */\nvar LDMigrationStage;\n(function (LDMigrationStage) {\n /**\n * Off - migration hasn't started, \"old\" is authoritative for reads and writes\n */\n LDMigrationStage[\"Off\"] = \"off\";\n /**\n * DualWrite - write to both \"old\" and \"new\", \"old\" is authoritative for reads\n */\n LDMigrationStage[\"DualWrite\"] = \"dualwrite\";\n /**\n * Shadow - both \"new\" and \"old\" versions run with a preference for \"old\"\n */\n LDMigrationStage[\"Shadow\"] = \"shadow\";\n /**\n * Live - both \"new\" and \"old\" versions run with a preference for \"new\"\n */\n LDMigrationStage[\"Live\"] = \"live\";\n /**\n * RampDown - only read from \"new\", write to \"old\" and \"new\"\n */\n LDMigrationStage[\"RampDown\"] = \"rampdown\";\n /**\n * Complete - migration is done\n */\n LDMigrationStage[\"Complete\"] = \"complete\";\n})(LDMigrationStage || (exports.LDMigrationStage = LDMigrationStage = {}));\n/**\n * Check if the given string is a migration stage.\n * @param value The string to check.\n * @returns True if the string is a migration stage.\n */\nfunction IsMigrationStage(value) {\n return Object.values(LDMigrationStage).includes(value);\n}\nexports.IsMigrationStage = IsMigrationStage;\n//# sourceMappingURL=LDMigrationStage.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDMigrationOpEvent.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LDConsistencyCheck = void 0;\n/**\n * Used for reporting the state of a consistency check.\n */\nvar LDConsistencyCheck;\n(function (LDConsistencyCheck) {\n LDConsistencyCheck[LDConsistencyCheck[\"Inconsistent\"] = 0] = \"Inconsistent\";\n LDConsistencyCheck[LDConsistencyCheck[\"Consistent\"] = 1] = \"Consistent\";\n LDConsistencyCheck[LDConsistencyCheck[\"NotChecked\"] = 2] = \"NotChecked\";\n})(LDConsistencyCheck || (exports.LDConsistencyCheck = LDConsistencyCheck = {}));\n//# sourceMappingURL=LDMigrationVariation.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./LDFlagsStateOptions\"), exports);\n__exportStar(require(\"./LDFlagsState\"), exports);\n__exportStar(require(\"./LDMigrationStage\"), exports);\n__exportStar(require(\"./LDMigrationOpEvent\"), exports);\n__exportStar(require(\"./LDMigrationVariation\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDBigSegmentsOptions.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDOptions.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDProxyOptions.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDTLSOptions.js.map","\"use strict\";\n/* eslint-disable max-classes-per-file */\n// Disabling max classes per file as these are tag classes without\n// logic implementation.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LDConcurrentExecution = exports.LDSerialExecution = exports.LDExecution = exports.LDExecutionOrdering = void 0;\n/**\n * When execution is sequential this enum is used to control if execution\n * should be in a fixed or random order.\n */\nvar LDExecutionOrdering;\n(function (LDExecutionOrdering) {\n LDExecutionOrdering[LDExecutionOrdering[\"Fixed\"] = 0] = \"Fixed\";\n LDExecutionOrdering[LDExecutionOrdering[\"Random\"] = 1] = \"Random\";\n})(LDExecutionOrdering || (exports.LDExecutionOrdering = LDExecutionOrdering = {}));\n/**\n * Tag used to determine if execution should be serial or concurrent.\n * Callers should not need to use this directly.\n */\nvar LDExecution;\n(function (LDExecution) {\n /**\n * Execution will be serial. One read method will be executed fully before\n * the other read method.\n */\n LDExecution[LDExecution[\"Serial\"] = 0] = \"Serial\";\n /**\n * Execution will be concurrent. The execution of the read methods will be\n * started and then resolved concurrently.\n */\n LDExecution[LDExecution[\"Concurrent\"] = 1] = \"Concurrent\";\n})(LDExecution || (exports.LDExecution = LDExecution = {}));\n/**\n * Configuration class for configuring serial execution of a migration.\n */\nclass LDSerialExecution {\n constructor(ordering) {\n this.ordering = ordering;\n this.type = LDExecution.Serial;\n }\n}\nexports.LDSerialExecution = LDSerialExecution;\n/**\n * Configuration class for configuring concurrent execution of a migration.\n */\nclass LDConcurrentExecution {\n constructor() {\n this.type = LDExecution.Concurrent;\n }\n}\nexports.LDConcurrentExecution = LDConcurrentExecution;\n//# sourceMappingURL=LDMigrationOptions.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isCustomOptions = exports.isPollingOnlyOptions = exports.isStreamingOnlyOptions = exports.isStandardOptions = void 0;\nfunction isStandardOptions(u) {\n return u.dataSourceOptionsType === 'standard';\n}\nexports.isStandardOptions = isStandardOptions;\nfunction isStreamingOnlyOptions(u) {\n return u.dataSourceOptionsType === 'streamingOnly';\n}\nexports.isStreamingOnlyOptions = isStreamingOnlyOptions;\nfunction isPollingOnlyOptions(u) {\n return u.dataSourceOptionsType === 'pollingOnly';\n}\nexports.isPollingOnlyOptions = isPollingOnlyOptions;\nfunction isCustomOptions(u) {\n return u.dataSourceOptionsType === 'custom';\n}\nexports.isCustomOptions = isCustomOptions;\n//# sourceMappingURL=LDDataSystemOptions.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./LDBigSegmentsOptions\"), exports);\n__exportStar(require(\"./LDOptions\"), exports);\n__exportStar(require(\"./LDProxyOptions\"), exports);\n__exportStar(require(\"./LDTLSOptions\"), exports);\n__exportStar(require(\"./LDMigrationOptions\"), exports);\n__exportStar(require(\"./LDDataSystemOptions\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDClient.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDMigration.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=DataKind.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDFeatureStore.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDTransactionalFeatureStore.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDWaitForInitializationOptions.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=FileDataSourceOptions.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=Hook.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./FileDataSourceOptions\"), exports);\n__exportStar(require(\"./Hook\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=BigSegmentStore.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=BigSegmentStoreMembership.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=BigSegmentStoreMetadata.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=BigSegmentStoreStatus.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=DataCollection.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=FullDataSet.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=KeyedItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=VersionedData.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=BigSegmentStoreStatusProvider.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=index.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./BigSegmentStore\"), exports);\n__exportStar(require(\"./BigSegmentStoreMembership\"), exports);\n__exportStar(require(\"./BigSegmentStoreMetadata\"), exports);\n__exportStar(require(\"./BigSegmentStoreStatus\"), exports);\n__exportStar(require(\"./DataCollection\"), exports);\n__exportStar(require(\"./DataKind\"), exports);\n__exportStar(require(\"./FullDataSet\"), exports);\n__exportStar(require(\"./KeyedItems\"), exports);\n__exportStar(require(\"./VersionedData\"), exports);\n__exportStar(require(\"./BigSegmentStoreStatusProvider\"), exports);\n__exportStar(require(\"./persistent_store\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDDataSourceUpdates.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDFeatureRequestor.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDTransactionalDataSourceUpdates.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./LDDataSourceUpdates\"), exports);\n__exportStar(require(\"./LDFeatureRequestor\"), exports);\n__exportStar(require(\"./LDFeatureStore\"), exports);\n__exportStar(require(\"./LDTransactionalDataSourceUpdates\"), exports);\n__exportStar(require(\"./LDTransactionalFeatureStore\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.subsystems = exports.interfaces = exports.integrations = void 0;\n__exportStar(require(\"./data\"), exports);\n__exportStar(require(\"./options\"), exports);\n__exportStar(require(\"./LDClient\"), exports);\n__exportStar(require(\"./LDMigration\"), exports);\n__exportStar(require(\"./interfaces/DataKind\"), exports);\n__exportStar(require(\"./subsystems/LDFeatureStore\"), exports);\n__exportStar(require(\"./subsystems/LDTransactionalFeatureStore\"), exports);\n__exportStar(require(\"./LDWaitForInitializationOptions\"), exports);\n// These are items that should be less frequently used, and therefore they\n// are namespaced to reduce clutter amongst the top level exports.\n// Integrations was overwritten by the exports of index.ts. On a major version\n// we should consider removing this and exporting integrations differently.\nexports.integrations = require(\"./integrations\");\nexports.interfaces = require(\"./interfaces\");\nexports.subsystems = require(\"./subsystems\");\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @internal\n */\nclass LruCache {\n constructor(options) {\n this._keyMap = new Map();\n this._head = 0;\n this._tail = 0;\n this._size = 0;\n const { max } = options;\n this._max = max;\n // This is effectively a struct-of-arrays implementation\n // of a linked list. All the nodes exist statically and then\n // the links between them are changed by updating the previous/next\n // arrays.\n this._values = new Array(max);\n this._keys = new Array(max);\n this._next = new Uint32Array(max);\n this._prev = new Uint32Array(max);\n if (options.maxAge) {\n this._lastUpdated = new Array(max).fill(0);\n this._maxAge = options.maxAge;\n }\n else {\n // To please linting.\n this._lastUpdated = [];\n this._maxAge = 0;\n }\n }\n set(key, val) {\n let index = this._keyMap.get(key);\n if (index === undefined) {\n index = this._index();\n this._keys[index] = key;\n this._keyMap.set(key, index);\n this._next[this._tail] = index;\n this._prev[index] = this._tail;\n this._tail = index;\n this._size += 1;\n }\n else {\n this._setTail(index);\n }\n this._values[index] = val;\n if (this._maxAge) {\n this._lastUpdated[index] = Date.now();\n }\n }\n get(key) {\n const index = this._keyMap.get(key);\n if (index !== undefined) {\n if (this._maxAge) {\n const lastUpdated = this._lastUpdated[index];\n if (Date.now() - lastUpdated > this._maxAge) {\n // The oldest items are always the head, so they get incrementally\n // replaced. This would not be the case if we supported per item TTL.\n return undefined;\n }\n }\n this._setTail(index);\n if (this._maxAge) {\n this._lastUpdated[index] = Date.now();\n }\n return this._values[index];\n }\n return undefined;\n }\n clear() {\n this._head = 0;\n this._tail = 0;\n this._size = 0;\n this._values.fill(undefined);\n this._keys.fill(undefined);\n this._next.fill(0);\n this._prev.fill(0);\n this._keyMap.clear();\n }\n _index() {\n if (this._size === 0) {\n return this._tail;\n }\n if (this._size === this._max) {\n return this._evict();\n }\n // The initial list is being populated, so we can just continue increasing size.\n return this._size;\n }\n _evict() {\n const { _head: head } = this;\n const k = this._keys[head];\n this._head = this._next[head];\n this._keyMap.delete(k);\n this._size -= 1;\n return head;\n }\n _link(p, n) {\n this._prev[n] = p;\n this._next[p] = n;\n }\n _setTail(index) {\n // If it is already the tail, then there is nothing to do.\n if (index !== this._tail) {\n // If this is the head, then we change the next item\n // to the head.\n if (index === this._head) {\n this._head = this._next[index];\n }\n else {\n // Link the previous item to the next item, effectively removing\n // the current node.\n this._link(this._prev[index], this._next[index]);\n }\n // Connect the current tail to this node.\n this._link(this._tail, index);\n this._tail = index;\n }\n }\n}\nexports.default = LruCache;\n//# sourceMappingURL=LruCache.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst BigSegmentStatusProviderImpl_1 = require(\"./BigSegmentStatusProviderImpl\");\nconst LruCache_1 = require(\"./cache/LruCache\");\nconst DEFAULT_STALE_AFTER_SECONDS = 120;\nconst DEFAULT_STATUS_POLL_INTERVAL_SECONDS = 5;\nconst DEFAULT_USER_CACHE_SIZE = 1000;\nconst DEFAULT_USER_CACHE_TIME_SECONDS = 5;\nclass BigSegmentsManager {\n constructor(_store, \n // The store will have been created before the manager is instantiated, so we do not need\n // it in the options at this stage.\n config, _logger, _crypto) {\n this._store = _store;\n this._logger = _logger;\n this._crypto = _crypto;\n this.statusProvider = new BigSegmentStatusProviderImpl_1.default(async () => this._pollStoreAndUpdateStatus());\n this._staleTimeMs =\n (js_sdk_common_1.TypeValidators.Number.is(config.staleAfter) && config.staleAfter > 0\n ? config.staleAfter\n : DEFAULT_STALE_AFTER_SECONDS) * 1000;\n const pollIntervalMs = (js_sdk_common_1.TypeValidators.Number.is(config.statusPollInterval) && config.statusPollInterval > 0\n ? config.statusPollInterval\n : DEFAULT_STATUS_POLL_INTERVAL_SECONDS) * 1000;\n this._pollHandle = _store\n ? setInterval(() => this._pollStoreAndUpdateStatus(), pollIntervalMs)\n : null;\n if (_store) {\n this._cache = new LruCache_1.default({\n max: config.userCacheSize || DEFAULT_USER_CACHE_SIZE,\n maxAge: (config.userCacheTime || DEFAULT_USER_CACHE_TIME_SECONDS) * 1000,\n });\n }\n }\n close() {\n if (this._pollHandle) {\n clearInterval(this._pollHandle);\n this._pollHandle = undefined;\n }\n if (this._store) {\n this._store.close();\n }\n }\n async getUserMembership(userKey) {\n var _a, _b, _c;\n if (!this._store) {\n return undefined;\n }\n const memberCache = (_a = this._cache) === null || _a === void 0 ? void 0 : _a.get(userKey);\n let membership;\n if (!memberCache) {\n try {\n membership = await this._store.getUserMembership(this._hashForUserKey(userKey));\n const cacheItem = { membership };\n (_b = this._cache) === null || _b === void 0 ? void 0 : _b.set(userKey, cacheItem);\n }\n catch (err) {\n (_c = this._logger) === null || _c === void 0 ? void 0 : _c.error(`Big Segment store membership query returned error: ${err}`);\n return [null, 'STORE_ERROR'];\n }\n }\n else {\n membership = memberCache.membership;\n }\n if (!this.statusProvider.getStatus()) {\n await this._pollStoreAndUpdateStatus();\n }\n // Status will be present, because polling is done earlier in this method if it is not.\n const lastStatus = this.statusProvider.getStatus();\n if (!lastStatus.available) {\n return [membership || null, 'STORE_ERROR'];\n }\n return [membership || null, lastStatus.stale ? 'STALE' : 'HEALTHY'];\n }\n async _pollStoreAndUpdateStatus() {\n var _a, _b, _c;\n if (!this._store) {\n this.statusProvider.setStatus({ available: false, stale: false });\n return;\n }\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Querying Big Segment store status');\n let newStatus;\n try {\n const metadata = await this._store.getMetadata();\n newStatus = {\n available: true,\n stale: !metadata || !metadata.lastUpToDate || this._isStale(metadata.lastUpToDate),\n };\n }\n catch (err) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error(`Big Segment store status query returned error: ${err}`);\n newStatus = { available: false, stale: false };\n }\n const lastStatus = this.statusProvider.getStatus();\n if (!lastStatus ||\n lastStatus.available !== newStatus.available ||\n lastStatus.stale !== newStatus.stale) {\n (_c = this._logger) === null || _c === void 0 ? void 0 : _c.debug('Big Segment store status changed from %s to %s', JSON.stringify(lastStatus), JSON.stringify(newStatus));\n this.statusProvider.setStatus(newStatus);\n this.statusProvider.notify();\n }\n }\n _hashForUserKey(userKey) {\n const hasher = this._crypto.createHash('sha256');\n hasher.update(userKey);\n if (!hasher.digest) {\n // This represents an error in platform implementation.\n throw new Error('Platform must implement digest or asyncDigest');\n }\n return hasher.digest('base64');\n }\n _isStale(timestamp) {\n return Date.now() - timestamp >= this._staleTimeMs;\n }\n}\nexports.default = BigSegmentsManager;\n//# sourceMappingURL=BigSegmentsManager.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createPluginEnvironmentMetadata = void 0;\nfunction createPluginEnvironmentMetadata(_platform, _sdkKey, config) {\n const environmentMetadata = {\n sdk: {\n name: _platform.info.sdkData().userAgentBase,\n version: _platform.info.sdkData().version,\n },\n sdkKey: _sdkKey,\n };\n if (_platform.info.sdkData().wrapperName) {\n environmentMetadata.sdk.wrapperName = _platform.info.sdkData().wrapperName;\n }\n if (_platform.info.sdkData().wrapperVersion) {\n environmentMetadata.sdk.wrapperVersion = _platform.info.sdkData().wrapperVersion;\n }\n if (config.applicationInfo) {\n environmentMetadata.application = config.applicationInfo;\n }\n return environmentMetadata;\n}\nexports.createPluginEnvironmentMetadata = createPluginEnvironmentMetadata;\n//# sourceMappingURL=createPluginEnvironmentMetadata.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createPayloadListener = void 0;\nconst namespaceForKind = (kind) => {\n switch (kind) {\n case 'flag':\n return 'features';\n case 'segment':\n return 'segments';\n default:\n return kind;\n }\n};\nconst createPayloadListener = (dataSourceUpdates, logger, basisReceived = () => { }) => (dataContainer) => {\n const { initMetadata, payload } = dataContainer;\n if (payload.basis) {\n logger === null || logger === void 0 ? void 0 : logger.debug('Initializing all data');\n }\n else if (payload.updates.length > 0) {\n logger === null || logger === void 0 ? void 0 : logger.debug('Applying updates');\n }\n else {\n logger === null || logger === void 0 ? void 0 : logger.debug('Payload had no updates, ignoring.');\n return;\n }\n // convert to LDFeatureStoreDataStorage structure\n const converted = {};\n payload.updates.forEach((it) => {\n const namespace = namespaceForKind(it.kind);\n if (converted[namespace]) {\n // entry for kind already exists, add key\n converted[namespace][it.key] = Object.assign(Object.assign({ version: it.version }, (it.deleted && { deleted: it.deleted })), it.object);\n }\n else {\n // entry for kind doesn't exist, add kind and key\n converted[namespace] = {\n [it.key]: Object.assign(Object.assign({ version: it.version }, (it.deleted && { deleted: it.deleted })), it.object),\n };\n }\n if (it.deleted) {\n logger === null || logger === void 0 ? void 0 : logger.debug(`Deleting ${it.key} in ${it.kind}`);\n }\n else {\n logger === null || logger === void 0 ? void 0 : logger.debug(`Updating ${it.key} in ${it.kind}`);\n }\n });\n // TODO: SDK-1209 - SUpport initMetadata in FDv2 datasources\n dataSourceUpdates.applyChanges(payload.basis, converted, basisReceived, initMetadata, payload.state);\n};\nexports.createPayloadListener = createPayloadListener;\n//# sourceMappingURL=createPayloadListenerFDv2.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass VersionedDataKinds {\n static getKeyFromPath(kind, path) {\n return path.startsWith(kind.streamApiPath)\n ? path.substring(kind.streamApiPath.length)\n : undefined;\n }\n}\nVersionedDataKinds.Features = {\n namespace: 'features',\n streamApiPath: '/flags/',\n};\nVersionedDataKinds.Segments = {\n namespace: 'segments',\n streamApiPath: '/segments/',\n};\nexports.default = VersionedDataKinds;\n//# sourceMappingURL=VersionedDataKinds.js.map","\"use strict\";\n// The deserialization will be updating parameter values, so we don't need this\n// warning in this file.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.deserializeSegment = exports.serializeSegment = exports.deserializeFlag = exports.serializeFlag = exports.deserializeDelete = exports.deserializePatch = exports.deserializePoll = exports.deserializeAll = exports.reviveFullPayload = exports.processSegment = exports.processFlag = exports.replacer = exports.nullReplacer = void 0;\n/* eslint-disable no-param-reassign */\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst VersionedDataKinds_1 = require(\"./VersionedDataKinds\");\n// The max size where we use an array instead of a set.\nconst TARGET_LIST_ARRAY_CUTOFF = 100;\n/**\n * Performs deep removal of null values.\n *\n * Does not remove null values from arrays.\n *\n * Note: This is a non-recursive implementation for performance and to avoid\n * potential stack overflows.\n *\n * @param target The target to remove null values from.\n * @param excludeKeys A list of top-level keys to exclude from null removal.\n */\nfunction nullReplacer(target, excludeKeys) {\n const stack = [];\n if (target === null || target === undefined) {\n return;\n }\n const filteredEntries = Object.entries(target).filter(([key, _value]) => !(excludeKeys === null || excludeKeys === void 0 ? void 0 : excludeKeys.includes(key)));\n stack.push(...filteredEntries.map(([key, value]) => ({\n key,\n value,\n parent: target,\n })));\n while (stack.length) {\n const item = stack.pop();\n // Do not remove items from arrays.\n if (item.value === null && !Array.isArray(item.parent)) {\n delete item.parent[item.key];\n }\n else if (typeof item.value === 'object' && item.value !== null) {\n // Add all the children to the stack. This includes array children.\n // The items in the array could themselves be objects which need nulls\n // removed from them.\n stack.push(...Object.entries(item.value).map(([key, value]) => ({\n key,\n value,\n parent: item.value,\n })));\n }\n }\n}\nexports.nullReplacer = nullReplacer;\n/**\n * For use when serializing flags/segments. This will ensure local types\n * are converted to the appropriate JSON representation.\n * @param this The scope containing the key/value.\n * @param key The key of the item being visited.\n * @param value The value of the item being visited.\n * @returns A transformed value for serialization.\n *\n * @internal\n */\nfunction replacer(key, value) {\n if (value instanceof js_sdk_common_1.AttributeReference) {\n return undefined;\n }\n if (Array.isArray(value)) {\n if (value[0] && value[0] instanceof js_sdk_common_1.AttributeReference) {\n return undefined;\n }\n }\n // Allow null/undefined values to pass through without modification.\n if (value === null || value === undefined) {\n return value;\n }\n if (value.generated_includedSet) {\n value.included = [...value.generated_includedSet];\n delete value.generated_includedSet;\n }\n if (value.generated_excludedSet) {\n value.excluded = [...value.generated_excludedSet];\n delete value.generated_excludedSet;\n }\n if (value.includedContexts) {\n value.includedContexts.forEach((target) => {\n if (target.generated_valuesSet) {\n target.values = [...target.generated_valuesSet];\n }\n delete target.generated_valuesSet;\n });\n }\n if (value.excludedContexts) {\n value.excludedContexts.forEach((target) => {\n if (target.generated_valuesSet) {\n target.values = [...target.generated_valuesSet];\n }\n delete target.generated_valuesSet;\n });\n }\n return value;\n}\nexports.replacer = replacer;\nfunction processRollout(rollout) {\n if (rollout && rollout.bucketBy) {\n rollout.bucketByAttributeReference = new js_sdk_common_1.AttributeReference(rollout.bucketBy, !rollout.contextKind);\n }\n}\n/**\n * @internal\n */\nfunction processFlag(flag) {\n var _a;\n nullReplacer(flag, ['variations']);\n if (flag.fallthrough && flag.fallthrough.rollout) {\n const rollout = flag.fallthrough.rollout;\n processRollout(rollout);\n }\n (_a = flag === null || flag === void 0 ? void 0 : flag.rules) === null || _a === void 0 ? void 0 : _a.forEach((rule) => {\n var _a;\n processRollout(rule.rollout);\n (_a = rule === null || rule === void 0 ? void 0 : rule.clauses) === null || _a === void 0 ? void 0 : _a.forEach((clause) => {\n if (clause && clause.attribute) {\n // Clauses before U2C would have had literals for attributes.\n // So use the contextKind to indicate if this is new or old data.\n clause.attributeReference = new js_sdk_common_1.AttributeReference(clause.attribute, !clause.contextKind);\n }\n else if (clause) {\n clause.attributeReference = js_sdk_common_1.AttributeReference.InvalidReference;\n }\n });\n });\n}\nexports.processFlag = processFlag;\n/**\n * @internal\n */\nfunction processSegment(segment) {\n var _a, _b, _c, _d, _e;\n nullReplacer(segment);\n if (((_a = segment === null || segment === void 0 ? void 0 : segment.included) === null || _a === void 0 ? void 0 : _a.length) && segment.included.length > TARGET_LIST_ARRAY_CUTOFF) {\n segment.generated_includedSet = new Set(segment.included);\n delete segment.included;\n }\n if (((_b = segment === null || segment === void 0 ? void 0 : segment.excluded) === null || _b === void 0 ? void 0 : _b.length) && segment.excluded.length > TARGET_LIST_ARRAY_CUTOFF) {\n segment.generated_excludedSet = new Set(segment.excluded);\n delete segment.excluded;\n }\n if ((_c = segment === null || segment === void 0 ? void 0 : segment.includedContexts) === null || _c === void 0 ? void 0 : _c.length) {\n segment.includedContexts.forEach((target) => {\n var _a;\n if (((_a = target === null || target === void 0 ? void 0 : target.values) === null || _a === void 0 ? void 0 : _a.length) && target.values.length > TARGET_LIST_ARRAY_CUTOFF) {\n target.generated_valuesSet = new Set(target.values);\n // Currently typing is non-optional, so we don't delete it.\n target.values = [];\n }\n });\n }\n if ((_d = segment === null || segment === void 0 ? void 0 : segment.excludedContexts) === null || _d === void 0 ? void 0 : _d.length) {\n segment.excludedContexts.forEach((target) => {\n var _a;\n if (((_a = target === null || target === void 0 ? void 0 : target.values) === null || _a === void 0 ? void 0 : _a.length) && target.values.length > TARGET_LIST_ARRAY_CUTOFF) {\n target.generated_valuesSet = new Set(target.values);\n // Currently typing is non-optional, so we don't delete it.\n target.values = [];\n }\n });\n }\n (_e = segment === null || segment === void 0 ? void 0 : segment.rules) === null || _e === void 0 ? void 0 : _e.forEach((rule) => {\n var _a;\n if (rule.bucketBy) {\n // Rules before U2C would have had literals for attributes.\n // So use the rolloutContextKind to indicate if this is new or old data.\n rule.bucketByAttributeReference = new js_sdk_common_1.AttributeReference(rule.bucketBy, !rule.rolloutContextKind);\n }\n (_a = rule === null || rule === void 0 ? void 0 : rule.clauses) === null || _a === void 0 ? void 0 : _a.forEach((clause) => {\n if (clause && clause.attribute) {\n // Clauses before U2C would have had literals for attributes.\n // So use the contextKind to indicate if this is new or old data.\n clause.attributeReference = new js_sdk_common_1.AttributeReference(clause.attribute, !clause.contextKind);\n }\n else if (clause) {\n clause.attributeReference = js_sdk_common_1.AttributeReference.InvalidReference;\n }\n });\n });\n}\nexports.processSegment = processSegment;\nfunction tryParse(data) {\n try {\n return JSON.parse(data);\n }\n catch (_a) {\n return undefined;\n }\n}\n/**\n * This function is intended for usage inside LaunchDarkly SDKs.\n * This function should NOT be used by customer applications.\n * This function may be changed or removed without a major version.\n *\n * @param payload Payload data from launchdarkly.\n * @returns The revived and processed data.\n */\nfunction reviveFullPayload(payload) {\n const flagsAndSegments = payload;\n Object.values((flagsAndSegments === null || flagsAndSegments === void 0 ? void 0 : flagsAndSegments.flags) || []).forEach((flag) => {\n processFlag(flag);\n });\n Object.values((flagsAndSegments === null || flagsAndSegments === void 0 ? void 0 : flagsAndSegments.segments) || []).forEach((segment) => {\n processSegment(segment);\n });\n return flagsAndSegments;\n}\nexports.reviveFullPayload = reviveFullPayload;\n/**\n * @internal\n */\nfunction deserializeAll(data) {\n // The reviver lacks the context of where a different key exists, being as it\n // starts at the deepest level and works outward. As a result attributes are\n // translated into references after the initial parsing. That way we can be sure\n // they are the correct ones. For instance if we added 'attribute' as a new field to\n // the schema for something that was NOT an attribute reference, then we wouldn't\n // want to construct an attribute reference out of it.\n const parsed = tryParse(data);\n if (!parsed) {\n return undefined;\n }\n reviveFullPayload(parsed === null || parsed === void 0 ? void 0 : parsed.data);\n return parsed;\n}\nexports.deserializeAll = deserializeAll;\n/**\n * This function is intended for usage inside LaunchDarkly SDKs.\n * This function should NOT be used by customer applications.\n * This function may be changed or removed without a major version.\n *\n * @param data String data from launchdarkly.\n * @returns The parsed and processed data.\n */\nfunction deserializePoll(data) {\n const parsed = tryParse(data);\n if (!parsed) {\n return undefined;\n }\n reviveFullPayload(parsed);\n return parsed;\n}\nexports.deserializePoll = deserializePoll;\n/**\n * @internal\n */\nfunction deserializePatch(data) {\n const parsed = tryParse(data);\n if (!parsed) {\n return undefined;\n }\n if (parsed.path.startsWith(VersionedDataKinds_1.default.Features.streamApiPath)) {\n processFlag(parsed.data);\n parsed.kind = VersionedDataKinds_1.default.Features;\n }\n else if (parsed.path.startsWith(VersionedDataKinds_1.default.Segments.streamApiPath)) {\n processSegment(parsed.data);\n parsed.kind = VersionedDataKinds_1.default.Segments;\n }\n return parsed;\n}\nexports.deserializePatch = deserializePatch;\n/**\n * @internal\n */\nfunction deserializeDelete(data) {\n const parsed = tryParse(data);\n if (!parsed) {\n return undefined;\n }\n if (parsed.path.startsWith(VersionedDataKinds_1.default.Features.streamApiPath)) {\n parsed.kind = VersionedDataKinds_1.default.Features;\n }\n else if (parsed.path.startsWith(VersionedDataKinds_1.default.Segments.streamApiPath)) {\n parsed.kind = VersionedDataKinds_1.default.Segments;\n }\n return parsed;\n}\nexports.deserializeDelete = deserializeDelete;\n/**\n * Serialize a single flag. Used for persistent data stores.\n *\n * @internal\n */\nfunction serializeFlag(flag) {\n return JSON.stringify(flag, replacer);\n}\nexports.serializeFlag = serializeFlag;\n/**\n * Deserialize a single flag. Used for persistent data stores.\n *\n * @internal\n */\nfunction deserializeFlag(data) {\n const parsed = tryParse(data);\n if (!parsed) {\n return undefined;\n }\n processFlag(parsed);\n return parsed;\n}\nexports.deserializeFlag = deserializeFlag;\n/**\n * Serialize a single segment. Used for persistent data stores.\n *\n * @internal\n */\nfunction serializeSegment(segment) {\n return JSON.stringify(segment, replacer);\n}\nexports.serializeSegment = serializeSegment;\n/**\n * Deserialize a single segment. Used for persistent data stores.\n *\n * @internal\n */\nfunction deserializeSegment(data) {\n const parsed = tryParse(data);\n if (!parsed) {\n return undefined;\n }\n processSegment(parsed);\n return parsed;\n}\nexports.deserializeSegment = deserializeSegment;\n//# sourceMappingURL=serialization.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createStreamListeners = exports.createDeleteListener = exports.createPatchListener = exports.createPutListener = void 0;\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst serialization_1 = require(\"../store/serialization\");\nconst VersionedDataKinds_1 = require(\"../store/VersionedDataKinds\");\nconst { initMetadataFromHeaders } = js_sdk_common_1.internal;\nconst createPutListener = (dataSourceUpdates, logger, onPutCompleteHandler = () => { }) => ({\n deserializeData: serialization_1.deserializeAll,\n processJson: async ({ data: { flags, segments } }, initHeaders) => {\n const initData = {\n [VersionedDataKinds_1.default.Features.namespace]: flags,\n [VersionedDataKinds_1.default.Segments.namespace]: segments,\n };\n logger === null || logger === void 0 ? void 0 : logger.debug('Initializing all data');\n dataSourceUpdates.init(initData, onPutCompleteHandler, initMetadataFromHeaders(initHeaders));\n },\n});\nexports.createPutListener = createPutListener;\nconst createPatchListener = (dataSourceUpdates, logger, onPatchCompleteHandler = () => { }) => ({\n deserializeData: serialization_1.deserializePatch,\n processJson: async ({ data, kind, path }) => {\n if (kind) {\n const key = VersionedDataKinds_1.default.getKeyFromPath(kind, path);\n if (key) {\n logger === null || logger === void 0 ? void 0 : logger.debug(`Updating ${key} in ${kind.namespace}`);\n dataSourceUpdates.upsert(kind, data, onPatchCompleteHandler);\n }\n }\n },\n});\nexports.createPatchListener = createPatchListener;\nconst createDeleteListener = (dataSourceUpdates, logger, onDeleteCompleteHandler = () => { }) => ({\n deserializeData: serialization_1.deserializeDelete,\n processJson: async ({ kind, path, version }) => {\n if (kind) {\n const key = VersionedDataKinds_1.default.getKeyFromPath(kind, path);\n if (key) {\n logger === null || logger === void 0 ? void 0 : logger.debug(`Deleting ${key} in ${kind.namespace}`);\n dataSourceUpdates.upsert(kind, {\n key,\n version,\n deleted: true,\n }, onDeleteCompleteHandler);\n }\n }\n },\n});\nexports.createDeleteListener = createDeleteListener;\nconst createStreamListeners = (dataSourceUpdates, logger, onCompleteHandlers) => {\n const listeners = new Map();\n listeners.set('put', (0, exports.createPutListener)(dataSourceUpdates, logger, onCompleteHandlers === null || onCompleteHandlers === void 0 ? void 0 : onCompleteHandlers.put));\n listeners.set('patch', (0, exports.createPatchListener)(dataSourceUpdates, logger, onCompleteHandlers === null || onCompleteHandlers === void 0 ? void 0 : onCompleteHandlers.patch));\n listeners.set('delete', (0, exports.createDeleteListener)(dataSourceUpdates, logger, onCompleteHandlers === null || onCompleteHandlers === void 0 ? void 0 : onCompleteHandlers.delete));\n return listeners;\n};\nexports.createStreamListeners = createStreamListeners;\n//# sourceMappingURL=createStreamListeners.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @internal\n */\nclass NamespacedDataSet {\n constructor() {\n this._itemsByNamespace = {};\n }\n get(namespace, key) {\n var _a;\n return (_a = this._itemsByNamespace[namespace]) === null || _a === void 0 ? void 0 : _a[key];\n }\n set(namespace, key, value) {\n if (!(namespace in this._itemsByNamespace)) {\n this._itemsByNamespace[namespace] = {};\n }\n this._itemsByNamespace[namespace][key] = value;\n }\n remove(namespace, key) {\n const items = this._itemsByNamespace[namespace];\n if (items) {\n delete items[key];\n }\n }\n removeAll() {\n this._itemsByNamespace = {};\n }\n enumerate(callback) {\n Object.entries(this._itemsByNamespace).forEach(([namespace, values]) => {\n Object.entries(values).forEach(([key, value]) => {\n callback(namespace, key, value);\n });\n });\n }\n mergeFrom(other) {\n other.enumerate(this.set.bind(this));\n }\n}\nexports.default = NamespacedDataSet;\n//# sourceMappingURL=NamespacedDataSet.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst NamespacedDataSet_1 = require(\"./NamespacedDataSet\");\n/**\n * @internal\n */\nclass DependencyTracker {\n constructor() {\n this._dependenciesFrom = new NamespacedDataSet_1.default();\n this._dependenciesTo = new NamespacedDataSet_1.default();\n }\n updateDependenciesFrom(namespace, key, newDependencySet) {\n const oldDependencySet = this._dependenciesFrom.get(namespace, key);\n oldDependencySet === null || oldDependencySet === void 0 ? void 0 : oldDependencySet.enumerate((depNs, depKey) => {\n const depsToThisDep = this._dependenciesTo.get(depNs, depKey);\n depsToThisDep === null || depsToThisDep === void 0 ? void 0 : depsToThisDep.remove(namespace, key);\n });\n this._dependenciesFrom.set(namespace, key, newDependencySet);\n newDependencySet === null || newDependencySet === void 0 ? void 0 : newDependencySet.enumerate((depNs, depKey) => {\n let depsToThisDep = this._dependenciesTo.get(depNs, depKey);\n if (!depsToThisDep) {\n depsToThisDep = new NamespacedDataSet_1.default();\n this._dependenciesTo.set(depNs, depKey, depsToThisDep);\n }\n depsToThisDep.set(namespace, key, true);\n });\n }\n updateModifiedItems(inDependencySet, modifiedNamespace, modifiedKey) {\n if (!inDependencySet.get(modifiedNamespace, modifiedKey)) {\n inDependencySet.set(modifiedNamespace, modifiedKey, true);\n const affectedItems = this._dependenciesTo.get(modifiedNamespace, modifiedKey);\n affectedItems === null || affectedItems === void 0 ? void 0 : affectedItems.enumerate((namespace, key) => {\n this.updateModifiedItems(inDependencySet, namespace, key);\n });\n }\n }\n reset() {\n this._dependenciesFrom.removeAll();\n this._dependenciesTo.removeAll();\n }\n}\nexports.default = DependencyTracker;\n//# sourceMappingURL=DependencyTracker.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.computeDependencies = void 0;\nconst VersionedDataKinds_1 = require(\"../store/VersionedDataKinds\");\nconst DependencyTracker_1 = require(\"./DependencyTracker\");\nconst NamespacedDataSet_1 = require(\"./NamespacedDataSet\");\nfunction computeDependencies(namespace, item) {\n var _a, _b;\n const ret = new NamespacedDataSet_1.default();\n const isFlag = namespace === VersionedDataKinds_1.default.Features.namespace;\n const isSegment = namespace === VersionedDataKinds_1.default.Segments.namespace;\n if (isFlag) {\n const flag = item;\n (_a = flag === null || flag === void 0 ? void 0 : flag.prerequisites) === null || _a === void 0 ? void 0 : _a.forEach((prereq) => {\n ret.set(namespace, prereq.key, true);\n });\n }\n if (isFlag || isSegment) {\n const itemWithRuleClauses = item;\n (_b = itemWithRuleClauses === null || itemWithRuleClauses === void 0 ? void 0 : itemWithRuleClauses.rules) === null || _b === void 0 ? void 0 : _b.forEach((rule) => {\n var _a;\n (_a = rule.clauses) === null || _a === void 0 ? void 0 : _a.forEach((clause) => {\n if (clause.op === 'segmentMatch') {\n clause.values.forEach((value) => {\n ret.set(VersionedDataKinds_1.default.Segments.namespace, value, true);\n });\n }\n });\n });\n }\n return ret;\n}\nexports.computeDependencies = computeDependencies;\n/**\n * @internal\n */\nclass DataSourceUpdates {\n constructor(_featureStore, _hasEventListeners, _onChange) {\n this._featureStore = _featureStore;\n this._hasEventListeners = _hasEventListeners;\n this._onChange = _onChange;\n this._dependencyTracker = new DependencyTracker_1.default();\n }\n init(allData, callback, initMetadata) {\n const checkForChanges = this._hasEventListeners();\n const doInit = (oldData) => {\n this._featureStore.init(allData, () => {\n // Defer change events so they execute after the callback.\n Promise.resolve().then(() => {\n this._dependencyTracker.reset();\n Object.entries(allData).forEach(([namespace, items]) => {\n Object.keys(items || {}).forEach((key) => {\n const item = items[key];\n this._dependencyTracker.updateDependenciesFrom(namespace, key, computeDependencies(namespace, item));\n });\n });\n if (checkForChanges) {\n const updatedItems = new NamespacedDataSet_1.default();\n Object.keys(allData).forEach((namespace) => {\n const oldDataForKind = (oldData === null || oldData === void 0 ? void 0 : oldData[namespace]) || {};\n const newDataForKind = allData[namespace];\n const mergedData = Object.assign(Object.assign({}, oldDataForKind), newDataForKind);\n Object.keys(mergedData).forEach((key) => {\n this.addIfModified(namespace, key, oldDataForKind && oldDataForKind[key], newDataForKind && newDataForKind[key], updatedItems);\n });\n });\n this.sendChangeEvents(updatedItems);\n }\n });\n callback === null || callback === void 0 ? void 0 : callback();\n }, initMetadata);\n };\n if (checkForChanges) {\n this._featureStore.all(VersionedDataKinds_1.default.Features, (oldFlags) => {\n this._featureStore.all(VersionedDataKinds_1.default.Segments, (oldSegments) => {\n const oldData = {\n [VersionedDataKinds_1.default.Features.namespace]: oldFlags,\n [VersionedDataKinds_1.default.Segments.namespace]: oldSegments,\n };\n doInit(oldData);\n });\n });\n }\n else {\n doInit();\n }\n }\n upsert(kind, data, callback) {\n const { key } = data;\n const checkForChanges = this._hasEventListeners();\n const doUpsert = (oldItem) => {\n this._featureStore.upsert(kind, data, () => {\n // Defer change events so they execute after the callback.\n Promise.resolve().then(() => {\n this._dependencyTracker.updateDependenciesFrom(kind.namespace, key, computeDependencies(kind.namespace, data));\n if (checkForChanges) {\n const updatedItems = new NamespacedDataSet_1.default();\n this.addIfModified(kind.namespace, key, oldItem, data, updatedItems);\n this.sendChangeEvents(updatedItems);\n }\n });\n callback === null || callback === void 0 ? void 0 : callback();\n });\n };\n if (checkForChanges) {\n this._featureStore.get(kind, key, doUpsert);\n }\n else {\n doUpsert();\n }\n }\n addIfModified(namespace, key, oldValue, newValue, toDataSet) {\n if (newValue && oldValue && newValue.version <= oldValue.version) {\n return;\n }\n this._dependencyTracker.updateModifiedItems(toDataSet, namespace, key);\n }\n sendChangeEvents(dataSet) {\n dataSet.enumerate((namespace, key) => {\n if (namespace === VersionedDataKinds_1.default.Features.namespace) {\n this._onChange(key);\n }\n });\n }\n}\nexports.default = DataSourceUpdates;\n//# sourceMappingURL=DataSourceUpdates.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * A debounced file load/watcher for use with the {@link FileDataSource}.\n *\n * The file loader will load all files specified and keep the string representations in memory.\n * Whenever a change is made to any of the files, then that file will be reloaded and the in\n * memory version updated.\n *\n * Updates to many files, which occur within 10ms of each other, will be coalesced into\n * a single callback.\n *\n * @internal\n */\nclass FileLoader {\n constructor(_filesystem, _paths, _watch, _callback) {\n this._filesystem = _filesystem;\n this._paths = _paths;\n this._watch = _watch;\n this._callback = _callback;\n this._watchers = [];\n this._fileData = {};\n this._fileTimestamps = {};\n }\n /**\n * Load all the files and start watching them if watching is enabled.\n */\n async loadAndWatch() {\n const promises = this._paths.map(async (path) => {\n const data = await this._filesystem.readFile(path);\n const timeStamp = await this._filesystem.getFileTimestamp(path);\n return { data, path, timeStamp };\n });\n // This promise could be rejected, let the caller handle it.\n const results = await Promise.all(promises);\n results.forEach((res) => {\n this._fileData[res.path] = res.data;\n this._fileTimestamps[res.path] = res.timeStamp;\n });\n this._callback(results);\n // If we are watching, then setup watchers and notify of any changes.\n if (this._watch) {\n this._paths.forEach((path) => {\n const watcher = this._filesystem.watch(path, async (_, updatePath) => {\n const timeStamp = await this._filesystem.getFileTimestamp(updatePath);\n // The modification time is the same, so we are going to ignore this update.\n // In some implementations watch might be triggered multiple times for a single update.\n if (timeStamp === this._fileTimestamps[updatePath]) {\n return;\n }\n this._fileTimestamps[updatePath] = timeStamp;\n const data = await this._filesystem.readFile(updatePath);\n this._fileData[updatePath] = data;\n this._debounceCallback();\n });\n this._watchers.push(watcher);\n });\n }\n }\n close() {\n this._watchers.forEach((watcher) => watcher.close());\n }\n _debounceCallback() {\n // If there is a handle, then we have already started the debounce process.\n if (!this._debounceHandle) {\n this._debounceHandle = setTimeout(() => {\n this._debounceHandle = undefined;\n this._callback(Object.entries(this._fileData).reduce((acc, [path, data]) => {\n acc.push({ path, data });\n return acc;\n }, []));\n }, 10);\n // The 10ms delay above is arbitrary - we just don't want to have the number be zero,\n // because in a case where multiple watch events are fired off one after another,\n // we want the reload to happen only after all of the event handlers have executed.\n }\n }\n}\nexports.default = FileLoader;\n//# sourceMappingURL=FileLoader.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst serialization_1 = require(\"../store/serialization\");\nconst FileLoader_1 = require(\"./FileLoader\");\n/**\n * @internal\n */\nclass FileDataInitializerFDv2 {\n constructor(options, platform, logger) {\n this._validateInputs(options, platform);\n this._paths = options.paths;\n this._logger = logger;\n this._filesystem = platform.fileSystem;\n this._yamlParser = options.yamlParser;\n }\n _validateInputs(options, platform) {\n if (!options.paths || options.paths.length === 0) {\n throw new Error('FileDataInitializerFDv2: paths are required');\n }\n if (!platform.fileSystem) {\n throw new Error('FileDataInitializerFDv2: file system is required');\n }\n }\n start(dataCallback, statusCallback) {\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Initializing);\n const initMetadata = js_sdk_common_1.internal.initMetadataFromHeaders(undefined);\n const payloadProcessor = new js_sdk_common_1.internal.PayloadProcessor({\n flag: (flag) => {\n (0, serialization_1.processFlag)(flag);\n return flag;\n },\n segment: (segment) => {\n (0, serialization_1.processSegment)(segment);\n return segment;\n },\n }, (errorKind, message) => {\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Interrupted, new js_sdk_common_1.LDPollingError(errorKind, message));\n }, this._logger);\n const adaptor = js_sdk_common_1.internal.FDv1PayloadAdaptor(payloadProcessor);\n this._fileLoader = new FileLoader_1.default(this._filesystem, this._paths, false, // autoupdate is always false for initializer\n (results) => {\n var _a;\n try {\n const parsedData = this._processFileData(results);\n payloadProcessor.addPayloadListener((payload) => {\n // NOTE: file data initializer will never have a valid basis, so we always pass false\n dataCallback(false, { initMetadata, payload });\n });\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Valid);\n adaptor.processFullTransfer(parsedData);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed);\n }\n catch (err) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error('File contained invalid data', err);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.InvalidData, 'Malformed data in file response'));\n }\n });\n this._fileLoader.loadAndWatch().catch((err) => {\n var _a;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error('Error loading files', err);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.NetworkError, `Failed to load files: ${err instanceof Error ? err.message : String(err)}`));\n });\n }\n _processFileData(results) {\n const combined = results.reduce((acc, curr) => {\n var _a, _b;\n let parsed;\n if (curr.path.endsWith('.yml') || curr.path.endsWith('.yaml')) {\n if (this._yamlParser) {\n parsed = this._yamlParser(curr.data);\n }\n else {\n throw new Error(`Attempted to parse yaml file (${curr.path}) without parser.`);\n }\n }\n else {\n parsed = JSON.parse(curr.data);\n }\n return {\n segments: Object.assign(Object.assign({}, acc.segments), ((_a = parsed.segments) !== null && _a !== void 0 ? _a : {})),\n flags: Object.assign(Object.assign({}, acc.flags), ((_b = parsed.flags) !== null && _b !== void 0 ? _b : {})),\n };\n }, {\n segments: {},\n flags: {},\n });\n return combined;\n }\n stop() {\n if (this._fileLoader) {\n this._fileLoader.close();\n }\n }\n}\nexports.default = FileDataInitializerFDv2;\n//# sourceMappingURL=fileDataInitilizerFDv2.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst serialization_1 = require(\"../store/serialization\");\n/**\n * @internal\n */\nclass OneShotInitializerFDv2 {\n constructor(_requestor, _logger) {\n this._requestor = _requestor;\n this._logger = _logger;\n this._stopped = false;\n }\n start(dataCallback, statusCallback) {\n var _a;\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Initializing);\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Performing initialization request to LaunchDarkly for feature flag data.');\n this._requestor.requestAllData((err, body, headers) => {\n var _a, _b, _c;\n if (this._stopped) {\n return;\n }\n if (err) {\n const { status } = err;\n const message = (0, js_sdk_common_1.httpErrorMessage)(err, 'initializer', 'initializer does not retry');\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error(message);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, message, status));\n return;\n }\n if (!body) {\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.InvalidData, 'One shot initializer response missing body.'));\n return;\n }\n const initMetadata = js_sdk_common_1.internal.initMetadataFromHeaders(headers);\n try {\n const parsed = JSON.parse(body);\n const payloadProcessor = new js_sdk_common_1.internal.PayloadProcessor({\n flag: (flag) => {\n (0, serialization_1.processFlag)(flag);\n return flag;\n },\n segment: (segment) => {\n (0, serialization_1.processSegment)(segment);\n return segment;\n },\n }, (errorKind, message) => {\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Interrupted, new js_sdk_common_1.LDPollingError(errorKind, message));\n }, this._logger);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Valid);\n payloadProcessor.addPayloadListener((payload) => {\n dataCallback(payload.basis, { initMetadata, payload });\n });\n payloadProcessor.processEvents(parsed.events);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed);\n }\n catch (error) {\n // We could not parse this JSON. Report the problem.\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error('Response contained invalid data');\n (_c = this._logger) === null || _c === void 0 ? void 0 : _c.debug(`${err} - Body follows: ${body}`);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.InvalidData, 'Malformed data in polling response'));\n }\n });\n }\n stop() {\n this._stopped = true;\n }\n}\nexports.default = OneShotInitializerFDv2;\n//# sourceMappingURL=OneShotInitializerFDv2.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * A basic wrapper to make async methods with callbacks into promises.\n *\n * @param method\n * @returns A promisified version of the method.\n */\nfunction promisify(method) {\n return new Promise((resolve) => {\n method((val) => {\n resolve(val);\n });\n });\n}\nexports.default = promisify;\n//# sourceMappingURL=promisify.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst promisify_1 = require(\"../async/promisify\");\n/**\n * Provides an async interface to a feature store.\n *\n * This allows for using a store using async/await instead of callbacks.\n *\n */\nclass AsyncStoreFacade {\n constructor(store) {\n this._store = store;\n }\n async get(kind, key) {\n return (0, promisify_1.default)((cb) => {\n this._store.get(kind, key, cb);\n });\n }\n async all(kind) {\n return (0, promisify_1.default)((cb) => {\n this._store.all(kind, cb);\n });\n }\n async init(allData, initMetadata) {\n return (0, promisify_1.default)((cb) => {\n this._store.init(allData, cb, initMetadata);\n });\n }\n async delete(kind, key, version) {\n return (0, promisify_1.default)((cb) => {\n this._store.delete(kind, key, version, cb);\n });\n }\n async upsert(kind, data) {\n return (0, promisify_1.default)((cb) => {\n this._store.upsert(kind, data, cb);\n });\n }\n async initialized() {\n return (0, promisify_1.default)((cb) => {\n this._store.initialized(cb);\n });\n }\n close() {\n this._store.close();\n }\n getInitMetadata() {\n var _a, _b;\n return (_b = (_a = this._store).getInitMetaData) === null || _b === void 0 ? void 0 : _b.call(_a);\n }\n}\nexports.default = AsyncStoreFacade;\n//# sourceMappingURL=AsyncStoreFacade.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst promisify_1 = require(\"../async/promisify\");\n/**\n * Provides an async interface to a feature store.\n *\n * This allows for using a store using async/await instead of callbacks.\n *\n */\nclass AsyncTransactionalStoreFacade {\n constructor(store) {\n this._store = store;\n }\n async get(kind, key) {\n return (0, promisify_1.default)((cb) => {\n this._store.get(kind, key, cb);\n });\n }\n async all(kind) {\n return (0, promisify_1.default)((cb) => {\n this._store.all(kind, cb);\n });\n }\n async init(allData, initMetadata) {\n return (0, promisify_1.default)((cb) => {\n this._store.init(allData, cb, initMetadata);\n });\n }\n async delete(kind, key, version) {\n return (0, promisify_1.default)((cb) => {\n this._store.delete(kind, key, version, cb);\n });\n }\n async upsert(kind, data) {\n return (0, promisify_1.default)((cb) => {\n this._store.upsert(kind, data, cb);\n });\n }\n async initialized() {\n return (0, promisify_1.default)((cb) => {\n this._store.initialized(cb);\n });\n }\n async applyChanges(basis, data, initMetadata, selector) {\n return (0, promisify_1.default)((cb) => {\n this._store.applyChanges(basis, data, cb, initMetadata, selector);\n });\n }\n close() {\n this._store.close();\n }\n getInitMetadata() {\n var _a, _b;\n return (_b = (_a = this._store).getInitMetaData) === null || _b === void 0 ? void 0 : _b.call(_a);\n }\n}\nexports.default = AsyncTransactionalStoreFacade;\n//# sourceMappingURL=AsyncTransactionalStoreFacade.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction isStale(record) {\n return Date.now() > record.expiration;\n}\n/**\n * A basic TTL cache with configurable TTL and check interval.\n */\nclass TtlCache {\n constructor(_options) {\n this._options = _options;\n this._storage = new Map();\n this._checkIntervalHandle = setInterval(() => {\n this._purgeStale();\n }, _options.checkInterval * 1000);\n }\n /**\n * Get a value from the cache.\n * @param key The key to get a value for.\n * @returns The value for the key, or undefined if the key was not added, or\n * if the value has expired.\n */\n get(key) {\n const record = this._storage.get(key);\n if (record && isStale(record)) {\n this._storage.delete(key);\n return undefined;\n }\n return record === null || record === void 0 ? void 0 : record.value;\n }\n /**\n * Set an item in the cache. It will expire after the TTL specified\n * in the cache configuration.\n * @param key The key for the value.\n * @param value The value to set.\n */\n set(key, value) {\n this._storage.set(key, {\n value,\n expiration: Date.now() + this._options.ttl * 1000,\n });\n }\n /**\n * Delete the item with the specific key. If the item does not exist,\n * then there will be no change to the cache.\n * @param key The key of the value to delete.\n */\n delete(key) {\n this._storage.delete(key);\n }\n /**\n * Clear the items that are in the cache.\n */\n clear() {\n this._storage.clear();\n }\n /**\n * Indicate that you are no longer going to use the cache. The cache will be\n * cleared and it will stop checking for stale items.\n */\n close() {\n this.clear();\n if (this._checkIntervalHandle) {\n clearInterval(this._checkIntervalHandle);\n this._checkIntervalHandle = null;\n }\n }\n _purgeStale() {\n this._storage.forEach((record, key) => {\n if (isStale(record)) {\n this._storage.delete(key);\n }\n });\n }\n /**\n * This is for testing.\n * @internal\n */\n get size() {\n return this._storage.size;\n }\n}\nexports.default = TtlCache;\n//# sourceMappingURL=TtlCache.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.persistentStoreKinds = void 0;\nconst serialization_1 = require(\"./serialization\");\nconst VersionedDataKinds_1 = require(\"./VersionedDataKinds\");\n/**\n * Map namespace to a persistent store kind.\n */\nexports.persistentStoreKinds = {\n segments: {\n namespace: VersionedDataKinds_1.default.Segments.namespace,\n deserialize: (data) => {\n const segment = (0, serialization_1.deserializeSegment)(data);\n if (segment) {\n return {\n version: segment.version,\n item: segment,\n };\n }\n return undefined;\n },\n serialize: (data) => {\n const serializedItem = (0, serialization_1.serializeSegment)(data);\n return {\n version: data.version,\n deleted: data.deleted,\n serializedItem,\n };\n },\n priority: 0,\n },\n features: {\n namespace: VersionedDataKinds_1.default.Features.namespace,\n deserialize: (data) => {\n const flag = (0, serialization_1.deserializeFlag)(data);\n if (flag) {\n return {\n version: flag.version,\n item: flag,\n };\n }\n return undefined;\n },\n serialize: (data) => {\n const serializedItem = (0, serialization_1.serializeFlag)(data);\n return {\n version: data.version,\n deleted: data.deleted,\n serializedItem,\n };\n },\n priority: 1,\n },\n};\n//# sourceMappingURL=persistentStoreKinds.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst persistentStoreKinds_1 = require(\"./persistentStoreKinds\");\nfunction getDependencyKeys(flag) {\n if (!flag.prerequisites || !flag.prerequisites.length) {\n return [];\n }\n return flag.prerequisites.map((preReq) => preReq.key);\n}\n/**\n * Do a topological sort using a depth-first search.\n * https://en.wikipedia.org/wiki/Topological_sorting\n */\nfunction topologicalSort(kind, itemsMap) {\n const sortedItems = [];\n const unvisitedItems = new Set(Object.keys(itemsMap));\n const visit = (key) => {\n if (!unvisitedItems.has(key)) {\n return;\n }\n // Typically in a depth-first search this would be done later, and there\n // would be a temporary mark to detect that this was not an directed acylic graph.\n // Removing it here will mean we cannot do that detection, but we also will\n // not infinitely recurse.\n unvisitedItems.delete(key);\n const item = itemsMap[key];\n if (kind.namespace === 'features') {\n getDependencyKeys(item).forEach((prereqKey) => {\n visit(prereqKey);\n });\n }\n sortedItems.push({\n key,\n item: kind.serialize(item),\n });\n };\n while (unvisitedItems.size > 0) {\n // Visit the next item, the order we visit doesn't matter.\n const key = unvisitedItems.values().next().value;\n visit(key);\n }\n return sortedItems;\n}\n/**\n * For non-atomic stores we want to insert items in an order that no items exist\n * in the store before their dependencies. Segments before flags, because flags\n * are dependent on segments. For flags we want to insert them such that no flags are\n * added before the prerequisites of those flags.\n *\n * Segments can also depend on other segments, but a segment will not be accessed\n * if there are no flags.\n */\nfunction sortDataSet(dataMap) {\n // We use a different type for collecting the results so that we have access\n // to the serialization methods and priorities.\n const result = [];\n Object.keys(dataMap).forEach((kindNamespace) => {\n const kind = persistentStoreKinds_1.persistentStoreKinds[kindNamespace];\n result.push({ key: kind, item: topologicalSort(kind, dataMap[kindNamespace]) });\n });\n result.sort((i1, i2) => i1.key.priority - i2.key.priority);\n return result;\n}\nexports.default = sortDataSet;\n//# sourceMappingURL=sortDataSet.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass UpdateQueue {\n constructor() {\n this._queue = [];\n }\n enqueue(updateFn, cb) {\n this._queue.push([updateFn, cb]);\n if (this._queue.length === 1) {\n // If this is the only item in the queue, then there is not a series\n // of updates already in progress. So we can start executing those updates.\n this.executePendingUpdates();\n }\n }\n executePendingUpdates() {\n if (this._queue.length > 0) {\n const [fn, cb] = this._queue[0];\n const newCb = () => {\n // We just completed work, so remove it from the queue.\n // Don't remove it before the work is done, because then the\n // count could hit 0, and overlapping execution chains could be started.\n this._queue.shift();\n // There is more work to do, so schedule an update.\n if (this._queue.length > 0) {\n setTimeout(() => this.executePendingUpdates(), 0);\n }\n // Call the original callback.\n cb === null || cb === void 0 ? void 0 : cb();\n };\n fn(newCb);\n }\n }\n}\nexports.default = UpdateQueue;\n//# sourceMappingURL=UpdateQueue.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst TtlCache_1 = require(\"../cache/TtlCache\");\nconst persistentStoreKinds_1 = require(\"./persistentStoreKinds\");\nconst sortDataSet_1 = require(\"./sortDataSet\");\nconst UpdateQueue_1 = require(\"./UpdateQueue\");\nfunction cacheKey(kind, key) {\n return `${kind.namespace}:${key}`;\n}\nfunction allForKindCacheKey(kind) {\n return `$all:${kind.namespace}`;\n}\n// This key will be set in the cache if we have checked that a store was\n// initialized and found that it was not. If we do not become initialized\n// within the TTL period, then the key will expire, and the next initialization\n// check will pass through to the store. Once we are initialized, then the key\n// will never be checked again.\nconst initializationCheckedKey = '$checkedInit';\n// The interval to check items in the TTL cache to purge expired items.\n// Expired items which are not purged, will be reactively purged when they are\n// accessed.\nconst defaultCheckInterval = 600;\nfunction itemIfNotDeleted(item) {\n return !item || item.item.deleted ? null : item.item;\n}\nfunction deletedDescriptor(version) {\n return {\n version,\n item: { version, deleted: true },\n };\n}\n/**\n * Deserialize a {@link SerializedItemDescriptor}\n * @param kind The persistent store data kind to deserialize.\n * @param descriptor The serialized descriptor we want to deserialize.\n * @returns An item descriptor for the deserialized item.\n */\nfunction deserialize(kind, descriptor) {\n if (descriptor.deleted || !descriptor.serializedItem) {\n return deletedDescriptor(descriptor.version);\n }\n const deserializedItem = kind.deserialize(descriptor.serializedItem);\n if (deserializedItem === undefined) {\n // This would only happen if the JSON is invalid.\n return deletedDescriptor(descriptor.version);\n }\n if (deserializedItem.version === 0 ||\n deserializedItem.version === descriptor.version ||\n deserializedItem.item === undefined) {\n return deserializedItem;\n }\n // There was a mismatch between the version of the serialized descriptor and the deserialized\n // descriptor. So we are going to trust the version of the serialized descriptor.\n return {\n version: descriptor.version,\n item: deserializedItem.item,\n };\n}\n/**\n * Internal implementation of {@link LDFeatureStore} that delegates the basic functionality to an\n * instance of {@link PersistentDataStore}. It provides optional caching behavior and other logic\n * that would otherwise be repeated in every data store implementation. This makes it easier to\n * create new database integrations by implementing only the database-specific logic.\n */\nclass PersistentDataStoreWrapper {\n constructor(_core, ttl) {\n this._core = _core;\n this._isInitialized = false;\n /**\n * Used to preserve order of operations of async requests.\n */\n this._queue = new UpdateQueue_1.default();\n if (ttl) {\n this._itemCache = new TtlCache_1.default({\n ttl,\n checkInterval: defaultCheckInterval,\n });\n this._allItemsCache = new TtlCache_1.default({\n ttl,\n checkInterval: defaultCheckInterval,\n });\n }\n }\n init(allData, callback) {\n this._queue.enqueue((cb) => {\n const afterStoreInit = () => {\n this._isInitialized = true;\n if (this._itemCache) {\n this._itemCache.clear();\n this._allItemsCache.clear();\n Object.keys(allData).forEach((kindNamespace) => {\n const kind = persistentStoreKinds_1.persistentStoreKinds[kindNamespace];\n const items = allData[kindNamespace];\n this._allItemsCache.set(allForKindCacheKey(kind), items);\n Object.keys(items).forEach((key) => {\n const itemForKey = items[key];\n const itemDescriptor = {\n version: itemForKey.version,\n item: itemForKey,\n };\n this._itemCache.set(cacheKey(kind, key), itemDescriptor);\n });\n });\n }\n cb();\n };\n this._core.init((0, sortDataSet_1.default)(allData), afterStoreInit);\n }, callback);\n }\n get(kind, key, callback) {\n if (this._itemCache) {\n const item = this._itemCache.get(cacheKey(kind, key));\n if (item) {\n callback(itemIfNotDeleted(item));\n return;\n }\n }\n const persistKind = persistentStoreKinds_1.persistentStoreKinds[kind.namespace];\n this._core.get(persistKind, key, (descriptor) => {\n var _a;\n if (descriptor && descriptor.serializedItem) {\n const value = deserialize(persistKind, descriptor);\n (_a = this._itemCache) === null || _a === void 0 ? void 0 : _a.set(cacheKey(kind, key), value);\n callback(itemIfNotDeleted(value));\n return;\n }\n callback(null);\n });\n }\n initialized(callback) {\n var _a;\n if (this._isInitialized) {\n callback(true);\n }\n else if ((_a = this._itemCache) === null || _a === void 0 ? void 0 : _a.get(initializationCheckedKey)) {\n callback(false);\n }\n else {\n this._core.initialized((storeInitialized) => {\n var _a;\n this._isInitialized = storeInitialized;\n if (!this._isInitialized) {\n (_a = this._itemCache) === null || _a === void 0 ? void 0 : _a.set(initializationCheckedKey, true);\n }\n callback(this._isInitialized);\n });\n }\n }\n all(kind, callback) {\n var _a;\n const items = (_a = this._allItemsCache) === null || _a === void 0 ? void 0 : _a.get(allForKindCacheKey(kind));\n if (items) {\n callback(items);\n return;\n }\n const persistKind = persistentStoreKinds_1.persistentStoreKinds[kind.namespace];\n this._core.getAll(persistKind, (storeItems) => {\n var _a;\n if (!storeItems) {\n callback({});\n return;\n }\n const filteredItems = {};\n storeItems.forEach(({ key, item }) => {\n const deserializedItem = deserialize(persistKind, item);\n const filteredItem = itemIfNotDeleted(deserializedItem);\n if (filteredItem) {\n filteredItems[key] = filteredItem;\n }\n });\n (_a = this._allItemsCache) === null || _a === void 0 ? void 0 : _a.set(allForKindCacheKey(kind), filteredItems);\n callback(filteredItems);\n });\n }\n upsert(kind, data, callback) {\n this._queue.enqueue((cb) => {\n // Clear the caches which contain all the values of a specific kind.\n if (this._allItemsCache) {\n this._allItemsCache.clear();\n }\n const persistKind = persistentStoreKinds_1.persistentStoreKinds[kind.namespace];\n this._core.upsert(persistKind, data.key, persistKind.serialize(data), (err, updatedDescriptor) => {\n var _a, _b;\n if (!err && updatedDescriptor) {\n if (updatedDescriptor.serializedItem) {\n const value = deserialize(persistKind, updatedDescriptor);\n (_a = this._itemCache) === null || _a === void 0 ? void 0 : _a.set(cacheKey(kind, data.key), value);\n }\n else if (updatedDescriptor.deleted) {\n // Deleted and there was not a serialized representation.\n (_b = this._itemCache) === null || _b === void 0 ? void 0 : _b.set(data.key, {\n key: data.key,\n version: updatedDescriptor.version,\n deleted: true,\n });\n }\n }\n cb();\n });\n }, callback);\n }\n delete(kind, key, version, callback) {\n this.upsert(kind, { key, version, deleted: true }, callback);\n }\n close() {\n var _a, _b;\n (_a = this._itemCache) === null || _a === void 0 ? void 0 : _a.close();\n (_b = this._allItemsCache) === null || _b === void 0 ? void 0 : _b.close();\n this._core.close();\n }\n getDescription() {\n return this._core.getDescription();\n }\n}\nexports.default = PersistentDataStoreWrapper;\n//# sourceMappingURL=PersistentDataStoreWrapper.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass InMemoryFeatureStore {\n constructor() {\n this._allData = {};\n this._initCalled = false;\n }\n get(kind, key, callback) {\n const items = this._allData[kind.namespace];\n if (items) {\n if (Object.prototype.hasOwnProperty.call(items, key)) {\n const item = items[key];\n if (item && !item.deleted) {\n return callback === null || callback === void 0 ? void 0 : callback(item);\n }\n }\n }\n return callback === null || callback === void 0 ? void 0 : callback(null);\n }\n all(kind, callback) {\n var _a;\n const result = {};\n const items = (_a = this._allData[kind.namespace]) !== null && _a !== void 0 ? _a : {};\n Object.entries(items).forEach(([key, item]) => {\n if (item && !item.deleted) {\n result[key] = item;\n }\n });\n callback === null || callback === void 0 ? void 0 : callback(result);\n }\n init(allData, callback, initMetadata) {\n this.applyChanges(true, allData, callback, initMetadata);\n }\n delete(kind, key, version, callback) {\n const item = { key, version, deleted: true };\n this.applyChanges(false, {\n [kind.namespace]: {\n [key]: item,\n },\n }, callback);\n }\n upsert(kind, data, callback) {\n this.applyChanges(false, {\n [kind.namespace]: {\n [data.key]: data,\n },\n }, callback);\n }\n applyChanges(basis, data, callback, initMetadata, selector) {\n if (basis) {\n this._initCalled = true;\n this._allData = data;\n this._initMetadata = initMetadata;\n }\n else {\n const tempData = {};\n // shallow copy to protect against concurrent read\n Object.entries(this._allData).forEach(([namespace, items]) => {\n tempData[namespace] = Object.assign({}, items);\n });\n Object.entries(data).forEach(([namespace, items]) => {\n Object.keys(items || {}).forEach((key) => {\n let existingItems = tempData[namespace];\n if (!existingItems) {\n existingItems = {};\n tempData[namespace] = existingItems;\n }\n const item = items[key];\n if (Object.hasOwnProperty.call(existingItems, key)) {\n const old = existingItems[key];\n // TODO: SDK-1046 - Determine if version check should be removed\n if (!old || old.version < item.version) {\n existingItems[key] = Object.assign({ key }, item);\n }\n }\n else {\n existingItems[key] = Object.assign({ key }, item);\n }\n });\n });\n this._allData = tempData;\n }\n this._selector = selector;\n callback === null || callback === void 0 ? void 0 : callback();\n }\n initialized(callback) {\n return callback === null || callback === void 0 ? void 0 : callback(this._initCalled);\n }\n /* eslint-disable class-methods-use-this */\n close() {\n // For the memory store this is a no-op.\n }\n getDescription() {\n return 'memory';\n }\n getInitMetaData() {\n return this._initMetadata;\n }\n getSelector() {\n return this._selector;\n }\n}\nexports.default = InMemoryFeatureStore;\n//# sourceMappingURL=InMemoryFeatureStore.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst InMemoryFeatureStore_1 = require(\"./InMemoryFeatureStore\");\n/**\n * This decorator can take a non-transactional {@link LDFeatureStore} implementation\n * and adapt it to be transactional through the use of an in-memory store acting as\n * cache.\n */\nclass TransactionalFeatureStore {\n constructor(_nonTransPersistenceStore) {\n this._nonTransPersistenceStore = _nonTransPersistenceStore;\n // persistence store is inital active store\n this._activeStore = this._nonTransPersistenceStore;\n this._memoryStore = new InMemoryFeatureStore_1.default();\n }\n get(kind, key, callback) {\n this._activeStore.get(kind, key, callback);\n }\n all(kind, callback) {\n this._activeStore.all(kind, callback);\n }\n init(allData, callback) {\n // adapt to applyChanges for common handling\n this.applyChanges(true, allData, callback);\n }\n delete(kind, key, version, callback) {\n // adapt to applyChanges for common handling\n const item = { key, version, deleted: true };\n this.applyChanges(false, {\n [kind.namespace]: {\n [key]: item,\n },\n }, callback);\n }\n upsert(kind, data, callback) {\n // adapt to applyChanges for common handling\n this.applyChanges(false, {\n [kind.namespace]: {\n [data.key]: data,\n },\n }, callback);\n }\n applyChanges(basis, data, callback, initMetadata, selector) {\n this._memoryStore.applyChanges(basis, data, () => {\n // TODO: SDK-1047 conditional propgation to persistence based on parameter\n if (basis) {\n // basis causes memory store to become the active store\n this._activeStore = this._memoryStore;\n this._nonTransPersistenceStore.init(data, callback);\n }\n else {\n const params = [];\n Object.entries(data).forEach(([namespace, items]) => {\n Object.keys(items || {}).forEach((key) => {\n params.push({ dataKind: { namespace }, item: Object.assign({ key }, items[key]) });\n });\n });\n params\n .reduce((previousPromise, nextParams) => previousPromise.then(() => new Promise((resolve) => {\n this._nonTransPersistenceStore.upsert(nextParams.dataKind, nextParams.item, resolve);\n })), Promise.resolve())\n .then(callback);\n }\n }, initMetadata, selector);\n }\n initialized(callback) {\n // this is valid because the active store will only switch to the in memory store\n // after it has already been initialized itself\n this._activeStore.initialized(callback);\n }\n close() {\n this._nonTransPersistenceStore.close();\n this._memoryStore.close();\n }\n getDescription() {\n return 'transactional persistent store';\n }\n}\nexports.default = TransactionalFeatureStore;\n//# sourceMappingURL=TransactionalFeatureStore.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.reviveFullPayload = exports.deserializePoll = exports.TransactionalFeatureStore = exports.PersistentDataStoreWrapper = exports.AsyncTransactionalStoreFacade = exports.AsyncStoreFacade = void 0;\nconst AsyncStoreFacade_1 = require(\"./AsyncStoreFacade\");\nexports.AsyncStoreFacade = AsyncStoreFacade_1.default;\nconst AsyncTransactionalStoreFacade_1 = require(\"./AsyncTransactionalStoreFacade\");\nexports.AsyncTransactionalStoreFacade = AsyncTransactionalStoreFacade_1.default;\nconst PersistentDataStoreWrapper_1 = require(\"./PersistentDataStoreWrapper\");\nexports.PersistentDataStoreWrapper = PersistentDataStoreWrapper_1.default;\nconst serialization_1 = require(\"./serialization\");\nObject.defineProperty(exports, \"deserializePoll\", { enumerable: true, get: function () { return serialization_1.deserializePoll; } });\nObject.defineProperty(exports, \"reviveFullPayload\", { enumerable: true, get: function () { return serialization_1.reviveFullPayload; } });\nconst TransactionalFeatureStore_1 = require(\"./TransactionalFeatureStore\");\nexports.TransactionalFeatureStore = TransactionalFeatureStore_1.default;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst store_1 = require(\"../store\");\nconst VersionedDataKinds_1 = require(\"../store/VersionedDataKinds\");\nconst { initMetadataFromHeaders } = js_sdk_common_1.internal;\n/**\n * @internal\n */\nclass PollingProcessor {\n constructor(_requestor, _pollInterval, _featureStore, _logger, _initSuccessHandler = () => { }, _errorHandler) {\n this._requestor = _requestor;\n this._pollInterval = _pollInterval;\n this._featureStore = _featureStore;\n this._logger = _logger;\n this._initSuccessHandler = _initSuccessHandler;\n this._errorHandler = _errorHandler;\n this._stopped = false;\n }\n _poll() {\n var _a;\n if (this._stopped) {\n return;\n }\n const reportJsonError = (data) => {\n var _a, _b, _c;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error('Polling received invalid data');\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.debug(`Invalid JSON follows: ${data}`);\n (_c = this._errorHandler) === null || _c === void 0 ? void 0 : _c.call(this, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.InvalidData, 'Malformed JSON data in polling response'));\n };\n const startTime = Date.now();\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Polling LaunchDarkly for feature flag updates');\n this._requestor.requestAllData((err, body, headers) => {\n var _a, _b, _c, _d;\n const elapsed = Date.now() - startTime;\n const sleepFor = Math.max(this._pollInterval * 1000 - elapsed, 0);\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Elapsed: %d ms, sleeping for %d ms', elapsed, sleepFor);\n if (err) {\n const { status } = err;\n if (status && !(0, js_sdk_common_1.isHttpRecoverable)(status)) {\n const message = (0, js_sdk_common_1.httpErrorMessage)(err, 'polling request');\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error(message);\n (_c = this._errorHandler) === null || _c === void 0 ? void 0 : _c.call(this, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, message, status));\n // It is not recoverable, return and do not trigger another\n // poll.\n return;\n }\n (_d = this._logger) === null || _d === void 0 ? void 0 : _d.warn((0, js_sdk_common_1.httpErrorMessage)(err, 'polling request', 'will retry'));\n }\n else if (body) {\n const parsed = (0, store_1.deserializePoll)(body);\n if (!parsed) {\n // We could not parse this JSON. Report the problem and fallthrough to\n // start another poll.\n reportJsonError(body);\n }\n else {\n const initData = {\n [VersionedDataKinds_1.default.Features.namespace]: parsed.flags,\n [VersionedDataKinds_1.default.Segments.namespace]: parsed.segments,\n };\n this._featureStore.init(initData, () => {\n this._initSuccessHandler();\n // Triggering the next poll after the init has completed.\n this._timeoutHandle = setTimeout(() => {\n this._poll();\n }, sleepFor);\n }, initMetadataFromHeaders(headers));\n // The poll will be triggered by the feature store initialization\n // completing.\n return;\n }\n }\n // Falling through, there was some type of error and we need to trigger\n // a new poll.\n this._timeoutHandle = setTimeout(() => {\n this._poll();\n }, sleepFor);\n });\n }\n start() {\n this._poll();\n }\n stop() {\n if (this._timeoutHandle) {\n clearTimeout(this._timeoutHandle);\n this._timeoutHandle = undefined;\n }\n this._stopped = true;\n }\n close() {\n this.stop();\n }\n}\nexports.default = PollingProcessor;\n//# sourceMappingURL=PollingProcessor.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst serialization_1 = require(\"../store/serialization\");\nfunction selectorAsQueryParams(selector) {\n if (!selector) {\n return [];\n }\n return [\n {\n key: 'basis',\n value: selector,\n },\n ];\n}\n// helper function to transform FDv1 response data into events the PayloadProcessor can parse\nfunction processFDv1FlagsAndSegments(payloadProcessor, data) {\n const adaptor = js_sdk_common_1.internal.FDv1PayloadAdaptor(payloadProcessor);\n adaptor.useSelector('FDv1Fallback').processFullTransfer(data);\n}\n/**\n * @internal\n */\nclass PollingProcessorFDv2 {\n /**\n * @param _requestor to fetch flags\n * @param _pollInterval in seconds controlling how frequently polling request is made\n * @param _logger for logging\n * @param _processResponseAsFDv1 defaults to false, but if set to true, this data source will process\n * the response body as FDv1 and convert it into a FDv2 payload.\n */\n constructor(_requestor, _pollInterval = 30, _logger, _processResponseAsFDv1 = false) {\n this._requestor = _requestor;\n this._pollInterval = _pollInterval;\n this._logger = _logger;\n this._processResponseAsFDv1 = _processResponseAsFDv1;\n this._stopped = false;\n }\n _poll(dataCallback, statusCallback, selectorGetter) {\n var _a;\n if (this._stopped) {\n return;\n }\n const startTime = Date.now();\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Polling LaunchDarkly for feature flag updates');\n this._requestor.requestAllData((err, body, headers) => {\n var _a, _b, _c, _d, _e, _f, _g;\n if (this._stopped) {\n return;\n }\n const elapsed = Date.now() - startTime;\n const sleepFor = Math.max(this._pollInterval * 1000 - elapsed, 0);\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Elapsed: %d ms, sleeping for %d ms', elapsed, sleepFor);\n if (err) {\n const { status } = err;\n // this is a short term error and will be removed once FDv2 adoption is sufficient.\n if (err instanceof js_sdk_common_1.LDFlagDeliveryFallbackError) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error(err.message);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, err);\n // It is not recoverable, return and do not trigger another poll.\n return;\n }\n if (status && !(0, js_sdk_common_1.isHttpRecoverable)(status)) {\n const message = (0, js_sdk_common_1.httpErrorMessage)(err, 'polling request');\n (_c = this._logger) === null || _c === void 0 ? void 0 : _c.error(message);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, message, status, false));\n // It is not recoverable, return and do not trigger another poll.\n return;\n }\n const message = (0, js_sdk_common_1.httpErrorMessage)(err, 'polling request', 'will retry');\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Interrupted, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, message, status));\n (_d = this._logger) === null || _d === void 0 ? void 0 : _d.warn(message);\n // schedule poll\n this._timeoutHandle = setTimeout(() => {\n this._poll(dataCallback, statusCallback, selectorGetter);\n }, sleepFor);\n return;\n }\n const initMetadata = js_sdk_common_1.internal.initMetadataFromHeaders(headers);\n if (body) {\n try {\n const payloadProcessor = new js_sdk_common_1.internal.PayloadProcessor({\n flag: (flag) => {\n (0, serialization_1.processFlag)(flag);\n return flag;\n },\n segment: (segment) => {\n (0, serialization_1.processSegment)(segment);\n return segment;\n },\n }, (errorKind, message) => {\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Interrupted, new js_sdk_common_1.LDPollingError(errorKind, message));\n }, this._logger);\n payloadProcessor.addPayloadListener((payload) => {\n dataCallback(payload.basis, { initMetadata, payload });\n });\n (_e = this._logger) === null || _e === void 0 ? void 0 : _e.debug(`Got body: ${body}`);\n if (!this._processResponseAsFDv1) {\n // FDv2 case\n const parsed = JSON.parse(body);\n payloadProcessor.processEvents(parsed.events);\n }\n else {\n // FDv1 case\n const parsed = JSON.parse(body);\n processFDv1FlagsAndSegments(payloadProcessor, parsed);\n }\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Valid);\n }\n catch (_h) {\n // We could not parse this JSON. Report the problem and fallthrough to\n // start another poll.\n (_f = this._logger) === null || _f === void 0 ? void 0 : _f.error('Response contained invalid data');\n (_g = this._logger) === null || _g === void 0 ? void 0 : _g.debug(`${err} - Body follows: ${body}`);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Interrupted, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.InvalidData, 'Malformed data in polling response'));\n }\n }\n // schedule poll\n this._timeoutHandle = setTimeout(() => {\n this._poll(dataCallback, statusCallback, selectorGetter);\n }, sleepFor);\n }, selectorAsQueryParams(selectorGetter === null || selectorGetter === void 0 ? void 0 : selectorGetter()));\n }\n start(dataCallback, statusCallback, selectorGetter) {\n this._statusCallback = statusCallback; // hold reference for usage in stop()\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Initializing);\n this._poll(dataCallback, statusCallback, selectorGetter);\n }\n stop() {\n var _a;\n if (this._timeoutHandle) {\n clearTimeout(this._timeoutHandle);\n this._timeoutHandle = undefined;\n }\n (_a = this._statusCallback) === null || _a === void 0 ? void 0 : _a.call(this, js_sdk_common_1.subsystem.DataSourceState.Closed);\n this._stopped = true;\n this._statusCallback = undefined;\n }\n}\nexports.default = PollingProcessorFDv2;\n//# sourceMappingURL=PollingProcessorFDv2.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\n/**\n * @internal\n */\nclass Requestor {\n constructor(config, _requests, baseHeaders, _path = '/sdk/latest-all', _logger) {\n this._requests = _requests;\n this._path = _path;\n this._logger = _logger;\n this._eTagCache = {};\n this._headers = Object.assign({}, baseHeaders);\n this._serviceEndpoints = config.serviceEndpoints;\n }\n /**\n * Perform a request and utilize the ETag cache. The ETags are cached in the\n * requestor instance.\n */\n async _requestWithETagCache(requestUrl, options) {\n const cacheEntry = this._eTagCache[requestUrl];\n const cachedETag = cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.etag;\n const updatedOptions = cachedETag\n ? Object.assign(Object.assign({}, options), { headers: Object.assign(Object.assign({}, options.headers), { 'if-none-match': cachedETag }) }) : options;\n const res = await this._requests.fetch(requestUrl, updatedOptions);\n if (res.status === 304 && cacheEntry) {\n return { res, body: cacheEntry.body };\n }\n const etag = res.headers.get('etag');\n const body = await res.text();\n if (etag) {\n this._eTagCache[requestUrl] = { etag, body };\n }\n return { res, body };\n }\n async requestAllData(cb, queryParams = []) {\n var _a, _b;\n const options = {\n method: 'GET',\n headers: this._headers,\n };\n const uri = (0, js_sdk_common_1.getPollingUri)(this._serviceEndpoints, this._path, queryParams);\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug(`Requestor making request to uri: ${uri}`);\n try {\n const { res, body } = await this._requestWithETagCache(uri, options);\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.debug(`Requestor got (possibly cached) body: ${JSON.stringify(body)}`);\n if (res.headers.get(`x-ld-fd-fallback`) === `true`) {\n const err = new js_sdk_common_1.LDFlagDeliveryFallbackError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, `Response header indicates to fallback to FDv1.`, res.status);\n return cb(err, undefined, undefined);\n }\n if (res.status !== 200 && res.status !== 304) {\n const err = new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, `Unexpected status code: ${res.status}`, res.status);\n return cb(err, undefined, undefined);\n }\n return cb(undefined, res.status === 304 ? null : body, Object.fromEntries(res.headers.entries()));\n }\n catch (err) {\n return cb(err, undefined, undefined);\n }\n }\n}\nexports.default = Requestor;\n//# sourceMappingURL=Requestor.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst reportJsonError = (type, data, logger, errorHandler) => {\n logger === null || logger === void 0 ? void 0 : logger.error(`Stream received invalid data in \"${type}\" message`);\n logger === null || logger === void 0 ? void 0 : logger.debug(`Invalid JSON follows: ${data}`);\n errorHandler === null || errorHandler === void 0 ? void 0 : errorHandler(new js_sdk_common_1.LDStreamingError(js_sdk_common_1.DataSourceErrorKind.InvalidData, 'Malformed JSON data in event stream'));\n};\nclass StreamingProcessor {\n constructor(clientContext, streamUriPath, parameters, _listeners, baseHeaders, _diagnosticsManager, _errorHandler, _streamInitialReconnectDelay = 1) {\n this._listeners = _listeners;\n this._diagnosticsManager = _diagnosticsManager;\n this._errorHandler = _errorHandler;\n this._streamInitialReconnectDelay = _streamInitialReconnectDelay;\n const { basicConfiguration, platform } = clientContext;\n const { logger } = basicConfiguration;\n const { requests } = platform;\n this._headers = Object.assign({}, baseHeaders);\n this._logger = logger;\n this._requests = requests;\n this._streamUri = (0, js_sdk_common_1.getStreamingUri)(basicConfiguration.serviceEndpoints, streamUriPath, parameters);\n }\n _logConnectionStarted() {\n this._connectionAttemptStartTime = Date.now();\n }\n _logConnectionResult(success) {\n if (this._connectionAttemptStartTime && this._diagnosticsManager) {\n this._diagnosticsManager.recordStreamInit(this._connectionAttemptStartTime, !success, Date.now() - this._connectionAttemptStartTime);\n }\n this._connectionAttemptStartTime = undefined;\n }\n /**\n * This is a wrapper around the passed errorHandler which adds additional\n * diagnostics and logging logic.\n *\n * @param err The error to be logged and handled.\n * @return boolean whether to retry the connection.\n *\n * @private\n */\n _retryAndHandleError(err) {\n var _a, _b, _c;\n if (!(0, js_sdk_common_1.shouldRetry)(err)) {\n this._logConnectionResult(false);\n (_a = this._errorHandler) === null || _a === void 0 ? void 0 : _a.call(this, new js_sdk_common_1.LDStreamingError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, err.message, err.status));\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error((0, js_sdk_common_1.httpErrorMessage)(err, 'streaming request'));\n return false;\n }\n (_c = this._logger) === null || _c === void 0 ? void 0 : _c.warn((0, js_sdk_common_1.httpErrorMessage)(err, 'streaming request', 'will retry'));\n this._logConnectionResult(false);\n this._logConnectionStarted();\n return true;\n }\n start() {\n this._logConnectionStarted();\n // TLS is handled by the platform implementation.\n const eventSource = this._requests.createEventSource(this._streamUri, {\n headers: this._headers,\n errorFilter: (error) => this._retryAndHandleError(error),\n initialRetryDelayMillis: 1000 * this._streamInitialReconnectDelay,\n readTimeoutMillis: 5 * 60 * 1000,\n retryResetIntervalMillis: 60 * 1000,\n });\n this._eventSource = eventSource;\n eventSource.onclose = () => {\n var _a;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.info('Closed LaunchDarkly stream connection');\n };\n eventSource.onerror = () => {\n // The work is done by `errorFilter`.\n };\n eventSource.onopen = (e) => {\n var _a;\n this._initHeaders = e.headers;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.info('Opened LaunchDarkly stream connection');\n };\n eventSource.onretrying = (e) => {\n var _a;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.info(`Will retry stream connection in ${e.delayMillis} milliseconds`);\n };\n this._listeners.forEach(({ deserializeData, processJson }, eventName) => {\n eventSource.addEventListener(eventName, (event) => {\n var _a, _b;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug(`Received ${eventName} event`);\n if (event === null || event === void 0 ? void 0 : event.data) {\n this._logConnectionResult(true);\n const { data } = event;\n const dataJson = deserializeData(data);\n if (!dataJson) {\n reportJsonError(eventName, data, this._logger, this._errorHandler);\n return;\n }\n processJson(dataJson, this._initHeaders);\n }\n else {\n (_b = this._errorHandler) === null || _b === void 0 ? void 0 : _b.call(this, new js_sdk_common_1.LDStreamingError(js_sdk_common_1.DataSourceErrorKind.Unknown, 'Unexpected payload from event stream'));\n }\n });\n });\n }\n stop() {\n var _a;\n (_a = this._eventSource) === null || _a === void 0 ? void 0 : _a.close();\n this._eventSource = undefined;\n }\n close() {\n this.stop();\n }\n}\nexports.default = StreamingProcessor;\n//# sourceMappingURL=StreamingProcessor.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst serialization_1 = require(\"../store/serialization\");\nclass StreamingProcessorFDv2 {\n constructor(clientContext, _streamUriPath, _parameters, baseHeaders, _diagnosticsManager, _streamInitialReconnectDelay = 1) {\n this._streamUriPath = _streamUriPath;\n this._parameters = _parameters;\n this._diagnosticsManager = _diagnosticsManager;\n this._streamInitialReconnectDelay = _streamInitialReconnectDelay;\n const { basicConfiguration, platform } = clientContext;\n const { logger, serviceEndpoints } = basicConfiguration;\n const { requests } = platform;\n this._headers = Object.assign({}, baseHeaders);\n this._serviceEndpoints = serviceEndpoints;\n this._logger = logger;\n this._requests = requests;\n }\n _logConnectionAttempt() {\n this._connectionAttemptStartTime = Date.now();\n }\n _logConnectionResult(success) {\n if (this._connectionAttemptStartTime && this._diagnosticsManager) {\n this._diagnosticsManager.recordStreamInit(this._connectionAttemptStartTime, !success, Date.now() - this._connectionAttemptStartTime);\n }\n this._connectionAttemptStartTime = undefined;\n }\n /**\n * This is a wrapper around the passed errorHandler which adds additional\n * diagnostics and logging logic.\n *\n * @param err The error to be logged and handled.\n * @return boolean whether to retry the connection.\n *\n * @private\n */\n _retryAndHandleError(err, statusCallback) {\n var _a, _b, _c;\n // this is a short term error and will be removed once FDv2 adoption is sufficient.\n if (((_a = err.headers) === null || _a === void 0 ? void 0 : _a[`x-ld-fd-fallback`]) === `true`) {\n const fallbackErr = new js_sdk_common_1.LDFlagDeliveryFallbackError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, `Response header indicates to fallback to FDv1`, err.status);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, fallbackErr);\n return false;\n }\n if (!(0, js_sdk_common_1.shouldRetry)(err)) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error((0, js_sdk_common_1.httpErrorMessage)(err, 'streaming request'));\n this._logConnectionResult(false);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, new js_sdk_common_1.LDStreamingError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, err.message, err.status, false));\n return false;\n }\n (_c = this._logger) === null || _c === void 0 ? void 0 : _c.warn((0, js_sdk_common_1.httpErrorMessage)(err, 'streaming request', 'will retry'));\n this._logConnectionResult(false);\n this._logConnectionAttempt();\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Interrupted);\n return true;\n }\n start(dataCallback, statusCallback, selectorGetter) {\n var _a;\n this._logConnectionAttempt();\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Initializing);\n const selector = selectorGetter === null || selectorGetter === void 0 ? void 0 : selectorGetter();\n const params = selector\n ? [...this._parameters, { key: 'basis', value: selector }] // if selector exists add basis parameter\n : this._parameters; // otherwise use params as is\n const uri = (0, js_sdk_common_1.getStreamingUri)(this._serviceEndpoints, this._streamUriPath, params);\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug(`Streaming processor opening event source to uri: ${uri}`);\n const eventSource = this._requests.createEventSource(uri, {\n headers: this._headers,\n errorFilter: (error) => this._retryAndHandleError(error, statusCallback),\n initialRetryDelayMillis: 1000 * this._streamInitialReconnectDelay,\n readTimeoutMillis: 5 * 60 * 1000,\n retryResetIntervalMillis: 60 * 1000,\n });\n this._eventSource = eventSource;\n const payloadReader = new js_sdk_common_1.internal.PayloadStreamReader(eventSource, {\n flag: (flag) => {\n (0, serialization_1.processFlag)(flag);\n return flag;\n },\n segment: (segment) => {\n (0, serialization_1.processSegment)(segment);\n return segment;\n },\n }, (errorKind, message) => {\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Interrupted, new js_sdk_common_1.LDStreamingError(errorKind, message));\n // parsing error was encountered, defensively close the data source\n this.stop();\n }, this._logger);\n payloadReader.addPayloadListener((payload) => {\n this._logConnectionResult(true);\n dataCallback(payload.basis, { initMetadata: this._initMetadata, payload });\n });\n eventSource.onclose = () => {\n var _a;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.info('Closed LaunchDarkly stream connection');\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed);\n };\n eventSource.onerror = () => {\n // The work is done by `errorFilter`.\n };\n eventSource.onopen = (e) => {\n var _a;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.info('Opened LaunchDarkly stream connection');\n this._initMetadata = js_sdk_common_1.internal.initMetadataFromHeaders(e.headers);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Valid);\n };\n eventSource.onretrying = (e) => {\n var _a;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.info(`Will retry stream connection in ${e.delayMillis} milliseconds`);\n };\n }\n stop() {\n var _a;\n (_a = this._eventSource) === null || _a === void 0 ? void 0 : _a.close();\n this._eventSource = undefined;\n }\n close() {\n this.stop();\n }\n}\nexports.default = StreamingProcessorFDv2;\n//# sourceMappingURL=StreamingProcessorFDv2.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst VersionedDataKinds_1 = require(\"../store/VersionedDataKinds\");\nconst DataSourceUpdates_1 = require(\"./DataSourceUpdates\");\nconst DependencyTracker_1 = require(\"./DependencyTracker\");\nconst NamespacedDataSet_1 = require(\"./NamespacedDataSet\");\n/**\n * @internal\n */\nclass TransactionalDataSourceUpdates {\n constructor(_featureStore, _hasEventListeners, _onChange) {\n this._featureStore = _featureStore;\n this._hasEventListeners = _hasEventListeners;\n this._onChange = _onChange;\n this._dependencyTracker = new DependencyTracker_1.default();\n }\n init(allData, callback, initMetadata) {\n this.applyChanges(true, allData, callback, initMetadata); // basis is true for init\n }\n upsert(kind, data, callback) {\n this.applyChanges(false, // basis is false for upserts\n {\n [kind.namespace]: {\n [data.key]: data,\n },\n }, callback);\n }\n applyChanges(basis, data, callback, initMetadata, selector) {\n const checkForChanges = this._hasEventListeners();\n const doApplyChanges = (oldData) => {\n this._featureStore.applyChanges(basis, data, () => {\n // Defer change events so they execute after the callback.\n Promise.resolve().then(() => {\n if (basis) {\n this._dependencyTracker.reset();\n }\n Object.entries(data).forEach(([namespace, items]) => {\n Object.keys(items || {}).forEach((key) => {\n const item = items[key];\n this._dependencyTracker.updateDependenciesFrom(namespace, key, (0, DataSourceUpdates_1.computeDependencies)(namespace, item));\n });\n });\n if (checkForChanges) {\n const updatedItems = new NamespacedDataSet_1.default();\n Object.keys(data).forEach((namespace) => {\n const oldDataForKind = oldData[namespace];\n const newDataForKind = data[namespace];\n let iterateData;\n if (basis) {\n // for basis, need to iterate on all keys\n iterateData = Object.assign(Object.assign({}, oldDataForKind), newDataForKind);\n }\n else {\n // for non basis, only need to iterate on keys in incoming data\n iterateData = Object.assign({}, newDataForKind);\n }\n Object.keys(iterateData).forEach((key) => {\n this.addIfModified(namespace, key, oldDataForKind && oldDataForKind[key], newDataForKind && newDataForKind[key], updatedItems);\n });\n });\n this.sendChangeEvents(updatedItems);\n }\n });\n callback === null || callback === void 0 ? void 0 : callback();\n }, initMetadata, selector);\n };\n let oldData = {};\n if (checkForChanges) {\n // record old data before making changes to use for change calculations\n this._featureStore.all(VersionedDataKinds_1.default.Features, (oldFlags) => {\n this._featureStore.all(VersionedDataKinds_1.default.Segments, (oldSegments) => {\n oldData = {\n [VersionedDataKinds_1.default.Features.namespace]: oldFlags,\n [VersionedDataKinds_1.default.Segments.namespace]: oldSegments,\n };\n });\n });\n }\n doApplyChanges(oldData);\n }\n addIfModified(namespace, key, oldValue, newValue, toDataSet) {\n if (newValue && oldValue && newValue.version <= oldValue.version) {\n return;\n }\n this._dependencyTracker.updateModifiedItems(toDataSet, namespace, key);\n }\n sendChangeEvents(dataSet) {\n dataSet.enumerate((namespace, key) => {\n if (namespace === VersionedDataKinds_1.default.Features.namespace) {\n this._onChange(key);\n }\n });\n }\n}\nexports.default = TransactionalDataSourceUpdates;\n//# sourceMappingURL=TransactionalDataSourceUpdates.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.defaultValues = exports.DEFAULT_STREAM_RECONNECT_DELAY = exports.DEFAULT_POLL_INTERVAL = void 0;\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst LDDataSystemOptions_1 = require(\"../api/options/LDDataSystemOptions\");\nconst InMemoryFeatureStore_1 = require(\"../store/InMemoryFeatureStore\");\n// Once things are internal to the implementation of the SDK we can depend on\n// types. Calls to the SDK could contain anything without any regard to typing.\n// So, data we take from external sources must be normalized into something\n// that can be trusted.\n/**\n * These perform cursory validations. Complex objects are implemented with classes\n * and these should allow for conditional construction.\n */\nconst validations = {\n baseUri: js_sdk_common_1.TypeValidators.String,\n streamUri: js_sdk_common_1.TypeValidators.String,\n eventsUri: js_sdk_common_1.TypeValidators.String,\n timeout: js_sdk_common_1.TypeValidators.Number,\n capacity: js_sdk_common_1.TypeValidators.Number,\n logger: js_sdk_common_1.TypeValidators.Object,\n featureStore: js_sdk_common_1.TypeValidators.ObjectOrFactory,\n dataSystem: js_sdk_common_1.TypeValidators.Object,\n bigSegments: js_sdk_common_1.TypeValidators.Object,\n updateProcessor: js_sdk_common_1.TypeValidators.ObjectOrFactory,\n flushInterval: js_sdk_common_1.TypeValidators.Number,\n pollInterval: js_sdk_common_1.TypeValidators.numberWithMin(30),\n proxyOptions: js_sdk_common_1.TypeValidators.Object,\n offline: js_sdk_common_1.TypeValidators.Boolean,\n stream: js_sdk_common_1.TypeValidators.Boolean,\n streamInitialReconnectDelay: js_sdk_common_1.TypeValidators.Number,\n useLdd: js_sdk_common_1.TypeValidators.Boolean,\n sendEvents: js_sdk_common_1.TypeValidators.Boolean,\n allAttributesPrivate: js_sdk_common_1.TypeValidators.Boolean,\n privateAttributes: js_sdk_common_1.TypeValidators.StringArray,\n contextKeysCapacity: js_sdk_common_1.TypeValidators.Number,\n contextKeysFlushInterval: js_sdk_common_1.TypeValidators.Number,\n tlsParams: js_sdk_common_1.TypeValidators.Object,\n diagnosticOptOut: js_sdk_common_1.TypeValidators.Boolean,\n diagnosticRecordingInterval: js_sdk_common_1.TypeValidators.numberWithMin(60),\n wrapperName: js_sdk_common_1.TypeValidators.String,\n wrapperVersion: js_sdk_common_1.TypeValidators.String,\n application: js_sdk_common_1.TypeValidators.Object,\n payloadFilterKey: js_sdk_common_1.TypeValidators.stringMatchingRegex(/^[a-zA-Z0-9](\\w|\\.|-)*$/),\n hooks: js_sdk_common_1.TypeValidators.createTypeArray('Hook[]', {}),\n enableEventCompression: js_sdk_common_1.TypeValidators.Boolean,\n dataSourceOptionsType: js_sdk_common_1.TypeValidators.String,\n};\nexports.DEFAULT_POLL_INTERVAL = 30;\nexports.DEFAULT_STREAM_RECONNECT_DELAY = 1;\nconst defaultStandardDataSourceOptions = {\n dataSourceOptionsType: 'standard',\n streamInitialReconnectDelay: exports.DEFAULT_STREAM_RECONNECT_DELAY,\n pollInterval: exports.DEFAULT_POLL_INTERVAL,\n};\nconst defaultStreamingDataSourceOptions = {\n dataSourceOptionsType: 'streamingOnly',\n streamInitialReconnectDelay: exports.DEFAULT_STREAM_RECONNECT_DELAY,\n};\nconst defaultPollingDataSourceOptions = {\n dataSourceOptionsType: 'pollingOnly',\n pollInterval: exports.DEFAULT_POLL_INTERVAL,\n};\nconst defaultDataSystemOptions = {\n dataSource: defaultStandardDataSourceOptions,\n};\n/**\n * @internal\n */\nexports.defaultValues = {\n baseUri: 'https://sdk.launchdarkly.com',\n streamUri: 'https://stream.launchdarkly.com',\n eventsUri: js_sdk_common_1.ServiceEndpoints.DEFAULT_EVENTS,\n stream: true,\n streamInitialReconnectDelay: exports.DEFAULT_STREAM_RECONNECT_DELAY,\n sendEvents: true,\n timeout: 5,\n capacity: 10000,\n flushInterval: 5,\n pollInterval: exports.DEFAULT_POLL_INTERVAL,\n offline: false,\n useLdd: false,\n allAttributesPrivate: false,\n privateAttributes: [],\n contextKeysCapacity: 1000,\n contextKeysFlushInterval: 300,\n diagnosticOptOut: false,\n diagnosticRecordingInterval: 900,\n featureStore: () => new InMemoryFeatureStore_1.default(),\n enableEventCompression: false,\n dataSystem: defaultDataSystemOptions,\n};\nfunction validateTypesAndNames(options, defaults) {\n const errors = [];\n const validatedOptions = Object.assign({}, defaults);\n Object.keys(options).forEach((optionName) => {\n var _a;\n // We need to tell typescript it doesn't actually know what options are.\n // If we don't then it complains we are doing crazy things with it.\n const optionValue = options[optionName];\n const validator = validations[optionName];\n if (validator) {\n if (!validator.is(optionValue)) {\n if (validator.getType() === 'boolean') {\n errors.push(js_sdk_common_1.OptionMessages.wrongOptionTypeBoolean(optionName, typeof optionValue));\n validatedOptions[optionName] = !!optionValue;\n }\n else if (validator instanceof js_sdk_common_1.NumberWithMinimum &&\n js_sdk_common_1.TypeValidators.Number.is(optionValue)) {\n const { min } = validator;\n errors.push(js_sdk_common_1.OptionMessages.optionBelowMinimum(optionName, optionValue, min));\n validatedOptions[optionName] = min;\n }\n else {\n errors.push(js_sdk_common_1.OptionMessages.wrongOptionType(optionName, validator.getType(), typeof optionValue));\n validatedOptions[optionName] = exports.defaultValues[optionName];\n }\n }\n else {\n validatedOptions[optionName] = optionValue;\n }\n }\n else {\n (_a = options.logger) === null || _a === void 0 ? void 0 : _a.warn(js_sdk_common_1.OptionMessages.unknownOption(optionName));\n }\n });\n return { errors, validatedOptions };\n}\nfunction validateEndpoints(options, validatedOptions) {\n var _a, _b, _c;\n const { baseUri, streamUri, eventsUri } = options;\n const streamingEndpointSpecified = streamUri !== undefined && streamUri !== null;\n const pollingEndpointSpecified = baseUri !== undefined && baseUri !== null;\n const eventEndpointSpecified = eventsUri !== undefined && eventsUri !== null;\n if (streamingEndpointSpecified === pollingEndpointSpecified &&\n streamingEndpointSpecified === eventEndpointSpecified) {\n // Either everything is default, or everything is set.\n return;\n }\n if (!streamingEndpointSpecified && validatedOptions.stream) {\n (_a = validatedOptions.logger) === null || _a === void 0 ? void 0 : _a.warn(js_sdk_common_1.OptionMessages.partialEndpoint('streamUri'));\n }\n if (!pollingEndpointSpecified) {\n (_b = validatedOptions.logger) === null || _b === void 0 ? void 0 : _b.warn(js_sdk_common_1.OptionMessages.partialEndpoint('baseUri'));\n }\n if (!eventEndpointSpecified && validatedOptions.sendEvents) {\n (_c = validatedOptions.logger) === null || _c === void 0 ? void 0 : _c.warn(js_sdk_common_1.OptionMessages.partialEndpoint('eventsUri'));\n }\n}\nfunction validateDataSystemOptions(options) {\n const allErrors = [];\n const validatedOptions = Object.assign({}, options);\n if (options.persistentStore && !js_sdk_common_1.TypeValidators.ObjectOrFactory.is(options.persistentStore)) {\n validatedOptions.persistentStore = undefined; // default is to not use this\n allErrors.push(js_sdk_common_1.OptionMessages.wrongOptionType('persistentStore', 'LDFeatureStore', typeof options.persistentStore));\n }\n if (options.dataSource) {\n let errors;\n let validatedDataSourceOptions;\n if ((0, LDDataSystemOptions_1.isStandardOptions)(options.dataSource)) {\n ({ errors, validatedOptions: validatedDataSourceOptions } = validateTypesAndNames(options.dataSource, defaultStandardDataSourceOptions));\n }\n else if ((0, LDDataSystemOptions_1.isStreamingOnlyOptions)(options.dataSource)) {\n ({ errors, validatedOptions: validatedDataSourceOptions } = validateTypesAndNames(options.dataSource, defaultStreamingDataSourceOptions));\n }\n else if ((0, LDDataSystemOptions_1.isPollingOnlyOptions)(options.dataSource)) {\n ({ errors, validatedOptions: validatedDataSourceOptions } = validateTypesAndNames(options.dataSource, defaultPollingDataSourceOptions));\n }\n else if ((0, LDDataSystemOptions_1.isCustomOptions)(options.dataSource)) {\n validatedDataSourceOptions = options.dataSource;\n errors = [];\n }\n else {\n // provided datasource options don't fit any expected form, drop them and use defaults\n validatedDataSourceOptions = defaultStandardDataSourceOptions;\n errors = [\n js_sdk_common_1.OptionMessages.wrongOptionType('dataSource', 'DataSourceOptions', typeof options.dataSource),\n ];\n }\n validatedOptions.dataSource = validatedDataSourceOptions;\n allErrors.push(...errors);\n }\n else {\n // use default datasource options if no datasource was specified\n validatedOptions.dataSource = defaultStandardDataSourceOptions;\n }\n return { errors: allErrors, validatedOptions };\n}\n/**\n * Configuration options for the LDClient.\n *\n * @internal\n */\nclass Configuration {\n constructor(options = {}, internalOptions = {}) {\n var _a;\n // The default will handle undefined, but not null.\n // Because we can be called from JS we need to be extra defensive.\n // eslint-disable-next-line no-param-reassign\n options = options || {};\n // If there isn't a valid logger from the platform, then logs would go nowhere.\n this.logger = options.logger;\n const { errors, validatedOptions: topLevelResult } = validateTypesAndNames(options, exports.defaultValues);\n const validatedOptions = topLevelResult;\n errors.forEach((error) => {\n var _a;\n (_a = this.logger) === null || _a === void 0 ? void 0 : _a.warn(error);\n });\n validateEndpoints(options, validatedOptions);\n if (options.dataSystem) {\n // validate the data system options, this will also apply reasonable defaults\n const { errors: dsErrors, validatedOptions: dsResult } = validateDataSystemOptions(options.dataSystem);\n const validatedDSOptions = dsResult;\n this.dataSystem = {\n dataSource: validatedDSOptions.dataSource,\n useLdd: validatedDSOptions.useLdd,\n // @ts-ignore\n featureStoreFactory: (clientContext) => {\n if (validatedDSOptions.persistentStore === undefined) {\n // the persistent store provided was either undefined or invalid, default to memory store\n return new InMemoryFeatureStore_1.default();\n }\n if (js_sdk_common_1.TypeValidators.Function.is(validatedDSOptions.persistentStore)) {\n return validatedDSOptions.persistentStore(clientContext);\n }\n return validatedDSOptions.persistentStore;\n },\n };\n dsErrors.forEach((error) => {\n var _a;\n (_a = this.logger) === null || _a === void 0 ? void 0 : _a.warn(error);\n });\n }\n this.serviceEndpoints = new js_sdk_common_1.ServiceEndpoints(validatedOptions.streamUri, validatedOptions.baseUri, validatedOptions.eventsUri, internalOptions.analyticsEventPath, internalOptions.diagnosticEventPath, internalOptions.includeAuthorizationHeader, validatedOptions.payloadFilterKey);\n this.eventsCapacity = validatedOptions.capacity;\n this.timeout = validatedOptions.timeout;\n this.bigSegments = validatedOptions.bigSegments;\n this.flushInterval = validatedOptions.flushInterval;\n this.pollInterval = validatedOptions.pollInterval;\n this.proxyOptions = validatedOptions.proxyOptions;\n this.offline = validatedOptions.offline;\n this.stream = validatedOptions.stream;\n this.streamInitialReconnectDelay = validatedOptions.streamInitialReconnectDelay;\n this.useLdd = validatedOptions.useLdd;\n this.sendEvents = validatedOptions.sendEvents;\n this.allAttributesPrivate = validatedOptions.allAttributesPrivate;\n this.privateAttributes = validatedOptions.privateAttributes;\n this.contextKeysCapacity = validatedOptions.contextKeysCapacity;\n this.contextKeysFlushInterval = validatedOptions.contextKeysFlushInterval;\n this.tlsParams = validatedOptions.tlsParams;\n this.diagnosticOptOut = validatedOptions.diagnosticOptOut;\n this.wrapperName = validatedOptions.wrapperName;\n this.payloadFilterKey = validatedOptions.payloadFilterKey;\n this.wrapperVersion = validatedOptions.wrapperVersion;\n this.tags = new js_sdk_common_1.ApplicationTags(validatedOptions);\n this.diagnosticRecordingInterval = validatedOptions.diagnosticRecordingInterval;\n if (js_sdk_common_1.TypeValidators.Function.is(validatedOptions.updateProcessor)) {\n // @ts-ignore\n this.updateProcessorFactory = validatedOptions.updateProcessor;\n }\n else {\n // The processor is already created, just have the method return it.\n // @ts-ignore\n this.updateProcessorFactory = () => validatedOptions.updateProcessor;\n }\n if (js_sdk_common_1.TypeValidators.Function.is(validatedOptions.featureStore)) {\n // @ts-ignore\n this.featureStoreFactory = validatedOptions.featureStore;\n }\n else {\n // The store is already created, just have the method return it.\n // @ts-ignore\n this.featureStoreFactory = () => validatedOptions.featureStore;\n }\n this.hooks = validatedOptions.hooks;\n this.enableEventCompression = validatedOptions.enableEventCompression;\n this.getImplementationHooks = (_a = internalOptions.getImplementationHooks) !== null && _a !== void 0 ? _a : (() => []);\n this.applicationInfo = validatedOptions.application;\n }\n}\nexports.default = Configuration;\n//# sourceMappingURL=Configuration.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst api_1 = require(\"../api\");\nconst Configuration_1 = require(\"../options/Configuration\");\nconst createDiagnosticsInitConfig = (config, platform, featureStore) => {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;\n let pollingIntervalMillis;\n if ((_a = config.dataSystem) === null || _a === void 0 ? void 0 : _a.dataSource) {\n if (((0, api_1.isStandardOptions)(config.dataSystem.dataSource) ||\n (0, api_1.isPollingOnlyOptions)(config.dataSystem.dataSource)) &&\n config.dataSystem.dataSource.pollInterval) {\n pollingIntervalMillis = (0, js_sdk_common_1.secondsToMillis)(config.dataSystem.dataSource.pollInterval);\n }\n }\n else {\n pollingIntervalMillis = (0, js_sdk_common_1.secondsToMillis)(config.pollInterval);\n }\n let reconnectTimeMillis;\n if ((_b = config.dataSystem) === null || _b === void 0 ? void 0 : _b.dataSource) {\n if (((0, api_1.isStandardOptions)(config.dataSystem.dataSource) ||\n (0, api_1.isStreamingOnlyOptions)(config.dataSystem.dataSource)) &&\n config.dataSystem.dataSource.streamInitialReconnectDelay) {\n reconnectTimeMillis = (0, js_sdk_common_1.secondsToMillis)(config.dataSystem.dataSource.streamInitialReconnectDelay);\n }\n }\n else {\n reconnectTimeMillis = (0, js_sdk_common_1.secondsToMillis)(config.streamInitialReconnectDelay);\n }\n let streamDisabled;\n if ((_c = config.dataSystem) === null || _c === void 0 ? void 0 : _c.dataSource) {\n streamDisabled = (0, api_1.isPollingOnlyOptions)((_d = config.dataSystem) === null || _d === void 0 ? void 0 : _d.dataSource);\n }\n else {\n streamDisabled = !config.stream;\n }\n return Object.assign(Object.assign(Object.assign({ customBaseURI: config.serviceEndpoints.polling !== Configuration_1.defaultValues.baseUri, customStreamURI: config.serviceEndpoints.streaming !== Configuration_1.defaultValues.streamUri, customEventsURI: config.serviceEndpoints.events !== Configuration_1.defaultValues.eventsUri, eventsCapacity: config.eventsCapacity, \n // Node doesn't distinguish between these two kinds of timeouts. It is unlikely other web\n // based implementations would be able to either.\n connectTimeoutMillis: (0, js_sdk_common_1.secondsToMillis)(config.timeout), socketTimeoutMillis: (0, js_sdk_common_1.secondsToMillis)(config.timeout), eventsFlushIntervalMillis: (0, js_sdk_common_1.secondsToMillis)(config.flushInterval) }, (pollingIntervalMillis ? { pollingIntervalMillis } : null)), (reconnectTimeMillis ? { reconnectTimeMillis } : null)), { contextKeysFlushIntervalMillis: (0, js_sdk_common_1.secondsToMillis)(config.contextKeysFlushInterval), diagnosticRecordingIntervalMillis: (0, js_sdk_common_1.secondsToMillis)(config.diagnosticRecordingInterval), streamingDisabled: streamDisabled, usingRelayDaemon: (_f = (_e = config.dataSystem) === null || _e === void 0 ? void 0 : _e.useLdd) !== null && _f !== void 0 ? _f : config.useLdd, offline: config.offline, allAttributesPrivate: config.allAttributesPrivate, contextKeysCapacity: config.contextKeysCapacity, usingProxy: !!((_h = (_g = platform.requests).usingProxy) === null || _h === void 0 ? void 0 : _h.call(_g)), usingProxyAuthenticator: !!((_k = (_j = platform.requests).usingProxyAuth) === null || _k === void 0 ? void 0 : _k.call(_j)), dataStoreType: (_m = (_l = featureStore.getDescription) === null || _l === void 0 ? void 0 : _l.call(featureStore)) !== null && _m !== void 0 ? _m : 'memory' });\n};\nexports.default = createDiagnosticsInitConfig;\n//# sourceMappingURL=createDiagnosticsInitConfig.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.allAsync = exports.firstSeriesAsync = exports.allSeriesAsync = exports.firstResult = void 0;\n/**\n * Iterate a collection any apply the specified operation. The first operation which\n * returns a value will be returned and iteration will stop.\n *\n * @param collection The collection to enumerate.\n * @param operator The operation to apply to each item.\n * @returns The result of the first successful operation.\n */\nfunction firstResult(collection, operator) {\n let res;\n collection === null || collection === void 0 ? void 0 : collection.some((item, index) => {\n res = operator(item, index);\n return !!res;\n });\n return res;\n}\nexports.firstResult = firstResult;\nconst ITERATION_RECURSION_LIMIT = 50;\nfunction seriesAsync(collection, check, all, index, cb) {\n if (!collection) {\n cb(false);\n return;\n }\n if (index < (collection === null || collection === void 0 ? void 0 : collection.length)) {\n check(collection[index], index, (res) => {\n if (all) {\n if (!res) {\n cb(false);\n return;\n }\n }\n else if (res) {\n cb(true);\n return;\n }\n if (collection.length > ITERATION_RECURSION_LIMIT) {\n // When we hit the recursion limit we defer execution\n // by using a resolved promise. This is similar to using setImmediate\n // but more portable.\n Promise.resolve().then(() => {\n seriesAsync(collection, check, all, index + 1, cb);\n });\n }\n else {\n seriesAsync(collection, check, all, index + 1, cb);\n }\n });\n }\n else {\n cb(all);\n }\n}\n/**\n * Iterate a collection in series awaiting each check operation.\n * @param collection The collection to iterate.\n * @param check The check to perform for each item in the container.\n * @param cb Called with true if all items pass the check.\n */\nfunction allSeriesAsync(collection, check, cb) {\n seriesAsync(collection, check, true, 0, cb);\n}\nexports.allSeriesAsync = allSeriesAsync;\n/**\n * Iterate a collection in series awaiting each check operation.\n * @param collection The collection to iterate.\n * @param check The check to perform for each item in the container.\n * @param cb called with true on the first item that passes the check. False\n * means no items passed the check.\n */\nfunction firstSeriesAsync(collection, check, cb) {\n seriesAsync(collection, check, false, 0, cb);\n}\nexports.firstSeriesAsync = firstSeriesAsync;\n/**\n * Iterate a collection and execute the the given check operation\n * for all items concurrently.\n * @param collection The collection to iterate.\n * @param check The check to run for each item.\n * @param cb Callback executed when all items have been checked. The callback\n * will be called with true if each item resulted in true, otherwise it will\n * be called with false.\n */\nfunction allAsync(collection, check, cb) {\n if (!collection) {\n cb(false);\n return;\n }\n Promise.all(collection === null || collection === void 0 ? void 0 : collection.map((item) => new Promise((resolve) => {\n check(item, resolve);\n }))).then((results) => {\n cb(results.every((success) => success));\n });\n}\nexports.allAsync = allAsync;\n//# sourceMappingURL=collection.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * A set of static evaluation reasons and methods for creating specific reason instances.\n *\n * @internal\n */\nclass Reasons {\n static prerequisiteFailed(prerequisiteKey) {\n return { kind: 'PREREQUISITE_FAILED', prerequisiteKey };\n }\n static ruleMatch(ruleId, ruleIndex) {\n return { kind: 'RULE_MATCH', ruleId, ruleIndex };\n }\n}\nReasons.Fallthrough = { kind: 'FALLTHROUGH' };\nReasons.Off = { kind: 'OFF' };\nReasons.TargetMatch = { kind: 'TARGET_MATCH' };\nexports.default = Reasons;\n//# sourceMappingURL=Reasons.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Reasons_1 = require(\"./Reasons\");\n/**\n * A class which encapsulates the result of an evaluation. It allows for differentiating between\n * successful and error result types.\n *\n * @internal\n */\nclass EvalResult {\n constructor(isError, detail, message) {\n this.isError = isError;\n this.detail = detail;\n this.message = message;\n this.isError = isError;\n this.detail = detail;\n this.message = message;\n }\n get isOff() {\n return this.detail.reason.kind === Reasons_1.default.Off.kind;\n }\n setDefault(def) {\n this.detail.value = def;\n }\n static forError(errorKind, message, def) {\n return new EvalResult(true, {\n value: def !== null && def !== void 0 ? def : null,\n variationIndex: null,\n reason: { kind: 'ERROR', errorKind },\n }, message);\n }\n static forSuccess(value, reason, variationIndex) {\n return new EvalResult(false, {\n value,\n variationIndex: variationIndex === undefined ? null : variationIndex,\n reason,\n });\n }\n}\nexports.default = EvalResult;\n//# sourceMappingURL=EvalResult.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Bucketing can be done by string or integer values. The need to be converted to a string\n * for the hashing process.\n * @param value The value to get a bucketable value for.\n * @returns The value as a string, or null if the value cannot be used for bucketing.\n */\nfunction valueForBucketing(value) {\n if (typeof value === 'string') {\n return value;\n }\n if (Number.isInteger(value)) {\n return String(value);\n }\n return null;\n}\nclass Bucketer {\n constructor(crypto) {\n this._crypto = crypto;\n }\n _sha1Hex(value) {\n const hash = this._crypto.createHash('sha1');\n hash.update(value);\n if (!hash.digest) {\n // This represents an error in platform implementation.\n throw new Error('Platform must implement digest or asyncDigest');\n }\n return hash.digest('hex');\n }\n /**\n * Bucket the provided context using the provided parameters.\n * @param context The context to bucket. Can be a 'multi' kind context, but\n * the bucketing will be by a specific contained kind.\n * @param key A key to use in hashing. Typically the flag key or the segment key.\n * @param attr The attribute to use for bucketing.\n * @param salt A salt to use in hashing.\n * @param kindForRollout The kind to use for bucketing.\n * @param seed A seed to use in hashing.\n *\n * @returns A tuple where the first value is the bucket, and the second value indicates if there\n * was a context for the value specified by `kindForRollout`. If there was not a context for the\n * specified kind, then the `inExperiment` attribute should be `false`.\n */\n bucket(context, key, attr, salt, kindForRollout = 'user', seed) {\n const value = context.valueForKind(attr, kindForRollout);\n const bucketableValue = valueForBucketing(value);\n // Bucketing cannot be done by the specified attribute value.\n if (bucketableValue === null) {\n // If we got a value, then we know there was a context, but if we didn't get a value, then\n // it could either be there wasn't an attribute, the attribute was undefined/null, or there\n // was not a context. So here check for the context.\n const hadContext = context.kinds.indexOf(kindForRollout) >= 0;\n return [0, hadContext];\n }\n const prefix = seed ? Number(seed) : `${key}.${salt}`;\n const hashKey = `${prefix}.${bucketableValue}`;\n const hashVal = parseInt(this._sha1Hex(hashKey).substring(0, 15), 16);\n // This is how this has worked in previous implementations, but it is not\n // ideal.\n // The maximum safe integer representation in JS is 2^53 - 1.\n // eslint-disable-next-line @typescript-eslint/no-loss-of-precision\n return [hashVal / 0xfffffffffffffff, true];\n }\n}\nexports.default = Bucketer;\n//# sourceMappingURL=Bucketer.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getBucketBy = exports.getOffVariation = exports.getVariation = void 0;\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst EvalResult_1 = require(\"./EvalResult\");\nconst { ErrorKinds } = js_sdk_common_1.internal;\nconst KEY_ATTR_REF = new js_sdk_common_1.AttributeReference('key');\n/**\n * Attempt to get an evaluation result for the specific variation/flag combination.\n * @param flag The flag to get a variation from.\n * @param index The index of the flag.\n * @param reason The initial evaluation reason. If there is a valid variation, then this reason\n * will be returned in the EvalResult.\n * @returns An evaluation result containing the successful evaluation, or an error if there is\n * a problem accessing the variation.\n *\n * @internal\n */\nfunction getVariation(flag, index, reason) {\n if (js_sdk_common_1.TypeValidators.Number.is(index) && index >= 0 && index < flag.variations.length) {\n return EvalResult_1.default.forSuccess(flag.variations[index], reason, index);\n }\n return EvalResult_1.default.forError(ErrorKinds.MalformedFlag, 'Invalid variation index in flag');\n}\nexports.getVariation = getVariation;\n/**\n * Attempt to get an off result for the specified flag.\n * @param flag The flag to get the off variation for.\n * @param reason The initial reason for the evaluation result.\n * @returns A successful evaluation result, or an error result if there is a problem accessing\n * the off variation. Flags which do not have an off variation specified will get a `null` flag\n * value with an `undefined` variation.\n *\n * @internal\n */\nfunction getOffVariation(flag, reason) {\n if (!js_sdk_common_1.TypeValidators.Number.is(flag.offVariation)) {\n return EvalResult_1.default.forSuccess(null, reason);\n }\n return getVariation(flag, flag.offVariation, reason);\n}\nexports.getOffVariation = getOffVariation;\nfunction getBucketBy(isExperiment, bucketByAttributeReference) {\n var _a;\n return (_a = (isExperiment ? undefined : bucketByAttributeReference)) !== null && _a !== void 0 ? _a : KEY_ATTR_REF;\n}\nexports.getBucketBy = getBucketBy;\n//# sourceMappingURL=variations.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst collection_1 = require(\"./collection\");\nconst Reasons_1 = require(\"./Reasons\");\nconst variations_1 = require(\"./variations\");\nfunction evalTarget(flag, target, context) {\n const contextKey = context.key(target.contextKind);\n if (contextKey !== undefined) {\n const found = target.values.indexOf(contextKey) >= 0;\n if (found) {\n return (0, variations_1.getVariation)(flag, target.variation, Reasons_1.default.TargetMatch);\n }\n }\n return undefined;\n}\n/**\n * Evaluate the targets of the specified flag against the given context.\n * @param flag The flag to evaluate targets for.\n * @param context The context to evaluate those targets against.\n * @returns An evaluation result if there is a target match/error or undefined if there is not.\n *\n * @internal\n */\nfunction evalTargets(flag, context) {\n var _a;\n if (!((_a = flag.contextTargets) === null || _a === void 0 ? void 0 : _a.length)) {\n // There are not context targets, so we are going to evaluate the user targets.\n return (0, collection_1.firstResult)(flag.targets, (target) => evalTarget(flag, target, context));\n }\n return (0, collection_1.firstResult)(flag.contextTargets, (target) => {\n if (!target.contextKind || target.contextKind === js_sdk_common_1.Context.UserKind) {\n // When a context target is for a user, then use a user target with the same variation.\n const userTarget = (flag.targets || []).find((ut) => ut.variation === target.variation);\n if (userTarget) {\n return evalTarget(flag, userTarget, context);\n }\n return undefined;\n }\n return evalTarget(flag, target, context);\n });\n}\nexports.default = evalTargets;\n//# sourceMappingURL=evalTargets.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @internal\n */\nfunction makeBigSegmentRef(segment) {\n // The format of Big Segment references is independent of what store implementation is being\n // used; the store implementation receives only this string and does not know the details of\n // the data model. The Relay Proxy will use the same format when writing to the store.\n return `${segment.key}.g${segment.generation}`;\n}\nexports.default = makeBigSegmentRef;\n//# sourceMappingURL=makeBigSegmentRef.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst semver_1 = require(\"semver\");\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst VERSION_COMPONENTS_REGEX = /^\\d+(\\.\\d+)?(\\.\\d+)?/;\nfunction parseSemver(input) {\n // A leading 'v' is not supported by the standard, but may be by the semver library.\n if (js_sdk_common_1.TypeValidators.String.is(input) && !input.startsWith('v')) {\n // If the input is able to be parsed, then return that.\n const parsed = (0, semver_1.parse)(input);\n if (parsed) {\n return parsed;\n }\n // If not, then we are going to make some exceptions to the format.\n // Specifically semver requires 3 components, but we allow versions with\n // less. For instance we allow '1' to be equivalent to '1.0.0'.\n const components = VERSION_COMPONENTS_REGEX.exec(input);\n if (components) {\n let transformed = components[0];\n // Start after the match.\n for (let i = 1; i < components.length; i += 1) {\n // The regex will return a match followed by each group.\n // Unmatched groups are 'undefined'.\n // So we will always have 3 entries, the match and 2 groups.\n // For each missing group we need to append a '.0' until we have the\n // standard 3.\n if (components[i] === undefined) {\n transformed += '.0';\n }\n }\n // If the original version contains pre-release information like '-beta.1',\n // then this will re-incorporate that into the string.\n transformed += input.substring(components[0].length);\n return (0, semver_1.parse)(transformed);\n }\n }\n return null;\n}\nfunction semVerOperator(fn) {\n return (a, b) => {\n const aVer = parseSemver(a);\n const bVer = parseSemver(b);\n return !!(aVer && bVer && fn(aVer, bVer));\n };\n}\nfunction makeOperator(fn, validator, converter) {\n return (a, b) => {\n if (validator.is(a) && validator.is(b)) {\n if (converter) {\n return fn(converter(a), converter(b));\n }\n return fn(a, b);\n }\n return false;\n };\n}\nfunction parseDate(input) {\n // Before calling this function we know the value is a date in a number\n // or as a string.\n if (typeof input === 'number') {\n return input;\n }\n return Date.parse(input);\n}\nfunction safeRegexMatch(pattern, value) {\n try {\n return new RegExp(pattern).test(value);\n }\n catch (_a) {\n return false;\n }\n}\nconst operators = {\n in: (a, b) => a === b,\n endsWith: makeOperator((a, b) => a.endsWith(b), js_sdk_common_1.TypeValidators.String),\n startsWith: makeOperator((a, b) => a.startsWith(b), js_sdk_common_1.TypeValidators.String),\n matches: makeOperator((value, pattern) => safeRegexMatch(pattern, value), js_sdk_common_1.TypeValidators.String),\n contains: makeOperator((a, b) => a.indexOf(b) > -1, js_sdk_common_1.TypeValidators.String),\n lessThan: makeOperator((a, b) => a < b, js_sdk_common_1.TypeValidators.Number),\n lessThanOrEqual: makeOperator((a, b) => a <= b, js_sdk_common_1.TypeValidators.Number),\n greaterThan: makeOperator((a, b) => a > b, js_sdk_common_1.TypeValidators.Number),\n greaterThanOrEqual: makeOperator((a, b) => a >= b, js_sdk_common_1.TypeValidators.Number),\n before: makeOperator((a, b) => a < b, js_sdk_common_1.TypeValidators.Date, parseDate),\n after: makeOperator((a, b) => a > b, js_sdk_common_1.TypeValidators.Date, parseDate),\n semVerEqual: semVerOperator((a, b) => a.compare(b) === 0),\n semVerLessThan: semVerOperator((a, b) => a.compare(b) < 0),\n semVerGreaterThan: semVerOperator((a, b) => a.compare(b) > 0),\n};\n/**\n * Allows checking if a specific operator is defined and allows execution of an operator on data.\n *\n * @internal\n */\nclass Operators {\n static is(op) {\n return Object.prototype.hasOwnProperty.call(operators, op);\n }\n static execute(op, a, b) {\n var _a, _b;\n return (_b = (_a = operators[op]) === null || _a === void 0 ? void 0 : _a.call(operators, a, b)) !== null && _b !== void 0 ? _b : false;\n }\n}\nexports.default = Operators;\n//# sourceMappingURL=Operations.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.maybeNegate = void 0;\nconst Operations_1 = require(\"./Operations\");\nfunction maybeNegate(clause, value) {\n if (clause.negate) {\n return !value;\n }\n return value;\n}\nexports.maybeNegate = maybeNegate;\nfunction matchAny(op, value, values) {\n return values.some((testValue) => Operations_1.default.execute(op, value, testValue));\n}\n/**\n * Match a clause against a context.\n * @param clause The clause to match against a context.\n * @param context The context to match.\n * @returns True if the clause matches.\n *\n * @internal\n */\nfunction matchClauseWithoutSegmentOperations(clause, context) {\n const contextValue = context.valueForKind(clause.attributeReference, clause.contextKind);\n if (contextValue === null || contextValue === undefined) {\n return false;\n }\n if (Array.isArray(contextValue)) {\n return maybeNegate(clause, contextValue.some((value) => matchAny(clause.op, value, clause.values)));\n }\n return maybeNegate(clause, matchAny(clause.op, contextValue, clause.values));\n}\nexports.default = matchClauseWithoutSegmentOperations;\n//# sourceMappingURL=matchClause.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction segmentSearch(context, contextTargets, userTargets, userTargetSet) {\n if (contextTargets) {\n for (let targetIndex = 0; targetIndex < contextTargets.length; targetIndex += 1) {\n const target = contextTargets[targetIndex];\n const key = context.key(target.contextKind);\n if (key) {\n if (target.generated_valuesSet) {\n // Only check generated_valuesSet if present.\n if (target.generated_valuesSet.has(key)) {\n return true;\n }\n }\n else if (target.values.includes(key)) {\n return true;\n }\n }\n }\n }\n if (userTargetSet) {\n const userKey = context.key('user');\n if (userKey) {\n if (userTargetSet.has(userKey)) {\n return true;\n }\n }\n }\n else if (userTargets) {\n const userKey = context.key('user');\n if (userKey) {\n if (userTargets.includes(userKey)) {\n return true;\n }\n }\n }\n return false;\n}\nfunction matchSegmentTargets(segment, context) {\n const included = segmentSearch(context, segment.includedContexts, segment.included, segment.generated_includedSet);\n if (included) {\n return true;\n }\n const excluded = segmentSearch(context, segment.excludedContexts, segment.excluded, segment.generated_excludedSet);\n if (excluded) {\n // The match was an exclusion, so it should be negated.\n return !excluded;\n }\n return undefined;\n}\nexports.default = matchSegmentTargets;\n//# sourceMappingURL=matchSegmentTargets.js.map","\"use strict\";\n/* eslint-disable class-methods-use-this */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/* eslint-disable max-classes-per-file */\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst Bucketer_1 = require(\"./Bucketer\");\nconst collection_1 = require(\"./collection\");\nconst EvalResult_1 = require(\"./EvalResult\");\nconst evalTargets_1 = require(\"./evalTargets\");\nconst makeBigSegmentRef_1 = require(\"./makeBigSegmentRef\");\nconst matchClause_1 = require(\"./matchClause\");\nconst matchSegmentTargets_1 = require(\"./matchSegmentTargets\");\nconst Reasons_1 = require(\"./Reasons\");\nconst variations_1 = require(\"./variations\");\nconst { ErrorKinds } = js_sdk_common_1.internal;\nconst bigSegmentsStatusPriority = {\n HEALTHY: 1,\n STALE: 2,\n STORE_ERROR: 3,\n NOT_CONFIGURED: 4,\n};\nfunction getBigSegmentsStatusPriority(status) {\n if (status !== undefined) {\n return bigSegmentsStatusPriority[status] || 0;\n }\n return 0;\n}\n/**\n * Given two big segment statuses return the one with the higher priority.\n * @returns The status with the higher priority.\n */\nfunction computeUpdatedBigSegmentsStatus(old, latest) {\n if (old !== undefined &&\n getBigSegmentsStatusPriority(old) > getBigSegmentsStatusPriority(latest)) {\n return old;\n }\n return latest;\n}\nfunction makeMatch(match) {\n return { error: false, isMatch: match, result: undefined };\n}\nfunction makeError(result) {\n return { error: true, isMatch: false, result };\n}\n/**\n * @internal\n */\nclass Evaluator {\n constructor(platform, queries) {\n this._queries = queries;\n this._bucketer = new Bucketer_1.default(platform.crypto);\n }\n async evaluate(flag, context, eventFactory) {\n return new Promise((resolve) => {\n this.evaluateCb(flag, context, resolve, eventFactory);\n });\n }\n evaluateCb(flag, context, cb, eventFactory) {\n const state = {};\n this._evaluateInternal(flag, context, state, [], (res) => {\n if (state.bigSegmentsStatus) {\n res.detail.reason = Object.assign(Object.assign({}, res.detail.reason), { bigSegmentsStatus: state.bigSegmentsStatus });\n }\n if (state.prerequisites) {\n res.prerequisites = state.prerequisites;\n }\n res.events = state.events;\n cb(res);\n }, true, eventFactory);\n }\n /**\n * Evaluate the given flag against the given context. This internal method is entered\n * initially from the external evaluation method, but may be recursively executed during\n * prerequisite evaluations.\n * @param flag The flag to evaluate.\n * @param context The context to evaluate the flag against.\n * @param state The current evaluation state.\n * @param visitedFlags The flags that have been visited during this evaluation.\n * This is not part of the state, because it needs to be forked during prerequisite evaluations.\n * @param topLevel True when this function is being called in the direct evaluation of a flag,\n * versus the evaluataion of a prerequisite.\n */\n _evaluateInternal(flag, context, state, visitedFlags, cb, topLevel, eventFactory) {\n if (!flag.on) {\n cb((0, variations_1.getOffVariation)(flag, Reasons_1.default.Off));\n return;\n }\n this._checkPrerequisites(flag, context, state, visitedFlags, (res) => {\n // If there is a prereq result, then prereqs have failed, or there was\n // an error.\n if (res) {\n cb(res);\n return;\n }\n const targetRes = (0, evalTargets_1.default)(flag, context);\n if (targetRes) {\n cb(targetRes);\n return;\n }\n this._evaluateRules(flag, context, state, (evalRes) => {\n if (evalRes) {\n cb(evalRes);\n return;\n }\n cb(this._variationForContext(flag.fallthrough, context, flag, Reasons_1.default.Fallthrough));\n });\n }, topLevel, eventFactory);\n }\n /**\n * Evaluate the prerequisite flags for the given flag.\n * @param flag The flag to evaluate prerequisites for.\n * @param context The context to evaluate the prerequisites against.\n * @param state used to accumulate prerequisite events.\n * @param visitedFlags Used to detect cycles in prerequisite evaluation.\n * @param cb A callback which is executed when prerequisite checks are complete it is called with\n * an {@link EvalResult} containing an error result or `undefined` if the prerequisites\n * are met.\n * @param topLevel True when this function is being called in the direct evaluation of a flag,\n * versus the evaluataion of a prerequisite.\n */\n _checkPrerequisites(flag, context, state, visitedFlags, cb, topLevel, eventFactory) {\n let prereqResult;\n if (!flag.prerequisites || !flag.prerequisites.length) {\n cb(undefined);\n return;\n }\n // On any error conditions the prereq result will be set, so we do not need\n // the result of the series evaluation.\n (0, collection_1.allSeriesAsync)(flag.prerequisites, (prereq, _index, iterCb) => {\n if (visitedFlags.indexOf(prereq.key) !== -1) {\n prereqResult = EvalResult_1.default.forError(ErrorKinds.MalformedFlag, `Prerequisite of ${flag.key} causing a circular reference.` +\n ' This is probably a temporary condition due to an incomplete update.');\n iterCb(true);\n return;\n }\n const updatedVisitedFlags = [...visitedFlags, prereq.key];\n this._queries.getFlag(prereq.key, (prereqFlag) => {\n if (!prereqFlag) {\n prereqResult = (0, variations_1.getOffVariation)(flag, Reasons_1.default.prerequisiteFailed(prereq.key));\n iterCb(false);\n return;\n }\n this._evaluateInternal(prereqFlag, context, state, updatedVisitedFlags, (res) => {\n var _a, _b;\n // eslint-disable-next-line no-param-reassign\n (_a = state.events) !== null && _a !== void 0 ? _a : (state.events = []);\n if (topLevel) {\n // eslint-disable-next-line no-param-reassign\n (_b = state.prerequisites) !== null && _b !== void 0 ? _b : (state.prerequisites = []);\n state.prerequisites.push(prereqFlag.key);\n }\n if (eventFactory) {\n state.events.push(eventFactory.evalEventServer(prereqFlag, context, res.detail, null, flag));\n }\n if (res.isError) {\n prereqResult = res;\n return iterCb(false);\n }\n if (res.isOff || res.detail.variationIndex !== prereq.variation) {\n prereqResult = (0, variations_1.getOffVariation)(flag, Reasons_1.default.prerequisiteFailed(prereq.key));\n return iterCb(false);\n }\n return iterCb(true);\n }, false, // topLevel false evaluating the prerequisite.\n eventFactory);\n });\n }, () => {\n cb(prereqResult);\n });\n }\n /**\n * Evaluate the rules for a flag and return an {@link EvalResult} if there is\n * a match or error.\n * @param flag The flag to evaluate rules for.\n * @param context The context to evaluate the rules against.\n * @param state The current evaluation state.\n * @param cb Callback called when rule evaluation is complete, it will be called with either\n * an {@link EvalResult} or 'undefined'.\n */\n _evaluateRules(flag, context, state, cb) {\n let ruleResult;\n (0, collection_1.firstSeriesAsync)(flag.rules, (rule, ruleIndex, iterCb) => {\n this._ruleMatchContext(flag, rule, ruleIndex, context, state, [], (res) => {\n ruleResult = res;\n iterCb(!!res);\n });\n }, () => cb(ruleResult));\n }\n _clauseMatchContext(clause, context, segmentsVisited, state, cb) {\n let errorResult;\n if (clause.op === 'segmentMatch') {\n (0, collection_1.firstSeriesAsync)(clause.values, (value, _index, iterCb) => {\n this._queries.getSegment(value, (segment) => {\n if (segment) {\n if (segmentsVisited.includes(segment.key)) {\n errorResult = EvalResult_1.default.forError(ErrorKinds.MalformedFlag, `Segment rule referencing segment ${segment.key} caused a circular reference. ` +\n 'This is probably a temporary condition due to an incomplete update');\n // There was an error, so stop checking further segments.\n iterCb(true);\n return;\n }\n const newVisited = [...segmentsVisited, segment === null || segment === void 0 ? void 0 : segment.key];\n this.segmentMatchContext(segment, context, state, newVisited, (res) => {\n if (res.error) {\n errorResult = res.result;\n }\n iterCb(res.error || res.isMatch);\n });\n }\n else {\n iterCb(false);\n }\n });\n }, (match) => {\n if (errorResult) {\n return cb(makeError(errorResult));\n }\n return cb(makeMatch((0, matchClause_1.maybeNegate)(clause, match)));\n });\n return;\n }\n // This is after segment matching, which does not use the reference.\n if (!clause.attributeReference.isValid) {\n cb(makeError(EvalResult_1.default.forError(ErrorKinds.MalformedFlag, 'Invalid attribute reference in clause')));\n return;\n }\n cb(makeMatch((0, matchClause_1.default)(clause, context)));\n }\n /**\n * Evaluate a flag rule against the given context.\n * @param flag The flag the rule is part of.\n * @param rule The rule to match.\n * @param rule The index of the rule.\n * @param context The context to match the rule against.\n * @param cb Called when matching is complete with an {@link EvalResult} or `undefined` if there\n * are no matches or errors.\n */\n _ruleMatchContext(flag, rule, ruleIndex, context, state, segmentsVisited, cb) {\n if (!rule.clauses) {\n cb(undefined);\n return;\n }\n let errorResult;\n (0, collection_1.allSeriesAsync)(rule.clauses, (clause, _index, iterCb) => {\n this._clauseMatchContext(clause, context, segmentsVisited, state, (res) => {\n errorResult = res.result;\n return iterCb(res.error || res.isMatch);\n });\n }, (match) => {\n if (errorResult) {\n return cb(errorResult);\n }\n if (match) {\n return cb(this._variationForContext(rule, context, flag, Reasons_1.default.ruleMatch(rule.id, ruleIndex)));\n }\n return cb(undefined);\n });\n }\n _variationForContext(varOrRollout, context, flag, reason) {\n if (varOrRollout === undefined) {\n // By spec this field should be defined, but better to be overly cautious.\n return EvalResult_1.default.forError(ErrorKinds.MalformedFlag, 'Fallthrough variation undefined');\n }\n if (varOrRollout.variation !== undefined) {\n // 0 would be false.\n return (0, variations_1.getVariation)(flag, varOrRollout.variation, reason);\n }\n if (varOrRollout.rollout) {\n const { rollout } = varOrRollout;\n const { variations } = rollout;\n const isExperiment = rollout.kind === 'experiment';\n if (variations && variations.length) {\n const bucketBy = (0, variations_1.getBucketBy)(isExperiment, rollout.bucketByAttributeReference);\n if (!bucketBy.isValid) {\n return EvalResult_1.default.forError(ErrorKinds.MalformedFlag, 'Invalid attribute reference for bucketBy in rollout');\n }\n const [bucket, hadContext] = this._bucketer.bucket(context, flag.key, bucketBy, flag.salt || '', rollout.contextKind, rollout.seed);\n const updatedReason = Object.assign({}, reason);\n let sum = 0;\n for (let i = 0; i < variations.length; i += 1) {\n const variate = variations[i];\n sum += variate.weight / 100000.0;\n if (bucket < sum) {\n if (isExperiment && hadContext && !variate.untracked) {\n updatedReason.inExperiment = true;\n }\n return (0, variations_1.getVariation)(flag, variate.variation, updatedReason);\n }\n }\n // The context's bucket value was greater than or equal to the end of\n // the last bucket. This could happen due to a rounding error, or due to\n // the fact that we are scaling to 100000 rather than 99999, or the flag\n // data could contain buckets that don't actually add up to 100000.\n // Rather than returning an error in this case (or changing the scaling,\n // which would potentially change the results for *all* users), we will\n // simply put the context in the last bucket.\n const lastVariate = variations[variations.length - 1];\n if (isExperiment && !lastVariate.untracked) {\n updatedReason.inExperiment = true;\n }\n return (0, variations_1.getVariation)(flag, lastVariate.variation, updatedReason);\n }\n }\n return EvalResult_1.default.forError(ErrorKinds.MalformedFlag, 'Variation/rollout object with no variation or rollout');\n }\n segmentRuleMatchContext(segment, rule, context, state, segmentsVisited, cb) {\n let errorResult;\n (0, collection_1.allSeriesAsync)(rule.clauses, (clause, _index, iterCb) => {\n this._clauseMatchContext(clause, context, segmentsVisited, state, (res) => {\n errorResult = res.result;\n iterCb(res.error || res.isMatch);\n });\n }, (match) => {\n if (errorResult) {\n return cb(makeError(errorResult));\n }\n if (match) {\n if (rule.weight === undefined) {\n return cb(makeMatch(match));\n }\n const bucketBy = (0, variations_1.getBucketBy)(false, rule.bucketByAttributeReference);\n if (!bucketBy.isValid) {\n return cb(makeError(EvalResult_1.default.forError(ErrorKinds.MalformedFlag, 'Invalid attribute reference in clause')));\n }\n const [bucket] = this._bucketer.bucket(context, segment.key, bucketBy, segment.salt || '', rule.rolloutContextKind);\n return cb(makeMatch(bucket < rule.weight / 100000.0));\n }\n return cb(makeMatch(false));\n });\n }\n // eslint-disable-next-line class-methods-use-this\n simpleSegmentMatchContext(segment, context, state, segmentsVisited, cb) {\n if (!segment.unbounded) {\n const includeExclude = (0, matchSegmentTargets_1.default)(segment, context);\n if (includeExclude !== undefined) {\n cb(makeMatch(includeExclude));\n return;\n }\n }\n let evalResult;\n (0, collection_1.firstSeriesAsync)(segment.rules, (rule, _index, iterCb) => {\n this.segmentRuleMatchContext(segment, rule, context, state, segmentsVisited, (res) => {\n evalResult = res.result;\n return iterCb(res.error || res.isMatch);\n });\n }, (matched) => {\n if (evalResult) {\n return cb(makeError(evalResult));\n }\n return cb(makeMatch(matched));\n });\n }\n segmentMatchContext(segment, context, state, segmentsVisited, cb) {\n if (!segment.unbounded) {\n this.simpleSegmentMatchContext(segment, context, state, segmentsVisited, cb);\n return;\n }\n const bigSegmentKind = segment.unboundedContextKind || 'user';\n const keyForBigSegment = context.key(bigSegmentKind);\n if (!keyForBigSegment) {\n cb(makeMatch(false));\n return;\n }\n if (!segment.generation) {\n // Big Segment queries can only be done if the generation is known. If it's unset,\n // that probably means the data store was populated by an older SDK that doesn't know\n // about the generation property and therefore dropped it from the JSON data. We'll treat\n // that as a \"not configured\" condition.\n // eslint-disable-next-line no-param-reassign\n state.bigSegmentsStatus = computeUpdatedBigSegmentsStatus(state.bigSegmentsStatus, 'NOT_CONFIGURED');\n cb(makeMatch(false));\n return;\n }\n if (state.bigSegmentsMembership && state.bigSegmentsMembership[keyForBigSegment]) {\n // We've already done the query at some point during the flag evaluation and stored\n // the result (if any) in stateOut.bigSegmentsMembership, so we don't need to do it\n // again. Even if multiple Big Segments are being referenced, the membership includes\n // *all* of the user's segment memberships.\n this.bigSegmentMatchContext(state.bigSegmentsMembership[keyForBigSegment], segment, context, state).then(cb);\n return;\n }\n this._queries.getBigSegmentsMembership(keyForBigSegment).then((result) => {\n // eslint-disable-next-line no-param-reassign\n state.bigSegmentsMembership = state.bigSegmentsMembership || {};\n if (result) {\n const [membership, status] = result;\n // eslint-disable-next-line no-param-reassign\n state.bigSegmentsMembership[keyForBigSegment] = membership;\n // eslint-disable-next-line no-param-reassign\n state.bigSegmentsStatus = computeUpdatedBigSegmentsStatus(state.bigSegmentsStatus, status);\n }\n else {\n // eslint-disable-next-line no-param-reassign\n state.bigSegmentsStatus = computeUpdatedBigSegmentsStatus(state.bigSegmentsStatus, 'NOT_CONFIGURED');\n }\n /* eslint-enable no-param-reassign */\n this.bigSegmentMatchContext(state.bigSegmentsMembership[keyForBigSegment], segment, context, state).then(cb);\n });\n }\n bigSegmentMatchContext(membership, segment, context, state) {\n const segmentRef = (0, makeBigSegmentRef_1.default)(segment);\n const included = membership === null || membership === void 0 ? void 0 : membership[segmentRef];\n return new Promise((resolve) => {\n // Typically null is not checked because we filter it from the data\n // we get in flag updates. Here it is checked because big segment data\n // will be contingent on the store that implements it.\n if (included !== undefined && included !== null) {\n resolve(makeMatch(included));\n return;\n }\n this.simpleSegmentMatchContext(segment, context, state, [], resolve);\n });\n }\n}\nexports.default = Evaluator;\n//# sourceMappingURL=Evaluator.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst LruCache_1 = require(\"../cache/LruCache\");\nclass ContextDeduplicator {\n constructor(options) {\n this._contextKeysCache = new LruCache_1.default({ max: options.contextKeysCapacity });\n this.flushInterval = options.contextKeysFlushInterval;\n }\n processContext(context) {\n const { canonicalKey } = context;\n const inCache = this._contextKeysCache.get(canonicalKey);\n this._contextKeysCache.set(canonicalKey, true);\n // If it is in the cache, then we do not want to add an event.\n return !inCache;\n }\n flush() {\n this._contextKeysCache.clear();\n }\n}\nexports.default = ContextDeduplicator;\n//# sourceMappingURL=ContextDeduplicator.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @internal\n */\nfunction isExperiment(flag, reason) {\n if (reason) {\n // If the reason says we're in an experiment, we are. Otherwise, apply\n // the legacy rule exclusion logic.\n if (reason.inExperiment) {\n return true;\n }\n switch (reason.kind) {\n case 'RULE_MATCH': {\n const index = reason.ruleIndex;\n if (index !== undefined) {\n const rules = flag.rules || [];\n return index >= 0 && index < rules.length && !!rules[index].trackEvents;\n }\n break;\n }\n case 'FALLTHROUGH':\n return !!flag.trackEventsFallthrough;\n default:\n // No action needed.\n }\n }\n return false;\n}\nexports.default = isExperiment;\n//# sourceMappingURL=isExperiment.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst isExperiment_1 = require(\"./isExperiment\");\n/**\n * @internal\n */\nclass EventFactory extends js_sdk_common_1.internal.EventFactoryBase {\n evalEventServer(flag, context, detail, defaultVal, prereqOfFlag) {\n var _a;\n const addExperimentData = (0, isExperiment_1.default)(flag, detail.reason);\n return super.evalEvent({\n addExperimentData,\n context,\n debugEventsUntilDate: flag.debugEventsUntilDate,\n defaultVal,\n excludeFromSummaries: flag.excludeFromSummaries,\n flagKey: flag.key,\n prereqOfFlagKey: prereqOfFlag === null || prereqOfFlag === void 0 ? void 0 : prereqOfFlag.key,\n reason: detail.reason,\n samplingRatio: flag.samplingRatio,\n trackEvents: flag.trackEvents || addExperimentData,\n value: detail.value,\n variation: (_a = detail.variationIndex) !== null && _a !== void 0 ? _a : undefined,\n version: flag.version,\n });\n }\n}\nexports.default = EventFactory;\n//# sourceMappingURL=EventFactory.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass FlagsStateBuilder {\n constructor(_valid, _withReasons) {\n this._valid = _valid;\n this._withReasons = _withReasons;\n this._flagValues = {};\n this._flagMetadata = {};\n }\n addFlag(flag, value, variation, reason, trackEvents, trackReason, detailsOnlyIfTracked, prerequisites) {\n this._flagValues[flag.key] = value;\n const meta = {};\n if (variation !== undefined) {\n meta.variation = variation;\n }\n const omitDetails = detailsOnlyIfTracked &&\n !trackEvents &&\n !trackReason &&\n flag.debugEventsUntilDate === undefined; // 0 probably doesn't matter.\n if (!omitDetails) {\n meta.version = flag.version;\n }\n if (reason && (trackReason || (this._withReasons && !omitDetails))) {\n meta.reason = reason;\n }\n if (trackEvents) {\n meta.trackEvents = true;\n }\n if (trackReason) {\n meta.trackReason = true;\n }\n if (flag.debugEventsUntilDate !== undefined) {\n meta.debugEventsUntilDate = flag.debugEventsUntilDate;\n }\n if (prerequisites && prerequisites.length) {\n meta.prerequisites = prerequisites;\n }\n this._flagMetadata[flag.key] = meta;\n }\n build() {\n return {\n valid: this._valid,\n allValues: () => this._flagValues,\n getFlagValue: (key) => this._flagValues[key],\n getFlagReason: (key) => { var _a; return (_a = (this._flagMetadata[key] ? this._flagMetadata[key].reason : null)) !== null && _a !== void 0 ? _a : null; },\n toJSON: () => (Object.assign(Object.assign({}, this._flagValues), { $flagsState: this._flagMetadata, $valid: this._valid })),\n };\n }\n}\nexports.default = FlagsStateBuilder;\n//# sourceMappingURL=FlagsStateBuilder.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst BEFORE_EVALUATION_STAGE_NAME = 'beforeEvaluation';\nconst AFTER_EVALUATION_STAGE_NAME = 'afterEvaluation';\nconst UNKNOWN_HOOK_NAME = 'unknown hook';\nclass HookRunner {\n constructor(_logger, hooks) {\n this._logger = _logger;\n this._hooks = [];\n this._hooks.push(...hooks);\n }\n async withEvaluationSeries(key, context, defaultValue, methodName, method, environmentId) {\n // This early return is here to avoid the extra async/await associated with\n // using withHooksDataWithDetail.\n if (this._hooks.length === 0) {\n return method();\n }\n return this.withEvaluationSeriesExtraDetail(key, context, defaultValue, methodName, async () => {\n const detail = await method();\n return { detail };\n }, environmentId).then(({ detail }) => detail);\n }\n /**\n * This function allows extra information to be returned with the detail for situations like\n * migrations where a tracker is returned with the detail.\n */\n async withEvaluationSeriesExtraDetail(key, context, defaultValue, methodName, method, environmentId) {\n if (this._hooks.length === 0) {\n return method();\n }\n const { hooks, hookContext } = this._prepareHooks(key, context, defaultValue, methodName, environmentId);\n const hookData = this._executeBeforeEvaluation(hooks, hookContext);\n const result = await method();\n this._executeAfterEvaluation(hooks, hookContext, hookData, result.detail);\n return result;\n }\n _tryExecuteStage(method, hookName, stage) {\n var _a;\n try {\n return stage();\n }\n catch (err) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error(`An error was encountered in \"${method}\" of the \"${hookName}\" hook: ${err}`);\n return {};\n }\n }\n _hookName(hook) {\n var _a, _b;\n try {\n return (_a = hook === null || hook === void 0 ? void 0 : hook.getMetadata().name) !== null && _a !== void 0 ? _a : UNKNOWN_HOOK_NAME;\n }\n catch (_c) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error(`Exception thrown getting metadata for hook. Unable to get hook name.`);\n return UNKNOWN_HOOK_NAME;\n }\n }\n _executeAfterEvaluation(hooks, hookContext, updatedData, result) {\n var _a;\n // This iterates in reverse, versus reversing a shallow copy of the hooks,\n // for efficiency.\n for (let hookIndex = hooks.length - 1; hookIndex >= 0; hookIndex -= 1) {\n const hook = hooks[hookIndex];\n const data = (_a = updatedData[hookIndex]) !== null && _a !== void 0 ? _a : {};\n this._tryExecuteStage(AFTER_EVALUATION_STAGE_NAME, this._hookName(hook), () => { var _a, _b; return (_b = (_a = hook === null || hook === void 0 ? void 0 : hook.afterEvaluation) === null || _a === void 0 ? void 0 : _a.call(hook, hookContext, data, result)) !== null && _b !== void 0 ? _b : {}; });\n }\n }\n _executeBeforeEvaluation(hooks, hookContext) {\n return hooks.map((hook) => this._tryExecuteStage(BEFORE_EVALUATION_STAGE_NAME, this._hookName(hook), () => { var _a, _b; return (_b = (_a = hook === null || hook === void 0 ? void 0 : hook.beforeEvaluation) === null || _a === void 0 ? void 0 : _a.call(hook, hookContext, {})) !== null && _b !== void 0 ? _b : {}; }));\n }\n _prepareHooks(key, context, defaultValue, methodName, environmentId) {\n // Copy the hooks to use a consistent set during evaluation. Hooks could be added and we want\n // to ensure all correct stages for any give hook execute. Not for instance the afterEvaluation\n // stage without beforeEvaluation having been called on that hook.\n const hooks = [...this._hooks];\n const hookContext = {\n flagKey: key,\n context,\n defaultValue,\n method: methodName,\n environmentId,\n };\n return { hooks, hookContext };\n }\n addHook(hook) {\n this._hooks.push(hook);\n }\n}\nexports.default = HookRunner;\n//# sourceMappingURL=HookRunner.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nfunction isOperation(value) {\n if (!js_sdk_common_1.TypeValidators.String.is(value)) {\n return false;\n }\n return value === 'read' || value === 'write';\n}\nfunction isLatencyMeasurement(value) {\n return value.key === 'latency_ms';\n}\nfunction isErrorMeasurement(value) {\n return value.key === 'error';\n}\nfunction isInvokedMeasurement(value) {\n return value.key === 'invoked';\n}\nfunction isConsistencyMeasurement(value) {\n return value.key === 'consistent';\n}\nfunction areValidNumbers(values) {\n const oldValue = values.old;\n const newValue = values.new;\n if (oldValue !== undefined && !js_sdk_common_1.TypeValidators.Number.is(oldValue)) {\n return false;\n }\n if (newValue !== undefined && !js_sdk_common_1.TypeValidators.Number.is(newValue)) {\n return false;\n }\n return true;\n}\nfunction areValidBooleans(values) {\n const oldValue = values.old;\n const newValue = values.new;\n if (oldValue !== undefined && !js_sdk_common_1.TypeValidators.Boolean.is(oldValue)) {\n return false;\n }\n if (newValue !== undefined && !js_sdk_common_1.TypeValidators.Boolean.is(newValue)) {\n return false;\n }\n return true;\n}\nfunction validateMeasurement(measurement) {\n // Here we are protecting ourselves from JS callers. TypeScript says that\n // it cannot be an empty string, but those using JS can do what they want.\n // @ts-ignore\n if (!js_sdk_common_1.TypeValidators.String.is(measurement.key) || measurement.key === '') {\n return undefined;\n }\n if (isLatencyMeasurement(measurement)) {\n if (!js_sdk_common_1.TypeValidators.Object.is(measurement.values)) {\n return undefined;\n }\n if (!areValidNumbers(measurement.values)) {\n return undefined;\n }\n return {\n key: measurement.key,\n values: {\n old: measurement.values.old,\n new: measurement.values.new,\n },\n };\n }\n if (isErrorMeasurement(measurement)) {\n if (!js_sdk_common_1.TypeValidators.Object.is(measurement.values)) {\n return undefined;\n }\n if (!areValidBooleans(measurement.values)) {\n return undefined;\n }\n return {\n key: measurement.key,\n values: {\n old: measurement.values.old,\n new: measurement.values.new,\n },\n };\n }\n if (isConsistencyMeasurement(measurement)) {\n if (!js_sdk_common_1.TypeValidators.Boolean.is(measurement.value) ||\n !js_sdk_common_1.TypeValidators.Number.is(measurement.samplingRatio)) {\n return undefined;\n }\n return {\n key: measurement.key,\n value: measurement.value,\n samplingRatio: measurement.samplingRatio,\n };\n }\n if (isInvokedMeasurement(measurement)) {\n if (!js_sdk_common_1.TypeValidators.Object.is(measurement.values)) {\n return undefined;\n }\n if (!areValidBooleans(measurement.values)) {\n return undefined;\n }\n return {\n key: measurement.key,\n values: {\n old: measurement.values.old,\n new: measurement.values.new,\n },\n };\n }\n // Not a supported measurement type.\n return undefined;\n}\nfunction validateMeasurements(measurements) {\n return measurements\n .map(validateMeasurement)\n .filter((value) => value !== undefined);\n}\nfunction validateEvaluation(evaluation) {\n if (!js_sdk_common_1.TypeValidators.String.is(evaluation.key) || evaluation.key === '') {\n return undefined;\n }\n if (!js_sdk_common_1.TypeValidators.Object.is(evaluation.reason)) {\n return undefined;\n }\n if (!js_sdk_common_1.TypeValidators.String.is(evaluation.reason.kind) || evaluation.reason.kind === '') {\n return undefined;\n }\n const validated = {\n key: evaluation.key,\n value: evaluation.value,\n default: evaluation.default,\n reason: {\n kind: evaluation.reason.kind,\n },\n };\n const inReason = evaluation.reason;\n const outReason = validated.reason;\n if (js_sdk_common_1.TypeValidators.String.is(inReason.errorKind)) {\n outReason.errorKind = inReason.errorKind;\n }\n if (js_sdk_common_1.TypeValidators.String.is(inReason.ruleId)) {\n outReason.ruleId = inReason.ruleId;\n }\n if (js_sdk_common_1.TypeValidators.String.is(inReason.prerequisiteKey)) {\n outReason.prerequisiteKey = inReason.prerequisiteKey;\n }\n if (js_sdk_common_1.TypeValidators.Boolean.is(inReason.inExperiment)) {\n outReason.inExperiment = inReason.inExperiment;\n }\n if (js_sdk_common_1.TypeValidators.Number.is(inReason.ruleIndex)) {\n outReason.ruleIndex = inReason.ruleIndex;\n }\n if (js_sdk_common_1.TypeValidators.String.is(inReason.bigSegmentsStatus)) {\n outReason.bigSegmentsStatus = inReason.bigSegmentsStatus;\n }\n if (evaluation.variation !== undefined && js_sdk_common_1.TypeValidators.Number.is(evaluation.variation)) {\n validated.variation = evaluation.variation;\n }\n if (evaluation.version !== undefined && js_sdk_common_1.TypeValidators.Number.is(evaluation.version)) {\n validated.version = evaluation.version;\n }\n return validated;\n}\n/**\n * Migration events can be generated directly in user code and may not follow the shape\n * expected by the TypeScript definitions. So we do some validation on these events, as well\n * as copying the data out of them, to reduce the amount of invalid data we may send.\n *\n * @param inEvent The event to process.\n * @returns An event, or undefined if it could not be converted.\n */\nfunction MigrationOpEventToInputEvent(inEvent) {\n var _a;\n // The sampling ratio is omitted and needs populated by the track migration method.\n if (inEvent.kind !== 'migration_op') {\n return undefined;\n }\n if (!isOperation(inEvent.operation)) {\n return undefined;\n }\n if (!js_sdk_common_1.TypeValidators.Number.is(inEvent.creationDate)) {\n return undefined;\n }\n const contextKeysOrContext = {};\n if (js_sdk_common_1.TypeValidators.Object.is(inEvent.context)) {\n const context = js_sdk_common_1.Context.fromLDContext(inEvent.context);\n if (context.valid) {\n contextKeysOrContext.context = context;\n }\n }\n else if (js_sdk_common_1.TypeValidators.Object.is(inEvent.contextKeys)) {\n if (Object.keys(inEvent.contextKeys).every((key) => js_sdk_common_1.TypeValidators.Kind.is(key)) &&\n Object.values(inEvent.contextKeys).every((value) => js_sdk_common_1.TypeValidators.String.is(value) && value !== '')) {\n contextKeysOrContext.contextKeys = Object.assign({}, inEvent.contextKeys);\n }\n }\n if (!contextKeysOrContext.context && !contextKeysOrContext.contextKeys) {\n return undefined;\n }\n const samplingRatio = (_a = inEvent.samplingRatio) !== null && _a !== void 0 ? _a : 1;\n if (!js_sdk_common_1.TypeValidators.Number.is(samplingRatio)) {\n return undefined;\n }\n const evaluation = validateEvaluation(inEvent.evaluation);\n if (!evaluation) {\n return undefined;\n }\n return Object.assign(Object.assign({ kind: inEvent.kind, operation: inEvent.operation, creationDate: inEvent.creationDate }, contextKeysOrContext), { measurements: validateMeasurements(inEvent.measurements), evaluation,\n samplingRatio });\n}\nexports.default = MigrationOpEventToInputEvent;\n//# sourceMappingURL=MigrationOpEventConversion.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst data_1 = require(\"./api/data\");\nfunction isPopulated(data) {\n return !Number.isNaN(data);\n}\nclass MigrationOpTracker {\n constructor(_flagKey, _context, _defaultStage, _stage, _reason, _checkRatio, _variation, _version, _samplingRatio, _logger) {\n this._flagKey = _flagKey;\n this._context = _context;\n this._defaultStage = _defaultStage;\n this._stage = _stage;\n this._reason = _reason;\n this._checkRatio = _checkRatio;\n this._variation = _variation;\n this._version = _version;\n this._samplingRatio = _samplingRatio;\n this._logger = _logger;\n this._errors = {\n old: false,\n new: false,\n };\n this._wasInvoked = {\n old: false,\n new: false,\n };\n this._consistencyCheck = data_1.LDConsistencyCheck.NotChecked;\n this._latencyMeasurement = {\n old: NaN,\n new: NaN,\n };\n }\n op(op) {\n this._operation = op;\n }\n error(origin) {\n this._errors[origin] = true;\n }\n consistency(check) {\n var _a, _b;\n if (js_sdk_common_1.internal.shouldSample((_a = this._checkRatio) !== null && _a !== void 0 ? _a : 1)) {\n try {\n const res = check();\n this._consistencyCheck = res\n ? data_1.LDConsistencyCheck.Consistent\n : data_1.LDConsistencyCheck.Inconsistent;\n }\n catch (exception) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error('Exception when executing consistency check function for migration' +\n ` '${this._flagKey}' the consistency check will not be included in the generated migration` +\n ` op event. Exception: ${exception}`);\n }\n }\n }\n latency(origin, value) {\n this._latencyMeasurement[origin] = value;\n }\n invoked(origin) {\n this._wasInvoked[origin] = true;\n }\n createEvent() {\n var _a, _b, _c, _d, _e;\n if (!js_sdk_common_1.TypeValidators.String.is(this._flagKey) || this._flagKey === '') {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error('The flag key for a migration operation must be a non-empty string.');\n return undefined;\n }\n if (!this._operation) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error('The operation must be set using \"op\" before an event can be created.');\n return undefined;\n }\n if (!js_sdk_common_1.Context.fromLDContext(this._context).valid) {\n (_c = this._logger) === null || _c === void 0 ? void 0 : _c.error('The migration was not done against a valid context and cannot generate an event.');\n return undefined;\n }\n if (!this._wasInvoked.old && !this._wasInvoked.new) {\n (_d = this._logger) === null || _d === void 0 ? void 0 : _d.error('The migration invoked neither the \"old\" or \"new\" implementation and' +\n 'an event cannot be generated');\n return undefined;\n }\n if (!this._measurementConsistencyCheck()) {\n return undefined;\n }\n const measurements = [];\n this._populateInvoked(measurements);\n this._populateConsistency(measurements);\n this._populateLatency(measurements);\n this._populateErrors(measurements);\n return {\n kind: 'migration_op',\n operation: this._operation,\n creationDate: Date.now(),\n context: this._context,\n evaluation: {\n key: this._flagKey,\n value: this._stage,\n default: this._defaultStage,\n reason: this._reason,\n variation: this._variation,\n version: this._version,\n },\n measurements,\n samplingRatio: (_e = this._samplingRatio) !== null && _e !== void 0 ? _e : 1,\n };\n }\n _logTag() {\n return `For migration ${this._operation}-${this._flagKey}:`;\n }\n _latencyConsistencyMessage(origin) {\n return `Latency measurement for \"${origin}\", but \"${origin}\" was not invoked.`;\n }\n _errorConsistencyMessage(origin) {\n return `Error occurred for \"${origin}\", but \"${origin}\" was not invoked.`;\n }\n _consistencyCheckConsistencyMessage(origin) {\n return (`Consistency check was done, but \"${origin}\" was not invoked.` +\n 'Both \"old\" and \"new\" must be invoked to do a consistency check.');\n }\n _checkOriginEventConsistency(origin) {\n var _a, _b, _c;\n if (this._wasInvoked[origin]) {\n return true;\n }\n // If the specific origin was not invoked, but it contains measurements, then\n // that is a problem. Check each measurement and log a message if it is present.\n if (!Number.isNaN(this._latencyMeasurement[origin])) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error(`${this._logTag()} ${this._latencyConsistencyMessage(origin)}`);\n return false;\n }\n if (this._errors[origin]) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error(`${this._logTag()} ${this._errorConsistencyMessage(origin)}`);\n return false;\n }\n if (this._consistencyCheck !== data_1.LDConsistencyCheck.NotChecked) {\n (_c = this._logger) === null || _c === void 0 ? void 0 : _c.error(`${this._logTag()} ${this._consistencyCheckConsistencyMessage(origin)}`);\n return false;\n }\n return true;\n }\n /**\n * Check that the latency, error, consistency and invoked measurements are self-consistent.\n */\n _measurementConsistencyCheck() {\n return this._checkOriginEventConsistency('old') && this._checkOriginEventConsistency('new');\n }\n _populateInvoked(measurements) {\n var _a;\n const measurement = {\n key: 'invoked',\n values: {},\n };\n if (!this._wasInvoked.old && !this._wasInvoked.new) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error('Migration op completed without executing any origins (old/new).');\n }\n if (this._wasInvoked.old) {\n measurement.values.old = true;\n }\n if (this._wasInvoked.new) {\n measurement.values.new = true;\n }\n measurements.push(measurement);\n }\n _populateConsistency(measurements) {\n var _a;\n if (this._consistencyCheck !== undefined &&\n this._consistencyCheck !== data_1.LDConsistencyCheck.NotChecked) {\n measurements.push({\n key: 'consistent',\n value: this._consistencyCheck === data_1.LDConsistencyCheck.Consistent,\n samplingRatio: (_a = this._checkRatio) !== null && _a !== void 0 ? _a : 1,\n });\n }\n }\n _populateErrors(measurements) {\n if (this._errors.new || this._errors.old) {\n const measurement = {\n key: 'error',\n values: {},\n };\n if (this._errors.new) {\n measurement.values.new = true;\n }\n if (this._errors.old) {\n measurement.values.old = true;\n }\n measurements.push(measurement);\n }\n }\n _populateLatency(measurements) {\n const newIsPopulated = isPopulated(this._latencyMeasurement.new);\n const oldIsPopulated = isPopulated(this._latencyMeasurement.old);\n if (newIsPopulated || oldIsPopulated) {\n const values = {};\n if (newIsPopulated) {\n values.new = this._latencyMeasurement.new;\n }\n if (oldIsPopulated) {\n values.old = this._latencyMeasurement.old;\n }\n measurements.push({\n key: 'latency_ms',\n values,\n });\n }\n }\n}\nexports.default = MigrationOpTracker;\n//# sourceMappingURL=MigrationOpTracker.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/* eslint-disable class-methods-use-this */\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst api_1 = require(\"./api\");\nconst LDDataSystemOptions_1 = require(\"./api/options/LDDataSystemOptions\");\nconst BigSegmentsManager_1 = require(\"./BigSegmentsManager\");\nconst createPluginEnvironmentMetadata_1 = require(\"./createPluginEnvironmentMetadata\");\nconst createPayloadListenerFDv2_1 = require(\"./data_sources/createPayloadListenerFDv2\");\nconst createStreamListeners_1 = require(\"./data_sources/createStreamListeners\");\nconst DataSourceUpdates_1 = require(\"./data_sources/DataSourceUpdates\");\nconst fileDataInitilizerFDv2_1 = require(\"./data_sources/fileDataInitilizerFDv2\");\nconst OneShotInitializerFDv2_1 = require(\"./data_sources/OneShotInitializerFDv2\");\nconst PollingProcessor_1 = require(\"./data_sources/PollingProcessor\");\nconst PollingProcessorFDv2_1 = require(\"./data_sources/PollingProcessorFDv2\");\nconst Requestor_1 = require(\"./data_sources/Requestor\");\nconst StreamingProcessor_1 = require(\"./data_sources/StreamingProcessor\");\nconst StreamingProcessorFDv2_1 = require(\"./data_sources/StreamingProcessorFDv2\");\nconst TransactionalDataSourceUpdates_1 = require(\"./data_sources/TransactionalDataSourceUpdates\");\nconst createDiagnosticsInitConfig_1 = require(\"./diagnostics/createDiagnosticsInitConfig\");\nconst collection_1 = require(\"./evaluation/collection\");\nconst EvalResult_1 = require(\"./evaluation/EvalResult\");\nconst Evaluator_1 = require(\"./evaluation/Evaluator\");\nconst ContextDeduplicator_1 = require(\"./events/ContextDeduplicator\");\nconst EventFactory_1 = require(\"./events/EventFactory\");\nconst isExperiment_1 = require(\"./events/isExperiment\");\nconst FlagsStateBuilder_1 = require(\"./FlagsStateBuilder\");\nconst HookRunner_1 = require(\"./hooks/HookRunner\");\nconst MigrationOpEventConversion_1 = require(\"./MigrationOpEventConversion\");\nconst MigrationOpTracker_1 = require(\"./MigrationOpTracker\");\nconst Configuration_1 = require(\"./options/Configuration\");\nconst VersionedDataKinds_1 = require(\"./store/VersionedDataKinds\");\nconst { ClientMessages, ErrorKinds, NullEventProcessor } = js_sdk_common_1.internal;\nvar InitState;\n(function (InitState) {\n InitState[InitState[\"Initializing\"] = 0] = \"Initializing\";\n InitState[InitState[\"Initialized\"] = 1] = \"Initialized\";\n InitState[InitState[\"Failed\"] = 2] = \"Failed\";\n})(InitState || (InitState = {}));\nconst HIGH_TIMEOUT_THRESHOLD = 60;\nconst BOOL_VARIATION_METHOD_NAME = 'LDClient.boolVariation';\nconst NUMBER_VARIATION_METHOD_NAME = 'LDClient.numberVariation';\nconst STRING_VARIATION_METHOD_NAME = 'LDClient.stringVariation';\nconst JSON_VARIATION_METHOD_NAME = 'LDClient.jsonVariation';\nconst VARIATION_METHOD_NAME = 'LDClient.variation';\nconst MIGRATION_VARIATION_METHOD_NAME = 'LDClient.migrationVariation';\nconst BOOL_VARIATION_DETAIL_METHOD_NAME = 'LDClient.boolVariationDetail';\nconst NUMBER_VARIATION_DETAIL_METHOD_NAME = 'LDClient.numberVariationDetail';\nconst STRING_VARIATION_DETAIL_METHOD_NAME = 'LDClient.stringVariationDetail';\nconst JSON_VARIATION_DETAIL_METHOD_NAME = 'LDClient.jsonVariationDetail';\nconst VARIATION_METHOD_DETAIL_NAME = 'LDClient.variationDetail';\nfunction constructFDv1(sdkKey, platform, config, callbacks, initSuccess, dataSourceErrorHandler, hooks) {\n var _a, _b, _c, _d, _e;\n const { onUpdate, hasEventListeners } = callbacks;\n const hookRunner = new HookRunner_1.default(config.logger, hooks);\n if (!sdkKey && !config.offline) {\n throw new Error('You must configure the client with an SDK key');\n }\n const { logger } = config;\n const baseHeaders = (0, js_sdk_common_1.defaultHeaders)(sdkKey, platform.info, config.tags);\n const clientContext = new js_sdk_common_1.ClientContext(sdkKey, config, platform);\n const featureStore = config.featureStoreFactory(clientContext);\n const dataSourceUpdates = new DataSourceUpdates_1.default(featureStore, hasEventListeners, onUpdate);\n let diagnosticsManager;\n if (config.sendEvents && !config.offline && !config.diagnosticOptOut) {\n diagnosticsManager = new js_sdk_common_1.internal.DiagnosticsManager(sdkKey, platform, (0, createDiagnosticsInitConfig_1.default)(config, platform, featureStore));\n }\n let eventProcessor;\n if (!config.sendEvents || config.offline) {\n eventProcessor = new NullEventProcessor();\n }\n else {\n eventProcessor = new js_sdk_common_1.internal.EventProcessor(config, clientContext, baseHeaders, new ContextDeduplicator_1.default(config), diagnosticsManager);\n }\n const bigSegmentsManager = new BigSegmentsManager_1.default((_b = (_a = config.bigSegments) === null || _a === void 0 ? void 0 : _a.store) === null || _b === void 0 ? void 0 : _b.call(_a, clientContext), (_c = config.bigSegments) !== null && _c !== void 0 ? _c : {}, config.logger, platform.crypto);\n const queries = {\n getFlag(key, cb) {\n featureStore.get(VersionedDataKinds_1.default.Features, key, (item) => cb(item));\n },\n getSegment(key, cb) {\n featureStore.get(VersionedDataKinds_1.default.Segments, key, (item) => cb(item));\n },\n getBigSegmentsMembership(userKey) {\n return bigSegmentsManager.getUserMembership(userKey);\n },\n };\n const evaluator = new Evaluator_1.default(platform, queries);\n const listeners = (0, createStreamListeners_1.createStreamListeners)(dataSourceUpdates, logger, {\n put: initSuccess,\n });\n const makeDefaultProcessor = () => config.stream\n ? new StreamingProcessor_1.default(clientContext, '/all', [], listeners, baseHeaders, diagnosticsManager, dataSourceErrorHandler, config.streamInitialReconnectDelay)\n : new PollingProcessor_1.default(new Requestor_1.default(config, platform.requests, baseHeaders), config.pollInterval, dataSourceUpdates, config.logger, initSuccess, dataSourceErrorHandler);\n let updateProcessor;\n if (!(config.offline || config.useLdd)) {\n updateProcessor =\n (_e = (_d = config.updateProcessorFactory) === null || _d === void 0 ? void 0 : _d.call(config, clientContext, dataSourceUpdates, initSuccess, dataSourceErrorHandler)) !== null && _e !== void 0 ? _e : makeDefaultProcessor();\n }\n return {\n config,\n logger,\n evaluator,\n featureStore,\n updateProcessor,\n eventProcessor,\n bigSegmentsManager,\n hookRunner,\n onError: callbacks.onError,\n onFailed: callbacks.onFailed,\n onReady: callbacks.onReady,\n };\n}\nfunction constructFDv2(sdkKey, platform, config, callbacks, initSuccess, hooks) {\n var _a, _b, _c, _d;\n const { onUpdate, hasEventListeners } = callbacks;\n const hookRunner = new HookRunner_1.default(config.logger, hooks);\n if (!sdkKey && !config.offline) {\n throw new Error('You must configure the client with an SDK key');\n }\n const { logger } = config;\n const baseHeaders = (0, js_sdk_common_1.defaultHeaders)(sdkKey, platform.info, config.tags);\n const clientContext = new js_sdk_common_1.ClientContext(sdkKey, config, platform);\n const dataSystem = config.dataSystem; // dataSystem must be defined to get into this construct function\n const featureStore = dataSystem.featureStoreFactory(clientContext);\n const dataSourceUpdates = new TransactionalDataSourceUpdates_1.default(featureStore, hasEventListeners, onUpdate);\n let diagnosticsManager;\n if (config.sendEvents && !config.offline && !config.diagnosticOptOut) {\n diagnosticsManager = new js_sdk_common_1.internal.DiagnosticsManager(sdkKey, platform, (0, createDiagnosticsInitConfig_1.default)(config, platform, featureStore));\n }\n let eventProcessor;\n if (!config.sendEvents || config.offline) {\n eventProcessor = new NullEventProcessor();\n }\n else {\n eventProcessor = new js_sdk_common_1.internal.EventProcessor(config, clientContext, baseHeaders, new ContextDeduplicator_1.default(config), diagnosticsManager);\n }\n const bigSegmentsManager = new BigSegmentsManager_1.default((_b = (_a = config.bigSegments) === null || _a === void 0 ? void 0 : _a.store) === null || _b === void 0 ? void 0 : _b.call(_a, clientContext), (_c = config.bigSegments) !== null && _c !== void 0 ? _c : {}, config.logger, platform.crypto);\n const queries = {\n getFlag(key, cb) {\n featureStore.get(VersionedDataKinds_1.default.Features, key, (item) => cb(item));\n },\n getSegment(key, cb) {\n featureStore.get(VersionedDataKinds_1.default.Segments, key, (item) => cb(item));\n },\n getBigSegmentsMembership(userKey) {\n return bigSegmentsManager.getUserMembership(userKey);\n },\n };\n const evaluator = new Evaluator_1.default(platform, queries);\n let dataSource;\n let payloadListener;\n if (!(config.offline || config.dataSystem.useLdd)) {\n // make the FDv2 composite datasource with initializers/synchronizers\n const initializers = [];\n const synchronizers = [];\n const fdv1FallbackSynchronizers = [];\n if ((0, LDDataSystemOptions_1.isCustomOptions)(dataSystem.dataSource)) {\n const { initializers: initializerConfigs = [], synchronizers: synchronizerConfigs = [] } = dataSystem.dataSource;\n initializerConfigs.forEach((initializerConfig) => {\n switch (initializerConfig.type) {\n case 'file': {\n initializers.push(() => new fileDataInitilizerFDv2_1.default(initializerConfig, platform, config.logger));\n break;\n }\n case 'polling': {\n initializers.push(() => new OneShotInitializerFDv2_1.default(new Requestor_1.default(config, platform.requests, baseHeaders, '/sdk/poll', config.logger), config.logger));\n break;\n }\n default: {\n throw new Error('Unsupported initializer type');\n }\n }\n });\n synchronizerConfigs.forEach((synchronizerConfig) => {\n switch (synchronizerConfig.type) {\n case 'streaming': {\n const { streamInitialReconnectDelay = Configuration_1.DEFAULT_STREAM_RECONNECT_DELAY } = synchronizerConfig;\n synchronizers.push(() => new StreamingProcessorFDv2_1.default(clientContext, '/sdk/stream', [], baseHeaders, diagnosticsManager, streamInitialReconnectDelay));\n break;\n }\n case 'polling': {\n const { pollInterval = Configuration_1.DEFAULT_POLL_INTERVAL } = synchronizerConfig;\n synchronizers.push(() => new PollingProcessorFDv2_1.default(new Requestor_1.default(config, platform.requests, baseHeaders, '/sdk/poll', config.logger), pollInterval, config.logger));\n break;\n }\n default: {\n throw new Error('Unsupported synchronizer type');\n }\n }\n });\n }\n else {\n // use one shot initializer for performance and cost if we can do a combination of polling and streaming\n if ((0, LDDataSystemOptions_1.isStandardOptions)(dataSystem.dataSource)) {\n initializers.push(() => new OneShotInitializerFDv2_1.default(new Requestor_1.default(config, platform.requests, baseHeaders, '/sdk/poll', config.logger), config.logger));\n }\n // if streaming is configured, add streaming synchronizer\n if ((0, LDDataSystemOptions_1.isStandardOptions)(dataSystem.dataSource) ||\n (0, LDDataSystemOptions_1.isStreamingOnlyOptions)(dataSystem.dataSource)) {\n const reconnectDelay = dataSystem.dataSource.streamInitialReconnectDelay;\n synchronizers.push(() => new StreamingProcessorFDv2_1.default(clientContext, '/sdk/stream', [], baseHeaders, diagnosticsManager, reconnectDelay));\n }\n let pollingInterval = Configuration_1.DEFAULT_POLL_INTERVAL;\n // if polling is configured, add polling synchronizer\n if ((0, LDDataSystemOptions_1.isStandardOptions)(dataSystem.dataSource) || (0, LDDataSystemOptions_1.isPollingOnlyOptions)(dataSystem.dataSource)) {\n pollingInterval = (_d = dataSystem.dataSource.pollInterval) !== null && _d !== void 0 ? _d : Configuration_1.DEFAULT_POLL_INTERVAL;\n synchronizers.push(() => new PollingProcessorFDv2_1.default(new Requestor_1.default(config, platform.requests, baseHeaders, '/sdk/poll', logger), pollingInterval, logger));\n }\n // This is short term handling and will be removed once FDv2 adoption is sufficient.\n fdv1FallbackSynchronizers.push(() => new PollingProcessorFDv2_1.default(new Requestor_1.default(config, platform.requests, baseHeaders, '/sdk/latest-all', config.logger), pollingInterval, config.logger, true));\n }\n dataSource = new js_sdk_common_1.CompositeDataSource(initializers, synchronizers, fdv1FallbackSynchronizers, logger);\n payloadListener = (0, createPayloadListenerFDv2_1.createPayloadListener)(dataSourceUpdates, logger, initSuccess);\n }\n return {\n config,\n logger,\n evaluator,\n featureStore,\n dataSource,\n payloadListener,\n eventProcessor,\n bigSegmentsManager,\n hookRunner,\n onError: callbacks.onError,\n onFailed: callbacks.onFailed,\n onReady: callbacks.onReady,\n };\n}\n/**\n * @ignore\n */\nclass LDClientImpl {\n get logger() {\n return this._logger;\n }\n constructor(_sdkKey, _platform, options, callbacks, internalOptions) {\n this._sdkKey = _sdkKey;\n this._platform = _platform;\n this._initState = InitState.Initializing;\n this._eventFactoryDefault = new EventFactory_1.default(false);\n this._eventFactoryWithReasons = new EventFactory_1.default(true);\n const config = new Configuration_1.default(options, internalOptions);\n this.environmentMetadata = (0, createPluginEnvironmentMetadata_1.createPluginEnvironmentMetadata)(_platform, _sdkKey, config);\n const hooks = [];\n if (config.hooks) {\n hooks.push(...config.hooks);\n }\n config.getImplementationHooks(this.environmentMetadata).forEach((hook) => {\n hooks.push(hook);\n });\n if (!config.dataSystem) {\n // setup for FDv1\n ({\n config: this._config,\n logger: this._logger,\n evaluator: this._evaluator,\n featureStore: this._featureStore,\n updateProcessor: this._updateProcessor,\n eventProcessor: this._eventProcessor,\n bigSegmentsManager: this._bigSegmentsManager,\n hookRunner: this._hookRunner,\n onError: this._onError,\n onFailed: this._onFailed,\n onReady: this._onReady,\n } = constructFDv1(_sdkKey, _platform, config, callbacks, () => this._initSuccess(), (e) => this._dataSourceErrorHandler(e), hooks));\n this.bigSegmentStatusProviderInternal = this._bigSegmentsManager\n .statusProvider;\n if (this._updateProcessor) {\n this._updateProcessor.start();\n }\n else {\n // Deferring the start callback should allow client construction to complete before we start\n // emitting events. Allowing the client an opportunity to register events.\n setTimeout(() => this._initSuccess(), 0);\n }\n }\n else {\n // setup for FDv2\n let transactionalStore;\n let payloadListener;\n ({\n config: this._config,\n logger: this._logger,\n evaluator: this._evaluator,\n featureStore: transactionalStore,\n dataSource: this._dataSource,\n payloadListener,\n eventProcessor: this._eventProcessor,\n bigSegmentsManager: this._bigSegmentsManager,\n hookRunner: this._hookRunner,\n onError: this._onError,\n onFailed: this._onFailed,\n onReady: this._onReady,\n } = constructFDv2(_sdkKey, _platform, config, callbacks, () => this._initSuccess(), hooks));\n this._featureStore = transactionalStore;\n this.bigSegmentStatusProviderInternal = this._bigSegmentsManager\n .statusProvider;\n if (this._dataSource) {\n this._dataSource.start((_, payload) => {\n payloadListener === null || payloadListener === void 0 ? void 0 : payloadListener(payload);\n }, (state, err) => {\n if (state === js_sdk_common_1.subsystem.DataSourceState.Closed && err) {\n this._dataSourceErrorHandler(err);\n }\n }, () => { var _a; return (_a = transactionalStore.getSelector) === null || _a === void 0 ? void 0 : _a.call(transactionalStore); });\n }\n else {\n // Deferring the start callback should allow client construction to complete before we start\n // emitting events. Allowing the client an opportunity to register events.\n setTimeout(() => this._initSuccess(), 0);\n }\n }\n }\n initialized() {\n return this._initState === InitState.Initialized;\n }\n waitForInitialization(options) {\n // An initialization promise is only created if someone is going to use that promise.\n // If we always created an initialization promise, and there was no call waitForInitialization\n // by the time the promise was rejected, then that would result in an unhandled promise\n // rejection.\n var _a, _b;\n // If there is no update processor, then there is functionally no initialization\n // so it is fine not to wait.\n if ((options === null || options === void 0 ? void 0 : options.timeout) === undefined &&\n (this._updateProcessor !== undefined || this._dataSource !== undefined)) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.warn('The waitForInitialization function was called without a timeout specified.' +\n ' In a future version a default timeout will be applied.');\n }\n if ((options === null || options === void 0 ? void 0 : options.timeout) !== undefined &&\n (options === null || options === void 0 ? void 0 : options.timeout) > HIGH_TIMEOUT_THRESHOLD &&\n (this._updateProcessor !== undefined || this._dataSource !== undefined)) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.warn('The waitForInitialization function was called with a timeout greater than ' +\n `${HIGH_TIMEOUT_THRESHOLD} seconds. We recommend a timeout of less than ` +\n `${HIGH_TIMEOUT_THRESHOLD} seconds.`);\n }\n // Initialization promise was created by a previous call to waitForInitialization.\n if (this._initializedPromise) {\n // This promise may already be resolved/rejected, but it doesn't hurt to wrap it in a timeout.\n return this._clientWithTimeout(this._initializedPromise, options === null || options === void 0 ? void 0 : options.timeout, this._logger);\n }\n // Initialization completed before waitForInitialization was called, so we have completed\n // and there was no promise. So we make a resolved promise and return it.\n if (this._initState === InitState.Initialized) {\n this._initializedPromise = Promise.resolve(this);\n // Already initialized, no need to timeout.\n return this._initializedPromise;\n }\n // Initialization failed before waitForInitialization was called, so we have completed\n // and there was no promise. So we make a rejected promise and return it.\n if (this._initState === InitState.Failed) {\n // Already failed, no need to timeout.\n this._initializedPromise = Promise.reject(this._rejectionReason);\n return this._initializedPromise;\n }\n if (!this._initializedPromise) {\n this._initializedPromise = new Promise((resolve, reject) => {\n this._initResolve = resolve;\n this._initReject = reject;\n });\n }\n return this._clientWithTimeout(this._initializedPromise, options === null || options === void 0 ? void 0 : options.timeout, this._logger);\n }\n variation(key, context, defaultValue, callback) {\n var _a, _b, _c;\n return this._hookRunner\n .withEvaluationSeries(key, context, defaultValue, VARIATION_METHOD_NAME, () => new Promise((resolve) => {\n this._evaluateIfPossible(key, context, defaultValue, this._eventFactoryDefault, (res) => {\n resolve(res.detail);\n });\n }), (_c = (_b = (_a = this._featureStore).getInitMetaData) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c.environmentId)\n .then((detail) => {\n callback === null || callback === void 0 ? void 0 : callback(null, detail.value);\n return detail.value;\n });\n }\n variationDetail(key, context, defaultValue, callback) {\n var _a, _b, _c;\n return this._hookRunner.withEvaluationSeries(key, context, defaultValue, VARIATION_METHOD_DETAIL_NAME, () => new Promise((resolve) => {\n this._evaluateIfPossible(key, context, defaultValue, this._eventFactoryWithReasons, (res) => {\n resolve(res.detail);\n callback === null || callback === void 0 ? void 0 : callback(null, res.detail);\n });\n }), (_c = (_b = (_a = this._featureStore).getInitMetaData) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c.environmentId);\n }\n _typedEval(key, context, defaultValue, eventFactory, methodName, typeChecker) {\n var _a, _b, _c;\n return this._hookRunner.withEvaluationSeries(key, context, defaultValue, methodName, () => new Promise((resolve) => {\n this._evaluateIfPossible(key, context, defaultValue, eventFactory, (res) => {\n const typedRes = {\n value: res.detail.value,\n reason: res.detail.reason,\n variationIndex: res.detail.variationIndex,\n };\n resolve(typedRes);\n }, typeChecker);\n }), (_c = (_b = (_a = this._featureStore).getInitMetaData) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c.environmentId);\n }\n async boolVariation(key, context, defaultValue) {\n return (await this._typedEval(key, context, defaultValue, this._eventFactoryDefault, BOOL_VARIATION_METHOD_NAME, (value) => [js_sdk_common_1.TypeValidators.Boolean.is(value), js_sdk_common_1.TypeValidators.Boolean.getType()])).value;\n }\n async numberVariation(key, context, defaultValue) {\n return (await this._typedEval(key, context, defaultValue, this._eventFactoryDefault, NUMBER_VARIATION_METHOD_NAME, (value) => [js_sdk_common_1.TypeValidators.Number.is(value), js_sdk_common_1.TypeValidators.Number.getType()])).value;\n }\n async stringVariation(key, context, defaultValue) {\n return (await this._typedEval(key, context, defaultValue, this._eventFactoryDefault, STRING_VARIATION_METHOD_NAME, (value) => [js_sdk_common_1.TypeValidators.String.is(value), js_sdk_common_1.TypeValidators.String.getType()])).value;\n }\n jsonVariation(key, context, defaultValue) {\n var _a, _b, _c;\n return this._hookRunner\n .withEvaluationSeries(key, context, defaultValue, JSON_VARIATION_METHOD_NAME, () => new Promise((resolve) => {\n this._evaluateIfPossible(key, context, defaultValue, this._eventFactoryDefault, (res) => {\n resolve(res.detail);\n });\n }), (_c = (_b = (_a = this._featureStore).getInitMetaData) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c.environmentId)\n .then((detail) => detail.value);\n }\n boolVariationDetail(key, context, defaultValue) {\n return this._typedEval(key, context, defaultValue, this._eventFactoryWithReasons, BOOL_VARIATION_DETAIL_METHOD_NAME, (value) => [js_sdk_common_1.TypeValidators.Boolean.is(value), js_sdk_common_1.TypeValidators.Boolean.getType()]);\n }\n numberVariationDetail(key, context, defaultValue) {\n return this._typedEval(key, context, defaultValue, this._eventFactoryWithReasons, NUMBER_VARIATION_DETAIL_METHOD_NAME, (value) => [js_sdk_common_1.TypeValidators.Number.is(value), js_sdk_common_1.TypeValidators.Number.getType()]);\n }\n stringVariationDetail(key, context, defaultValue) {\n return this._typedEval(key, context, defaultValue, this._eventFactoryWithReasons, STRING_VARIATION_DETAIL_METHOD_NAME, (value) => [js_sdk_common_1.TypeValidators.String.is(value), js_sdk_common_1.TypeValidators.String.getType()]);\n }\n jsonVariationDetail(key, context, defaultValue) {\n var _a, _b, _c;\n return this._hookRunner.withEvaluationSeries(key, context, defaultValue, JSON_VARIATION_DETAIL_METHOD_NAME, () => new Promise((resolve) => {\n this._evaluateIfPossible(key, context, defaultValue, this._eventFactoryWithReasons, (res) => {\n resolve(res.detail);\n });\n }), (_c = (_b = (_a = this._featureStore).getInitMetaData) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c.environmentId);\n }\n async _migrationVariationInternal(key, context, defaultValue) {\n var _a;\n const res = await new Promise((resolve) => {\n this._evaluateIfPossible(key, context, defaultValue, this._eventFactoryWithReasons, ({ detail }, flag) => {\n if (!(0, api_1.IsMigrationStage)(detail.value)) {\n const error = new Error(`Unrecognized MigrationState for \"${key}\"; returning default value.`);\n this._onError(error);\n const reason = {\n kind: 'ERROR',\n errorKind: ErrorKinds.WrongType,\n };\n resolve({\n detail: {\n value: defaultValue,\n reason,\n },\n flag,\n });\n return;\n }\n resolve({ detail, flag });\n });\n });\n const { detail, flag } = res;\n const checkRatio = (_a = flag === null || flag === void 0 ? void 0 : flag.migration) === null || _a === void 0 ? void 0 : _a.checkRatio;\n const samplingRatio = flag === null || flag === void 0 ? void 0 : flag.samplingRatio;\n return {\n detail,\n migration: {\n value: detail.value,\n tracker: new MigrationOpTracker_1.default(key, context, defaultValue, detail.value, detail.reason, checkRatio, \n // Can be null for compatibility reasons.\n detail.variationIndex === null ? undefined : detail.variationIndex, flag === null || flag === void 0 ? void 0 : flag.version, samplingRatio, this._logger),\n },\n };\n }\n async migrationVariation(key, context, defaultValue) {\n var _a, _b, _c;\n const res = await this._hookRunner.withEvaluationSeriesExtraDetail(key, context, defaultValue, MIGRATION_VARIATION_METHOD_NAME, () => this._migrationVariationInternal(key, context, defaultValue), (_c = (_b = (_a = this._featureStore).getInitMetaData) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c.environmentId);\n return res.migration;\n }\n allFlagsState(context, options, callback) {\n var _a, _b, _c;\n if (this._config.offline) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.info('allFlagsState() called in offline mode. Returning empty state.');\n const allFlagState = new FlagsStateBuilder_1.default(false, false).build();\n callback === null || callback === void 0 ? void 0 : callback(null, allFlagState);\n return Promise.resolve(allFlagState);\n }\n const evalContext = js_sdk_common_1.Context.fromLDContext(context);\n if (!evalContext.valid) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.info(`${(_c = evalContext.message) !== null && _c !== void 0 ? _c : 'Invalid context.'}. Returning empty state.`);\n return Promise.resolve(new FlagsStateBuilder_1.default(false, false).build());\n }\n return new Promise((resolve) => {\n const doEval = (valid) => this._featureStore.all(VersionedDataKinds_1.default.Features, (allFlags) => {\n const builder = new FlagsStateBuilder_1.default(valid, !!(options === null || options === void 0 ? void 0 : options.withReasons));\n const clientOnly = !!(options === null || options === void 0 ? void 0 : options.clientSideOnly);\n const detailsOnlyIfTracked = !!(options === null || options === void 0 ? void 0 : options.detailsOnlyForTrackedFlags);\n (0, collection_1.allAsync)(Object.values(allFlags), (storeItem, iterCb) => {\n var _a;\n const flag = storeItem;\n if (clientOnly && !((_a = flag.clientSideAvailability) === null || _a === void 0 ? void 0 : _a.usingEnvironmentId)) {\n iterCb(true);\n return;\n }\n this._evaluator.evaluateCb(flag, evalContext, (res) => {\n var _a;\n if (res.isError) {\n this._onError(new Error(`Error for feature flag \"${flag.key}\" while evaluating all flags: ${res.message}`));\n }\n const requireExperimentData = (0, isExperiment_1.default)(flag, res.detail.reason);\n builder.addFlag(flag, res.detail.value, (_a = res.detail.variationIndex) !== null && _a !== void 0 ? _a : undefined, res.detail.reason, flag.trackEvents || requireExperimentData, requireExperimentData, detailsOnlyIfTracked, res.prerequisites);\n iterCb(true);\n });\n }, () => {\n const res = builder.build();\n callback === null || callback === void 0 ? void 0 : callback(null, res);\n resolve(res);\n });\n });\n if (!this.initialized()) {\n this._featureStore.initialized((storeInitialized) => {\n var _a, _b;\n let valid = true;\n if (storeInitialized) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.warn('Called allFlagsState before client initialization; using last known' +\n ' values from data store');\n }\n else {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.warn('Called allFlagsState before client initialization. Data store not available; ' +\n 'returning empty state');\n valid = false;\n }\n doEval(valid);\n });\n }\n else {\n doEval(true);\n }\n });\n }\n secureModeHash(context) {\n const checkedContext = js_sdk_common_1.Context.fromLDContext(context);\n const key = checkedContext.valid ? checkedContext.canonicalKey : undefined;\n if (!this._platform.crypto.createHmac) {\n // This represents an error in platform implementation.\n throw new Error('Platform must implement createHmac');\n }\n const hmac = this._platform.crypto.createHmac('sha256', this._sdkKey);\n if (key === undefined) {\n throw new js_sdk_common_1.LDClientError('Could not generate secure mode hash for invalid context');\n }\n hmac.update(key);\n return hmac.digest('hex');\n }\n close() {\n var _a, _b;\n this._eventProcessor.close();\n (_a = this._updateProcessor) === null || _a === void 0 ? void 0 : _a.close();\n (_b = this._dataSource) === null || _b === void 0 ? void 0 : _b.stop();\n this._featureStore.close();\n this._bigSegmentsManager.close();\n }\n isOffline() {\n return this._config.offline;\n }\n track(key, context, data, metricValue) {\n var _a, _b;\n const checkedContext = js_sdk_common_1.Context.fromLDContext(context);\n if (!checkedContext.valid) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.warn(ClientMessages.MissingContextKeyNoEvent);\n return;\n }\n // 0 is valid, so do not truthy check the metric value\n if (metricValue !== undefined && !js_sdk_common_1.TypeValidators.Number.is(metricValue)) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.warn(ClientMessages.invalidMetricValue(typeof metricValue));\n }\n this._eventProcessor.sendEvent(this._eventFactoryDefault.customEvent(key, checkedContext, data, metricValue));\n }\n trackMigration(event) {\n const converted = (0, MigrationOpEventConversion_1.default)(event);\n if (!converted) {\n return;\n }\n this._eventProcessor.sendEvent(converted);\n }\n identify(context) {\n var _a;\n const checkedContext = js_sdk_common_1.Context.fromLDContext(context);\n if (!checkedContext.valid) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.warn(ClientMessages.MissingContextKeyNoEvent);\n return;\n }\n this._eventProcessor.sendEvent(this._eventFactoryDefault.identifyEvent(checkedContext));\n }\n async flush(callback) {\n try {\n await this._eventProcessor.flush();\n }\n catch (err) {\n return callback === null || callback === void 0 ? void 0 : callback(err, false);\n }\n return callback === null || callback === void 0 ? void 0 : callback(null, true);\n }\n addHook(hook) {\n this._hookRunner.addHook(hook);\n }\n _variationInternal(flagKey, context, defaultValue, eventFactory, cb, typeChecker) {\n var _a, _b;\n if (this._config.offline) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.info('Variation called in offline mode. Returning default value.');\n cb(EvalResult_1.default.forError(ErrorKinds.ClientNotReady, undefined, defaultValue));\n return;\n }\n const evalContext = js_sdk_common_1.Context.fromLDContext(context);\n if (!evalContext.valid) {\n this._onError(new js_sdk_common_1.LDClientError(`${(_b = evalContext.message) !== null && _b !== void 0 ? _b : 'Context not valid;'} returning default value.`));\n cb(EvalResult_1.default.forError(ErrorKinds.UserNotSpecified, undefined, defaultValue));\n return;\n }\n this._featureStore.get(VersionedDataKinds_1.default.Features, flagKey, (item) => {\n const flag = item;\n if (!flag) {\n const error = new js_sdk_common_1.LDClientError(`Unknown feature flag \"${flagKey}\"; returning default value`);\n this._onError(error);\n const result = EvalResult_1.default.forError(ErrorKinds.FlagNotFound, undefined, defaultValue);\n this._eventProcessor.sendEvent(this._eventFactoryDefault.unknownFlagEvent(flagKey, defaultValue, evalContext));\n cb(result);\n return;\n }\n this._evaluator.evaluateCb(flag, evalContext, (evalRes) => {\n var _a;\n if (evalRes.detail.variationIndex === undefined ||\n evalRes.detail.variationIndex === null) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Result value is null in variation');\n evalRes.setDefault(defaultValue);\n }\n if (typeChecker) {\n const [matched, type] = typeChecker(evalRes.detail.value);\n if (!matched) {\n const errorRes = EvalResult_1.default.forError(ErrorKinds.WrongType, `Did not receive expected type (${type}) evaluating feature flag \"${flagKey}\"`, defaultValue);\n this._sendEvalEvent(errorRes, eventFactory, flag, evalContext, defaultValue);\n cb(errorRes, flag);\n return;\n }\n }\n this._sendEvalEvent(evalRes, eventFactory, flag, evalContext, defaultValue);\n cb(evalRes, flag);\n }, eventFactory);\n });\n }\n _sendEvalEvent(evalRes, eventFactory, flag, evalContext, defaultValue) {\n var _a;\n (_a = evalRes.events) === null || _a === void 0 ? void 0 : _a.forEach((event) => {\n this._eventProcessor.sendEvent(Object.assign({}, event));\n });\n this._eventProcessor.sendEvent(eventFactory.evalEventServer(flag, evalContext, evalRes.detail, defaultValue, undefined));\n }\n _evaluateIfPossible(flagKey, context, defaultValue, eventFactory, cb, typeChecker) {\n if (!this.initialized()) {\n this._featureStore.initialized((storeInitialized) => {\n var _a, _b;\n if (storeInitialized) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.warn('Variation called before LaunchDarkly client initialization completed' +\n \" (did you wait for the 'ready' event?) - using last known values from feature store\");\n this._variationInternal(flagKey, context, defaultValue, eventFactory, cb, typeChecker);\n return;\n }\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.warn('Variation called before LaunchDarkly client initialization completed (did you wait for the' +\n \"'ready' event?) - using default value\");\n cb(EvalResult_1.default.forError(ErrorKinds.ClientNotReady, undefined, defaultValue));\n });\n return;\n }\n this._variationInternal(flagKey, context, defaultValue, eventFactory, cb, typeChecker);\n }\n _dataSourceErrorHandler(e) {\n var _a;\n const error = e.code === 401 ? new Error('Authentication failed. Double check your SDK key.') : e;\n this._onError(error);\n this._onFailed(error);\n if (!this.initialized()) {\n this._initState = InitState.Failed;\n this._rejectionReason = error;\n (_a = this._initReject) === null || _a === void 0 ? void 0 : _a.call(this, error);\n }\n }\n _initSuccess() {\n var _a;\n if (!this.initialized()) {\n this._initState = InitState.Initialized;\n (_a = this._initResolve) === null || _a === void 0 ? void 0 : _a.call(this, this);\n this._onReady();\n }\n }\n /**\n * Apply a timeout promise to a base promise. This is for use with waitForInitialization.\n * Currently it returns a LDClient. In the future it should return a status.\n *\n * The client isn't always the expected type of the consumer. It returns an LDClient interface\n * which is less capable than, for example, the node client interface.\n *\n * @param basePromise The promise to race against a timeout.\n * @param timeout The timeout in seconds.\n * @param logger A logger to log when the timeout expires.\n * @returns\n */\n _clientWithTimeout(basePromise, timeout, logger) {\n if (timeout) {\n const cancelableTimeout = (0, js_sdk_common_1.cancelableTimedPromise)(timeout, 'waitForInitialization');\n return Promise.race([\n basePromise.then(() => this),\n cancelableTimeout.promise.then(() => this),\n ])\n .catch((reason) => {\n if (reason instanceof js_sdk_common_1.LDTimeoutError) {\n logger === null || logger === void 0 ? void 0 : logger.error(reason.message);\n }\n throw reason;\n })\n .finally(() => cancelableTimeout.cancel());\n }\n return basePromise;\n }\n}\nexports.default = LDClientImpl;\n//# sourceMappingURL=LDClientImpl.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createMigration = exports.LDMigrationError = exports.LDMigrationSuccess = void 0;\nconst api_1 = require(\"./api\");\nconst LDMigrationOptions_1 = require(\"./api/options/LDMigrationOptions\");\nasync function safeCall(method) {\n try {\n // Awaiting to allow catching.\n const res = await method();\n return res;\n }\n catch (error) {\n return {\n success: false,\n error,\n };\n }\n}\n/**\n * Report a successful migration operation from `readNew`, `readOld`, `writeNew` or `writeOld`.\n *\n * ```\n * readNew: async () => {\n * const myResult = doMyOldRead();\n * if(myResult.wasGood) {\n * return LDMigrationSuccess(myResult);\n * }\n * return LDMigrationError(myResult.error)\n * }\n * ```\n *\n * @param result The result of the operation.\n * @returns An {@link LDMethodResult}\n */\nfunction LDMigrationSuccess(result) {\n return {\n success: true,\n result,\n };\n}\nexports.LDMigrationSuccess = LDMigrationSuccess;\n/**\n * Report a failed migration operation from `readNew`, `readOld`, `writeNew` or `writeOld`.\n *\n * ```\n * readNew: async () => {\n * const myResult = doMyOldRead();\n * if(myResult.wasGood) {\n * return LDMigrationSuccess(myResult);\n * }\n * return LDMigrationError(myResult.error)\n * }\n * ```\n *\n * @param result The result of the operations.\n * @returns An {@link LDMethodResult}\n */\nfunction LDMigrationError(error) {\n return {\n success: false,\n error,\n };\n}\nexports.LDMigrationError = LDMigrationError;\n/**\n * Class which allows performing technology migrations.\n */\nclass Migration {\n constructor(_client, _config) {\n var _a, _b;\n this._client = _client;\n this._config = _config;\n this._readTable = {\n [api_1.LDMigrationStage.Off]: async (context) => this._doSingleOp(context, 'old', this._config.readOld.bind(this._config)),\n [api_1.LDMigrationStage.DualWrite]: async (context) => this._doSingleOp(context, 'old', this._config.readOld.bind(this._config)),\n [api_1.LDMigrationStage.Shadow]: async (context) => {\n const { fromOld, fromNew } = await this._doRead(context);\n this._trackConsistency(context, fromOld, fromNew);\n return fromOld;\n },\n [api_1.LDMigrationStage.Live]: async (context) => {\n const { fromNew, fromOld } = await this._doRead(context);\n this._trackConsistency(context, fromOld, fromNew);\n return fromNew;\n },\n [api_1.LDMigrationStage.RampDown]: async (context) => this._doSingleOp(context, 'new', this._config.readNew.bind(this._config)),\n [api_1.LDMigrationStage.Complete]: async (context) => this._doSingleOp(context, 'new', this._config.readNew.bind(this._config)),\n };\n this._writeTable = {\n [api_1.LDMigrationStage.Off]: async (context) => ({\n authoritative: await this._doSingleOp(context, 'old', this._config.writeOld.bind(this._config)),\n }),\n [api_1.LDMigrationStage.DualWrite]: async (context) => {\n const fromOld = await this._doSingleOp(context, 'old', this._config.writeOld.bind(this._config));\n if (!fromOld.success) {\n return {\n authoritative: fromOld,\n };\n }\n const fromNew = await this._doSingleOp(context, 'new', this._config.writeNew.bind(this._config));\n return {\n authoritative: fromOld,\n nonAuthoritative: fromNew,\n };\n },\n [api_1.LDMigrationStage.Shadow]: async (context) => {\n const fromOld = await this._doSingleOp(context, 'old', this._config.writeOld.bind(this._config));\n if (!fromOld.success) {\n return {\n authoritative: fromOld,\n };\n }\n const fromNew = await this._doSingleOp(context, 'new', this._config.writeNew.bind(this._config));\n return {\n authoritative: fromOld,\n nonAuthoritative: fromNew,\n };\n },\n [api_1.LDMigrationStage.Live]: async (context) => {\n const fromNew = await this._doSingleOp(context, 'new', this._config.writeNew.bind(this._config));\n if (!fromNew.success) {\n return {\n authoritative: fromNew,\n };\n }\n const fromOld = await this._doSingleOp(context, 'old', this._config.writeOld.bind(this._config));\n return {\n authoritative: fromNew,\n nonAuthoritative: fromOld,\n };\n },\n [api_1.LDMigrationStage.RampDown]: async (context) => {\n const fromNew = await this._doSingleOp(context, 'new', this._config.writeNew.bind(this._config));\n if (!fromNew.success) {\n return {\n authoritative: fromNew,\n };\n }\n const fromOld = await this._doSingleOp(context, 'old', this._config.writeOld.bind(this._config));\n return {\n authoritative: fromNew,\n nonAuthoritative: fromOld,\n };\n },\n [api_1.LDMigrationStage.Complete]: async (context) => ({\n authoritative: await this._doSingleOp(context, 'new', this._config.writeNew.bind(this._config)),\n }),\n };\n if (this._config.execution) {\n this._execution = this._config.execution;\n }\n else {\n this._execution = new LDMigrationOptions_1.LDConcurrentExecution();\n }\n this._latencyTracking = (_a = this._config.latencyTracking) !== null && _a !== void 0 ? _a : true;\n this._errorTracking = (_b = this._config.errorTracking) !== null && _b !== void 0 ? _b : true;\n }\n async read(key, context, defaultStage, payload) {\n const stage = await this._client.migrationVariation(key, context, defaultStage);\n const res = await this._readTable[stage.value]({\n payload,\n tracker: stage.tracker,\n });\n stage.tracker.op('read');\n this._sendEvent(stage.tracker);\n return res;\n }\n async write(key, context, defaultStage, payload) {\n const stage = await this._client.migrationVariation(key, context, defaultStage);\n const res = await this._writeTable[stage.value]({\n payload,\n tracker: stage.tracker,\n });\n stage.tracker.op('write');\n this._sendEvent(stage.tracker);\n return res;\n }\n _sendEvent(tracker) {\n const event = tracker.createEvent();\n if (event) {\n this._client.trackMigration(event);\n }\n }\n _trackConsistency(context, oldValue, newValue) {\n if (!this._config.check) {\n return;\n }\n if (oldValue.success && newValue.success) {\n // Check is validated before this point, so it is force unwrapped.\n context.tracker.consistency(() => this._config.check(oldValue.result, newValue.result));\n }\n }\n async _readSequentialFixed(context) {\n const fromOld = await this._doSingleOp(context, 'old', this._config.readOld.bind(this._config));\n const fromNew = await this._doSingleOp(context, 'new', this._config.readNew.bind(this._config));\n return { fromOld, fromNew };\n }\n async _readConcurrent(context) {\n const fromOldPromise = this._doSingleOp(context, 'old', this._config.readOld.bind(this._config));\n const fromNewPromise = this._doSingleOp(context, 'new', this._config.readNew.bind(this._config));\n const [fromOld, fromNew] = await Promise.all([fromOldPromise, fromNewPromise]);\n return { fromOld, fromNew };\n }\n async _readSequentialRandom(context) {\n // This number is not used for a purpose requiring cryptographic security.\n const randomIndex = Math.floor(Math.random() * 2);\n // Effectively flip a coin and do it on one order or the other.\n if (randomIndex === 0) {\n const fromOld = await this._doSingleOp(context, 'old', this._config.readOld.bind(this._config));\n const fromNew = await this._doSingleOp(context, 'new', this._config.readNew.bind(this._config));\n return { fromOld, fromNew };\n }\n const fromNew = await this._doSingleOp(context, 'new', this._config.readNew.bind(this._config));\n const fromOld = await this._doSingleOp(context, 'old', this._config.readOld.bind(this._config));\n return { fromOld, fromNew };\n }\n async _doRead(context) {\n var _a;\n if (((_a = this._execution) === null || _a === void 0 ? void 0 : _a.type) === LDMigrationOptions_1.LDExecution.Serial) {\n const serial = this._execution;\n if (serial.ordering === LDMigrationOptions_1.LDExecutionOrdering.Fixed) {\n return this._readSequentialFixed(context);\n }\n return this._readSequentialRandom(context);\n }\n return this._readConcurrent(context);\n }\n async _doSingleOp(context, origin, method) {\n context.tracker.invoked(origin);\n const res = await this._trackLatency(context.tracker, origin, () => safeCall(() => method(context.payload)));\n if (!res.success && this._errorTracking) {\n context.tracker.error(origin);\n }\n return Object.assign({ origin }, res);\n }\n async _trackLatency(tracker, origin, method) {\n if (!this._latencyTracking) {\n return method();\n }\n let start;\n let end;\n let result;\n // TODO: Need to validate performance existence check with edge SDKs.\n if (typeof performance !== 'undefined') {\n start = performance.now();\n result = await method();\n end = performance.now();\n }\n else {\n start = Date.now();\n result = await method();\n end = Date.now();\n }\n // Performance timer is in ms, but may have a microsecond resolution\n // fractional component.\n const latency = end - start;\n tracker.latency(origin, latency);\n return result;\n }\n}\nfunction createMigration(client, config) {\n return new Migration(client, config);\n}\nexports.createMigration = createMigration;\n//# sourceMappingURL=Migration.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst serialization_1 = require(\"../store/serialization\");\nconst VersionedDataKinds_1 = require(\"../store/VersionedDataKinds\");\nconst FileLoader_1 = require(\"./FileLoader\");\nfunction makeFlagWithValue(key, value, version) {\n return {\n key,\n on: true,\n fallthrough: { variation: 0 },\n variations: [value],\n version,\n };\n}\nclass FileDataSource {\n /**\n * This is internal because we want instances to only be created with the\n * factory.\n * @internal\n */\n constructor(options, filesystem, _featureStore, _initSuccessHandler = () => { }, _errorHandler) {\n var _a;\n this._featureStore = _featureStore;\n this._initSuccessHandler = _initSuccessHandler;\n this._errorHandler = _errorHandler;\n this._allData = {};\n this._fileLoader = new FileLoader_1.default(filesystem, options.paths, (_a = options.autoUpdate) !== null && _a !== void 0 ? _a : false, (results) => {\n var _a, _b;\n // Whenever changes are detected we re-process all of the data.\n // The FileLoader will have handled debouncing for us.\n try {\n this._processFileData(results);\n }\n catch (err) {\n // If this was during start, then the initCallback will be present.\n (_a = this._errorHandler) === null || _a === void 0 ? void 0 : _a.call(this, err);\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error(`Error processing files: ${err}`);\n }\n });\n this._logger = options.logger;\n this._yamlParser = options.yamlParser;\n }\n start() {\n // Use an immediately invoked function expression to allow handling of the\n // async loading without making start async itself.\n (async () => {\n var _a;\n try {\n await this._fileLoader.loadAndWatch();\n }\n catch (err) {\n // There was an issue loading/watching the files.\n // Report back to the caller.\n (_a = this._errorHandler) === null || _a === void 0 ? void 0 : _a.call(this, err);\n }\n })();\n }\n stop() {\n this._fileLoader.close();\n }\n close() {\n this.stop();\n }\n _addItem(kind, item) {\n if (!this._allData[kind.namespace]) {\n this._allData[kind.namespace] = {};\n }\n if (this._allData[kind.namespace][item.key]) {\n throw new Error(`found duplicate key: \"${item.key}\"`);\n }\n else {\n this._allData[kind.namespace][item.key] = item;\n }\n }\n _processFileData(fileData) {\n // Clear any existing data before re-populating it.\n const oldData = this._allData;\n this._allData = {};\n // We let the parsers throw, and the caller can handle the rejection.\n fileData.forEach((fd) => {\n let parsed;\n if (fd.path.endsWith('.yml') || fd.path.endsWith('.yaml')) {\n if (this._yamlParser) {\n parsed = this._yamlParser(fd.data);\n }\n else {\n throw new Error(`Attempted to parse yaml file (${fd.path}) without parser.`);\n }\n }\n else {\n parsed = JSON.parse(fd.data);\n }\n this._processParsedData(parsed, oldData);\n });\n this._featureStore.init(this._allData, () => {\n // Call the init callback if present.\n // Then clear the callback so we cannot call it again.\n this._initSuccessHandler();\n this._initSuccessHandler = () => { };\n });\n }\n _processParsedData(parsed, oldData) {\n Object.keys(parsed.flags || {}).forEach((key) => {\n (0, serialization_1.processFlag)(parsed.flags[key]);\n this._addItem(VersionedDataKinds_1.default.Features, parsed.flags[key]);\n });\n Object.keys(parsed.flagValues || {}).forEach((key) => {\n var _a, _b;\n const previousInstance = (_a = oldData[VersionedDataKinds_1.default.Features.namespace]) === null || _a === void 0 ? void 0 : _a[key];\n let { version } = previousInstance !== null && previousInstance !== void 0 ? previousInstance : { version: 1 };\n // If the data is different, then we want to increment the version.\n if (previousInstance &&\n JSON.stringify(parsed.flagValues[key]) !== JSON.stringify((_b = previousInstance === null || previousInstance === void 0 ? void 0 : previousInstance.variations) === null || _b === void 0 ? void 0 : _b[0])) {\n version += 1;\n }\n const flag = makeFlagWithValue(key, parsed.flagValues[key], version);\n (0, serialization_1.processFlag)(flag);\n this._addItem(VersionedDataKinds_1.default.Features, flag);\n });\n Object.keys(parsed.segments || {}).forEach((key) => {\n (0, serialization_1.processSegment)(parsed.segments[key]);\n this._addItem(VersionedDataKinds_1.default.Segments, parsed.segments[key]);\n });\n }\n}\nexports.default = FileDataSource;\n//# sourceMappingURL=FileDataSource.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst FileDataSource_1 = require(\"../data_sources/FileDataSource\");\n/**\n * Class for creating file data sources.\n */\nclass FileDataSourceFactory {\n constructor(_options) {\n this._options = _options;\n }\n /**\n * Method for creating instances of the file data source. This method is intended to be used\n * by the SDK.\n *\n * @param config SDK configuration required by the file data source.\n * @param filesystem Platform abstraction used for filesystem access.\n * @returns a {@link FileDataSource}\n *\n * @internal\n */\n create(ldClientContext, featureStore, initSuccessHandler, errorHandler) {\n const updatedOptions = {\n paths: this._options.paths,\n autoUpdate: this._options.autoUpdate,\n logger: this._options.logger || ldClientContext.basicConfiguration.logger,\n yamlParser: this._options.yamlParser,\n };\n return new FileDataSource_1.default(updatedOptions, ldClientContext.platform.fileSystem, featureStore, initSuccessHandler, errorHandler);\n }\n getFactory() {\n return (ldClientContext, featureStore, initSuccessHandler, errorHandler) => this.create(ldClientContext, featureStore, initSuccessHandler, errorHandler);\n }\n}\nexports.default = FileDataSourceFactory;\n//# sourceMappingURL=FileDataSourceFactory.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.variationForBoolean = exports.FALSE_VARIATION_INDEX = exports.TRUE_VARIATION_INDEX = void 0;\nexports.TRUE_VARIATION_INDEX = 0;\nexports.FALSE_VARIATION_INDEX = 1;\n/**\n * @internal\n */\nfunction variationForBoolean(val) {\n return val ? exports.TRUE_VARIATION_INDEX : exports.FALSE_VARIATION_INDEX;\n}\nexports.variationForBoolean = variationForBoolean;\n//# sourceMappingURL=booleanVariation.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst booleanVariation_1 = require(\"./booleanVariation\");\n/**\n * A builder for feature flag rules to be used with {@link TestDataFlagBuilder}.\n *\n * In the LaunchDarkly model, a flag can have any number of rules, and\n * a rule can have any number of clauses. A clause is an individual test\n * such as \"name is 'X'\". A rule matches a user if all of the rule's\n * clauses match the user.\n *\n * To start defining a rule, use one of the flag builder's matching methods\n * such as `ifMatch`. This defines the first clause for the rule. Optionally,\n * you may add more clauses with the rule builder's methods such as `andMatch`.\n * Finally, call `thenReturn` to finish defining the rule.\n */\nclass TestDataRuleBuilder {\n /**\n * @internal\n */\n constructor(_flagBuilder, clauses, variation) {\n this._flagBuilder = _flagBuilder;\n this._clauses = [];\n if (clauses) {\n this._clauses = [...clauses];\n }\n if (variation !== undefined) {\n this._variation = variation;\n }\n }\n /**\n * Adds another clause using the \"is one of\" operator.\n *\n * For example, this creates a rule that returns `true` if the name is\n * \"Patsy\" and the country is \"gb\":\n *\n * testData.flag('flag')\n * .ifMatch('name', 'Patsy')\n * .andMatch('country', 'gb')\n * .thenReturn(true)\n *\n * @param contextKind the kind of the context\n * @param attribute the user attribute to match against\n * @param values values to compare to\n * @return the flag rule builder\n */\n andMatch(contextKind, attribute, ...values) {\n this._clauses.push({\n contextKind,\n attribute,\n attributeReference: new js_sdk_common_1.AttributeReference(attribute),\n op: 'in',\n values,\n negate: false,\n });\n return this;\n }\n /**\n * Adds another clause using the \"is not one of\" operator.\n *\n * For example, this creates a rule that returns `true` if the name is\n * \"Patsy\" and the country is not \"gb\":\n *\n * testData.flag('flag')\n * .ifMatch('name', 'Patsy')\n * .andNotMatch('country', 'gb')\n * .thenReturn(true)\n *\n * @param contextKind the kind of the context\n * @param attribute the user attribute to match against\n * @param values values to compare to\n * @return the flag rule builder\n */\n andNotMatch(contextKind, attribute, ...values) {\n this._clauses.push({\n contextKind,\n attribute,\n attributeReference: new js_sdk_common_1.AttributeReference(attribute),\n op: 'in',\n values,\n negate: true,\n });\n return this;\n }\n /**\n * Finishes defining the rule, specifying the result value as either a boolean or an index\n *\n * If the variation is a boolean value and the flag was not already a boolean\n * flag, this also changes it to be a boolean flag.\n *\n * If the variation is an integer, it specifies a variation out of whatever\n * variation values have already been defined.\n *\n * @param variation\n * either `true` or `false` or the index of the desired variation:\n * 0 for the first, 1 for the second, etc.\n * @return the flag rule builder\n */\n thenReturn(variation) {\n if (js_sdk_common_1.TypeValidators.Boolean.is(variation)) {\n this._flagBuilder.booleanFlag();\n return this.thenReturn((0, booleanVariation_1.variationForBoolean)(variation));\n }\n this._variation = variation;\n this._flagBuilder.addRule(this);\n return this._flagBuilder;\n }\n /**\n * @internal\n */\n build(id) {\n return {\n id: `rule${id}`,\n variation: this._variation,\n clauses: this._clauses,\n };\n }\n /**\n * @internal\n */\n clone() {\n return new TestDataRuleBuilder(this._flagBuilder, this._clauses, this._variation);\n }\n}\nexports.default = TestDataRuleBuilder;\n//# sourceMappingURL=TestDataRuleBuilder.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst booleanVariation_1 = require(\"./booleanVariation\");\nconst TestDataRuleBuilder_1 = require(\"./TestDataRuleBuilder\");\n/**\n * A builder for feature flag configurations to be used with {@link TestData}.\n */\nclass TestDataFlagBuilder {\n /**\n * @internal\n */\n constructor(_key, data) {\n this._key = _key;\n this._data = {\n on: true,\n variations: [],\n };\n if (data) {\n // Not the fastest way to deep copy, but this is a testing mechanism.\n this._data = {\n on: data.on,\n variations: [...data.variations],\n };\n if (data.offVariation !== undefined) {\n this._data.offVariation = data.offVariation;\n }\n if (data.fallthroughVariation !== undefined) {\n this._data.fallthroughVariation = data.fallthroughVariation;\n }\n if (data.targetsByVariation) {\n this._data.targetsByVariation = JSON.parse(JSON.stringify(data.targetsByVariation));\n }\n if (data.rules) {\n this._data.rules = [];\n data.rules.forEach((rule) => {\n var _a;\n (_a = this._data.rules) === null || _a === void 0 ? void 0 : _a.push(rule.clone());\n });\n }\n }\n }\n get _isBooleanFlag() {\n return (this._data.variations.length === 2 &&\n this._data.variations[booleanVariation_1.TRUE_VARIATION_INDEX] === true &&\n this._data.variations[booleanVariation_1.FALSE_VARIATION_INDEX] === false);\n }\n /**\n * A shortcut for setting the flag to use the standard boolean configuration.\n *\n * This is the default for all new flags created with {@link TestData.flag}. The\n * flag will have two variations, `true` and `false` (in that order). It\n * will return `false` whenever targeting is off and `true` when targeting\n * is on unless other settings specify otherwise.\n *\n * @return the flag builder\n */\n booleanFlag() {\n if (this._isBooleanFlag) {\n return this;\n }\n // Change this flag into a boolean flag.\n return this.variations(true, false)\n .fallthroughVariation(booleanVariation_1.TRUE_VARIATION_INDEX)\n .offVariation(booleanVariation_1.FALSE_VARIATION_INDEX);\n }\n /**\n * Sets the allowable variation values for the flag.\n *\n * The values may be of any JSON-compatible type: boolean, number, string, array,\n * or object. For instance, a boolean flag normally has `variations(true, false)`;\n * a string-valued flag might have `variations(\"red\", \"green\")`; etc.\n *\n * @param values any number of variation values\n * @return the flag builder\n */\n variations(...values) {\n this._data.variations = [...values];\n return this;\n }\n /**\n * Sets targeting to be on or off for this flag.\n *\n * The effect of this depends on the rest of the flag configuration, just\n * as it does on the real LaunchDarkly dashboard. In the default configuration\n * that you get from calling {@link TestData.flag} with a new flag key, the flag\n * will return `false` whenever targeting is off and `true` when targeting\n * is on.\n *\n * @param targetingOn true if targeting should be on\n * @return the flag builder\n */\n on(targetingOn) {\n this._data.on = targetingOn;\n return this;\n }\n /**\n * Specifies the fallthrough variation for a flag. The fallthrough is\n * the value that is returned if targeting is on and the user was not\n * matched by a more specific target or rule.\n *\n * If a boolean is supplied, and the flag was previously configured with\n * other variations, this also changes it to a boolean flag.\n *\n * @param variation\n * either `true` or `false` or the index of the desired fallthrough\n * variation: 0 for the first, 1 for the second, etc.\n * @return the flag builder\n */\n fallthroughVariation(variation) {\n if (js_sdk_common_1.TypeValidators.Boolean.is(variation)) {\n return this.booleanFlag().fallthroughVariation((0, booleanVariation_1.variationForBoolean)(variation));\n }\n this._data.fallthroughVariation = variation;\n return this;\n }\n /**\n * Specifies the off variation for a flag. This is the variation that is\n * returned whenever targeting is off.\n *\n * If a boolean is supplied, and the flag was previously configured with\n * other variations, this also changes it to a boolean flag.\n *\n * @param variation\n * either `true` or `false` or the index of the desired off\n * variation: 0 for the first, 1 for the second, etc.\n * @return the flag builder\n */\n offVariation(variation) {\n if (js_sdk_common_1.TypeValidators.Boolean.is(variation)) {\n return this.booleanFlag().offVariation((0, booleanVariation_1.variationForBoolean)(variation));\n }\n this._data.offVariation = variation;\n return this;\n }\n /**\n * Sets the flag to always return the specified variation for all contexts.\n *\n * Targeting is switched on, any existing targets or rules are removed,\n * and the fallthrough variation is set to the specified value. The off\n * variation is left unchanged.\n *\n * If a boolean is supplied, and the flag was previously configured with\n * other variations, this also changes it to a boolean flag.\n *\n * @param varation\n * either `true` or `false` or the index of the desired variation:\n * 0 for the first, 1 for the second, etc.\n * @return the flag builder\n */\n variationForAll(variation) {\n return this.on(true).clearRules().clearAllTargets().fallthroughVariation(variation);\n }\n /**\n * Sets the flag to always return the specified variation value for all contexts.\n *\n * The value may be of any valid JSON type. This method changes the flag to have\n * only a single variation, which is this value, and to return the same variation\n * regardless of whether targeting is on or off. Any existing targets or rules\n * are removed.\n *\n * @param value The desired value to be returned for all contexts.\n * @return the flag builder\n */\n valueForAll(value) {\n return this.variations(value).variationForAll(0);\n }\n /**\n * Sets the flag to return the specified variation for a specific context key\n * when targeting is on. The context kind for contexts created with this method\n * will be 'user'.\n *\n * This has no effect when targeting is turned off for the flag.\n *\n * If the variation is a boolean value and the flag was not already a boolean\n * flag, this also changes it to be a boolean flag.\n *\n * If the variation is an integer, it specifies a variation out of whatever\n * variation values have already been defined.\n *\n * @param contextKey a context key\n * @param variation\n * either `true` or `false` or the index of the desired variation:\n * 0 for the first, 1 for the second, etc.\n * @return the flag builder\n */\n variationForUser(contextKey, variation) {\n return this.variationForContext('user', contextKey, variation);\n }\n /**\n * Sets the flag to return the specified variation for a specific context key\n * when targeting is on.\n *\n * This has no effect when targeting is turned off for the flag.\n *\n * If the variation is a boolean value and the flag was not already a boolean\n * flag, this also changes it to be a boolean flag.\n *\n * If the variation is an integer, it specifies a variation out of whatever\n * variation values have already been defined.\n *\n * @param contextKind a context kind\n * @param contextKey a context key\n * @param variation\n * either `true` or `false` or the index of the desired variation:\n * 0 for the first, 1 for the second, etc.\n * @return the flag builder\n */\n variationForContext(contextKind, contextKey, variation) {\n if (js_sdk_common_1.TypeValidators.Boolean.is(variation)) {\n return this.booleanFlag().variationForContext(contextKind, contextKey, (0, booleanVariation_1.variationForBoolean)(variation));\n }\n if (!this._data.targetsByVariation) {\n this._data.targetsByVariation = {};\n }\n this._data.variations.forEach((_, i) => {\n if (i === variation) {\n // If there is nothing set at the current variation then set it to the empty array\n const targetsForVariation = this._data.targetsByVariation[i] || {};\n if (!(contextKind in targetsForVariation)) {\n targetsForVariation[contextKind] = [];\n }\n const exists = targetsForVariation[contextKind].indexOf(contextKey) !== -1;\n // Add context to current variation set if they aren't already there\n if (!exists) {\n targetsForVariation[contextKind].push(contextKey);\n }\n this._data.targetsByVariation[i] = targetsForVariation;\n }\n else {\n // remove user from other variation set if necessary\n const targetsForVariation = this._data.targetsByVariation[i];\n if (targetsForVariation) {\n const targetsForContextKind = targetsForVariation[contextKind];\n if (targetsForContextKind) {\n const targetIndex = targetsForContextKind.indexOf(contextKey);\n if (targetIndex !== -1) {\n targetsForContextKind.splice(targetIndex, 1);\n if (!targetsForContextKind.length) {\n delete targetsForVariation[contextKind];\n }\n }\n }\n if (!Object.keys(targetsForVariation).length) {\n delete this._data.targetsByVariation[i];\n }\n }\n }\n });\n return this;\n }\n /**\n * Removes any existing rules from the flag. This undoes the effect of methods\n * like {@link ifMatch}.\n *\n * @return the same flag builder\n */\n clearRules() {\n delete this._data.rules;\n return this;\n }\n /**\n * Removes any existing targets from the flag. This undoes the effect of\n * methods like {@link variationForContext}.\n *\n * @return the same flag builder\n */\n clearAllTargets() {\n delete this._data.targetsByVariation;\n return this;\n }\n /**\n * Starts defining a flag rule using the \"is one of\" operator.\n *\n * For example, this creates a rule that returnes `true` if the name is\n * \"Patsy\" or \"Edina\":\n *\n * testData.flag('flag')\n * .ifMatch('user', name', 'Patsy', 'Edina')\n * .thenReturn(true)\n *\n * @param contextKind the kind of the context\n * @param attribute the context attribute to match against\n * @param values values to compare to\n * @return\n * a flag rule builder; call `thenReturn` to finish the rule\n * or add more tests with another method like `andMatch`\n */\n ifMatch(contextKind, attribute, ...values) {\n const flagRuleBuilder = new TestDataRuleBuilder_1.default(this);\n return flagRuleBuilder.andMatch(contextKind, attribute, ...values);\n }\n /**\n * Starts defining a flag rule using the \"is not one of\" operator.\n *\n * For example, this creates a rule that returns `true` if the name is\n * neither \"Saffron\" nor \"Bubble\":\n *\n * testData.flag('flag')\n * .ifNotMatch('user', 'name', 'Saffron', 'Bubble')\n * .thenReturn(true)\n *\n * @param contextKind the kind of the context\n * @param attribute the user attribute to match against\n * @param values values to compare to\n * @return\n * a flag rule builder; call `thenReturn` to finish the rule\n * or add more tests with another method like `andNotMatch`\n */\n ifNotMatch(contextKind, attribute, ...values) {\n const flagRuleBuilder = new TestDataRuleBuilder_1.default(this);\n return flagRuleBuilder.andNotMatch(contextKind, attribute, ...values);\n }\n checkRatio(ratio) {\n var _a;\n this._data.migration = (_a = this._data.migration) !== null && _a !== void 0 ? _a : {};\n this._data.migration.checkRatio = ratio;\n return this;\n }\n samplingRatio(ratio) {\n this._data.samplingRatio = ratio;\n return this;\n }\n /**\n * @internal\n */\n addRule(flagRuleBuilder) {\n if (!this._data.rules) {\n this._data.rules = [];\n }\n this._data.rules.push(flagRuleBuilder);\n }\n /**\n * @internal\n */\n build(version) {\n const baseFlagObject = {\n key: this._key,\n version,\n on: this._data.on,\n offVariation: this._data.offVariation,\n fallthrough: {\n variation: this._data.fallthroughVariation,\n },\n variations: [...this._data.variations],\n migration: this._data.migration,\n samplingRatio: this._data.samplingRatio,\n };\n if (this._data.targetsByVariation) {\n const contextTargets = [];\n const userTargets = [];\n Object.entries(this._data.targetsByVariation).forEach(([variation, contextTargetsForVariation]) => {\n Object.entries(contextTargetsForVariation).forEach(([contextKind, values]) => {\n const numberVariation = parseInt(variation, 10);\n contextTargets.push({\n contextKind,\n values: contextKind === 'user' ? [] : values,\n // Iterating the object it will be a string.\n variation: numberVariation,\n });\n if (contextKind === 'user') {\n userTargets.push({ values, variation: numberVariation });\n }\n });\n });\n baseFlagObject.targets = userTargets;\n baseFlagObject.contextTargets = contextTargets;\n }\n if (this._data.rules) {\n baseFlagObject.rules = this._data.rules.map((rule, i) => rule.build(String(i)));\n }\n return baseFlagObject;\n }\n /**\n * @internal\n */\n clone() {\n return new TestDataFlagBuilder(this._key, this._data);\n }\n /**\n * @internal\n */\n getKey() {\n return this._key;\n }\n}\nexports.default = TestDataFlagBuilder;\n//# sourceMappingURL=TestDataFlagBuilder.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @internal\n */\nclass TestDataSource {\n constructor(_featureStore, initialFlags, initialSegments, _onStop, _listeners) {\n this._featureStore = _featureStore;\n this._onStop = _onStop;\n this._listeners = _listeners;\n // make copies of these objects to decouple them from the originals\n // so updates made to the originals don't affect these internal data.\n this._flags = Object.assign({}, initialFlags);\n this._segments = Object.assign({}, initialSegments);\n }\n async start() {\n this._listeners.forEach(({ processJson }) => {\n const dataJson = { data: { flags: this._flags, segments: this._segments } };\n processJson(dataJson);\n });\n }\n stop() {\n this._onStop(this);\n }\n close() {\n this.stop();\n }\n async upsert(kind, value) {\n return this._featureStore.upsert(kind, value);\n }\n}\nexports.default = TestDataSource;\n//# sourceMappingURL=TestDataSource.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst createStreamListeners_1 = require(\"../../data_sources/createStreamListeners\");\nconst AsyncStoreFacade_1 = require(\"../../store/AsyncStoreFacade\");\nconst serialization_1 = require(\"../../store/serialization\");\nconst VersionedDataKinds_1 = require(\"../../store/VersionedDataKinds\");\nconst TestDataFlagBuilder_1 = require(\"./TestDataFlagBuilder\");\nconst TestDataSource_1 = require(\"./TestDataSource\");\n/**\n * A mechanism for providing dynamically updatable feature flag state in a simplified form to an SDK\n * client in test scenarios.\n *\n * Unlike `FileData`, this mechanism does not use any external resources. It provides only the\n * data that the application has put into it using the {@link TestData.update} method.\n *\n * ```\n * // Import TestData from the integrations package of the SDK you are using.\n * // This is a common implementation and may be used in multiple SDKs.\n *\n * const td = TestData();\n * testData.update(td.flag(\"flag-key-1\").booleanFlag().variationForAll(true));\n * // Use the initialization mechanism specified by your SDK.\n * const client = LDClient.init(sdkKey, { updateProcessor: td.getFactory() });\n *\n * // flags can be updated at any time:\n * td.update(td.flag(\"flag-key-2\")\n * .variationForContext(\"user\", \"some-user-key\", true)\n * .fallthroughVariation(false));\n * ```\n *\n * The above example uses a simple boolean flag, but more complex configurations are possible using\n * the methods of the {@link TestDataFlagBuilder} that is returned by {@link TestData.flag}.\n * {@link TestDataFlagBuilder} supports many of the ways a flag can be configured on the\n * LaunchDarkly dashboard, but does not currently support\n * 1. rule operators other than \"in\" and \"not in\", or\n * 2. percentage rollouts.\n *\n * If the same `TestData` instance is used to configure multiple `LDClient` instances,\n * any changes made to the data will propagate to all of the `LDClient`s.\n */\nclass TestData {\n constructor() {\n this._currentFlags = {};\n this._currentSegments = {};\n this._dataSources = [];\n this._flagBuilders = {};\n }\n /**\n * Get a factory for update processors that will be attached to this TestData instance.\n * @returns An update processor factory.\n */\n getFactory() {\n // Provides an arrow function to prevent needed to bind the method to\n // maintain `this`.\n return (clientContext, featureStore, initSuccessHandler, _errorHandler) => {\n const listeners = (0, createStreamListeners_1.createStreamListeners)(featureStore, clientContext.basicConfiguration.logger, {\n put: initSuccessHandler,\n });\n const newSource = new TestDataSource_1.default(new AsyncStoreFacade_1.default(featureStore), this._currentFlags, this._currentSegments, (tds) => {\n this._dataSources.splice(this._dataSources.indexOf(tds));\n }, listeners);\n this._dataSources.push(newSource);\n return newSource;\n };\n }\n /**\n * Creates or copies a {@link TestDataFlagBuilder} for building a test flag configuration.\n *\n * If the flag key has already been defined in this `TestData` instance,\n * then the builder starts with the same configuration that was last\n * provided for this flag.\n *\n * Otherwise, it starts with a new default configuration in which the flag\n * has `true` and `false` variations, is `true` for all users when targeting\n * is turned on and `false` otherwise, and currently has targeting turned on.\n * You can change any of those properties and provide more complex behavior\n * using the `TestDataFlagBuilder` methods.\n *\n * Once you have set the desired configuration, pass the builder to\n * {@link TestData.update}.\n *\n * @param key the flag key\n * @returns a flag configuration builder\n *\n */\n flag(key) {\n if (this._flagBuilders[key]) {\n return this._flagBuilders[key].clone();\n }\n return new TestDataFlagBuilder_1.default(key).booleanFlag();\n }\n /**\n * Updates the test data with the specified flag configuration.\n *\n * This has the same effect as if a flag were added or modified in the\n * LaunchDarkly dashboard. It immediately propagates the flag changes to\n * any `LDClient` instance(s) that you have already configured to use\n * this `TestData`. If no `LDClient` has been started yet, it simply adds\n * this flag to the test data which will be provided to any `LDClient`\n * that you subsequently configure.\n *\n * Any subsequent changes to this `TestDataFlagBuilder` instance do not affect\n * the test data unless you call `update` again.\n *\n * @param flagBuilder a flag configuration builder\n * @return a promise that will resolve when the feature stores are updated\n */\n update(flagBuilder) {\n const flagKey = flagBuilder.getKey();\n const oldItem = this._currentFlags[flagKey];\n const oldVersion = oldItem ? oldItem.version : 0;\n const newFlag = flagBuilder.build(oldVersion + 1);\n this._currentFlags[flagKey] = newFlag;\n this._flagBuilders[flagKey] = flagBuilder.clone();\n return Promise.all(this._dataSources.map((impl) => impl.upsert(VersionedDataKinds_1.default.Features, newFlag)));\n }\n /**\n * Copies a full feature flag data model object into the test data.\n *\n * It immediately propagates the flag change to any `LDClient` instance(s) that you have already\n * configured to use this `TestData`. If no `LDClient` has been started yet, it simply adds this\n * flag to the test data which will be provided to any LDClient that you subsequently configure.\n *\n * Use this method if you need to use advanced flag configuration properties that are not\n * supported by the simplified {@link TestDataFlagBuilder} API. Otherwise it is recommended to use\n * the regular {@link flag}/{@link update} mechanism to avoid dependencies on details of the data\n * model.\n *\n * You cannot make incremental changes with {@link flag}/{@link update} to a flag that has been\n * added in this way; you can only replace it with an entirely new flag configuration.\n *\n * @param flagConfig the flag configuration as a JSON object\n * @return a promise that will resolve when the feature stores are updated\n */\n usePreconfiguredFlag(inConfig) {\n // We need to do things like process attribute reference, and\n // we do not want to modify the passed in value.\n const flagConfig = JSON.parse(JSON.stringify(inConfig));\n const oldItem = this._currentFlags[flagConfig.key];\n const newItem = Object.assign(Object.assign({}, flagConfig), { version: oldItem ? oldItem.version + 1 : flagConfig.version });\n (0, serialization_1.processFlag)(newItem);\n this._currentFlags[flagConfig.key] = newItem;\n return Promise.all(this._dataSources.map((impl) => impl.upsert(VersionedDataKinds_1.default.Features, newItem)));\n }\n /**\n * Copies a full segment data model object into the test data.\n *\n * It immediately propagates the change to any `LDClient` instance(s) that you have already\n * configured to use this `TestData`. If no `LDClient` has been started yet, it simply adds\n * this segment to the test data which will be provided to any LDClient that you subsequently\n * configure.\n *\n * This method is currently the only way to inject segment data, since there is no builder\n * API for segments. It is mainly intended for the SDK's own tests of segment functionality,\n * since application tests that need to produce a desired evaluation state could do so more easily\n * by just setting flag values.\n *\n * @param segmentConfig the segment configuration as a JSON object\n * @return a promise that will resolve when the feature stores are updated\n */\n usePreconfiguredSegment(inConfig) {\n const segmentConfig = JSON.parse(JSON.stringify(inConfig));\n const oldItem = this._currentSegments[segmentConfig.key];\n const newItem = Object.assign(Object.assign({}, segmentConfig), { version: oldItem ? oldItem.version + 1 : segmentConfig.version });\n (0, serialization_1.processSegment)(newItem);\n this._currentSegments[segmentConfig.key] = newItem;\n return Promise.all(this._dataSources.map((impl) => impl.upsert(VersionedDataKinds_1.default.Segments, newItem)));\n }\n}\nexports.default = TestData;\n//# sourceMappingURL=TestData.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TestDataRuleBuilder = exports.TestDataFlagBuilder = exports.TestData = void 0;\nconst TestData_1 = require(\"./TestData\");\nexports.TestData = TestData_1.default;\nconst TestDataFlagBuilder_1 = require(\"./TestDataFlagBuilder\");\nexports.TestDataFlagBuilder = TestDataFlagBuilder_1.default;\nconst TestDataRuleBuilder_1 = require(\"./TestDataRuleBuilder\");\nexports.TestDataRuleBuilder = TestDataRuleBuilder_1.default;\n//# sourceMappingURL=index.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.FileDataSourceFactory = void 0;\nconst FileDataSourceFactory_1 = require(\"./FileDataSourceFactory\");\nexports.FileDataSourceFactory = FileDataSourceFactory_1.default;\n__exportStar(require(\"./test_data\"), exports);\n// Api exported integrations, but it was overwritten by the more specific\n// integrations from index.ts.\n__exportStar(require(\"../api/integrations\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass NullEventSource {\n constructor(url, options) {\n this.handlers = {};\n this.closed = false;\n this.url = url;\n this.options = options;\n }\n addEventListener(type, listener) {\n this.handlers[type] = listener;\n }\n close() {\n this.closed = true;\n }\n simulateError(error) {\n const shouldRetry = this.options.errorFilter(error);\n if (!shouldRetry) {\n this.closed = true;\n }\n }\n}\nexports.default = NullEventSource;\n//# sourceMappingURL=NullEventSource.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.NullEventSource = void 0;\nconst NullEventSource_1 = require(\"./NullEventSource\");\nexports.NullEventSource = NullEventSource_1.default;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TtlCache = void 0;\nconst TtlCache_1 = require(\"../cache/TtlCache\");\nexports.TtlCache = TtlCache_1.default;\n//# sourceMappingURL=index.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createMigration = exports.LDMigrationSuccess = exports.LDMigrationError = exports.BigSegmentStoreStatusProviderImpl = exports.LDClientImpl = exports.internalServer = exports.platform = exports.integrations = void 0;\nconst BigSegmentStatusProviderImpl_1 = require(\"./BigSegmentStatusProviderImpl\");\nexports.BigSegmentStoreStatusProviderImpl = BigSegmentStatusProviderImpl_1.default;\nconst LDClientImpl_1 = require(\"./LDClientImpl\");\nexports.LDClientImpl = LDClientImpl_1.default;\nconst Migration_1 = require(\"./Migration\");\nObject.defineProperty(exports, \"createMigration\", { enumerable: true, get: function () { return Migration_1.createMigration; } });\nObject.defineProperty(exports, \"LDMigrationError\", { enumerable: true, get: function () { return Migration_1.LDMigrationError; } });\nObject.defineProperty(exports, \"LDMigrationSuccess\", { enumerable: true, get: function () { return Migration_1.LDMigrationSuccess; } });\nexports.integrations = require(\"./integrations\");\nexports.platform = require(\"@launchdarkly/js-sdk-common\");\n__exportStar(require(\"./api\"), exports);\n__exportStar(require(\"./store\"), exports);\n__exportStar(require(\"./events\"), exports);\n__exportStar(require(\"@launchdarkly/js-sdk-common\"), exports);\nexports.internalServer = require(\"./internal\");\n//# sourceMappingURL=index.js.map","import CryptoJS from 'crypto-js';\nexport default class CryptoJSHasher {\n constructor(algorithm) {\n let algo;\n switch (algorithm) {\n case 'sha1':\n algo = CryptoJS.algo.SHA1;\n break;\n case 'sha256':\n algo = CryptoJS.algo.SHA256;\n break;\n default:\n throw new Error('unsupported hash algorithm. Only sha1 and sha256 are supported.');\n }\n this._cryptoJSHasher = algo.create();\n }\n digest(encoding) {\n const result = this._cryptoJSHasher.finalize();\n let enc;\n switch (encoding) {\n case 'base64':\n enc = CryptoJS.enc.Base64;\n break;\n case 'hex':\n enc = CryptoJS.enc.Hex;\n break;\n default:\n throw new Error('unsupported output encoding. Only base64 and hex are supported.');\n }\n return result.toString(enc);\n }\n update(data) {\n this._cryptoJSHasher.update(data);\n return this;\n }\n}\n//# sourceMappingURL=cryptoJSHasher.js.map","import CryptoJS from 'crypto-js';\nexport default class CryptoJSHmac {\n constructor(algorithm, key) {\n let algo;\n switch (algorithm) {\n case 'sha1':\n algo = CryptoJS.algo.SHA1;\n break;\n case 'sha256':\n algo = CryptoJS.algo.SHA256;\n break;\n default:\n throw new Error('unsupported hash algorithm. Only sha1 and sha256 are supported.');\n }\n this._cryptoJSHmac = CryptoJS.algo.HMAC.create(algo, key);\n }\n digest(encoding) {\n const result = this._cryptoJSHmac.finalize();\n if (encoding === 'base64') {\n return result.toString(CryptoJS.enc.Base64);\n }\n if (encoding === 'hex') {\n return result.toString(CryptoJS.enc.Hex);\n }\n throw new Error('unsupported output encoding. Only base64 and hex are supported.');\n }\n update(data) {\n this._cryptoJSHmac.update(data);\n return this;\n }\n}\n//# sourceMappingURL=cryptoJSHmac.js.map","import CryptoJSHasher from './cryptoJSHasher';\nimport CryptoJSHmac from './cryptoJSHmac';\n/**\n * Uses crypto-js as substitute to node:crypto because the latter\n * is not yet supported in some runtimes.\n * https://cryptojs.gitbook.io/docs/\n */\nexport default class EdgeCrypto {\n createHash(algorithm) {\n return new CryptoJSHasher(algorithm);\n }\n createHmac(algorithm, key) {\n return new CryptoJSHmac(algorithm, key);\n }\n randomUUID() {\n return crypto.randomUUID();\n }\n}\n//# sourceMappingURL=index.js.map","import { NullEventSource } from '@launchdarkly/js-server-sdk-common';\nexport default class EdgeRequests {\n fetch(url, options = {}) {\n // @ts-ignore\n return fetch(url, options);\n }\n createEventSource(url, eventSourceInitDict) {\n return new NullEventSource(url, eventSourceInitDict);\n }\n getEventSourceCapabilities() {\n return {\n readTimeout: false,\n headers: false,\n customMethod: false,\n };\n }\n}\n//# sourceMappingURL=requests.js.map","import EdgeCrypto from './crypto';\nimport EdgeRequests from './requests';\nexport default class EdgePlatform {\n constructor(info) {\n this.crypto = new EdgeCrypto();\n this.requests = new EdgeRequests();\n this.info = info;\n }\n}\n//# sourceMappingURL=index.js.map","import { noop } from '@launchdarkly/js-server-sdk-common';\nconst createCallbacks = (emitter, logger) => ({\n onError: (err) => {\n if (emitter.listenerCount('error')) {\n emitter.emit('error', err);\n }\n else {\n logger === null || logger === void 0 ? void 0 : logger.error(err.message);\n }\n },\n onFailed: (err) => {\n emitter.emit('failed', err);\n },\n onReady: () => {\n emitter.emit('ready');\n },\n onUpdate: noop,\n hasEventListeners: () => false,\n});\nexport default createCallbacks;\n//# sourceMappingURL=createCallbacks.js.map","import { BasicLogger } from '@launchdarkly/js-server-sdk-common';\nexport const defaultOptions = {\n stream: false,\n sendEvents: false,\n useLdd: true,\n diagnosticOptOut: true,\n logger: BasicLogger.get(),\n};\nconst createOptions = (options) => (Object.assign(Object.assign({}, defaultOptions), options));\nexport default createOptions;\n//# sourceMappingURL=createOptions.js.map","import { EventEmitter } from 'node:events';\nimport { LDClientImpl } from '@launchdarkly/js-server-sdk-common';\nimport EdgePlatform from '../platform';\nimport createCallbacks from './createCallbacks';\nimport createOptions from './createOptions';\n/**\n * The LaunchDarkly SDK edge client object.\n */\nexport default class LDClient extends LDClientImpl {\n // clientSideID is only used to query the edge key-value store and send analytics, not to initialize with LD servers\n constructor(clientSideID, platformInfo, options) {\n const em = new EventEmitter();\n const platform = new EdgePlatform(platformInfo);\n const internalOptions = {\n analyticsEventPath: `/events/bulk/${clientSideID}`,\n diagnosticEventPath: `/events/diagnostic/${clientSideID}`,\n includeAuthorizationHeader: false,\n };\n const finalOptions = createOptions(options);\n super(clientSideID, platform, finalOptions, createCallbacks(em, finalOptions.logger), internalOptions);\n this.emitter = em;\n }\n}\n//# sourceMappingURL=LDClient.js.map","import { deserializePoll, noop, reviveFullPayload } from '@launchdarkly/js-server-sdk-common';\nexport class EdgeFeatureStore {\n constructor(_edgeProvider, sdkKey, _description, _logger, _cache) {\n this._edgeProvider = _edgeProvider;\n this._description = _description;\n this._logger = _logger;\n this._cache = _cache;\n // unused\n this.delete = noop;\n this.upsert = noop;\n this._rootKey = `LD-Env-${sdkKey}`;\n }\n async get(kind, dataKey, callback) {\n const { namespace } = kind;\n const kindKey = namespace === 'features' ? 'flags' : namespace;\n this._logger.debug(`Requesting ${dataKey} from ${this._rootKey}.${kindKey}`);\n try {\n const storePayload = await this._getStorePayload();\n switch (namespace) {\n case 'features':\n callback(storePayload.flags[dataKey]);\n break;\n case 'segments':\n callback(storePayload.segments[dataKey]);\n break;\n default:\n callback(null);\n }\n }\n catch (err) {\n this._logger.error(err);\n callback(null);\n }\n }\n async all(kind, callback = noop) {\n const { namespace } = kind;\n const kindKey = namespace === 'features' ? 'flags' : namespace;\n this._logger.debug(`Requesting all from ${this._rootKey}.${kindKey}`);\n try {\n const storePayload = await this._getStorePayload();\n switch (namespace) {\n case 'features':\n callback(storePayload.flags);\n break;\n case 'segments':\n callback(storePayload.segments);\n break;\n default:\n callback({});\n }\n }\n catch (err) {\n this._logger.error(err);\n callback({});\n }\n }\n /**\n * This method is used to retrieve the environment payload from the edge\n * provider. If a cache is provided, it will serve from that.\n */\n async _getStorePayload() {\n var _a, _b;\n let payload = (_a = this._cache) === null || _a === void 0 ? void 0 : _a.get(this._rootKey);\n if (payload !== undefined) {\n return payload;\n }\n const providerData = await this._edgeProvider.get(this._rootKey);\n if (!providerData) {\n throw new Error(`${this._rootKey} is not found in KV.`);\n }\n payload =\n typeof providerData === 'string'\n ? deserializePoll(providerData)\n : reviveFullPayload(providerData);\n if (!payload) {\n throw new Error(`Error deserializing ${this._rootKey}`);\n }\n (_b = this._cache) === null || _b === void 0 ? void 0 : _b.set(this._rootKey, payload);\n return payload;\n }\n async initialized(callback = noop) {\n const config = await this._edgeProvider.get(this._rootKey);\n const result = config !== null;\n this._logger.debug(`Is ${this._rootKey} initialized? ${result}`);\n callback(result);\n }\n init(allData, callback) {\n callback();\n }\n getDescription() {\n return this._description;\n }\n close() {\n var _a;\n return (_a = this._cache) === null || _a === void 0 ? void 0 : _a.close();\n }\n}\n//# sourceMappingURL=EdgeFeatureStore.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nconst validateOptions = (sdkKey, options) => {\n const { featureStore, logger, sendEvents } = options, rest = __rest(options, [\"featureStore\", \"logger\", \"sendEvents\"]);\n if (!sdkKey) {\n throw new Error('You must configure the client with a client key');\n }\n if (!featureStore || typeof featureStore !== 'object' || !featureStore.get) {\n throw new Error('You must configure the client with a feature store');\n }\n if (!logger) {\n throw new Error('You must configure the client with a logger');\n }\n if (JSON.stringify(rest) !== '{}') {\n throw new Error(`Invalid configuration: ${Object.keys(rest).toString()} not supported`);\n }\n return true;\n};\nexport default validateOptions;\n//# sourceMappingURL=validateOptions.js.map","import type { Info, PlatformData, SdkData } from '@launchdarkly/js-server-sdk-common-edge';\n\nconst name = '@launchdarkly/cloudflare-server-sdk';\nconst version = '2.7.11'; // x-release-please-version\n\nclass CloudflarePlatformInfo implements Info {\n platformData(): PlatformData {\n return {\n name: 'Cloudflare',\n };\n }\n\n sdkData(): SdkData {\n return {\n name,\n version,\n userAgentBase: 'CloudflareEdgeSDK',\n };\n }\n}\n\nconst createPlatformInfo = (): CloudflarePlatformInfo => new CloudflarePlatformInfo();\n\nexport default createPlatformInfo;\n","/**\n * This is the API reference for the Cloudflare LaunchDarkly SDK.\n *\n * In typical usage, you will call {@link init} once at startup time to obtain an instance of\n * {@link LDClient}, which provides access to all of the SDK's functionality.\n *\n * For more information, see the SDK reference guide.\n *\n * @packageDocumentation\n */\nimport type { KVNamespace } from '@cloudflare/workers-types';\n\nimport {\n BasicLogger,\n EdgeFeatureStore,\n init as initEdge,\n internalServer,\n type LDClient,\n type LDOptions as LDOptionsCommon,\n} from '@launchdarkly/js-server-sdk-common-edge';\n\nimport createPlatformInfo from './createPlatformInfo';\n\nexport {\n createMigration,\n BasicLogger,\n type BasicLoggerOptions,\n type Cache,\n EdgeFeatureStore,\n type EdgeProvider,\n integrations,\n IsMigrationStage,\n type LDBigSegmentsOptions,\n type LDClient,\n type LDClientContext,\n type LDContext,\n LDConcurrentExecution,\n type LDEvaluationDetail,\n type LDEvaluationDetailTyped,\n type LDFeatureStore,\n type LDFlagValue,\n type LDFlagsState,\n type LDFlagsStateOptions,\n type LDLogger,\n type LDMigration,\n type LDMethodResult,\n type LDMigrationOptions,\n type LDMigrationOpEvent,\n type LDMigrationOrigin,\n type LDMigrationReadResult,\n type LDMigrationResult,\n LDMigrationStage,\n LDMigrationSuccess,\n type LDMigrationWriteResult,\n type LDMigrationVariation,\n type LDProxyOptions,\n type LDTLSOptions,\n type LDWaitForInitializationOptions,\n} from '@launchdarkly/js-server-sdk-common-edge';\n\nexport type TtlCacheOptions = internalServer.TtlCacheOptions;\n\n/**\n * The Launchdarkly Edge SDKs configuration options.\n */\nexport type LDOptions = {\n /**\n * Optional TTL cache configuration which allows for caching feature flags in\n * memory.\n */\n cache?: TtlCacheOptions;\n} & LDOptionsCommon;\n\n/**\n * Creates an instance of the Cloudflare LaunchDarkly client.\n *\n * Applications should instantiate a single instance for the lifetime of the worker.\n * The client will begin attempting to connect to the configured Cloudflare KV as\n * soon as it is created. To determine when it is ready to use, call {@link LDClient.waitForInitialization}.\n *\n * **Important:** Do **not** try to instantiate `LDClient` with its constructor\n * (`new LDClient()/new LDClientImpl()/new LDClient()`); the SDK does not currently support\n * this.\n *\n * @param clientSideID\n * The client side ID. This is only used to query the kvNamespace above,\n * not to connect with LaunchDarkly servers.\n * @param kvNamespace\n * The Cloudflare KV configured for LaunchDarkly.\n * @param options\n * Optional configuration settings.\n * @return\n * The new {@link LDClient} instance.\n */\nexport const init = (\n clientSideID: string,\n kvNamespace: KVNamespace,\n options: LDOptions = {},\n): LDClient => {\n const logger = options.logger ?? BasicLogger.get();\n\n const { cache: _cacheOptions, ...rest } = options;\n const cache = options.cache ? new internalServer.TtlCache(options.cache) : undefined;\n return initEdge(clientSideID, createPlatformInfo(), {\n featureStore: new EdgeFeatureStore(kvNamespace, clientSideID, 'Cloudflare', logger, cache),\n logger,\n ...rest,\n });\n};\n","import { EdgeFeatureStore, LDClient } from './api';\nimport validateOptions from './utils/validateOptions';\nexport * from '@launchdarkly/js-server-sdk-common';\nexport { EdgeFeatureStore };\n/**\n * Do not use this function directly.\n *\n * This is an internal API to be used directly only by LaunchDarkly Edge SDKs.\n */\nexport const init = (clientSideID, platformInfo, options) => {\n // this throws if options are invalid\n validateOptions(clientSideID, options);\n return new LDClient(clientSideID, platformInfo, options);\n};\n//# sourceMappingURL=index.js.map"],"names":["Object","defineProperty","BigSegmentStatusProviderImpl","value","default","constructor","_onRequestStatus","this","getStatus","_lastStatus","requireStatus","notify","_a","_listener","call","setListener","listener","setStatus","status","unescape","ref","indexOf","replace","AttributeReference","refOrLiteral","literal","literalVal","_components","isValid","redactionName","startsWith","match","reference","isLiteral","slice","substring","split","map","component","getComponents","get","target","components","current","index","length","prototype","hasOwnProperty","Array","isArray","getComponent","depth","isKind","compare","other","every","InvalidReference","FactoryOrInstance","is","factoryOrInstance","typeOfFactory","getType","Type","typeName","example","_typeName","typeOf","u","TypeArray","val","NumberWithMinimum","min","super","StringMatchingRegex","expression","Function","NullableBoolean","DATE_REGEX","DateValidator","test","KindValidator","TypeValidators","createTypeArray","numberWithMin","stringMatchingRegex","isSingleKind","context","String","kind","isMultiKind","isLegacyUser","undefined","canonicalize","object","visited","JSON","stringify","includes","Error","item","join","keys","sort","key","filter","Number","ObjectOrFactory","StringArray","Boolean","Date","Kind","DEFAULT_KIND","encodeKey","validKind","validKey","processPrivateAttributes","privateAttributes","literals","privateAttribute","Context","valid","message","_isMulti","_isUser","_wasLegacy","_contexts","_contextForError","_getValueFromContext","anonymous","_contextForKind","_context","_fromMultiKindContext","kinds","kindsValid","contextsAreObjects","contexts","reduce","acc","singleContext","kindOrContext","_meta","values","part","created","_privateAttributeReferences","_fromSingleKindContext","kindValid","keyValid","privateAttributeReferences","_fromLegacyUser","user","singleKindContext","custom","name","ip","firstName","lastName","email","avatar","country","privateAttributeNames","legacyToSingleKind","fromLDContext","toLDContext","getContexts","result","forEach","kindAndContext","nestedContext","valueForKind","canonicalKey","kindsAndKeys","entries","legacy","canonicalUnfilteredJson","_cachedCanonicalJson","UserKind","protectedAttributes","str","legacyTopLevelCopyAttributes","ContextFilter","_allAttributesPrivate","_privateAttributes","redactAnonymousAttributes","_filterSingleKind","filteredMulti","single","_getAttributesToFilter","redactAllAttributes","k","attr","some","protectedAttr","cloned","excluded","references","stack","push","ptr","source","parent","pop","redactRef","find","a","b","cloneWithRedactions","redactedAttributes","DefaultBackoff","initialRetryDelayMillis","_retryResetIntervalMillis","_random","Math","random","_retryCount","_initialRetryDelayMillis","max","_maxExponent","ceil","log2","_backoff","exponent","delay","_jitter","computedDelayMillis","trunc","success","timeStampMs","now","_activeSince","fail","CallbackHandler","_dataCallback","_statusCallback","_disabled","disable","dataHandler","basis","data","statusHandler","err","DataSourceState","DataSourceList","circular","initialList","_list","_circular","_pos","next","input","remove","element","splice","reset","pos","clear","LDFileDataSourceError","LDPollingError","recoverable","LDStreamingError","code","LDFlagDeliveryFallbackError","DataSourceErrorKind","AutoEnvAttributes","LDEventType","LDDeliveryStatus","exports","index$1","freeze","__proto__","tryStringify","toString","error","TypeError","escapes","s","d","toNumber","i","parseInt","toInt","f","parseFloat","toFloat","j","o","O","c","format","args","formatString","shift","out","char","charAt","nextChar","LogPriority","LEVEL_NAMES","BasicLogger","options","_logLevel","level","info","_name","_formatter","formatter","destination","_destinations","debug","warn","_tryFormat","_tryWrite","msg","console","_log","prefix","loggerRequirements","SafeLogger","logger","fallback","validator","_logger","_fallback","OptionMessages","deprecated","oldName","newName","optionBelowMinimum","unknownOption","wrongOptionType","expectedType","actualType","wrongOptionTypeBoolean","invalidTagValue","tagValueTooLong","partialEndpoint","regexValidator","tagValidator","canonicalizeUri","uri","canonicalizePath","path","ServiceEndpoints","streaming","polling","events","DEFAULT_EVENTS","analyticsEventPath","diagnosticEventPath","includeAuthorizationHeader","payloadFilterKey","getWithParams","parameters","getEventsUri","endpoints","canonicalizedPath","LDUnexpectedResponseError","LDClientError","LDTimeoutError","isHttpRecoverable","isHttpLocallyRecoverable","deepCompact","obj","ignoreKeys","isEmptyObject","httpErrorMessage","retryMessage","desc","sleep","async","delayMillis","Promise","resolve","setTimeout","ErrorKinds","ErrorKinds$1","ClientMessages","invalidMetricValue","badType","MissingContextKeyNoEvent","EventSender","clientContext","baseHeaders","basicConfiguration","platform","serviceEndpoints","crypto","requests","_defaultHeaders","_eventsUri","_diagnosticEventsUri","_requests","_crypto","_tryPostingEvents","payloadId","canRetry","tryRes","Succeeded","headers","resHeaders","fetch","body","compressBodyIfPossible","method","keepalive","serverDate","parse","serverTime","Failed","FailedAndMustShutDown","sendEventData","type","AnalyticsEvents","randomUUID","isFeature","SummaryCounter","count","defValue","version","variation","increment","EventSummarizer","_singleContext","_contextFilter","_startDate","_endDate","_counters","_contextKinds","summarizeEvent","event","excludeFromSummaries","countKey","counterKey","counter","Set","add","creationDate","getSummary","features","flagSummary","counters","contextKinds","counterOut","unknown","startDate","endDate","_clearSummary","LDInvalidSDKKeyError","MultiEventSummarizer","_summarizers","summarizer","getSummaries","summarizersToFlush","shouldSample","ratio","truncated","floor","InputCustomEvent","metricValue","samplingRatio","url","InputEvalEvent","withReasons","trackEvents","prereqOf","reason","debugEventsUntilDate","InputIdentifyEvent","PAYLOAD_ID","PayloadProcessor","_objProcessors","_errorHandler","_listeners","_tempId","_tempBasis","_tempUpdates","_processServerIntent","_resetAll","payloads","payload","intentCode","_processIntentNone","id","_processPutObject","_processObj","_processDeleteObject","deleted","intent","updates","it","_resetAfterEmission","_processPayloadTransferred","state","_processGoodbye","_processError","_resetAfterError","addPayloadListener","removePayloadListener","processEvents","jsonObj","UNKNOWN_PLUGIN_NAME","safeGetName","plugin","getMetadata","DiagnosticsManager","sdkKey","_platform","_diagnosticInitConfig","_streamInits","_startTime","_dataSinceDate","_id","diagnosticId","sdkKeySuffix","createInitEvent","sdkData","platformData","sdk","configuration","osArch","os","arch","osName","osVersion","additional","recordStreamInit","timestamp","failed","durationMillis","createStatsEventAndReset","droppedEvents","deduplicatedUsers","eventsInLastBatch","currentTime","evt","dataSinceDate","streamInits","EventFactoryBase","_withReasons","evalEvent","e","flagKey","defaultVal","addExperimentData","prereqOfFlagKey","unknownFlagEvent","defVal","identifyEvent","customEvent","EventProcessor","_config","_contextDeduplicator","_diagnosticsManager","start","summariesPerContext","_queue","_lastKnownPastTime","_droppedEvents","_deduplicatedUsers","_exceededCapacity","_eventsInLastBatch","_shutdown","_flushUsersTimer","_capacity","eventsCapacity","_eventSender","allAttributesPrivate","_summarizer","flushInterval","setInterval","flush","_flushTimer","initEvent","_postDiagnosticEvent","_diagnosticsTimer","statsEvent","diagnosticRecordingInterval","DiagnosticEvent","close","clearInterval","eventsToFlush","summary","sendEvent","inputEvent","migrationEvent","_enqueue","isFeatureEvent","addFullEvent","addDebugEvent","_shouldDebugEvent","isIdentifyEvent","isIdentify","shouldNotDeduplicate","processContext","_makeOutputEvent","contextKeys","selector","res","FDv1PayloadAdaptor","processor","_processor","_selector","useSelector","processFullTransfer","flags","flag","segments","segment","NullEventProcessor","PayloadStreamReader","eventStream","_attachHandler","_payloadProcessor","stream","eventName","addEventListener","InvalidData","Unknown","initMetadataFromHeaders","initHeaders","envIdKey","toLowerCase","environmentId","safeGetHooks","environmentMetadata","plugins","hooks","pluginHooks","getHooks","safeRegisterPlugins","client","register","ApplicationTags","tags","application","tagKeys","flatMap","ClientContext","offline","CompositeDataSource","initializers","synchronizers","fdv1Synchronizers","_transitionConditions","Valid","durationMS","transition","Interrupted","_stopped","_cancelTokens","_cancellableDelay","delayMS","timeout","promise","_","cancel","clearTimeout","_externalTransitionPromise","resolveTransition","_externalTransitionResolve","_initPhaseActive","_initFactories","_syncFactories","_fdv1Synchronizers","dataCallback","statusCallback","selectorGetter","sanitizedStatusCallback","_wrapStatusCallbackWithSanitizer","lastTransition","Initializing","dataSource","currentDS","isPrimary","cullDSFactory","_pickDataSource","internalTransitionPromise","transitionResolve","lastState","cancelScheduledTransition","callbackHandler","_consumeCancelToken","Closed","condition","_lookupTransitionCondition","then","transitionRequest","race","stop","cancelDelay","delayedTransition","_reset","tr","factory","excludeRecover","lastStatus","lastErr","alreadyReportedInitializing","sanitized","base64UrlEncode","encoding","btoa","cancelableTimedPromise","t","taskName","_res","reject","clone","createSafeLogger","basicLogger","debounce","fn","delayMs","timer","defaultHeaders","userAgentHeaderName","userAgentBase","wrapperName","wrapperVersion","authorization","fastDeepEqual","Map","size","has","ArrayBuffer","isView","RegExp","valueOf","getPollingUri","combinedParameters","getStreamingUri","internal","noop","secondsToMillis","sec","shouldRetry","subsystem","timedPromise","LDFlagsStateOptions","LDFlagsState","LDMigrationStage","LDMigrationStage_1","IsMigrationStage","LDMigrationOpEvent","LDConsistencyCheck","__createBinding","__exportStar","LDMigrationVariation","create","m","k2","getOwnPropertyDescriptor","__esModule","writable","configurable","enumerable","p","require$$0","require$$1","require$$2","require$$3","require$$4","LDBigSegmentsOptions","LDOptions","LDProxyOptions","LDTLSOptions","LDExecutionOrdering","LDExecution","LDMigrationOptions","LDConcurrentExecution","LDSerialExecution","ordering","Serial","Concurrent","LDDataSystemOptions","isCustomOptions","isStreamingOnlyOptions","isStandardOptions","dataSourceOptionsType","isPollingOnlyOptions","require$$5","LDClient","LDMigration","DataKind","LDFeatureStore","LDTransactionalFeatureStore","LDWaitForInitializationOptions","FileDataSourceOptions","Hook","BigSegmentStore","BigSegmentStoreMembership","BigSegmentStoreMetadata","BigSegmentStoreStatus","DataCollection","FullDataSet","KeyedItems","VersionedData","BigSegmentStoreStatusProvider","persistent_store","require$$6","require$$7","require$$8","require$$9","require$$10","LDDataSourceUpdates","LDFeatureRequestor","LDTransactionalDataSourceUpdates","subsystems","interfaces","integrations","LruCache_1","_keyMap","_head","_tail","_size","_max","_values","_keys","_next","Uint32Array","_prev","maxAge","_lastUpdated","fill","_maxAge","set","_index","_setTail","lastUpdated","_evict","head","delete","_link","n","BigSegmentsManager_1","js_sdk_common_1","BigSegmentStatusProviderImpl_1","_store","config","statusProvider","_pollStoreAndUpdateStatus","_staleTimeMs","staleAfter","pollIntervalMs","statusPollInterval","_pollHandle","_cache","userCacheSize","userCacheTime","getUserMembership","userKey","_b","_c","memberCache","membership","_hashForUserKey","cacheItem","available","stale","newStatus","metadata","lastUpToDate","_isStale","hasher","createHash","update","digest","createPluginEnvironmentMetadata_1","createPluginEnvironmentMetadata","_sdkKey","applicationInfo","createPayloadListenerFDv2","createPayloadListener","dataSourceUpdates","basisReceived","dataContainer","initMetadata","converted","namespace","namespaceForKind","assign","applyChanges","VersionedDataKinds_1","VersionedDataKinds","getKeyFromPath","streamApiPath","Features","Segments","serialization","deserializeSegment","serializeSegment","deserializeFlag","serializeFlag","deserializeDelete","deserializePatch","deserializePoll","reviveFullPayload","processSegment","processFlag","replacer","nullReplacer","TARGET_LIST_ARRAY_CUTOFF","excludeKeys","filteredEntries","_value","generated_includedSet","included","generated_excludedSet","includedContexts","generated_valuesSet","excludedContexts","processRollout","rollout","bucketBy","bucketByAttributeReference","contextKind","fallthrough","rules","rule","clauses","clause","attribute","attributeReference","_d","_e","rolloutContextKind","tryParse","flagsAndSegments","deserializeAll","parsed","createStreamListeners","createDeleteListener","createPatchListener","createPutListener","serialization_1","onPutCompleteHandler","deserializeData","processJson","initData","init","onPatchCompleteHandler","upsert","onDeleteCompleteHandler","onCompleteHandlers","listeners","put","patch","NamespacedDataSet_1","_itemsByNamespace","items","removeAll","enumerate","callback","mergeFrom","bind","DependencyTracker_1","_dependenciesFrom","_dependenciesTo","updateDependenciesFrom","newDependencySet","oldDependencySet","depNs","depKey","depsToThisDep","updateModifiedItems","inDependencySet","modifiedNamespace","modifiedKey","affectedItems","DataSourceUpdates_1","computeDependencies","ret","isFlag","isSegment","prerequisites","prereq","itemWithRuleClauses","op","_featureStore","_hasEventListeners","_onChange","_dependencyTracker","allData","checkForChanges","doInit","oldData","updatedItems","oldDataForKind","newDataForKind","mergedData","addIfModified","sendChangeEvents","all","oldFlags","oldSegments","doUpsert","oldItem","oldValue","newValue","toDataSet","dataSet","FileLoader_1","_filesystem","_paths","_watch","_callback","_watchers","_fileData","_fileTimestamps","loadAndWatch","promises","readFile","timeStamp","getFileTimestamp","results","watcher","watch","updatePath","_debounceCallback","_debounceHandle","fileDataInitilizerFDv2","_validateInputs","paths","fileSystem","_yamlParser","yamlParser","payloadProcessor","errorKind","adaptor","_fileLoader","parsedData","_processFileData","catch","NetworkError","curr","endsWith","OneShotInitializerFDv2_1","_requestor","requestAllData","ErrorResponse","promisify_1","AsyncStoreFacade_1","store","cb","initialized","getInitMetadata","getInitMetaData","AsyncTransactionalStoreFacade_1","isStale","record","expiration","TtlCache_1","_options","_storage","_checkIntervalHandle","_purgeStale","checkInterval","ttl","persistentStoreKinds","deserialize","serialize","serializedItem","priority","sortDataSet_1","persistentStoreKinds_1","topologicalSort","itemsMap","sortedItems","unvisitedItems","visit","preReq","prereqKey","dataMap","kindNamespace","i1","i2","UpdateQueue_1","enqueue","updateFn","executePendingUpdates","PersistentDataStoreWrapper_1","cacheKey","allForKindCacheKey","initializationCheckedKey","itemIfNotDeleted","deletedDescriptor","descriptor","deserializedItem","_core","_isInitialized","_itemCache","_allItemsCache","itemForKey","itemDescriptor","persistKind","storeInitialized","getAll","storeItems","filteredItems","filteredItem","updatedDescriptor","getDescription","InMemoryFeatureStore_1","_allData","_initCalled","_initMetadata","tempData","existingItems","old","getSelector","TransactionalFeatureStore_1","_nonTransPersistenceStore","_activeStore","_memoryStore","params","dataKind","previousPromise","nextParams","TransactionalFeatureStore","PersistentDataStoreWrapper","AsyncTransactionalStoreFacade","AsyncStoreFacade","PollingProcessor_1","store_1","_pollInterval","_initSuccessHandler","_poll","reportJsonError","startTime","elapsed","sleepFor","_timeoutHandle","PollingProcessorFDv2_1","_processResponseAsFDv1","_f","_g","processFDv1FlagsAndSegments","_h","Requestor_1","_path","_eTagCache","_headers","_serviceEndpoints","_requestWithETagCache","requestUrl","cacheEntry","cachedETag","etag","updatedOptions","text","queryParams","fromEntries","StreamingProcessor_1","streamUriPath","_streamInitialReconnectDelay","_streamUri","_logConnectionStarted","_connectionAttemptStartTime","_logConnectionResult","_retryAndHandleError","eventSource","createEventSource","errorFilter","readTimeoutMillis","retryResetIntervalMillis","_eventSource","onclose","onerror","onopen","_initHeaders","onretrying","dataJson","errorHandler","StreamingProcessorFDv2_1","_streamUriPath","_parameters","_logConnectionAttempt","fallbackErr","TransactionalDataSourceUpdates_1","iterateData","doApplyChanges","defaultValues","DEFAULT_STREAM_RECONNECT_DELAY","DEFAULT_POLL_INTERVAL","LDDataSystemOptions_1","validations","baseUri","streamUri","eventsUri","capacity","featureStore","dataSystem","bigSegments","updateProcessor","pollInterval","proxyOptions","streamInitialReconnectDelay","useLdd","sendEvents","contextKeysCapacity","contextKeysFlushInterval","tlsParams","diagnosticOptOut","enableEventCompression","defaultStandardDataSourceOptions","defaultStreamingDataSourceOptions","defaultPollingDataSourceOptions","defaultDataSystemOptions","validateTypesAndNames","defaults","errors","validatedOptions","optionName","optionValue","internalOptions","topLevelResult","streamingEndpointSpecified","pollingEndpointSpecified","eventEndpointSpecified","validateEndpoints","dsErrors","dsResult","allErrors","persistentStore","validatedDataSourceOptions","validateDataSystemOptions","validatedDSOptions","featureStoreFactory","updateProcessorFactory","getImplementationHooks","createDiagnosticsInitConfig_1","api_1","Configuration_1","_j","_k","_l","_m","pollingIntervalMillis","reconnectTimeMillis","streamDisabled","customBaseURI","customStreamURI","customEventsURI","connectTimeoutMillis","socketTimeoutMillis","eventsFlushIntervalMillis","contextKeysFlushIntervalMillis","diagnosticRecordingIntervalMillis","streamingDisabled","usingRelayDaemon","usingProxy","usingProxyAuthenticator","usingProxyAuth","dataStoreType","collection","allAsync","allSeriesAsync","firstResult","operator","seriesAsync","check","firstSeriesAsync","Reasons_1","Reasons","prerequisiteFailed","prerequisiteKey","ruleMatch","ruleId","ruleIndex","Fallthrough","Off","TargetMatch","EvalResult_1","EvalResult","isError","detail","isOff","setDefault","def","forError","variationIndex","forSuccess","Bucketer_1","_sha1Hex","hash","bucket","salt","kindForRollout","seed","bucketableValue","isInteger","valueForBucketing","hashKey","variations","getBucketBy","getOffVariation","getVariation","KEY_ATTR_REF","MalformedFlag","offVariation","isExperiment","evalTargets_1","collection_1","variations_1","evalTarget","contextKey","contextTargets","userTarget","targets","ut","makeBigSegmentRef_1","generation","Operations","semver_1","VERSION_COMPONENTS_REGEX","parseSemver","exec","transformed","semVerOperator","aVer","bVer","makeOperator","converter","parseDate","operators","in","matches","pattern","safeRegexMatch","contains","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","before","after","semVerEqual","semVerLessThan","semVerGreaterThan","execute","matchClause","maybeNegate","Operations_1","negate","matchAny","testValue","contextValue","segmentSearch","userTargets","userTargetSet","targetIndex","matchSegmentTargets_1","Evaluator_1","matchClause_1","bigSegmentsStatusPriority","HEALTHY","STALE","STORE_ERROR","NOT_CONFIGURED","getBigSegmentsStatusPriority","computeUpdatedBigSegmentsStatus","latest","makeMatch","isMatch","makeError","queries","_queries","_bucketer","evaluate","eventFactory","evaluateCb","_evaluateInternal","bigSegmentsStatus","visitedFlags","topLevel","on","_checkPrerequisites","targetRes","_evaluateRules","evalRes","_variationForContext","prereqResult","iterCb","updatedVisitedFlags","getFlag","prereqFlag","evalEventServer","ruleResult","_ruleMatchContext","_clauseMatchContext","segmentsVisited","errorResult","getSegment","newVisited","segmentMatchContext","varOrRollout","hadContext","updatedReason","sum","variate","weight","untracked","inExperiment","lastVariate","segmentRuleMatchContext","simpleSegmentMatchContext","unbounded","includeExclude","evalResult","matched","bigSegmentKind","unboundedContextKind","keyForBigSegment","bigSegmentsMembership","bigSegmentMatchContext","getBigSegmentsMembership","segmentRef","ContextDeduplicator_1","_contextKeysCache","inCache","isExperiment_1","trackEventsFallthrough","EventFactory_1","EventFactory","prereqOfFlag","FlagsStateBuilder_1","_valid","_flagValues","_flagMetadata","addFlag","trackReason","detailsOnlyIfTracked","meta","omitDetails","build","allValues","getFlagValue","getFlagReason","toJSON","$flagsState","$valid","HookRunner_1","UNKNOWN_HOOK_NAME","_hooks","withEvaluationSeries","defaultValue","methodName","withEvaluationSeriesExtraDetail","hookContext","_prepareHooks","hookData","_executeBeforeEvaluation","_executeAfterEvaluation","_tryExecuteStage","hookName","stage","_hookName","hook","updatedData","hookIndex","afterEvaluation","beforeEvaluation","addHook","MigrationOpEventConversion","areValidBooleans","new","validateMeasurement","measurement","areValidNumbers","isErrorMeasurement","isConsistencyMeasurement","isInvokedMeasurement","inEvent","operation","contextKeysOrContext","evaluation","validated","inReason","outReason","validateEvaluation","measurements","MigrationOpTracker_1","data_1","isPopulated","isNaN","_flagKey","_defaultStage","_stage","_reason","_checkRatio","_variation","_version","_samplingRatio","_errors","_wasInvoked","_consistencyCheck","NotChecked","_latencyMeasurement","NaN","_operation","origin","consistency","Consistent","Inconsistent","exception","latency","invoked","createEvent","_measurementConsistencyCheck","_populateInvoked","_populateConsistency","_populateLatency","_populateErrors","_logTag","_latencyConsistencyMessage","_errorConsistencyMessage","_consistencyCheckConsistencyMessage","_checkOriginEventConsistency","newIsPopulated","oldIsPopulated","LDClientImpl_1","createPayloadListenerFDv2_1","createStreamListeners_1","fileDataInitilizerFDv2_1","require$$11","require$$12","require$$13","require$$14","require$$15","require$$16","require$$17","require$$18","require$$19","require$$20","require$$21","require$$22","require$$23","require$$24","MigrationOpEventConversion_1","require$$25","require$$26","require$$27","require$$28","InitState","constructFDv1","callbacks","initSuccess","dataSourceErrorHandler","onUpdate","hasEventListeners","hookRunner","diagnosticsManager","eventProcessor","bigSegmentsManager","evaluator","onError","onFailed","onReady","_initState","_eventFactoryDefault","_eventFactoryWithReasons","transactionalStore","payloadListener","_evaluator","_dataSource","_eventProcessor","_bigSegmentsManager","_hookRunner","_onError","_onFailed","_onReady","fdv1FallbackSynchronizers","initializerConfigs","synchronizerConfigs","initializerConfig","synchronizerConfig","reconnectDelay","pollingInterval","constructFDv2","_initSuccess","bigSegmentStatusProviderInternal","_dataSourceErrorHandler","_updateProcessor","Initialized","waitForInitialization","_initializedPromise","_clientWithTimeout","_rejectionReason","_initResolve","_initReject","_evaluateIfPossible","variationDetail","_typedEval","typeChecker","typedRes","boolVariation","numberVariation","stringVariation","jsonVariation","boolVariationDetail","numberVariationDetail","stringVariationDetail","jsonVariationDetail","_migrationVariationInternal","WrongType","checkRatio","migration","tracker","migrationVariation","allFlagsState","allFlagState","evalContext","doEval","allFlags","builder","clientOnly","clientSideOnly","detailsOnlyForTrackedFlags","storeItem","clientSideAvailability","usingEnvironmentId","requireExperimentData","secureModeHash","checkedContext","createHmac","hmac","isOffline","track","trackMigration","identify","_variationInternal","ClientNotReady","UserNotSpecified","FlagNotFound","errorRes","_sendEvalEvent","basePromise","cancelableTimeout","finally","Migration_1","createMigration","LDMigrationError","LDMigrationSuccess","LDMigrationOptions_1","Migration","_client","_readTable","_doSingleOp","readOld","DualWrite","Shadow","fromOld","fromNew","_doRead","_trackConsistency","Live","RampDown","readNew","Complete","_writeTable","authoritative","writeOld","nonAuthoritative","writeNew","execution","_execution","_latencyTracking","latencyTracking","_errorTracking","errorTracking","read","defaultStage","_sendEvent","write","_readSequentialFixed","_readConcurrent","fromOldPromise","fromNewPromise","_readSequentialRandom","Fixed","_trackLatency","safeCall","end","performance","FileDataSource_1","filesystem","autoUpdate","_addItem","fileData","fd","_processParsedData","flagValues","previousInstance","makeFlagWithValue","FileDataSourceFactory_1","ldClientContext","initSuccessHandler","getFactory","variationForBoolean","FALSE_VARIATION_INDEX","TRUE_VARIATION_INDEX","TestDataRuleBuilder_1","booleanVariation_1","TestDataRuleBuilder","_flagBuilder","_clauses","andMatch","andNotMatch","thenReturn","booleanFlag","addRule","TestDataFlagBuilder_1","TestDataFlagBuilder","_key","_data","fallthroughVariation","targetsByVariation","_isBooleanFlag","targetingOn","variationForAll","clearRules","clearAllTargets","valueForAll","variationForUser","variationForContext","targetsForVariation","targetsForContextKind","ifMatch","ifNotMatch","flagRuleBuilder","baseFlagObject","contextTargetsForVariation","getKey","TestDataSource_1","initialFlags","initialSegments","_onStop","_flags","_segments","TestData_1","_currentFlags","_currentSegments","_dataSources","_flagBuilders","newSource","tds","flagBuilder","oldVersion","newFlag","impl","usePreconfiguredFlag","inConfig","flagConfig","newItem","usePreconfiguredSegment","segmentConfig","test_data","TestData","FileDataSourceFactory","NullEventSource_1","handlers","closed","simulateError","NullEventSource","TtlCache","BigSegmentStoreStatusProviderImpl","LDClientImpl","internalServer","CryptoJSHasher","algorithm","algo","CryptoJS","SHA1","SHA256","_cryptoJSHasher","finalize","enc","Base64","Hex","CryptoJSHmac","_cryptoJSHmac","HMAC","EdgeCrypto","EdgeRequests","eventSourceInitDict","getEventSourceCapabilities","readTimeout","customMethod","EdgePlatform","defaultOptions","clientSideID","platformInfo","em","EventEmitter","finalOptions","createOptions","emitter","listenerCount","emit","EdgeFeatureStore","_edgeProvider","_description","_rootKey","dataKey","kindKey","storePayload","_getStorePayload","providerData","validateOptions","rest","getOwnPropertySymbols","propertyIsEnumerable","__rest","CloudflarePlatformInfo","kvNamespace","__objRest","cache","initEdge","__spreadValues"],"mappings":"yPACAA,OAAOC,eAAeC,EAAS,aAAc,CAAEC,OAAO,IA0CtDD,EAAAE,QAtCA,MACI,WAAAC,CAAYC,GACRC,KAAKD,iBAAmBA,CAChC,CAOI,SAAAE,GACI,OAAOD,KAAKE,WACpB,CAMI,mBAAMC,GAKF,OAJKH,KAAKE,mBACAF,KAAKD,mBAGRC,KAAKE,WACpB,CACI,MAAAE,GACQ,IAAAC,EACAL,KAAKE,cACqB,QAAzBG,EAAKL,KAAKM,iBAA8B,IAAPD,GAAyBA,EAAGE,KAAKP,KAAMA,KAAKE,aAE1F,CACI,WAAAM,CAAYC,GACRT,KAAKM,UAAYG,CACzB,CACI,SAAAC,CAAUC,GACNX,KAAKE,YAAcS,CAC3B,8BC1BA,SAASC,EAASC,GACd,OAAOA,EAAIC,QAAQ,KAAOD,EAAIE,QAAQ,MAAO,KAAKA,QAAQ,MAAO,KAAOF,CAC5E,CAWA,MAAMG,EAeF,WAAAlB,CAAYmB,EAAcC,GAAU,GAChC,GAAKA,EA2BA,CACD,MAAMC,EAAaF,EACnBjB,KAAKoB,YAAc,CAACD,GACpBnB,KAAKqB,QAAyB,KAAfF,EAEfnB,KAAKs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C,EAAQ09C,GACpF19C,UACGm9C"}
1
+ {"version":3,"file":"index.js","sources":["../../../../shared/sdk-server/dist/BigSegmentStatusProviderImpl.js","../../../../shared/common/dist/cjs/index.cjs","../../../../shared/sdk-server/dist/api/data/LDFlagsStateOptions.js","../../../../shared/sdk-server/dist/api/data/LDFlagsState.js","../../../../shared/sdk-server/dist/api/data/LDMigrationStage.js","../../../../shared/sdk-server/dist/api/data/LDMigrationOpEvent.js","../../../../shared/sdk-server/dist/api/data/LDMigrationVariation.js","../../../../shared/sdk-server/dist/api/data/index.js","../../../../shared/sdk-server/dist/api/options/LDBigSegmentsOptions.js","../../../../shared/sdk-server/dist/api/options/LDOptions.js","../../../../shared/sdk-server/dist/api/options/LDProxyOptions.js","../../../../shared/sdk-server/dist/api/options/LDTLSOptions.js","../../../../shared/sdk-server/dist/api/options/LDMigrationOptions.js","../../../../shared/sdk-server/dist/api/options/LDDataSystemOptions.js","../../../../shared/sdk-server/dist/api/options/index.js","../../../../shared/sdk-server/dist/api/LDClient.js","../../../../shared/sdk-server/dist/api/LDMigration.js","../../../../shared/sdk-server/dist/api/interfaces/DataKind.js","../../../../shared/sdk-server/dist/api/subsystems/LDFeatureStore.js","../../../../shared/sdk-server/dist/api/subsystems/LDTransactionalFeatureStore.js","../../../../shared/sdk-server/dist/api/LDWaitForInitializationOptions.js","../../../../shared/sdk-server/dist/api/integrations/FileDataSourceOptions.js","../../../../shared/sdk-server/dist/api/integrations/Hook.js","../../../../shared/sdk-server/dist/api/integrations/index.js","../../../../shared/sdk-server/dist/api/interfaces/BigSegmentStore.js","../../../../shared/sdk-server/dist/api/interfaces/BigSegmentStoreMembership.js","../../../../shared/sdk-server/dist/api/interfaces/BigSegmentStoreMetadata.js","../../../../shared/sdk-server/dist/api/interfaces/BigSegmentStoreStatus.js","../../../../shared/sdk-server/dist/api/interfaces/DataCollection.js","../../../../shared/sdk-server/dist/api/interfaces/FullDataSet.js","../../../../shared/sdk-server/dist/api/interfaces/KeyedItems.js","../../../../shared/sdk-server/dist/api/interfaces/VersionedData.js","../../../../shared/sdk-server/dist/api/interfaces/BigSegmentStoreStatusProvider.js","../../../../shared/sdk-server/dist/api/interfaces/persistent_store/index.js","../../../../shared/sdk-server/dist/api/interfaces/index.js","../../../../shared/sdk-server/dist/api/subsystems/LDDataSourceUpdates.js","../../../../shared/sdk-server/dist/api/subsystems/LDFeatureRequestor.js","../../../../shared/sdk-server/dist/api/subsystems/LDTransactionalDataSourceUpdates.js","../../../../shared/sdk-server/dist/api/subsystems/index.js","../../../../shared/sdk-server/dist/api/index.js","../../../../shared/sdk-server/dist/cache/LruCache.js","../../../../shared/sdk-server/dist/BigSegmentsManager.js","../../../../shared/sdk-server/dist/createPluginEnvironmentMetadata.js","../../../../shared/sdk-server/dist/data_sources/createPayloadListenerFDv2.js","../../../../shared/sdk-server/dist/store/VersionedDataKinds.js","../../../../shared/sdk-server/dist/store/serialization.js","../../../../shared/sdk-server/dist/data_sources/createStreamListeners.js","../../../../shared/sdk-server/dist/data_sources/NamespacedDataSet.js","../../../../shared/sdk-server/dist/data_sources/DependencyTracker.js","../../../../shared/sdk-server/dist/data_sources/DataSourceUpdates.js","../../../../shared/sdk-server/dist/data_sources/FileLoader.js","../../../../shared/sdk-server/dist/data_sources/fileDataInitilizerFDv2.js","../../../../shared/sdk-server/dist/data_sources/OneShotInitializerFDv2.js","../../../../shared/sdk-server/dist/async/promisify.js","../../../../shared/sdk-server/dist/store/AsyncStoreFacade.js","../../../../shared/sdk-server/dist/store/AsyncTransactionalStoreFacade.js","../../../../shared/sdk-server/dist/cache/TtlCache.js","../../../../shared/sdk-server/dist/store/persistentStoreKinds.js","../../../../shared/sdk-server/dist/store/sortDataSet.js","../../../../shared/sdk-server/dist/store/UpdateQueue.js","../../../../shared/sdk-server/dist/store/PersistentDataStoreWrapper.js","../../../../shared/sdk-server/dist/store/InMemoryFeatureStore.js","../../../../shared/sdk-server/dist/store/TransactionalFeatureStore.js","../../../../shared/sdk-server/dist/store/index.js","../../../../shared/sdk-server/dist/data_sources/PollingProcessor.js","../../../../shared/sdk-server/dist/data_sources/PollingProcessorFDv2.js","../../../../shared/sdk-server/dist/data_sources/Requestor.js","../../../../shared/sdk-server/dist/data_sources/StreamingProcessor.js","../../../../shared/sdk-server/dist/data_sources/StreamingProcessorFDv2.js","../../../../shared/sdk-server/dist/data_sources/TransactionalDataSourceUpdates.js","../../../../shared/sdk-server/dist/options/Configuration.js","../../../../shared/sdk-server/dist/diagnostics/createDiagnosticsInitConfig.js","../../../../shared/sdk-server/dist/evaluation/collection.js","../../../../shared/sdk-server/dist/evaluation/Reasons.js","../../../../shared/sdk-server/dist/evaluation/EvalResult.js","../../../../shared/sdk-server/dist/evaluation/Bucketer.js","../../../../shared/sdk-server/dist/evaluation/variations.js","../../../../shared/sdk-server/dist/evaluation/evalTargets.js","../../../../shared/sdk-server/dist/evaluation/makeBigSegmentRef.js","../../../../shared/sdk-server/dist/evaluation/Operations.js","../../../../shared/sdk-server/dist/evaluation/matchClause.js","../../../../shared/sdk-server/dist/evaluation/matchSegmentTargets.js","../../../../shared/sdk-server/dist/evaluation/Evaluator.js","../../../../shared/sdk-server/dist/events/ContextDeduplicator.js","../../../../shared/sdk-server/dist/events/isExperiment.js","../../../../shared/sdk-server/dist/events/EventFactory.js","../../../../shared/sdk-server/dist/FlagsStateBuilder.js","../../../../shared/sdk-server/dist/hooks/HookRunner.js","../../../../shared/sdk-server/dist/MigrationOpEventConversion.js","../../../../shared/sdk-server/dist/MigrationOpTracker.js","../../../../shared/sdk-server/dist/LDClientImpl.js","../../../../shared/sdk-server/dist/Migration.js","../../../../shared/sdk-server/dist/data_sources/FileDataSource.js","../../../../shared/sdk-server/dist/integrations/FileDataSourceFactory.js","../../../../shared/sdk-server/dist/integrations/test_data/booleanVariation.js","../../../../shared/sdk-server/dist/integrations/test_data/TestDataRuleBuilder.js","../../../../shared/sdk-server/dist/integrations/test_data/TestDataFlagBuilder.js","../../../../shared/sdk-server/dist/integrations/test_data/TestDataSource.js","../../../../shared/sdk-server/dist/integrations/test_data/TestData.js","../../../../shared/sdk-server/dist/integrations/test_data/index.js","../../../../shared/sdk-server/dist/integrations/index.js","../../../../shared/sdk-server/dist/events/NullEventSource.js","../../../../shared/sdk-server/dist/events/index.js","../../../../shared/sdk-server/dist/internal/index.js","../../../../shared/sdk-server/dist/index.js","../../../../shared/sdk-server-edge/dist/esm/src/platform/crypto/cryptoJSHasher.js","../../../../shared/sdk-server-edge/dist/esm/src/platform/crypto/cryptoJSHmac.js","../../../../shared/sdk-server-edge/dist/esm/src/platform/crypto/index.js","../../../../shared/sdk-server-edge/dist/esm/src/platform/requests.js","../../../../shared/sdk-server-edge/dist/esm/src/platform/index.js","../../../../shared/sdk-server-edge/dist/esm/src/api/createCallbacks.js","../../../../shared/sdk-server-edge/dist/esm/src/api/createOptions.js","../../../../shared/sdk-server-edge/dist/esm/src/api/LDClient.js","../../../../shared/sdk-server-edge/dist/esm/src/api/EdgeFeatureStore.js","../../../../shared/sdk-server-edge/dist/esm/src/utils/validateOptions.js","../../src/createPlatformInfo.ts","../../src/index.ts","../../../../shared/sdk-server-edge/dist/esm/src/index.js"],"sourcesContent":["\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @ignore\n */\nclass BigSegmentStoreStatusProviderImpl {\n constructor(_onRequestStatus) {\n this._onRequestStatus = _onRequestStatus;\n }\n /**\n * Gets the current status of the store, if known.\n *\n * @returns a {@link BigSegmentStoreStatus}, or `undefined` if the SDK has not yet queried the\n * Big Segment store status\n */\n getStatus() {\n return this._lastStatus;\n }\n /**\n * Gets the current status of the store, querying it if the status has not already been queried.\n *\n * @returns a Promise for the status of the store\n */\n async requireStatus() {\n if (!this._lastStatus) {\n await this._onRequestStatus();\n }\n // Status will be defined at this point.\n return this._lastStatus;\n }\n notify() {\n var _a;\n if (this._lastStatus) {\n (_a = this._listener) === null || _a === void 0 ? void 0 : _a.call(this, this._lastStatus);\n }\n }\n setListener(listener) {\n this._listener = listener;\n }\n setStatus(status) {\n this._lastStatus = status;\n }\n}\nexports.default = BigSegmentStoreStatusProviderImpl;\n//# sourceMappingURL=BigSegmentStatusProviderImpl.js.map","'use strict';\n\n/**\n * Converts a literal to a ref string.\n * @param value\n * @returns An escaped literal which can be used as a ref.\n */\nfunction toRefString(value) {\n return `/${value.replace(/~/g, '~0').replace(/\\//g, '~1')}`;\n}\n/**\n * Produce a literal from a ref component.\n * @param ref\n * @returns A literal version of the ref.\n */\nfunction unescape(ref) {\n return ref.indexOf('~') ? ref.replace(/~1/g, '/').replace(/~0/g, '~') : ref;\n}\nfunction getComponents(reference) {\n const referenceWithoutPrefix = reference.startsWith('/') ? reference.substring(1) : reference;\n return referenceWithoutPrefix.split('/').map((component) => unescape(component));\n}\nfunction isLiteral(reference) {\n return !reference.startsWith('/');\n}\nfunction validate(reference) {\n return !reference.match(/\\/\\/|(^\\/.*~[^0|^1])|~$/);\n}\nclass AttributeReference {\n /**\n * Take an attribute reference string, or literal string, and produce\n * an attribute reference.\n *\n * Legacy user objects would have been created with names not\n * references. So, in that case, we need to use them as a component\n * without escaping them.\n *\n * e.g. A user could contain a custom attribute of `/a` which would\n * become the literal `a` if treated as a reference. Which would cause\n * it to no longer be redacted.\n * @param refOrLiteral The attribute reference string or literal string.\n * @param literal it true the value should be treated as a literal.\n */\n constructor(refOrLiteral, literal = false) {\n if (!literal) {\n this.redactionName = refOrLiteral;\n if (refOrLiteral === '' || refOrLiteral === '/' || !validate(refOrLiteral)) {\n this.isValid = false;\n this._components = [];\n return;\n }\n if (isLiteral(refOrLiteral)) {\n this._components = [refOrLiteral];\n }\n else if (refOrLiteral.indexOf('/', 1) < 0) {\n this._components = [unescape(refOrLiteral.slice(1))];\n }\n else {\n this._components = getComponents(refOrLiteral);\n }\n // The items inside of '_meta' are not intended to be addressable.\n // Excluding it as a valid reference means that we can make it non-addressable\n // without having to copy all the attributes out of the context object\n // provided by the user.\n if (this._components[0] === '_meta') {\n this.isValid = false;\n }\n else {\n this.isValid = true;\n }\n }\n else {\n const literalVal = refOrLiteral;\n this._components = [literalVal];\n this.isValid = literalVal !== '';\n // Literals which start with '/' need escaped to prevent ambiguity.\n this.redactionName = literalVal.startsWith('/') ? toRefString(literalVal) : literalVal;\n }\n }\n get(target) {\n const { _components: components, isValid } = this;\n if (!isValid) {\n return undefined;\n }\n let current = target;\n // This doesn't use a range based for loops, because those use generators.\n // See `no-restricted-syntax`.\n // It also doesn't use a collection method because this logic is more\n // straightforward with a loop.\n for (let index = 0; index < components.length; index += 1) {\n const component = components[index];\n if (current !== null &&\n current !== undefined &&\n // See https://eslint.org/docs/rules/no-prototype-builtins\n Object.prototype.hasOwnProperty.call(current, component) &&\n typeof current === 'object' &&\n // We do not want to allow indexing into an array.\n !Array.isArray(current)) {\n current = current[component];\n }\n else {\n return undefined;\n }\n }\n return current;\n }\n getComponent(depth) {\n return this._components[depth];\n }\n get depth() {\n return this._components.length;\n }\n get isKind() {\n return this._components.length === 1 && this._components[0] === 'kind';\n }\n compare(other) {\n return (this.depth === other.depth &&\n this._components.every((value, index) => value === other.getComponent(index)));\n }\n get components() {\n return [...this._components];\n }\n}\n/**\n * For use as invalid references when deserializing Flag/Segment data.\n */\nAttributeReference.InvalidReference = new AttributeReference('');\n\n/* eslint-disable class-methods-use-this */\n/* eslint-disable max-classes-per-file */\n/**\n * Validate a factory or instance.\n */\nclass FactoryOrInstance {\n is(factoryOrInstance) {\n if (Array.isArray(factoryOrInstance)) {\n return false;\n }\n const anyFactory = factoryOrInstance;\n const typeOfFactory = typeof anyFactory;\n return typeOfFactory === 'function' || typeOfFactory === 'object';\n }\n getType() {\n return 'factory method or object';\n }\n}\n/**\n * Validate a basic type.\n */\nclass Type {\n constructor(typeName, example) {\n this._typeName = typeName;\n this.typeOf = typeof example;\n }\n is(u) {\n if (Array.isArray(u)) {\n return false;\n }\n return typeof u === this.typeOf;\n }\n getType() {\n return this._typeName;\n }\n}\n/**\n * Validate an array of the specified type.\n *\n * This does not validate instances of types. All class instances\n * of classes will simply objects.\n */\nclass TypeArray {\n constructor(typeName, example) {\n this._typeName = typeName;\n this.typeOf = typeof example;\n }\n is(u) {\n if (Array.isArray(u)) {\n if (u.length > 0) {\n return u.every((val) => typeof val === this.typeOf);\n }\n return true;\n }\n return false;\n }\n getType() {\n return this._typeName;\n }\n}\n/**\n * Validate a value is a number and is greater or eval than a minimum.\n */\nclass NumberWithMinimum extends Type {\n constructor(min) {\n super(`number with minimum value of ${min}`, 0);\n this.min = min;\n }\n is(u) {\n return typeof u === this.typeOf && u >= this.min;\n }\n}\n/**\n * Validate a value is a string and it matches the given expression.\n */\nclass StringMatchingRegex extends Type {\n constructor(expression) {\n super(`string matching ${expression}`, '');\n this.expression = expression;\n }\n is(u) {\n return typeof u === 'string' && !!u.match(this.expression);\n }\n}\n/**\n * Validate a value is a function.\n */\nclass Function {\n is(u) {\n // We cannot inspect the parameters and there isn't really\n // a generic function type we can instantiate.\n // So the type guard is here just to make TS comfortable\n // calling something after using this guard.\n return typeof u === 'function';\n }\n getType() {\n return 'function';\n }\n}\nclass NullableBoolean {\n is(u) {\n return typeof u === 'boolean' || typeof u === 'undefined' || u === null;\n }\n getType() {\n return 'boolean | undefined | null';\n }\n}\n// Our reference SDK, Go, parses date/time strings with the time.RFC3339Nano format.\n// This regex should match strings that are valid in that format, and no others.\n// Acceptable:\n// 2019-10-31T23:59:59Z, 2019-10-31T23:59:59.100Z,\n// 2019-10-31T23:59:59-07, 2019-10-31T23:59:59-07:00, etc.\n// Unacceptable: no \"T\", no time zone designation\nconst DATE_REGEX = /^\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(\\.\\d\\d*)?(Z|[-+]\\d\\d(:\\d\\d)?)/;\n/**\n * Validate a value is a date. Values which are numbers are treated as dates and any string\n * which if compliant with `time.RFC3339Nano` is a date.\n */\nclass DateValidator {\n is(u) {\n return typeof u === 'number' || (typeof u === 'string' && DATE_REGEX.test(u));\n }\n getType() {\n return 'date';\n }\n}\n/**\n * Validates that a string is a valid kind.\n */\nclass KindValidator extends StringMatchingRegex {\n constructor() {\n super(/^(\\w|\\.|-)+$/);\n }\n is(u) {\n return super.is(u) && u !== 'kind';\n }\n}\n/**\n * A set of standard type validators.\n */\nclass TypeValidators {\n static createTypeArray(typeName, example) {\n return new TypeArray(typeName, example);\n }\n static numberWithMin(min) {\n return new NumberWithMinimum(min);\n }\n static stringMatchingRegex(expression) {\n return new StringMatchingRegex(expression);\n }\n}\nTypeValidators.String = new Type('string', '');\nTypeValidators.Number = new Type('number', 0);\nTypeValidators.ObjectOrFactory = new FactoryOrInstance();\nTypeValidators.Object = new Type('object', {});\nTypeValidators.StringArray = new TypeArray('string[]', '');\nTypeValidators.Boolean = new Type('boolean', true);\nTypeValidators.Function = new Function();\nTypeValidators.Date = new DateValidator();\nTypeValidators.Kind = new KindValidator();\nTypeValidators.NullableBoolean = new NullableBoolean();\n\n/**\n * Check if a context is a single kind context.\n * @param context\n * @returns true if the context is a single kind context.\n */\nfunction isSingleKind(context) {\n if ('kind' in context) {\n return TypeValidators.String.is(context.kind) && context.kind !== 'multi';\n }\n return false;\n}\n/**\n * Check if a context is a multi-kind context.\n * @param context\n * @returns true if it is a multi-kind context.\n */\nfunction isMultiKind(context) {\n if ('kind' in context) {\n return TypeValidators.String.is(context.kind) && context.kind === 'multi';\n }\n return false;\n}\n/**\n * Check if a context is a legacy user context.\n * @param context\n * @returns true if it is a legacy user context.\n */\nfunction isLegacyUser(context) {\n return !('kind' in context) || context.kind === null || context.kind === undefined;\n}\n\n/**\n * Given some object to serialize product a canonicalized JSON string.\n * https://www.rfc-editor.org/rfc/rfc8785.html\n *\n * We do not support custom toJSON methods on objects. Objects should be limited to basic types.\n *\n * @param object The object to serialize.\n */\nfunction canonicalize(object, visited = []) {\n // For JavaScript the default JSON serialization will produce canonicalized output for basic types.\n if (object === null || typeof object !== 'object') {\n return JSON.stringify(object);\n }\n if (visited.includes(object)) {\n throw new Error('Cycle detected');\n }\n if (Array.isArray(object)) {\n const values = object\n .map((item) => canonicalize(item, [...visited, object]))\n .map((item) => (item === undefined ? 'null' : item));\n return `[${values.join(',')}]`;\n }\n const values = Object.keys(object)\n .sort()\n .map((key) => {\n const value = canonicalize(object[key], [...visited, object]);\n if (value !== undefined) {\n return `${JSON.stringify(key)}:${value}`;\n }\n return undefined;\n })\n .filter((item) => item !== undefined);\n return `{${values.join(',')}}`;\n}\n\n// The general strategy for the context is to transform the passed in context\n// as little as possible. We do convert the legacy users to a single kind\n// context, but we do not translate all passed contexts into a rigid structure.\n// The context will have to be copied for events, but we want to avoid any\n// copying that we can.\n// So we validate that the information we are given is correct, and then we\n// just proxy calls with a nicely typed interface.\n// This is to reduce work on the hot-path. Later, for event processing, deeper\n// cloning of the context will be done.\n// When no kind is specified, then this kind will be used.\nconst DEFAULT_KIND = 'user';\n// The API allows for calling with an `LDContext` which is\n// `LDUser | LDSingleKindContext | LDMultiKindContext`. When ingesting a context\n// first the type must be determined to allow us to put it into a consistent type.\n/**\n * The partial URL encoding is needed because : is a valid character in context keys.\n *\n * Partial encoding is the replacement of all colon (:) characters with the URL\n * encoded equivalent (%3A) and all percent (%) characters with the URL encoded\n * equivalent (%25).\n * @param key The key to encode.\n * @returns Partially URL encoded key.\n */\nfunction encodeKey(key) {\n if (key.includes('%') || key.includes(':')) {\n return key.replace(/%/g, '%25').replace(/:/g, '%3A');\n }\n return key;\n}\n/**\n * Check if the given value is a LDContextCommon.\n * @param kindOrContext\n * @returns true if it is an LDContextCommon\n *\n * Due to a limitation in the expressiveness of these highly polymorphic types any field\n * in a multi-kind context can either be a context or 'kind'. So we need to re-assure\n * the compiler that it isn't the word multi.\n *\n * Because we do not allow top level values in a multi-kind context we can validate\n * that as well.\n */\nfunction isContextCommon(kindOrContext) {\n return kindOrContext && TypeValidators.Object.is(kindOrContext);\n}\n/**\n * Validate a context kind.\n * @param kind\n * @returns true if the kind is valid.\n */\nfunction validKind(kind) {\n return TypeValidators.Kind.is(kind);\n}\n/**\n * Validate a context key.\n * @param key\n * @returns true if the key is valid.\n */\nfunction validKey(key) {\n return TypeValidators.String.is(key) && key !== '';\n}\nfunction processPrivateAttributes(privateAttributes, literals = false) {\n if (privateAttributes) {\n return privateAttributes.map((privateAttribute) => new AttributeReference(privateAttribute, literals));\n }\n return [];\n}\nfunction defined(value) {\n return value !== null && value !== undefined;\n}\n/**\n * Convert a legacy user to a single kind context.\n * @param user\n * @returns A single kind context.\n */\nfunction legacyToSingleKind(user) {\n const singleKindContext = {\n // Key was coerced to a string for eval and events, so we can do that up-front.\n ...(user.custom || []),\n kind: 'user',\n key: String(user.key),\n };\n // For legacy users we never established a difference between null\n // and undefined for inputs. Because anonymous can be used in evaluations\n // we would want it to not possibly match true/false unless defined.\n // Which is different than coercing a null/undefined anonymous as `false`.\n if (defined(user.anonymous)) {\n const anonymous = !!user.anonymous;\n delete singleKindContext.anonymous;\n singleKindContext.anonymous = anonymous;\n }\n if (user.name !== null && user.name !== undefined) {\n singleKindContext.name = user.name;\n }\n if (user.ip !== null && user.ip !== undefined) {\n singleKindContext.ip = user.ip;\n }\n if (user.firstName !== null && user.firstName !== undefined) {\n singleKindContext.firstName = user.firstName;\n }\n if (user.lastName !== null && user.lastName !== undefined) {\n singleKindContext.lastName = user.lastName;\n }\n if (user.email !== null && user.email !== undefined) {\n singleKindContext.email = user.email;\n }\n if (user.avatar !== null && user.avatar !== undefined) {\n singleKindContext.avatar = user.avatar;\n }\n if (user.country !== null && user.country !== undefined) {\n singleKindContext.country = user.country;\n }\n if (user.privateAttributeNames !== null && user.privateAttributeNames !== undefined) {\n singleKindContext._meta = {\n privateAttributes: user.privateAttributeNames,\n };\n }\n // We are not pulling private attributes over because we will serialize\n // those from attribute references for events.\n return singleKindContext;\n}\n/**\n * Container for a context/contexts. Because contexts come from external code\n * they must be thoroughly validated and then formed to comply with\n * the type system.\n */\nclass Context {\n /**\n * Contexts should be created using the static factory method {@link Context.fromLDContext}.\n * @param kind The kind of the context.\n *\n * The factory methods are static functions within the class because they access private\n * implementation details, so they cannot be free functions.\n */\n constructor(valid, kind, message) {\n this._isMulti = false;\n this._isUser = false;\n this._wasLegacy = false;\n this._contexts = {};\n this.kind = kind;\n this.valid = valid;\n this.message = message;\n }\n static _contextForError(kind, message) {\n return new Context(false, kind, message);\n }\n static _getValueFromContext(reference, context) {\n if (!context || !reference.isValid) {\n return undefined;\n }\n if (reference.depth === 1 && reference.getComponent(0) === 'anonymous') {\n return !!context?.anonymous;\n }\n return reference.get(context);\n }\n _contextForKind(kind) {\n if (this._isMulti) {\n return this._contexts[kind];\n }\n if (this.kind === kind) {\n return this._context;\n }\n return undefined;\n }\n static _fromMultiKindContext(context) {\n const kinds = Object.keys(context).filter((key) => key !== 'kind');\n const kindsValid = kinds.every(validKind);\n if (!kinds.length) {\n return Context._contextForError('multi', 'A multi-kind context must contain at least one kind');\n }\n if (!kindsValid) {\n return Context._contextForError('multi', 'Context contains invalid kinds');\n }\n const privateAttributes = {};\n let contextsAreObjects = true;\n const contexts = kinds.reduce((acc, kind) => {\n const singleContext = context[kind];\n if (isContextCommon(singleContext)) {\n acc[kind] = singleContext;\n privateAttributes[kind] = processPrivateAttributes(singleContext._meta?.privateAttributes);\n }\n else {\n // No early break isn't the most efficient, but it is an error condition.\n contextsAreObjects = false;\n }\n return acc;\n }, {});\n if (!contextsAreObjects) {\n return Context._contextForError('multi', 'Context contained contexts that were not objects');\n }\n if (!Object.values(contexts).every((part) => validKey(part.key))) {\n return Context._contextForError('multi', 'Context contained invalid keys');\n }\n // There was only a single kind in the multi-kind context.\n // So we can just translate this to a single-kind context.\n if (kinds.length === 1) {\n const kind = kinds[0];\n const created = new Context(true, kind);\n created._context = { ...contexts[kind], kind };\n created._privateAttributeReferences = privateAttributes;\n created._isUser = kind === 'user';\n return created;\n }\n const created = new Context(true, context.kind);\n created._contexts = contexts;\n created._privateAttributeReferences = privateAttributes;\n created._isMulti = true;\n return created;\n }\n static _fromSingleKindContext(context) {\n const { key, kind } = context;\n const kindValid = validKind(kind);\n const keyValid = validKey(key);\n if (!kindValid) {\n return Context._contextForError(kind ?? 'unknown', 'The kind was not valid for the context');\n }\n if (!keyValid) {\n return Context._contextForError(kind, 'The key for the context was not valid');\n }\n // The JSON interfaces uses dangling _.\n // eslint-disable-next-line no-underscore-dangle\n const privateAttributeReferences = processPrivateAttributes(context._meta?.privateAttributes);\n const created = new Context(true, kind);\n created._isUser = kind === 'user';\n created._context = context;\n created._privateAttributeReferences = {\n [kind]: privateAttributeReferences,\n };\n return created;\n }\n static _fromLegacyUser(context) {\n const keyValid = context.key !== undefined && context.key !== null;\n // For legacy users we allow empty keys.\n if (!keyValid) {\n return Context._contextForError('user', 'The key for the context was not valid');\n }\n const created = new Context(true, 'user');\n created._isUser = true;\n created._wasLegacy = true;\n created._context = legacyToSingleKind(context);\n created._privateAttributeReferences = {\n user: processPrivateAttributes(context.privateAttributeNames, true),\n };\n return created;\n }\n /**\n * Attempt to create a {@link Context} from an {@link LDContext}.\n * @param context The input context to create a Context from.\n * @returns a {@link Context}, if the context was not valid, then the returned contexts `valid`\n * property will be false.\n */\n static fromLDContext(context) {\n if (!context) {\n return Context._contextForError('unknown', 'No context specified. Returning default value');\n }\n if (isSingleKind(context)) {\n return Context._fromSingleKindContext(context);\n }\n if (isMultiKind(context)) {\n return Context._fromMultiKindContext(context);\n }\n if (isLegacyUser(context)) {\n return Context._fromLegacyUser(context);\n }\n return Context._contextForError('unknown', 'Context was not of a valid kind');\n }\n /**\n * Creates a {@link LDContext} from a {@link Context}.\n * @param context to be converted\n * @returns an {@link LDContext} if input was valid, otherwise undefined\n */\n static toLDContext(context) {\n if (!context.valid) {\n return undefined;\n }\n const contexts = context.getContexts();\n if (!context._isMulti) {\n return contexts[0][1];\n }\n const result = {\n kind: 'multi',\n };\n contexts.forEach((kindAndContext) => {\n const kind = kindAndContext[0];\n const nestedContext = kindAndContext[1];\n result[kind] = nestedContext;\n });\n return result;\n }\n /**\n * Attempt to get a value for the given context kind using the given reference.\n * @param reference The reference to the value to get.\n * @param kind The kind of the context to get the value for.\n * @returns a value or `undefined` if one is not found.\n */\n valueForKind(reference, kind = DEFAULT_KIND) {\n if (reference.isKind) {\n return this.kinds;\n }\n return Context._getValueFromContext(reference, this._contextForKind(kind));\n }\n /**\n * Attempt to get a key for the specified kind.\n * @param kind The kind to get a key for.\n * @returns The key for the specified kind, or undefined.\n */\n key(kind = DEFAULT_KIND) {\n return this._contextForKind(kind)?.key;\n }\n /**\n * True if this is a multi-kind context.\n */\n get isMultiKind() {\n return this._isMulti;\n }\n /**\n * Get the canonical key for this context.\n */\n get canonicalKey() {\n if (this._isUser) {\n return this._context.key;\n }\n if (this._isMulti) {\n return Object.keys(this._contexts)\n .sort()\n .map((key) => `${key}:${encodeKey(this._contexts[key].key)}`)\n .join(':');\n }\n return `${this.kind}:${encodeKey(this._context.key)}`;\n }\n /**\n * Get the kinds of this context.\n */\n get kinds() {\n if (this._isMulti) {\n return Object.keys(this._contexts);\n }\n return [this.kind];\n }\n /**\n * Get the kinds, and their keys, for this context.\n */\n get kindsAndKeys() {\n if (this._isMulti) {\n return Object.entries(this._contexts).reduce((acc, [kind, context]) => {\n acc[kind] = context.key;\n return acc;\n }, {});\n }\n return { [this.kind]: this._context.key };\n }\n /**\n * Get the attribute references.\n *\n * @param kind\n */\n privateAttributes(kind) {\n return this._privateAttributeReferences?.[kind] || [];\n }\n /**\n * Get the underlying context objects from this context.\n *\n * This method is intended to be used in event generation.\n *\n * The returned objects should not be modified.\n */\n getContexts() {\n if (this._isMulti) {\n return Object.entries(this._contexts);\n }\n return [[this.kind, this._context]];\n }\n get legacy() {\n return this._wasLegacy;\n }\n /**\n * Get the serialized canonical JSON for this context. This is not filtered for use in events.\n *\n * This method will cache the result.\n *\n * @returns The serialized canonical JSON or undefined if it cannot be serialized.\n */\n canonicalUnfilteredJson() {\n if (!this.valid) {\n return undefined;\n }\n if (this._cachedCanonicalJson) {\n return this._cachedCanonicalJson;\n }\n try {\n this._cachedCanonicalJson = canonicalize(Context.toLDContext(this));\n }\n catch {\n // Indicated by undefined being returned.\n }\n return this._cachedCanonicalJson;\n }\n}\nContext.UserKind = DEFAULT_KIND;\n\n// _meta is part of the specification.\n// These attributes cannot be removed via a private attribute.\nconst protectedAttributes = ['key', 'kind', '_meta', 'anonymous'].map((str) => new AttributeReference(str, true));\n// Attributes that should be stringified for legacy users.\nconst legacyTopLevelCopyAttributes = [\n 'name',\n 'ip',\n 'firstName',\n 'lastName',\n 'email',\n 'avatar',\n 'country',\n];\nfunction compare(a, b) {\n return a.depth === b.length && b.every((value, index) => value === a.getComponent(index));\n}\nfunction cloneWithRedactions(target, references) {\n const stack = [];\n const cloned = {};\n const excluded = [];\n stack.push(...Object.keys(target).map((key) => ({\n key,\n ptr: [key],\n source: target,\n parent: cloned,\n visited: [target],\n })));\n while (stack.length) {\n const item = stack.pop();\n const redactRef = references.find((ref) => compare(ref, item.ptr));\n if (!redactRef) {\n const value = item.source[item.key];\n // Handle null because it overlaps with object, which we will want to handle later.\n if (value === null) {\n item.parent[item.key] = value;\n }\n else if (Array.isArray(value)) {\n item.parent[item.key] = [...value];\n }\n else if (typeof value === 'object') {\n // Arrays and null must already be handled.\n // Prevent cycles by not visiting the same object\n // with in the same branch. Different branches\n // may contain the same object.\n //\n // Same object visited twice in different branches.\n // A -> B -> D\n // -> C -> D\n // This is fine, which is why it doesn't just check if the object\n // was visited ever.\n if (!item.visited.includes(value)) {\n item.parent[item.key] = {};\n stack.push(...Object.keys(value).map((key) => ({\n key,\n ptr: [...item.ptr, key],\n source: value,\n parent: item.parent[item.key],\n visited: [...item.visited, value],\n })));\n }\n }\n else {\n item.parent[item.key] = value;\n }\n }\n else {\n excluded.push(redactRef.redactionName);\n }\n }\n return { cloned, excluded: excluded.sort() };\n}\nclass ContextFilter {\n constructor(_allAttributesPrivate, _privateAttributes) {\n this._allAttributesPrivate = _allAttributesPrivate;\n this._privateAttributes = _privateAttributes;\n }\n filter(context, redactAnonymousAttributes = false) {\n const contexts = context.getContexts();\n if (contexts.length === 1) {\n return this._filterSingleKind(context, contexts[0][1], contexts[0][0], redactAnonymousAttributes);\n }\n const filteredMulti = {\n kind: 'multi',\n };\n contexts.forEach(([kind, single]) => {\n filteredMulti[kind] = this._filterSingleKind(context, single, kind, redactAnonymousAttributes);\n });\n return filteredMulti;\n }\n _getAttributesToFilter(context, single, kind, redactAllAttributes) {\n return (redactAllAttributes\n ? Object.keys(single).map((k) => new AttributeReference(k, true))\n : [...this._privateAttributes, ...context.privateAttributes(kind)]).filter((attr) => !protectedAttributes.some((protectedAttr) => protectedAttr.compare(attr)));\n }\n _filterSingleKind(context, single, kind, redactAnonymousAttributes) {\n const redactAllAttributes = this._allAttributesPrivate || (redactAnonymousAttributes && single.anonymous === true);\n const { cloned, excluded } = cloneWithRedactions(single, this._getAttributesToFilter(context, single, kind, redactAllAttributes));\n if (context.legacy) {\n legacyTopLevelCopyAttributes.forEach((name) => {\n if (name in cloned) {\n cloned[name] = String(cloned[name]);\n }\n });\n }\n if (excluded.length) {\n if (!cloned._meta) {\n cloned._meta = {};\n }\n cloned._meta.redactedAttributes = excluded;\n }\n if (cloned._meta) {\n delete cloned._meta.privateAttributes;\n if (Object.keys(cloned._meta).length === 0) {\n delete cloned._meta;\n }\n }\n return cloned;\n }\n}\n\nconst MAX_RETRY_DELAY = 30 * 1000; // Maximum retry delay 30 seconds.\nconst JITTER_RATIO = 0.5; // Delay should be 50%-100% of calculated time.\n/**\n * Implements exponential backoff and jitter. This class tracks successful connections and failures\n * and produces a retry delay.\n *\n * It does not start any timers or directly control a connection.\n *\n * The backoff follows an exponential backoff scheme with 50% jitter starting at\n * initialRetryDelayMillis and capping at MAX_RETRY_DELAY. If RESET_INTERVAL has elapsed after a\n * success, without an intervening faulure, then the backoff is reset to initialRetryDelayMillis.\n */\nclass DefaultBackoff {\n constructor(initialRetryDelayMillis, _retryResetIntervalMillis, _random = Math.random) {\n this._retryResetIntervalMillis = _retryResetIntervalMillis;\n this._random = _random;\n this._retryCount = 0;\n // Initial retry delay cannot be 0.\n this._initialRetryDelayMillis = Math.max(1, initialRetryDelayMillis);\n this._maxExponent = Math.ceil(Math.log2(MAX_RETRY_DELAY / this._initialRetryDelayMillis));\n }\n _backoff() {\n const exponent = Math.min(this._retryCount, this._maxExponent);\n const delay = this._initialRetryDelayMillis * 2 ** exponent;\n return Math.min(delay, MAX_RETRY_DELAY);\n }\n _jitter(computedDelayMillis) {\n return computedDelayMillis - Math.trunc(this._random() * JITTER_RATIO * computedDelayMillis);\n }\n /**\n * This function should be called when a connection attempt is successful.\n *\n * @param timeStampMs The time of the success. Used primarily for testing, when not provided\n * the current time is used.\n */\n success(timeStampMs = Date.now()) {\n this._activeSince = timeStampMs;\n }\n /**\n * This function should be called when a connection fails. It returns the a delay, in\n * milliseconds, after which a reconnection attempt should be made.\n *\n * @param timeStampMs The time of the success. Used primarily for testing, when not provided\n * the current time is used.\n * @returns The delay before the next connection attempt.\n */\n fail(timeStampMs = Date.now()) {\n // If the last successful connection was active for more than the RESET_INTERVAL, then we\n // return to the initial retry delay.\n if (this._activeSince !== undefined &&\n timeStampMs - this._activeSince > this._retryResetIntervalMillis) {\n this._retryCount = 0;\n }\n this._activeSince = undefined;\n const delay = this._jitter(this._backoff());\n this._retryCount += 1;\n return delay;\n }\n}\n\n/**\n * Handler that connects the current {@link DataSource} to the {@link CompositeDataSource}. A single\n * {@link CallbackHandler} should only be given to one {@link DataSource}. Use {@link disable()} to\n * prevent additional callback events.\n */\nclass CallbackHandler {\n constructor(_dataCallback, _statusCallback) {\n this._dataCallback = _dataCallback;\n this._statusCallback = _statusCallback;\n this._disabled = false;\n }\n disable() {\n this._disabled = true;\n }\n async dataHandler(basis, data) {\n if (this._disabled) {\n return;\n }\n this._dataCallback(basis, data);\n }\n async statusHandler(status, err) {\n if (this._disabled) {\n return;\n }\n this._statusCallback(status, err);\n }\n}\n\n// TODO: refactor client-sdk to use this enum\n/**\n * @experimental\n * This feature is not stable and not subject to any backwards compatibility guarantees or semantic\n * versioning. It is not suitable for production usage.\n */\nvar DataSourceState;\n(function (DataSourceState) {\n // Positive confirmation of connection/data receipt\n DataSourceState[DataSourceState[\"Valid\"] = 0] = \"Valid\";\n // Spinning up to make first connection attempt\n DataSourceState[DataSourceState[\"Initializing\"] = 1] = \"Initializing\";\n // Transient issue, automatic retry is expected\n DataSourceState[DataSourceState[\"Interrupted\"] = 2] = \"Interrupted\";\n // Data source was closed and will not retry automatically.\n DataSourceState[DataSourceState[\"Closed\"] = 3] = \"Closed\";\n})(DataSourceState || (DataSourceState = {}));\n\n/**\n * Helper class for {@link CompositeDataSource} to manage iterating on data sources and removing them on the fly.\n */\nclass DataSourceList {\n /**\n * @param circular whether to loop off the end of the list back to the start\n * @param initialList of content\n */\n constructor(circular, initialList) {\n this._list = initialList ? [...initialList] : [];\n this._circular = circular;\n this._pos = 0;\n }\n /**\n * Returns the current head and then iterates.\n */\n next() {\n if (this._list.length <= 0 || this._pos >= this._list.length) {\n return undefined;\n }\n const result = this._list[this._pos];\n if (this._circular) {\n this._pos = (this._pos + 1) % this._list.length;\n }\n else {\n this._pos += 1;\n }\n return result;\n }\n /**\n * Replaces all elements with the provided list and resets the position of head to the start.\n *\n * @param input that will replace existing list\n */\n replace(input) {\n this._list = [...input];\n this._pos = 0;\n }\n /**\n * Removes the provided element from the list. If the removed element was the head, head moves to next. Consider head may be undefined if list is empty after removal.\n *\n * @param element to remove\n * @returns true if element was removed\n */\n remove(element) {\n const index = this._list.indexOf(element);\n if (index < 0) {\n return false;\n }\n this._list.splice(index, 1);\n if (this._list.length > 0) {\n // if removed item was before head, adjust head\n if (index < this._pos) {\n this._pos -= 1;\n }\n if (this._circular && this._pos > this._list.length - 1) {\n this._pos = 0;\n }\n }\n return true;\n }\n /**\n * Reset the head position to the start of the list.\n */\n reset() {\n this._pos = 0;\n }\n /**\n * @returns the current head position in the list, 0 indexed.\n */\n pos() {\n return this._pos;\n }\n /**\n * @returns the current length of the list\n */\n length() {\n return this._list.length;\n }\n /**\n * Clears the list and resets head.\n */\n clear() {\n this._list = [];\n this._pos = 0;\n }\n}\n\nclass LDFileDataSourceError extends Error {\n constructor(message) {\n super(message);\n this.name = 'LaunchDarklyFileDataSourceError';\n }\n}\nclass LDPollingError extends Error {\n constructor(kind, message, status, recoverable = true) {\n super(message);\n this.kind = kind;\n this.status = status;\n this.name = 'LaunchDarklyPollingError';\n this.recoverable = recoverable;\n }\n}\nclass LDStreamingError extends Error {\n constructor(kind, message, code, recoverable = true) {\n super(message);\n this.kind = kind;\n this.code = code;\n this.name = 'LaunchDarklyStreamingError';\n this.recoverable = recoverable;\n }\n}\n/**\n * This is a short term error and will be removed once FDv2 adoption is sufficient.\n */\nclass LDFlagDeliveryFallbackError extends Error {\n constructor(kind, message, code) {\n super(message);\n this.kind = kind;\n this.code = code;\n this.name = 'LDFlagDeliveryFallbackError';\n this.recoverable = false;\n }\n}\n\nconst DEFAULT_FALLBACK_TIME_MS = 2 * 60 * 1000;\nconst DEFAULT_RECOVERY_TIME_MS = 5 * 60 * 1000;\n/**\n * The {@link CompositeDataSource} can combine a number of {@link DataSystemInitializer}s and {@link DataSystemSynchronizer}s\n * into a single {@link DataSource}, implementing fallback and recovery logic internally to choose where data is sourced from.\n */\nclass CompositeDataSource {\n /**\n * @param initializers factories to create {@link DataSystemInitializer}s, in priority order.\n * @param synchronizers factories to create {@link DataSystemSynchronizer}s, in priority order.\n * @param fdv1Synchronizers factories to fallback to if we need to fallback to FDv1.\n * @param _logger for logging\n * @param _transitionConditions to control automated transition between datasources. Typically only used for testing.\n * @param _backoff to control delay between transitions. Typically only used for testing.\n */\n constructor(initializers, synchronizers, fdv1Synchronizers, _logger, _transitionConditions = {\n [DataSourceState.Valid]: {\n durationMS: DEFAULT_RECOVERY_TIME_MS,\n transition: 'recover',\n },\n [DataSourceState.Interrupted]: {\n durationMS: DEFAULT_FALLBACK_TIME_MS,\n transition: 'fallback',\n },\n }, _backoff = new DefaultBackoff(1000, 30000)) {\n this._logger = _logger;\n this._transitionConditions = _transitionConditions;\n this._backoff = _backoff;\n this._stopped = true;\n this._cancelTokens = [];\n this._cancellableDelay = (delayMS) => {\n let timeout;\n const promise = new Promise((res, _) => {\n timeout = setTimeout(res, delayMS);\n });\n return {\n promise,\n cancel() {\n if (timeout) {\n clearTimeout(timeout);\n timeout = undefined;\n }\n },\n };\n };\n this._externalTransitionPromise = new Promise((resolveTransition) => {\n this._externalTransitionResolve = resolveTransition;\n });\n this._initPhaseActive = initializers.length > 0; // init phase if we have initializers\n this._initFactories = new DataSourceList(false, initializers);\n this._syncFactories = new DataSourceList(true, synchronizers);\n this._fdv1Synchronizers = new DataSourceList(true, fdv1Synchronizers);\n }\n async start(dataCallback, statusCallback, selectorGetter) {\n if (!this._stopped) {\n // don't allow multiple simultaneous runs\n this._logger?.info('CompositeDataSource already running. Ignoring call to start.');\n return;\n }\n this._stopped = false;\n this._logger?.debug(`CompositeDataSource starting with (${this._initFactories.length()} initializers, ${this._syncFactories.length()} synchronizers).`);\n // this wrapper turns status updates from underlying data sources into a valid series of status updates for the consumer of this\n // composite data source\n const sanitizedStatusCallback = this._wrapStatusCallbackWithSanitizer(statusCallback);\n sanitizedStatusCallback(DataSourceState.Initializing);\n let lastTransition;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { dataSource: currentDS, isPrimary, cullDSFactory, } = this._pickDataSource(lastTransition);\n const internalTransitionPromise = new Promise((transitionResolve) => {\n if (currentDS) {\n // these local variables are used for handling automatic transition related to data source status (ex: recovering to primary after\n // secondary has been valid for N many seconds)\n let lastState;\n let cancelScheduledTransition = () => { };\n // this callback handler can be disabled and ensures only one transition request occurs\n const callbackHandler = new CallbackHandler((basis, data) => {\n this._backoff.success();\n dataCallback(basis, data);\n if (basis && this._initPhaseActive) {\n // transition to sync if we get basis during init\n callbackHandler.disable();\n this._consumeCancelToken(cancelScheduledTransition);\n sanitizedStatusCallback(DataSourceState.Interrupted);\n transitionResolve({ transition: 'switchToSync' });\n }\n }, (state, err) => {\n // When we get a status update, we want to fallback if it is an error. We also want to schedule a transition for some\n // time in the future if this status remains for some duration (ex: Recover to primary synchronizer after the secondary\n // synchronizer has been Valid for some time). These scheduled transitions are configurable in the constructor.\n this._logger?.debug(`CompositeDataSource received state ${state} from underlying data source. Err is ${err}`);\n if (err || state === DataSourceState.Closed) {\n callbackHandler.disable();\n if (err?.recoverable === false) {\n // don't use this datasource's factory again\n this._logger?.debug(`Culling data source due to err ${err}`);\n cullDSFactory?.();\n // this error indicates we should fallback to only using FDv1 synchronizers\n if (err instanceof LDFlagDeliveryFallbackError) {\n this._logger?.debug(`Falling back to FDv1`);\n this._syncFactories = this._fdv1Synchronizers;\n }\n }\n sanitizedStatusCallback(state, err);\n this._consumeCancelToken(cancelScheduledTransition);\n transitionResolve({ transition: 'fallback', err }); // unrecoverable error has occurred, so fallback\n }\n else {\n sanitizedStatusCallback(state);\n if (state !== lastState) {\n lastState = state;\n this._consumeCancelToken(cancelScheduledTransition); // cancel previously scheduled status transition if one was scheduled\n // primary source cannot recover to itself, so exclude it\n const condition = this._lookupTransitionCondition(state, isPrimary);\n if (condition) {\n const { promise, cancel } = this._cancellableDelay(condition.durationMS);\n cancelScheduledTransition = cancel;\n this._cancelTokens.push(cancelScheduledTransition);\n promise.then(() => {\n this._consumeCancelToken(cancel);\n callbackHandler.disable();\n sanitizedStatusCallback(DataSourceState.Interrupted);\n transitionResolve({ transition: condition.transition });\n });\n }\n }\n }\n });\n currentDS.start((basis, data) => callbackHandler.dataHandler(basis, data), (status, err) => callbackHandler.statusHandler(status, err), selectorGetter);\n }\n else {\n // we don't have a data source to use!\n transitionResolve({\n transition: 'stop',\n err: {\n name: 'ExhaustedDataSources',\n message: `CompositeDataSource has exhausted all configured initializers and synchronizers.`,\n },\n });\n }\n });\n // await transition triggered by internal data source or an external stop request\n let transitionRequest = await Promise.race([\n internalTransitionPromise,\n this._externalTransitionPromise,\n ]);\n // stop the underlying datasource before transitioning to next state\n currentDS?.stop();\n if (transitionRequest.err && transitionRequest.transition !== 'stop') {\n // if the transition was due to an error we're not in the initializer phase, throttle the transition. Fallback between initializers is not throttled.\n const delay = this._initPhaseActive ? 0 : this._backoff.fail();\n const { promise, cancel: cancelDelay } = this._cancellableDelay(delay);\n this._cancelTokens.push(cancelDelay);\n const delayedTransition = promise.then(() => {\n this._consumeCancelToken(cancelDelay);\n return transitionRequest;\n });\n // race the delayed transition and external transition requests to be responsive\n transitionRequest = await Promise.race([\n delayedTransition,\n this._externalTransitionPromise,\n ]);\n // consume the delay cancel token (even if it resolved, need to stop tracking its token)\n this._consumeCancelToken(cancelDelay);\n }\n lastTransition = transitionRequest.transition;\n if (transitionRequest.transition === 'stop') {\n // exit the loop, this is intentionally not the sanitized status callback\n statusCallback(DataSourceState.Closed, transitionRequest.err);\n break;\n }\n }\n // reset so that run can be called again in the future\n this._reset();\n }\n async stop() {\n this._cancelTokens.forEach((cancel) => cancel());\n this._cancelTokens = [];\n this._externalTransitionResolve?.({ transition: 'stop' });\n }\n _reset() {\n this._stopped = true;\n this._initPhaseActive = this._initFactories.length() > 0; // init phase if we have initializers;\n this._initFactories.reset();\n this._syncFactories.reset();\n this._fdv1Synchronizers.reset();\n this._externalTransitionPromise = new Promise((tr) => {\n this._externalTransitionResolve = tr;\n });\n // intentionally not resetting the backoff to avoid a code path that could circumvent throttling\n }\n /**\n * Determines the next datasource and returns that datasource as well as a closure to cull the\n * datasource from the datasource lists. One example where the cull closure is invoked is if the\n * datasource has an unrecoverable error.\n */\n _pickDataSource(transition) {\n let factory;\n let isPrimary;\n switch (transition) {\n case 'switchToSync':\n this._initPhaseActive = false; // one way toggle to false, unless this class is reset()\n this._syncFactories.reset();\n isPrimary = this._syncFactories.pos() === 0;\n factory = this._syncFactories.next();\n break;\n case 'recover':\n if (this._initPhaseActive) {\n this._initFactories.reset();\n isPrimary = this._initFactories.pos() === 0;\n factory = this._initFactories.next();\n }\n else {\n this._syncFactories.reset();\n isPrimary = this._syncFactories.pos() === 0;\n factory = this._syncFactories.next();\n }\n break;\n case 'fallback':\n default:\n // if asked to fallback after using all init factories, switch to sync factories\n if (this._initPhaseActive && this._initFactories.pos() >= this._initFactories.length()) {\n this._initPhaseActive = false;\n this._syncFactories.reset();\n }\n if (this._initPhaseActive) {\n isPrimary = this._initFactories.pos() === 0;\n factory = this._initFactories.next();\n }\n else {\n isPrimary = this._syncFactories.pos() === 0;\n factory = this._syncFactories.next();\n }\n break;\n }\n if (!factory) {\n return { dataSource: undefined, isPrimary, cullDSFactory: undefined };\n }\n return {\n dataSource: factory(),\n isPrimary,\n cullDSFactory: () => {\n if (factory) {\n this._syncFactories.remove(factory);\n }\n },\n };\n }\n /**\n * @returns the transition condition for the provided data source state or undefined\n * if there is no transition condition\n */\n _lookupTransitionCondition(state, excludeRecover) {\n const condition = this._transitionConditions[state];\n // exclude recovery can happen for certain initializers/synchronizers (ex: the primary synchronizer shouldn't recover to itself)\n if (excludeRecover && condition?.transition === 'recover') {\n return undefined;\n }\n return condition;\n }\n _consumeCancelToken(cancel) {\n cancel();\n const index = this._cancelTokens.indexOf(cancel, 0);\n if (index > -1) {\n this._cancelTokens.splice(index, 1);\n }\n }\n /**\n * This wrapper will ensure the following:\n *\n * Don't report DataSourceState.Initializing except as first status callback.\n * Map underlying DataSourceState.Closed to interrupted.\n * Don't report the same status and error twice in a row.\n */\n _wrapStatusCallbackWithSanitizer(statusCallback) {\n let alreadyReportedInitializing = false;\n let lastStatus;\n let lastErr;\n return (status, err) => {\n let sanitized = status;\n // underlying errors, closed state, or off are masked as interrupted while we transition\n if (status === DataSourceState.Closed) {\n sanitized = DataSourceState.Interrupted;\n }\n // don't report the same combination of values twice in a row\n if (sanitized === lastStatus && err === lastErr) {\n return;\n }\n if (sanitized === DataSourceState.Initializing) {\n // don't report initializing again if that has already been reported\n if (alreadyReportedInitializing) {\n return;\n }\n alreadyReportedInitializing = true;\n }\n lastStatus = sanitized;\n lastErr = err;\n statusCallback(sanitized, err);\n };\n }\n}\n\nexports.DataSourceErrorKind = void 0;\n(function (DataSourceErrorKind) {\n /// An unexpected error, such as an uncaught exception, further\n /// described by the error message.\n DataSourceErrorKind[\"Unknown\"] = \"UNKNOWN\";\n /// An I/O error such as a dropped connection.\n DataSourceErrorKind[\"NetworkError\"] = \"NETWORK_ERROR\";\n /// The LaunchDarkly service returned an HTTP response with an error\n /// status, available in the status code.\n DataSourceErrorKind[\"ErrorResponse\"] = \"ERROR_RESPONSE\";\n /// The SDK received malformed data from the LaunchDarkly service.\n DataSourceErrorKind[\"InvalidData\"] = \"INVALID_DATA\";\n})(exports.DataSourceErrorKind || (exports.DataSourceErrorKind = {}));\n\n/* eslint-disable import/prefer-default-export */\n/**\n * Enable / disable Auto environment attributes. When enabled, the SDK will automatically\n * provide data about the mobile environment where the application is running. This data makes it simpler to target\n * your mobile customers based on application name or version, or on device characteristics including manufacturer,\n * model, operating system, locale, and so on. We recommend enabling this when you configure the SDK. To learn more,\n * read [Automatic environment attributes](https://docs.launchdarkly.com/sdk/features/environment-attributes).\n * for more documentation.\n */\nexports.AutoEnvAttributes = void 0;\n(function (AutoEnvAttributes) {\n AutoEnvAttributes[AutoEnvAttributes[\"Disabled\"] = 0] = \"Disabled\";\n AutoEnvAttributes[AutoEnvAttributes[\"Enabled\"] = 1] = \"Enabled\";\n})(exports.AutoEnvAttributes || (exports.AutoEnvAttributes = {}));\n\nvar LDEventType;\n(function (LDEventType) {\n LDEventType[LDEventType[\"AnalyticsEvents\"] = 0] = \"AnalyticsEvents\";\n LDEventType[LDEventType[\"DiagnosticEvent\"] = 1] = \"DiagnosticEvent\";\n})(LDEventType || (LDEventType = {}));\nvar LDDeliveryStatus;\n(function (LDDeliveryStatus) {\n LDDeliveryStatus[LDDeliveryStatus[\"Succeeded\"] = 0] = \"Succeeded\";\n LDDeliveryStatus[LDDeliveryStatus[\"Failed\"] = 1] = \"Failed\";\n LDDeliveryStatus[LDDeliveryStatus[\"FailedAndMustShutDown\"] = 2] = \"FailedAndMustShutDown\";\n})(LDDeliveryStatus || (LDDeliveryStatus = {}));\n\nvar index$1 = /*#__PURE__*/Object.freeze({\n __proto__: null,\n get DataSourceState () { return DataSourceState; },\n get LDDeliveryStatus () { return LDDeliveryStatus; },\n get LDEventType () { return LDEventType; }\n});\n\n/**\n * Attempt to produce a string representation of a value.\n * The format should be roughly comparable to `util.format`\n * aside from object which will be JSON versus the `util.inspect`\n * format.\n * @param val\n * @returns A string representation of the value if possible.\n */\nfunction tryStringify(val) {\n if (typeof val === 'string') {\n return val;\n }\n if (val === undefined) {\n return 'undefined';\n }\n if (val === null) {\n return 'null';\n }\n if (Object.prototype.hasOwnProperty.call(val, 'toString')) {\n try {\n return val.toString();\n }\n catch {\n /* Keep going */\n }\n }\n if (typeof val === 'bigint') {\n return `${val}n`;\n }\n try {\n return JSON.stringify(val);\n }\n catch (error) {\n if (error instanceof TypeError && error.message.indexOf('circular') >= 0) {\n return '[Circular]';\n }\n return '[Not Stringifiable]';\n }\n}\n/**\n * Attempt to produce a numeric representation.\n * BigInts have an `n` suffix.\n * @param val\n * @returns The numeric representation or 'NaN' if not numeric.\n */\nfunction toNumber(val) {\n // Symbol has to be treated special because it will\n // throw an exception if an attempt is made to convert it.\n if (typeof val === 'symbol') {\n return 'NaN';\n }\n if (typeof val === 'bigint') {\n return `${val}n`;\n }\n return String(Number(val));\n}\n/**\n * Attempt to produce an integer representation.\n * BigInts have an `n` suffix.\n * @param val\n * @returns The integer representation or 'NaN' if not numeric.\n */\nfunction toInt(val) {\n if (typeof val === 'symbol') {\n return 'NaN';\n }\n if (typeof val === 'bigint') {\n return `${val}n`;\n }\n return String(parseInt(val, 10));\n}\n/**\n * Attempt to produce a float representation.\n * BigInts have an `n` suffix.\n * @param val\n * @returns The integer representation or 'NaN' if not numeric.\n */\nfunction toFloat(val) {\n if (typeof val === 'symbol') {\n return 'NaN';\n }\n return String(parseFloat(val));\n}\n// Based on:\n// https://nodejs.org/api/util.html#utilformatformat-args\n// The result will not match node exactly, but it should get the\n// right information through.\nconst escapes = {\n s: (val) => tryStringify(val),\n d: (val) => toNumber(val),\n i: (val) => toInt(val),\n f: (val) => toFloat(val),\n j: (val) => tryStringify(val),\n o: (val) => tryStringify(val),\n // eslint-disable-next-line @typescript-eslint/naming-convention\n O: (val) => tryStringify(val),\n c: () => '',\n};\n/**\n * A basic formatted for use where `util.format` is not available.\n * This will not be as performant, but it will produce formatted\n * messages.\n *\n * @internal\n *\n * @param args\n * @returns Formatted string.\n */\nfunction format(...args) {\n const formatString = args.shift();\n if (TypeValidators.String.is(formatString)) {\n let out = '';\n let i = 0;\n while (i < formatString.length) {\n const char = formatString.charAt(i);\n if (char === '%') {\n const nextIndex = i + 1;\n if (nextIndex < formatString.length) {\n const nextChar = formatString.charAt(i + 1);\n if (nextChar in escapes && args.length) {\n const value = args.shift();\n // This rule is for math.\n // eslint-disable-next-line no-unsafe-optional-chaining\n out += escapes[nextChar]?.(value);\n }\n else if (nextChar === '%') {\n out += '%';\n }\n else {\n out += `%${nextChar}`;\n }\n i += 2;\n }\n }\n else {\n out += char;\n i += 1;\n }\n }\n // If there are any args left after we exhaust the format string\n // then just stick those on the end.\n if (args.length) {\n if (out.length) {\n out += ' ';\n }\n out += args.map(tryStringify).join(' ');\n }\n return out;\n }\n return args.map(tryStringify).join(' ');\n}\n\nvar LogPriority;\n(function (LogPriority) {\n LogPriority[LogPriority[\"debug\"] = 0] = \"debug\";\n LogPriority[LogPriority[\"info\"] = 1] = \"info\";\n LogPriority[LogPriority[\"warn\"] = 2] = \"warn\";\n LogPriority[LogPriority[\"error\"] = 3] = \"error\";\n LogPriority[LogPriority[\"none\"] = 4] = \"none\";\n})(LogPriority || (LogPriority = {}));\nconst LEVEL_NAMES = ['debug', 'info', 'warn', 'error', 'none'];\n/**\n * A basic logger which handles filtering by level.\n *\n * With the default options it will write to `console.error`\n * and it will use the formatting provided by `console.error`.\n * If the destination is overwritten, then it will use an included\n * formatter similar to `util.format`.\n *\n * If a formatter is available, then that should be overridden\n * as well for performance.\n */\nclass BasicLogger {\n /**\n * This should only be used as a default fallback and not as a convenient\n * solution. In most cases you should construct a new instance with the\n * appropriate options for your specific needs.\n */\n static get() {\n return new BasicLogger({});\n }\n constructor(options) {\n this._logLevel = LogPriority[options.level ?? 'info'] ?? LogPriority.info;\n this._name = options.name ?? 'LaunchDarkly';\n this._formatter = options.formatter;\n if (typeof options.destination === 'object') {\n this._destinations = {\n [LogPriority.debug]: options.destination.debug,\n [LogPriority.info]: options.destination.info,\n [LogPriority.warn]: options.destination.warn,\n [LogPriority.error]: options.destination.error,\n };\n }\n else if (typeof options.destination === 'function') {\n const { destination } = options;\n this._destinations = {\n [LogPriority.debug]: destination,\n [LogPriority.info]: destination,\n [LogPriority.warn]: destination,\n [LogPriority.error]: destination,\n };\n }\n }\n _tryFormat(...args) {\n try {\n if (this._formatter) {\n // In case the provided formatter fails.\n return this._formatter?.(...args);\n }\n return format(...args);\n }\n catch {\n return format(...args);\n }\n }\n _tryWrite(destination, msg) {\n try {\n destination(msg);\n }\n catch {\n // eslint-disable-next-line no-console\n console.error(msg);\n }\n }\n _log(level, args) {\n if (level >= this._logLevel) {\n const prefix = `${LEVEL_NAMES[level]}: [${this._name}]`;\n try {\n const destination = this._destinations?.[level];\n if (destination) {\n this._tryWrite(destination, `${prefix} ${this._tryFormat(...args)}`);\n }\n else {\n // `console.error` has its own formatter.\n // So we don't need to do anything.\n // eslint-disable-next-line no-console\n console.error(...args);\n }\n }\n catch {\n // If all else fails do not break.\n // eslint-disable-next-line no-console\n console.error(...args);\n }\n }\n }\n error(...args) {\n this._log(LogPriority.error, args);\n }\n warn(...args) {\n this._log(LogPriority.warn, args);\n }\n info(...args) {\n this._log(LogPriority.info, args);\n }\n debug(...args) {\n this._log(LogPriority.debug, args);\n }\n}\n\nconst loggerRequirements = {\n error: TypeValidators.Function,\n warn: TypeValidators.Function,\n info: TypeValidators.Function,\n debug: TypeValidators.Function,\n};\n/**\n * The safeLogger logic exists because we allow the application to pass in a custom logger, but\n * there is no guarantee that the logger works correctly and if it ever throws exceptions there\n * could be serious consequences (e.g. an uncaught exception within an error event handler, due\n * to the SDK trying to log the error, can terminate the application). An exception could result\n * from faulty logic in the logger implementation, or it could be that this is not a logger at\n * all but some other kind of object; the former is handled by a catch block that logs an error\n * message to the SDK's default logger, and we can at least partly guard against the latter by\n * checking for the presence of required methods at configuration time.\n */\nclass SafeLogger {\n /**\n * Construct a safe logger with the specified logger.\n * @param logger The logger to use.\n * @param fallback A fallback logger to use in case an issue is encountered using\n * the provided logger.\n */\n constructor(logger, fallback) {\n Object.entries(loggerRequirements).forEach(([level, validator]) => {\n if (!validator.is(logger[level])) {\n throw new Error(`Provided logger instance must support logger.${level}(...) method`);\n // Note that the SDK normally does not throw exceptions to the application, but that rule\n // does not apply to LDClient.init() which will throw an exception if the parameters are so\n // invalid that we cannot proceed with creating the client. An invalid logger meets those\n // criteria since the SDK calls the logger during nearly all of its operations.\n }\n });\n this._logger = logger;\n this._fallback = fallback;\n }\n _log(level, args) {\n try {\n this._logger[level](...args);\n }\n catch {\n // If all else fails do not break.\n this._fallback[level](...args);\n }\n }\n error(...args) {\n this._log('error', args);\n }\n warn(...args) {\n this._log('warn', args);\n }\n info(...args) {\n this._log('info', args);\n }\n debug(...args) {\n this._log('debug', args);\n }\n}\n\nconst createSafeLogger = (logger) => {\n const basicLogger = new BasicLogger({\n level: 'info',\n // eslint-disable-next-line no-console\n destination: console.error,\n formatter: format,\n });\n return logger ? new SafeLogger(logger, basicLogger) : basicLogger;\n};\n\n/**\n * Messages for issues which can be encountered from processing the configuration options.\n */\nclass OptionMessages {\n static deprecated(oldName, newName) {\n return `\"${oldName}\" is deprecated, please use \"${newName}\"`;\n }\n static optionBelowMinimum(name, value, min) {\n return `Config option \"${name}\" had invalid value of ${value}, using minimum of ${min} instead`;\n }\n static unknownOption(name) {\n return `Ignoring unknown config option \"${name}\"`;\n }\n static wrongOptionType(name, expectedType, actualType) {\n return `Config option \"${name}\" should be of type ${expectedType}, got ${actualType}, using default value`;\n }\n static wrongOptionTypeBoolean(name, actualType) {\n return `Config option \"${name}\" should be a boolean, got ${actualType}, converting to boolean`;\n }\n static invalidTagValue(name) {\n return `Config option \"${name}\" must only contain letters, numbers, ., _ or -.`;\n }\n static tagValueTooLong(name) {\n return `Value of \"${name}\" was longer than 64 characters and was discarded.`;\n }\n static partialEndpoint(name) {\n return `You have set custom uris without specifying the ${name} URI; connections may not work properly`;\n }\n}\n\n/**\n * Expression to validate characters that are allowed in tag keys and values.\n */\nconst allowedTagCharacters = /^(\\w|\\.|-)+$/;\nconst regexValidator = TypeValidators.stringMatchingRegex(allowedTagCharacters);\nconst tagValidator = {\n is: (u, name) => {\n if (regexValidator.is(u)) {\n if (u.length > 64) {\n return { valid: false, message: OptionMessages.tagValueTooLong(name) };\n }\n return { valid: true };\n }\n return { valid: false, message: OptionMessages.invalidTagValue(name) };\n },\n};\n/**\n * Class for managing tags.\n */\nclass ApplicationTags {\n constructor(options) {\n const tags = {};\n const application = options?.application;\n const logger = options?.logger;\n if (application) {\n Object.entries(application).forEach(([key, value]) => {\n if (value !== null && value !== undefined) {\n const { valid, message } = tagValidator.is(value, `application.${key}`);\n if (!valid) {\n logger?.warn(message);\n }\n else if (key === 'versionName') {\n tags[`application-version-name`] = [value];\n }\n else {\n tags[`application-${key}`] = [value];\n }\n }\n });\n }\n const tagKeys = Object.keys(tags);\n if (tagKeys.length) {\n this.value = tagKeys\n .sort()\n .flatMap((key) => tags[key].sort().map((value) => `${key}/${value}`))\n .join(' ');\n }\n }\n}\n\n/**\n * The client context provides basic configuration and platform support which are required\n * when building SDK components.\n */\nclass ClientContext {\n constructor(sdkKey, configuration, platform) {\n this.platform = platform;\n this.basicConfiguration = {\n tags: configuration.tags,\n logger: configuration.logger,\n offline: configuration.offline,\n serviceEndpoints: configuration.serviceEndpoints,\n sdkKey,\n };\n }\n}\n\nfunction canonicalizeUri(uri) {\n return uri.replace(/\\/+$/, '');\n}\nfunction canonicalizePath(path) {\n return path.replace(/^\\/+/, '').replace(/\\?$/, '');\n}\n/**\n * Specifies the base service URIs used by SDK components.\n */\nclass ServiceEndpoints {\n constructor(streaming, polling, events = ServiceEndpoints.DEFAULT_EVENTS, analyticsEventPath = '/bulk', diagnosticEventPath = '/diagnostic', includeAuthorizationHeader = true, payloadFilterKey) {\n this.streaming = canonicalizeUri(streaming);\n this.polling = canonicalizeUri(polling);\n this.events = canonicalizeUri(events);\n this.analyticsEventPath = analyticsEventPath;\n this.diagnosticEventPath = diagnosticEventPath;\n this.includeAuthorizationHeader = includeAuthorizationHeader;\n this.payloadFilterKey = payloadFilterKey;\n }\n}\n// eslint-disable-next-line @typescript-eslint/naming-convention\nServiceEndpoints.DEFAULT_EVENTS = 'https://events.launchdarkly.com';\nfunction getWithParams(uri, parameters = []) {\n if (parameters.length === 0) {\n return uri;\n }\n const parts = parameters.map(({ key, value }) => `${key}=${value}`);\n return `${uri}?${parts.join('&')}`;\n}\n/**\n * Get the URI for the streaming endpoint.\n *\n * @param endpoints The service endpoints.\n * @param path The path to the resource, devoid of any query parameters or hrefs.\n * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.\n */\nfunction getStreamingUri(endpoints, path, parameters) {\n const canonicalizedPath = canonicalizePath(path);\n const combinedParameters = [...parameters];\n if (endpoints.payloadFilterKey) {\n combinedParameters.push({ key: 'filter', value: endpoints.payloadFilterKey });\n }\n return getWithParams(`${endpoints.streaming}/${canonicalizedPath}`, combinedParameters);\n}\n/**\n * Get the URI for the polling endpoint.\n *\n * @param endpoints The service endpoints.\n * @param path The path to the resource, devoid of any query parameters or hrefs.\n * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.\n */\nfunction getPollingUri(endpoints, path, parameters = []) {\n const canonicalizedPath = canonicalizePath(path);\n const combinedParameters = [...parameters];\n if (endpoints.payloadFilterKey) {\n combinedParameters.push({ key: 'filter', value: endpoints.payloadFilterKey });\n }\n return getWithParams(`${endpoints.polling}/${canonicalizedPath}`, combinedParameters);\n}\n/**\n * Get the URI for the events endpoint.\n *\n * @param endpoints The service endpoints.\n * @param path The path to the resource, devoid of any query parameters or hrefs.\n * @param parameters The query parameters. These query parameters must already have the appropriate encoding applied. This function WILL NOT apply it for you.\n */\nfunction getEventsUri(endpoints, path, parameters = []) {\n const canonicalizedPath = canonicalizePath(path);\n return getWithParams(`${endpoints.events}/${canonicalizedPath}`, parameters);\n}\n\n// These classes are of trivial complexity. If they become\n// more complex, then they could be independent files.\n/* eslint-disable max-classes-per-file */\nclass LDUnexpectedResponseError extends Error {\n constructor(message) {\n super(message);\n this.name = 'LaunchDarklyUnexpectedResponseError';\n }\n}\nclass LDClientError extends Error {\n constructor(message) {\n super(message);\n this.name = 'LaunchDarklyClientError';\n }\n}\nclass LDTimeoutError extends Error {\n constructor(message) {\n super(message);\n this.name = 'LaunchDarklyTimeoutError';\n }\n}\n/**\n * Check if the HTTP error is recoverable. This will return false if a request\n * made with any payload could not recover. If the reason for the failure\n * is payload specific, for instance a payload that is too large, then\n * it could recover with a different payload.\n */\nfunction isHttpRecoverable(status) {\n if (status >= 400 && status < 500) {\n return status === 400 || status === 408 || status === 429;\n }\n return true;\n}\n/**\n * Returns true if the status could recover for a different payload.\n *\n * When used with event processing this indicates that we should discard\n * the payload, but that a subsequent payload may succeed. Therefore we should\n * not stop event processing.\n */\nfunction isHttpLocallyRecoverable(status) {\n if (status === 413) {\n return true;\n }\n return isHttpRecoverable(status);\n}\n\n/**\n * Returns a promise which errors after t seconds.\n *\n * @param t Timeout in seconds.\n * @param taskName Name of task being timed for logging and error reporting.\n */\nfunction cancelableTimedPromise(t, taskName) {\n let timeout;\n let resolve;\n const promise = new Promise((_res, reject) => {\n resolve = _res;\n timeout = setTimeout(() => {\n const e = `${taskName} timed out after ${t} seconds.`;\n reject(new LDTimeoutError(e));\n }, t * 1000);\n });\n return {\n promise,\n cancel: () => {\n resolve();\n clearTimeout(timeout);\n },\n };\n}\n\nfunction clone(obj) {\n if (obj === undefined || obj === null) {\n return obj;\n }\n return JSON.parse(JSON.stringify(obj));\n}\n\n// eslint-disable-next-line import/prefer-default-export\nfunction secondsToMillis(sec) {\n return Math.trunc(sec * 1000);\n}\n\n/**\n * Wait before calling the same function. Useful for expensive calls.\n * Adapted from https://amitd.co/code/typescript/debounce.\n *\n * @return The debounced function.\n *\n * @example\n *\n * ```js\n * const debouncedFunction = debounce(e => {\n * console.log(e);\n * }, 5000);\n *\n * // Console logs 'Hello world again ' after 5 seconds\n * debouncedFunction('Hello world');\n * debouncedFunction('Hello world again');\n * ```\n * @param fn The function to be debounced.\n * @param delayMs Defaults to 5 seconds.\n */\nconst debounce = (fn, delayMs = 5000) => {\n let timer;\n return (...args) => {\n clearTimeout(timer);\n timer = setTimeout(() => {\n fn(...args);\n }, delayMs);\n };\n};\n\nconst isEmptyObject = (obj) => JSON.stringify(obj) === '{}';\n\n/**\n * Strips all falsy and empty {} from a given object. Returns a new object with only truthy values.\n * Sourced from below but modified to include checks for empty object and ignoring keys.\n * https://www.w3resource.com/javascript-exercises/javascript-array-exercise-47.php\n *\n * @param obj\n * @param ignoreKeys\n */\nconst deepCompact = (obj, ignoreKeys) => {\n if (!obj) {\n return obj;\n }\n return Object.entries(obj).reduce((acc, [key, value]) => {\n if (Boolean(value) && !isEmptyObject(value) && !ignoreKeys?.includes(key)) {\n acc[key] = typeof value === 'object' ? deepCompact(value, ignoreKeys) : value;\n }\n return acc;\n }, {});\n};\n\n/* eslint-disable */\n// Ripped from https://github.com/epoberezkin/fast-deep-fastDeepEqual\n// {{? it.es6 }}\n// var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';\n// {{?}}\nfunction fastDeepEqual(a, b) {\n if (a === b)\n return true;\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor)\n return false;\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length)\n return false;\n for (i = length; i-- !== 0;)\n if (!fastDeepEqual(a[i], b[i]))\n return false;\n return true;\n }\n // {{? it.es6 }}\n if (a instanceof Map && b instanceof Map) {\n if (a.size !== b.size)\n return false;\n for (i of a.entries())\n if (!b.has(i[0]))\n return false;\n for (i of a.entries())\n if (!fastDeepEqual(i[1], b.get(i[0])))\n return false;\n return true;\n }\n if (a instanceof Set && b instanceof Set) {\n if (a.size !== b.size)\n return false;\n for (i of a.entries())\n if (!b.has(i[0]))\n return false;\n return true;\n }\n if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {\n // @ts-ignore\n length = a.length;\n // @ts-ignore\n if (length != b.length)\n return false;\n for (i = length; i-- !== 0;) {\n // @ts-ignore\n if (a[i] !== b[i])\n return false;\n }\n return true;\n }\n // {{?}}\n if (a.constructor === RegExp)\n return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf)\n return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString)\n return a.toString() === b.toString();\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length)\n return false;\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i]))\n return false;\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n // {{? it.react }}\n // if (key === '_owner' && a.$$typeof) {\n // // React-specific: avoid traversing React elements' _owner.\n // // _owner contains circular references\n // // and is not needed when comparing the actual elements (and not their owners)\n // continue;\n // }\n // {{?}}\n if (!fastDeepEqual(a[key], b[key]))\n return false;\n }\n return true;\n }\n // true if both NaN, false otherwise\n return a !== a && b !== b;\n}\n\nfunction defaultHeaders(sdkKey, info, tags, includeAuthorizationHeader = true, userAgentHeaderName = 'user-agent') {\n const { userAgentBase, version, wrapperName, wrapperVersion } = info.sdkData();\n const headers = {\n [userAgentHeaderName]: `${userAgentBase ?? 'NodeJSClient'}/${version}`,\n };\n // edge sdks sets this to false because they use the clientSideID\n // and they don't need the authorization header\n if (includeAuthorizationHeader) {\n headers.authorization = sdkKey;\n }\n if (wrapperName) {\n headers['x-launchdarkly-wrapper'] = wrapperVersion\n ? `${wrapperName}/${wrapperVersion}`\n : wrapperName;\n }\n if (tags?.value) {\n headers['x-launchdarkly-tags'] = tags.value;\n }\n return headers;\n}\nfunction httpErrorMessage(err, context, retryMessage) {\n let desc;\n if (err.status) {\n desc = `error ${err.status}${err.status === 401 ? ' (invalid SDK key)' : ''}`;\n }\n else {\n desc = `I/O error (${err.message || 'unknown error'})`;\n }\n const action = retryMessage ?? 'giving up permanently';\n return `Received ${desc} for ${context} - ${action}`;\n}\nfunction shouldRetry({ status }) {\n return status ? isHttpRecoverable(status) : true;\n}\n/**\n * In react-native use base64-js to polyfill btoa. This is safe\n * because the react-native repo uses it too. Set the global.btoa to the encode\n * function of base64-js.\n * https://github.com/beatgammit/base64-js\n * https://github.com/axios/axios/issues/2235#issuecomment-512204616\n *\n * Ripped from https://thewoods.blog/base64url/\n */\nconst base64UrlEncode = (s, encoding) => encoding.btoa(s).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n\nvar noop = () => { };\n\nconst sleep = async (delayMillis = 1000) => new Promise((resolve) => {\n setTimeout(resolve, delayMillis);\n});\n\n/**\n * Returns a promise which errors after t seconds.\n *\n * @param t Timeout in seconds.\n * @param taskName Name of task being timed for logging and error reporting.\n */\nconst timedPromise = (t, taskName) => new Promise((_res, reject) => {\n setTimeout(() => {\n const e = `${taskName} timed out after ${t} seconds.`;\n reject(new LDTimeoutError(e));\n }, t * 1000);\n});\n\nclass DiagnosticsManager {\n constructor(sdkKey, _platform, _diagnosticInitConfig) {\n this._platform = _platform;\n this._diagnosticInitConfig = _diagnosticInitConfig;\n this._streamInits = [];\n this._startTime = Date.now();\n this._dataSinceDate = this._startTime;\n this._id = {\n diagnosticId: _platform.crypto.randomUUID(),\n sdkKeySuffix: sdkKey.length > 6 ? sdkKey.substring(sdkKey.length - 6) : sdkKey,\n };\n }\n /**\n * Creates the initial event that is sent by the event processor when the SDK starts up. This will\n * not be repeated during the lifetime of the SDK client.\n */\n createInitEvent() {\n const sdkData = this._platform.info.sdkData();\n const platformData = this._platform.info.platformData();\n return {\n kind: 'diagnostic-init',\n id: this._id,\n creationDate: this._startTime,\n sdk: sdkData,\n configuration: this._diagnosticInitConfig,\n platform: {\n name: platformData.name,\n osArch: platformData.os?.arch,\n osName: platformData.os?.name,\n osVersion: platformData.os?.version,\n ...(platformData.additional || {}),\n },\n };\n }\n /**\n * Records a stream connection attempt (called by the stream processor).\n *\n * @param timestamp Time of the *beginning* of the connection attempt.\n * @param failed True if the connection failed, or we got a read timeout before receiving a \"put\".\n * @param durationMillis Elapsed time between starting timestamp and when we either gave up/lost\n * the connection or received a successful \"put\".\n */\n recordStreamInit(timestamp, failed, durationMillis) {\n const item = { timestamp, failed, durationMillis };\n this._streamInits.push(item);\n }\n /**\n * Creates a periodic event containing time-dependent stats, and resets the state of the manager\n * with regard to those stats.\n *\n * Note: the reason droppedEvents, deduplicatedUsers, and eventsInLastBatch are passed into this\n * function, instead of being properties of the DiagnosticsManager, is that the event processor is\n * the one who's calling this function and is also the one who's tracking those stats.\n */\n createStatsEventAndReset(droppedEvents, deduplicatedUsers, eventsInLastBatch) {\n const currentTime = Date.now();\n const evt = {\n kind: 'diagnostic',\n id: this._id,\n creationDate: currentTime,\n dataSinceDate: this._dataSinceDate,\n droppedEvents,\n deduplicatedUsers,\n eventsInLastBatch,\n streamInits: this._streamInits,\n };\n this._streamInits = [];\n this._dataSinceDate = currentTime;\n return evt;\n }\n}\n\n/**\n * Different kinds of error which may be encountered during evaluation.\n */\nvar ErrorKinds;\n(function (ErrorKinds) {\n ErrorKinds[\"MalformedFlag\"] = \"MALFORMED_FLAG\";\n ErrorKinds[\"UserNotSpecified\"] = \"USER_NOT_SPECIFIED\";\n ErrorKinds[\"FlagNotFound\"] = \"FLAG_NOT_FOUND\";\n ErrorKinds[\"ClientNotReady\"] = \"CLIENT_NOT_READY\";\n ErrorKinds[\"WrongType\"] = \"WRONG_TYPE\";\n})(ErrorKinds || (ErrorKinds = {}));\nvar ErrorKinds$1 = ErrorKinds;\n\n/**\n * Messages for issues which can be encountered processing client requests.\n */\nclass ClientMessages {\n static invalidMetricValue(badType) {\n return ('The track function was called with a non-numeric \"metricValue\"' +\n ` (${badType}), only numeric metric values are supported.`);\n }\n}\nClientMessages.MissingContextKeyNoEvent = 'Context was unspecified or had no key; event will not be sent';\n\nclass EventSender {\n constructor(clientContext, baseHeaders) {\n const { basicConfiguration, platform } = clientContext;\n const { serviceEndpoints: { analyticsEventPath, diagnosticEventPath }, } = basicConfiguration;\n const { crypto, requests } = platform;\n this._defaultHeaders = { ...baseHeaders };\n this._eventsUri = getEventsUri(basicConfiguration.serviceEndpoints, analyticsEventPath, []);\n this._diagnosticEventsUri = getEventsUri(basicConfiguration.serviceEndpoints, diagnosticEventPath, []);\n this._requests = requests;\n this._crypto = crypto;\n }\n async _tryPostingEvents(events, uri, payloadId, canRetry) {\n const tryRes = {\n status: LDDeliveryStatus.Succeeded,\n };\n const headers = {\n ...this._defaultHeaders,\n 'content-type': 'application/json',\n };\n if (payloadId) {\n headers['x-launchdarkly-payload-id'] = payloadId;\n headers['x-launchDarkly-event-schema'] = '4';\n }\n let error;\n try {\n const { status, headers: resHeaders } = await this._requests.fetch(uri, {\n headers,\n body: JSON.stringify(events),\n compressBodyIfPossible: true,\n method: 'POST',\n // When sending events from browser environments the request should be completed even\n // if the user is navigating away from the page.\n keepalive: true,\n });\n const serverDate = Date.parse(resHeaders.get('date') || '');\n if (serverDate) {\n tryRes.serverTime = serverDate;\n }\n if (status <= 204) {\n return tryRes;\n }\n error = new LDUnexpectedResponseError(httpErrorMessage({ status, message: 'some events were dropped' }, 'event posting'));\n if (!isHttpRecoverable(status)) {\n // If the HTTP request isn't recoverable. Meaning if we made the same request it\n // would not recover, then we check if a different request could recover.\n // If a different request could not recover, then we shutdown. If a different request could\n // recover, then we just don't retry this specific request.\n if (!isHttpLocallyRecoverable(status)) {\n tryRes.status = LDDeliveryStatus.FailedAndMustShutDown;\n }\n else {\n tryRes.status = LDDeliveryStatus.Failed;\n }\n tryRes.error = error;\n return tryRes;\n }\n }\n catch (err) {\n error = err;\n }\n // recoverable but not retrying\n if (error && !canRetry) {\n tryRes.status = LDDeliveryStatus.Failed;\n tryRes.error = error;\n return tryRes;\n }\n // wait 1 second before retrying\n await sleep();\n return this._tryPostingEvents(events, this._eventsUri, payloadId, false);\n }\n async sendEventData(type, data) {\n const payloadId = type === LDEventType.AnalyticsEvents ? this._crypto.randomUUID() : undefined;\n const uri = type === LDEventType.AnalyticsEvents ? this._eventsUri : this._diagnosticEventsUri;\n return this._tryPostingEvents(data, uri, payloadId, true);\n }\n}\n\nfunction isFeature(u) {\n return u.kind === 'feature';\n}\nfunction isIdentify(u) {\n return u.kind === 'identify';\n}\nfunction isMigration(u) {\n return u.kind === 'migration_op';\n}\n\n/**\n * @internal\n */\nclass SummaryCounter {\n constructor(count, key, value, defValue, version, variation) {\n this.count = count;\n this.key = key;\n this.value = value;\n this.version = version;\n this.variation = variation;\n this.default = defValue;\n }\n increment() {\n this.count += 1;\n }\n}\n\nfunction counterKey(event) {\n return `${event.key}:${event.variation !== null && event.variation !== undefined ? event.variation : ''}:${event.version !== null && event.version !== undefined ? event.version : ''}`;\n}\n/**\n * @internal\n */\nclass EventSummarizer {\n constructor(_singleContext = false, _contextFilter) {\n this._singleContext = _singleContext;\n this._contextFilter = _contextFilter;\n this._startDate = 0;\n this._endDate = 0;\n this._counters = {};\n this._contextKinds = {};\n }\n summarizeEvent(event) {\n if (isFeature(event) && !event.excludeFromSummaries) {\n if (!this._context) {\n this._context = event.context;\n }\n const countKey = counterKey(event);\n const counter = this._counters[countKey];\n let kinds = this._contextKinds[event.key];\n if (!kinds) {\n kinds = new Set();\n this._contextKinds[event.key] = kinds;\n }\n event.context.kinds.forEach((kind) => kinds.add(kind));\n if (counter) {\n counter.increment();\n }\n else {\n this._counters[countKey] = new SummaryCounter(1, event.key, event.value, event.default, event.version, event.variation);\n }\n if (this._startDate === 0 || event.creationDate < this._startDate) {\n this._startDate = event.creationDate;\n }\n if (event.creationDate > this._endDate) {\n this._endDate = event.creationDate;\n }\n }\n }\n getSummary() {\n const features = Object.values(this._counters).reduce((acc, counter) => {\n let flagSummary = acc[counter.key];\n if (!flagSummary) {\n flagSummary = {\n default: counter.default,\n counters: [],\n contextKinds: [...this._contextKinds[counter.key]],\n };\n acc[counter.key] = flagSummary;\n }\n const counterOut = {\n value: counter.value,\n count: counter.count,\n };\n if (counter.variation !== undefined && counter.variation !== null) {\n counterOut.variation = counter.variation;\n }\n if (counter.version !== undefined && counter.version !== null) {\n counterOut.version = counter.version;\n }\n else {\n counterOut.unknown = true;\n }\n flagSummary.counters.push(counterOut);\n return acc;\n }, {});\n const event = {\n startDate: this._startDate,\n endDate: this._endDate,\n features,\n kind: 'summary',\n context: this._context !== undefined && this._singleContext\n ? this._contextFilter?.filter(this._context)\n : undefined,\n };\n this._clearSummary();\n return event;\n }\n _clearSummary() {\n this._startDate = 0;\n this._endDate = 0;\n this._counters = {};\n this._contextKinds = {};\n }\n}\n\nclass LDInvalidSDKKeyError extends Error {\n constructor(message) {\n super(message);\n this.name = 'LaunchDarklyInvalidSDKKeyError';\n }\n}\n\nclass MultiEventSummarizer {\n constructor(_contextFilter, _logger) {\n this._contextFilter = _contextFilter;\n this._logger = _logger;\n this._summarizers = {};\n }\n summarizeEvent(event) {\n if (isFeature(event)) {\n const key = event.context.canonicalUnfilteredJson();\n if (!key) {\n if (event.context.valid) {\n // The context appeared valid, but it could not be hashed.\n // This is likely because of a cycle in the data.\n this._logger?.error('Unable to serialize context, likely the context contains a cycle.');\n }\n return;\n }\n let summarizer = this._summarizers[key];\n if (!summarizer) {\n this._summarizers[key] = new EventSummarizer(true, this._contextFilter);\n summarizer = this._summarizers[key];\n }\n summarizer.summarizeEvent(event);\n }\n }\n getSummaries() {\n const summarizersToFlush = this._summarizers;\n this._summarizers = {};\n return Object.values(summarizersToFlush).map((summarizer) => summarizer.getSummary());\n }\n}\n\n/**\n * The contents of this file are for event sampling. They are not used for\n * any purpose requiring cryptographic security.\n * */\nfunction shouldSample(ratio) {\n const truncated = Math.trunc(ratio);\n // A radio of 1 means 1 in 1. So that will always sample. No need\n // to draw a random number.\n if (truncated === 1) {\n return true;\n }\n if (truncated === 0) {\n return false;\n }\n // Math.random() * truncated) would return 0, 1, ... (ratio - 1).\n // Checking for any number in the range will have approximately a 1 in X\n // chance. So we check for 0 as it is part of any range.\n return Math.floor(Math.random() * truncated) === 0;\n}\n\nfunction isMultiEventSummarizer(summarizer) {\n return summarizer.getSummaries !== undefined;\n}\nclass EventProcessor {\n constructor(_config, clientContext, baseHeaders, _contextDeduplicator, _diagnosticsManager, start = true, summariesPerContext = false) {\n this._config = _config;\n this._contextDeduplicator = _contextDeduplicator;\n this._diagnosticsManager = _diagnosticsManager;\n this._queue = [];\n this._lastKnownPastTime = 0;\n this._droppedEvents = 0;\n this._deduplicatedUsers = 0;\n this._exceededCapacity = false;\n this._eventsInLastBatch = 0;\n this._shutdown = false;\n this._flushUsersTimer = null;\n this._capacity = _config.eventsCapacity;\n this._logger = clientContext.basicConfiguration.logger;\n this._eventSender = new EventSender(clientContext, baseHeaders);\n this._contextFilter = new ContextFilter(_config.allAttributesPrivate, _config.privateAttributes.map((ref) => new AttributeReference(ref)));\n if (summariesPerContext) {\n this._summarizer = new MultiEventSummarizer(this._contextFilter, this._logger);\n }\n else {\n this._summarizer = new EventSummarizer();\n }\n if (start) {\n this.start();\n }\n }\n start() {\n if (this._contextDeduplicator?.flushInterval !== undefined) {\n this._flushUsersTimer = setInterval(() => {\n this._contextDeduplicator?.flush();\n }, this._contextDeduplicator.flushInterval * 1000);\n }\n this._flushTimer = setInterval(async () => {\n try {\n await this.flush();\n }\n catch (e) {\n // Log errors and swallow them\n this._logger?.debug(`Flush failed: ${e}`);\n }\n }, this._config.flushInterval * 1000);\n if (this._diagnosticsManager) {\n const initEvent = this._diagnosticsManager.createInitEvent();\n this._postDiagnosticEvent(initEvent);\n this._diagnosticsTimer = setInterval(() => {\n const statsEvent = this._diagnosticsManager.createStatsEventAndReset(this._droppedEvents, this._deduplicatedUsers, this._eventsInLastBatch);\n this._droppedEvents = 0;\n this._deduplicatedUsers = 0;\n this._postDiagnosticEvent(statsEvent);\n }, this._config.diagnosticRecordingInterval * 1000);\n }\n this._logger?.debug('Started EventProcessor.');\n }\n _postDiagnosticEvent(event) {\n this._eventSender.sendEventData(LDEventType.DiagnosticEvent, event);\n }\n close() {\n clearInterval(this._flushTimer);\n if (this._flushUsersTimer) {\n clearInterval(this._flushUsersTimer);\n }\n if (this._diagnosticsTimer) {\n clearInterval(this._diagnosticsTimer);\n }\n }\n async flush() {\n if (this._shutdown) {\n throw new LDInvalidSDKKeyError('Events cannot be posted because a permanent error has been encountered. ' +\n 'This is most likely an invalid SDK key. The specific error information ' +\n 'is logged independently.');\n }\n const eventsToFlush = this._queue;\n this._queue = [];\n if (isMultiEventSummarizer(this._summarizer)) {\n const summaries = this._summarizer.getSummaries();\n summaries.forEach((summary) => {\n if (Object.keys(summary.features).length) {\n eventsToFlush.push(summary);\n }\n });\n }\n else {\n const summary = this._summarizer.getSummary();\n if (Object.keys(summary.features).length) {\n eventsToFlush.push(summary);\n }\n }\n if (!eventsToFlush.length) {\n return;\n }\n this._eventsInLastBatch = eventsToFlush.length;\n this._logger?.debug('Flushing %d events', eventsToFlush.length);\n await this._tryPostingEvents(eventsToFlush);\n }\n sendEvent(inputEvent) {\n if (this._shutdown) {\n return;\n }\n if (isMigration(inputEvent)) {\n // These conditions are not combined, because we always want to stop\n // processing at this point for a migration event. It cannot generate\n // an index event or debug event.\n if (shouldSample(inputEvent.samplingRatio)) {\n const migrationEvent = {\n ...inputEvent,\n context: inputEvent.context ? this._contextFilter.filter(inputEvent.context) : undefined,\n };\n if (migrationEvent.samplingRatio === 1) {\n delete migrationEvent.samplingRatio;\n }\n this._enqueue(migrationEvent);\n }\n return;\n }\n this._summarizer.summarizeEvent(inputEvent);\n const isFeatureEvent = isFeature(inputEvent);\n const addFullEvent = (isFeatureEvent && inputEvent.trackEvents) || !isFeatureEvent;\n const addDebugEvent = this._shouldDebugEvent(inputEvent);\n const isIdentifyEvent = isIdentify(inputEvent);\n const shouldNotDeduplicate = this._contextDeduplicator?.processContext(inputEvent.context);\n // If there is no cache, then it will never be in the cache.\n if (!shouldNotDeduplicate) {\n if (!isIdentifyEvent) {\n this._deduplicatedUsers += 1;\n }\n }\n const addIndexEvent = shouldNotDeduplicate && !isIdentifyEvent;\n if (addIndexEvent) {\n this._enqueue(this._makeOutputEvent({\n kind: 'index',\n creationDate: inputEvent.creationDate,\n context: inputEvent.context,\n samplingRatio: 1,\n }, false));\n }\n if (addFullEvent && shouldSample(inputEvent.samplingRatio)) {\n this._enqueue(this._makeOutputEvent(inputEvent, false));\n }\n if (addDebugEvent && shouldSample(inputEvent.samplingRatio)) {\n this._enqueue(this._makeOutputEvent(inputEvent, true));\n }\n }\n _makeOutputEvent(event, debug) {\n switch (event.kind) {\n case 'feature': {\n const out = {\n kind: debug ? 'debug' : 'feature',\n creationDate: event.creationDate,\n context: this._contextFilter.filter(event.context, !debug),\n key: event.key,\n value: event.value,\n default: event.default,\n };\n if (event.samplingRatio !== 1) {\n out.samplingRatio = event.samplingRatio;\n }\n if (event.prereqOf) {\n out.prereqOf = event.prereqOf;\n }\n if (event.variation !== undefined) {\n out.variation = event.variation;\n }\n if (event.version !== undefined) {\n out.version = event.version;\n }\n if (event.reason) {\n out.reason = event.reason;\n }\n return out;\n }\n case 'index': // Intentional fallthrough.\n case 'identify': {\n const out = {\n kind: event.kind,\n creationDate: event.creationDate,\n context: this._contextFilter.filter(event.context),\n };\n if (event.samplingRatio !== 1) {\n out.samplingRatio = event.samplingRatio;\n }\n return out;\n }\n case 'custom': {\n const out = {\n kind: 'custom',\n creationDate: event.creationDate,\n key: event.key,\n context: this._contextFilter.filter(event.context),\n };\n if (event.samplingRatio !== 1) {\n out.samplingRatio = event.samplingRatio;\n }\n if (event.data !== undefined) {\n out.data = event.data;\n }\n if (event.metricValue !== undefined) {\n out.metricValue = event.metricValue;\n }\n if (event.url !== undefined) {\n out.url = event.url;\n }\n return out;\n }\n case 'click': {\n const out = {\n kind: 'click',\n creationDate: event.creationDate,\n contextKeys: event.context.kindsAndKeys,\n key: event.key,\n url: event.url,\n selector: event.selector,\n };\n return out;\n }\n case 'pageview': {\n const out = {\n kind: 'pageview',\n creationDate: event.creationDate,\n contextKeys: event.context.kindsAndKeys,\n key: event.key,\n url: event.url,\n };\n return out;\n }\n default:\n // This would happen during the addition of a new event type to the SDK.\n return event;\n }\n }\n _enqueue(event) {\n if (this._queue.length < this._capacity) {\n this._queue.push(event);\n this._exceededCapacity = false;\n }\n else {\n if (!this._exceededCapacity) {\n this._exceededCapacity = true;\n this._logger?.warn('Exceeded event queue capacity. Increase capacity to avoid dropping events.');\n }\n this._droppedEvents += 1;\n }\n }\n _shouldDebugEvent(event) {\n return (isFeature(event) &&\n event.debugEventsUntilDate &&\n event.debugEventsUntilDate > this._lastKnownPastTime &&\n event.debugEventsUntilDate > Date.now());\n }\n async _tryPostingEvents(events) {\n const res = await this._eventSender.sendEventData(LDEventType.AnalyticsEvents, events);\n if (res.status === LDDeliveryStatus.FailedAndMustShutDown) {\n this._shutdown = true;\n }\n if (res.serverTime) {\n this._lastKnownPastTime = res.serverTime;\n }\n if (res.error) {\n throw res.error;\n }\n }\n}\n\nclass InputCustomEvent {\n constructor(context, key, data, metricValue, \n // Currently custom events are not sampled, but this is here to make the handling\n // code more uniform.\n samplingRatio = 1, \n // Browser SDKs can include a URL for custom events.\n url) {\n this.context = context;\n this.key = key;\n this.data = data;\n this.metricValue = metricValue;\n this.samplingRatio = samplingRatio;\n this.url = url;\n this.kind = 'custom';\n this.creationDate = Date.now();\n this.context = context;\n }\n}\n\nclass InputEvalEvent {\n constructor(withReasons, context, key, value, defValue, // default is a reserved keyword in this context.\n version, variation, trackEvents, prereqOf, reason, debugEventsUntilDate, excludeFromSummaries, samplingRatio = 1) {\n this.withReasons = withReasons;\n this.context = context;\n this.key = key;\n this.samplingRatio = samplingRatio;\n this.kind = 'feature';\n this.creationDate = Date.now();\n this.value = value;\n this.default = defValue;\n if (version !== undefined) {\n this.version = version;\n }\n if (variation !== undefined) {\n this.variation = variation;\n }\n if (trackEvents !== undefined) {\n this.trackEvents = trackEvents;\n }\n if (prereqOf !== undefined) {\n this.prereqOf = prereqOf;\n }\n if (reason !== undefined) {\n this.reason = reason;\n }\n if (debugEventsUntilDate !== undefined) {\n this.debugEventsUntilDate = debugEventsUntilDate;\n }\n if (excludeFromSummaries !== undefined) {\n this.excludeFromSummaries = excludeFromSummaries;\n }\n }\n}\n\nclass InputIdentifyEvent {\n constructor(context, samplingRatio = 1) {\n this.context = context;\n this.samplingRatio = samplingRatio;\n this.kind = 'identify';\n this.creationDate = Date.now();\n }\n}\n\nclass NullEventProcessor {\n close() { }\n async flush() {\n // empty comment to keep ts and eslint happy\n }\n sendEvent() { }\n}\n\nclass EventFactoryBase {\n constructor(_withReasons) {\n this._withReasons = _withReasons;\n }\n evalEvent(e) {\n return new InputEvalEvent(this._withReasons, e.context, e.flagKey, e.value, e.defaultVal, e.version, \n // Exclude null as a possibility.\n e.variation ?? undefined, e.trackEvents || e.addExperimentData, e.prereqOfFlagKey, this._withReasons || e.addExperimentData ? e.reason : undefined, e.debugEventsUntilDate, e.excludeFromSummaries, e.samplingRatio);\n }\n unknownFlagEvent(key, defVal, context) {\n return new InputEvalEvent(this._withReasons, context, key, defVal, defVal, \n // This isn't ideal, but the purpose of the factory is to at least\n // handle this situation.\n undefined, // version\n undefined, // variation index\n undefined, // track events\n undefined, // prereqOf\n undefined, // reason\n undefined, // debugEventsUntilDate\n undefined, // exclude from summaries\n undefined);\n }\n /* eslint-disable-next-line class-methods-use-this */\n identifyEvent(context) {\n // Currently sampling for identify events is always 1.\n return new InputIdentifyEvent(context, 1);\n }\n /* eslint-disable-next-line class-methods-use-this */\n customEvent(key, context, data, metricValue, samplingRatio = 1) {\n return new InputCustomEvent(context, key, data ?? undefined, metricValue ?? undefined, samplingRatio);\n }\n}\n\nconst PAYLOAD_ID = 'FDv1Fallback';\nfunction fdv1PayloadAdaptor(processor) {\n return {\n _processor: processor,\n _selector: '',\n useSelector(selector) {\n this._selector = selector;\n return this;\n },\n processFullTransfer(data) {\n const events = [\n {\n event: 'server-intent',\n data: {\n payloads: [\n {\n id: PAYLOAD_ID,\n target: 1,\n intentCode: 'xfer-full',\n reason: 'payload-missing',\n },\n ],\n },\n },\n ];\n Object.entries(data?.flags || []).forEach(([key, flag]) => {\n events.push({\n event: 'put-object',\n data: {\n kind: 'flag',\n key,\n version: flag.version || 1,\n object: flag,\n },\n });\n });\n Object.entries(data?.segments || []).forEach(([key, segment]) => {\n events.push({\n event: 'put-object',\n data: {\n kind: 'segment',\n key,\n version: segment.version || 1,\n object: segment,\n },\n });\n });\n events.push({\n event: 'payload-transferred',\n data: {\n // IMPORTANT: the selector MUST be empty or \"live\" data synchronizers\n // will not work as it would try to resume from a bogus state.\n state: this._selector,\n version: 1,\n id: PAYLOAD_ID,\n },\n });\n this._processor.processEvents(events);\n },\n };\n}\n\n/**\n * A FDv2 PayloadProcessor can be used to parse payloads from a stream of FDv2 events. It will send payloads\n * to the PayloadListeners as the payloads are received. Invalid series of events may be dropped silently,\n * but the payload processor will continue to operate.\n */\nclass PayloadProcessor {\n /**\n * Creates a PayloadProcessor\n *\n * @param _objProcessors defines object processors for each object kind.\n * @param _errorHandler that will be called with parsing errors as they are encountered\n * @param _logger for logging\n */\n constructor(_objProcessors, _errorHandler, _logger) {\n this._objProcessors = _objProcessors;\n this._errorHandler = _errorHandler;\n this._logger = _logger;\n this._listeners = [];\n this._tempId = undefined;\n this._tempBasis = false;\n this._tempUpdates = [];\n this._processServerIntent = (data) => {\n // clear state in prep for handling data\n this._resetAll();\n // if there's no payloads, return\n if (!data.payloads.length) {\n return;\n }\n // at the time of writing this, it was agreed upon that SDKs could assume exactly 1 element in this list. In the future, a negotiation of protocol version will be required to remove this assumption.\n const payload = data.payloads[0];\n switch (payload?.intentCode) {\n case 'xfer-full':\n this._tempBasis = true;\n break;\n case 'xfer-changes':\n this._tempBasis = false;\n break;\n case 'none':\n this._tempBasis = false;\n this._processIntentNone(payload);\n break;\n default:\n // unrecognized intent code, return\n this._logger?.warn(`Unable to process intent code '${payload?.intentCode}'.`);\n return;\n }\n this._tempId = payload?.id;\n };\n this._processPutObject = (data) => {\n // if the following properties haven't been provided by now, we should ignore the event\n if (!this._tempId || // server intent hasn't been received yet.\n !data.kind ||\n !data.key ||\n !data.version ||\n !data.object) {\n return;\n }\n const obj = this._processObj(data.kind, data.object);\n if (!obj) {\n this._logger?.warn(`Unable to process object for kind: '${data.kind}'`);\n // ignore unrecognized kinds\n return;\n }\n this._tempUpdates.push({\n kind: data.kind,\n key: data.key,\n version: data.version,\n object: obj,\n // intentionally omit deleted for this put\n });\n };\n this._processDeleteObject = (data) => {\n // if the following properties haven't been provided by now, we should ignore the event\n if (!this._tempId || !data.kind || !data.key || !data.version) {\n return;\n }\n this._tempUpdates.push({\n kind: data.kind,\n key: data.key,\n version: data.version,\n // intentionally omit object for this delete\n deleted: true,\n });\n };\n this._processIntentNone = (intent) => {\n // if the following properties aren't present ignore the event\n if (!intent.id || !intent.target) {\n return;\n }\n const payload = {\n id: intent.id,\n version: intent.target,\n basis: false,\n updates: [], // payload with no updates to hide the intent none concept from the consumer\n // note: state is absent here as that only appears in payload transferred events\n };\n this._listeners.forEach((it) => it(payload));\n this._resetAfterEmission();\n };\n this._processPayloadTransferred = (data) => {\n // if the following properties haven't been provided by now, we should reset\n if (\n // server intent hasn't been received yet.\n !this._tempId ||\n // selector can be an empty string if we are using a file data initilizer\n data.state === null ||\n data.state === undefined ||\n !data.version) {\n this._resetAll(); // a reset is best defensive action since payload transferred terminates a payload\n return;\n }\n const payload = {\n id: this._tempId,\n version: data.version,\n state: data.state,\n basis: this._tempBasis,\n updates: this._tempUpdates,\n };\n this._listeners.forEach((it) => it(payload));\n this._resetAfterEmission();\n };\n this._processGoodbye = (data) => {\n this._logger?.info(`Goodbye was received from the LaunchDarkly connection with reason: ${data.reason}.`);\n this._resetAll();\n };\n this._processError = (data) => {\n this._logger?.info(`An issue was encountered receiving updates for payload ${this._tempId} with reason: ${data.reason}.`);\n this._resetAfterError();\n };\n }\n addPayloadListener(listener) {\n this._listeners.push(listener);\n }\n removePayloadListener(listener) {\n const index = this._listeners.indexOf(listener, 0);\n if (index > -1) {\n this._listeners.splice(index, 1);\n }\n }\n /**\n * Gives the {@link PayloadProcessor} a series of events that it will statefully, incrementally process.\n * This may lead to listeners being invoked as necessary.\n * @param events to be processed (can be a single element)\n */\n processEvents(events) {\n events.forEach((event) => {\n switch (event.event) {\n case 'server-intent': {\n this._processServerIntent(event.data);\n break;\n }\n case 'put-object': {\n this._processPutObject(event.data);\n break;\n }\n case 'delete-object': {\n this._processDeleteObject(event.data);\n break;\n }\n case 'payload-transferred': {\n this._processPayloadTransferred(event.data);\n break;\n }\n case 'goodbye': {\n this._processGoodbye(event.data);\n break;\n }\n case 'error': {\n this._processError(event.data);\n break;\n }\n }\n });\n }\n _processObj(kind, jsonObj) {\n return this._objProcessors[kind]?.(jsonObj);\n }\n _resetAfterEmission() {\n this._tempBasis = false;\n this._tempUpdates = [];\n }\n _resetAfterError() {\n this._tempUpdates = [];\n }\n _resetAll() {\n this._tempId = undefined;\n this._tempBasis = false;\n this._tempUpdates = [];\n }\n}\n\n/**\n * A FDv2 PayloadStreamReader can be used to parse payloads from a stream of FDv2 events. See {@link PayloadProcessor}\n * for more details.\n */\nclass PayloadStreamReader {\n /**\n * Creates a PayloadStreamReader\n *\n * @param eventStream event stream of FDv2 events\n * @param _objProcessors defines object processors for each object kind.\n * @param _errorHandler that will be called with parsing errors as they are encountered\n * @param _logger for logging\n */\n constructor(eventStream, _objProcessors, _errorHandler, _logger) {\n this._errorHandler = _errorHandler;\n this._logger = _logger;\n this._attachHandler(eventStream, 'server-intent');\n this._attachHandler(eventStream, 'put-object');\n this._attachHandler(eventStream, 'delete-object');\n this._attachHandler(eventStream, 'payload-transferred');\n this._attachHandler(eventStream, 'goodbye');\n this._attachHandler(eventStream, 'error');\n this._payloadProcessor = new PayloadProcessor(_objProcessors, _errorHandler, _logger);\n }\n addPayloadListener(listener) {\n this._payloadProcessor.addPayloadListener(listener);\n }\n removePayloadListener(listener) {\n this._payloadProcessor.removePayloadListener(listener);\n }\n _attachHandler(stream, eventName) {\n stream.addEventListener(eventName, async (event) => {\n if (event?.data) {\n this._logger?.debug(`Received ${eventName} event. Data is ${event.data}`);\n try {\n this._payloadProcessor.processEvents([\n { event: eventName, data: JSON.parse(event.data) },\n ]);\n }\n catch {\n this._logger?.error(`Stream received data that was unable to be processed in \"${eventName}\" message`);\n this._logger?.debug(`Data follows: ${event.data}`);\n this._errorHandler?.(exports.DataSourceErrorKind.InvalidData, 'Malformed data in EventStream.');\n }\n }\n else {\n this._errorHandler?.(exports.DataSourceErrorKind.Unknown, 'Event from EventStream missing data.');\n }\n });\n }\n}\n\n/**\n * Creates an InitMetadata object from initialization headers.\n *\n * @param initHeaders Initialization headers received when establishing\n * a streaming or polling connection to LD.\n * @returns InitMetadata object, or undefined if initHeaders is undefined\n * or missing the required header values.\n */\nfunction initMetadataFromHeaders(initHeaders) {\n if (initHeaders) {\n const envIdKey = Object.keys(initHeaders).find((key) => key.toLowerCase() === 'x-ld-envid');\n if (envIdKey) {\n return { environmentId: initHeaders[envIdKey] };\n }\n }\n return undefined;\n}\n\nconst UNKNOWN_PLUGIN_NAME = 'unknown plugin';\nfunction safeGetName(logger, plugin) {\n try {\n return plugin.getMetadata().name || UNKNOWN_PLUGIN_NAME;\n }\n catch {\n logger.error(`Exception thrown getting metadata for plugin. Unable to get plugin name.`);\n return UNKNOWN_PLUGIN_NAME;\n }\n}\n\nfunction safeGetHooks(logger, environmentMetadata, plugins) {\n const hooks = [];\n plugins.forEach((plugin) => {\n try {\n const pluginHooks = plugin.getHooks?.(environmentMetadata);\n if (pluginHooks === undefined) {\n logger.error(`Plugin ${safeGetName(logger, plugin)} returned undefined from getHooks.`);\n }\n else if (pluginHooks && pluginHooks.length > 0) {\n hooks.push(...pluginHooks);\n }\n }\n catch (error) {\n logger.error(`Exception thrown getting hooks for plugin ${safeGetName(logger, plugin)}. Unable to get hooks.`);\n }\n });\n return hooks;\n}\n\nfunction safeRegisterPlugins(logger, environmentMetadata, client, plugins) {\n plugins.forEach((plugin) => {\n try {\n plugin.register(client, environmentMetadata);\n }\n catch (error) {\n logger.error(`Exception thrown registering plugin ${safeGetName(logger, plugin)}.`);\n }\n });\n}\n\nvar index = /*#__PURE__*/Object.freeze({\n __proto__: null,\n ClientMessages: ClientMessages,\n DiagnosticsManager: DiagnosticsManager,\n ErrorKinds: ErrorKinds$1,\n EventFactoryBase: EventFactoryBase,\n EventProcessor: EventProcessor,\n FDv1PayloadAdaptor: fdv1PayloadAdaptor,\n InputCustomEvent: InputCustomEvent,\n InputEvalEvent: InputEvalEvent,\n InputIdentifyEvent: InputIdentifyEvent,\n NullEventProcessor: NullEventProcessor,\n PayloadProcessor: PayloadProcessor,\n PayloadStreamReader: PayloadStreamReader,\n canonicalize: canonicalize,\n initMetadataFromHeaders: initMetadataFromHeaders,\n isLegacyUser: isLegacyUser,\n isMultiKind: isMultiKind,\n isSingleKind: isSingleKind,\n safeGetHooks: safeGetHooks,\n safeGetName: safeGetName,\n safeRegisterPlugins: safeRegisterPlugins,\n shouldSample: shouldSample\n});\n\nexports.ApplicationTags = ApplicationTags;\nexports.AttributeReference = AttributeReference;\nexports.BasicLogger = BasicLogger;\nexports.ClientContext = ClientContext;\nexports.CompositeDataSource = CompositeDataSource;\nexports.Context = Context;\nexports.ContextFilter = ContextFilter;\nexports.DateValidator = DateValidator;\nexports.DefaultBackoff = DefaultBackoff;\nexports.FactoryOrInstance = FactoryOrInstance;\nexports.Function = Function;\nexports.KindValidator = KindValidator;\nexports.LDClientError = LDClientError;\nexports.LDFileDataSourceError = LDFileDataSourceError;\nexports.LDFlagDeliveryFallbackError = LDFlagDeliveryFallbackError;\nexports.LDPollingError = LDPollingError;\nexports.LDStreamingError = LDStreamingError;\nexports.LDTimeoutError = LDTimeoutError;\nexports.LDUnexpectedResponseError = LDUnexpectedResponseError;\nexports.NullableBoolean = NullableBoolean;\nexports.NumberWithMinimum = NumberWithMinimum;\nexports.OptionMessages = OptionMessages;\nexports.SafeLogger = SafeLogger;\nexports.ServiceEndpoints = ServiceEndpoints;\nexports.StringMatchingRegex = StringMatchingRegex;\nexports.Type = Type;\nexports.TypeArray = TypeArray;\nexports.TypeValidators = TypeValidators;\nexports.base64UrlEncode = base64UrlEncode;\nexports.cancelableTimedPromise = cancelableTimedPromise;\nexports.clone = clone;\nexports.createSafeLogger = createSafeLogger;\nexports.debounce = debounce;\nexports.deepCompact = deepCompact;\nexports.defaultHeaders = defaultHeaders;\nexports.fastDeepEqual = fastDeepEqual;\nexports.getEventsUri = getEventsUri;\nexports.getPollingUri = getPollingUri;\nexports.getStreamingUri = getStreamingUri;\nexports.httpErrorMessage = httpErrorMessage;\nexports.internal = index;\nexports.isHttpLocallyRecoverable = isHttpLocallyRecoverable;\nexports.isHttpRecoverable = isHttpRecoverable;\nexports.noop = noop;\nexports.secondsToMillis = secondsToMillis;\nexports.shouldRetry = shouldRetry;\nexports.sleep = sleep;\nexports.subsystem = index$1;\nexports.timedPromise = timedPromise;\n//# sourceMappingURL=index.cjs.map\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDFlagsStateOptions.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDFlagsState.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.IsMigrationStage = exports.LDMigrationStage = void 0;\n/**\n * Stage denotes one of six possible stages a technology migration could be a\n * part of, progressing through the following order.\n *\n * Off -> DualWrite -> Shadow -> Live -> RampDown -> Complete\n */\nvar LDMigrationStage;\n(function (LDMigrationStage) {\n /**\n * Off - migration hasn't started, \"old\" is authoritative for reads and writes\n */\n LDMigrationStage[\"Off\"] = \"off\";\n /**\n * DualWrite - write to both \"old\" and \"new\", \"old\" is authoritative for reads\n */\n LDMigrationStage[\"DualWrite\"] = \"dualwrite\";\n /**\n * Shadow - both \"new\" and \"old\" versions run with a preference for \"old\"\n */\n LDMigrationStage[\"Shadow\"] = \"shadow\";\n /**\n * Live - both \"new\" and \"old\" versions run with a preference for \"new\"\n */\n LDMigrationStage[\"Live\"] = \"live\";\n /**\n * RampDown - only read from \"new\", write to \"old\" and \"new\"\n */\n LDMigrationStage[\"RampDown\"] = \"rampdown\";\n /**\n * Complete - migration is done\n */\n LDMigrationStage[\"Complete\"] = \"complete\";\n})(LDMigrationStage || (exports.LDMigrationStage = LDMigrationStage = {}));\n/**\n * Check if the given string is a migration stage.\n * @param value The string to check.\n * @returns True if the string is a migration stage.\n */\nfunction IsMigrationStage(value) {\n return Object.values(LDMigrationStage).includes(value);\n}\nexports.IsMigrationStage = IsMigrationStage;\n//# sourceMappingURL=LDMigrationStage.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDMigrationOpEvent.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LDConsistencyCheck = void 0;\n/**\n * Used for reporting the state of a consistency check.\n */\nvar LDConsistencyCheck;\n(function (LDConsistencyCheck) {\n LDConsistencyCheck[LDConsistencyCheck[\"Inconsistent\"] = 0] = \"Inconsistent\";\n LDConsistencyCheck[LDConsistencyCheck[\"Consistent\"] = 1] = \"Consistent\";\n LDConsistencyCheck[LDConsistencyCheck[\"NotChecked\"] = 2] = \"NotChecked\";\n})(LDConsistencyCheck || (exports.LDConsistencyCheck = LDConsistencyCheck = {}));\n//# sourceMappingURL=LDMigrationVariation.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./LDFlagsStateOptions\"), exports);\n__exportStar(require(\"./LDFlagsState\"), exports);\n__exportStar(require(\"./LDMigrationStage\"), exports);\n__exportStar(require(\"./LDMigrationOpEvent\"), exports);\n__exportStar(require(\"./LDMigrationVariation\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDBigSegmentsOptions.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDOptions.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDProxyOptions.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDTLSOptions.js.map","\"use strict\";\n/* eslint-disable max-classes-per-file */\n// Disabling max classes per file as these are tag classes without\n// logic implementation.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.LDConcurrentExecution = exports.LDSerialExecution = exports.LDExecution = exports.LDExecutionOrdering = void 0;\n/**\n * When execution is sequential this enum is used to control if execution\n * should be in a fixed or random order.\n */\nvar LDExecutionOrdering;\n(function (LDExecutionOrdering) {\n LDExecutionOrdering[LDExecutionOrdering[\"Fixed\"] = 0] = \"Fixed\";\n LDExecutionOrdering[LDExecutionOrdering[\"Random\"] = 1] = \"Random\";\n})(LDExecutionOrdering || (exports.LDExecutionOrdering = LDExecutionOrdering = {}));\n/**\n * Tag used to determine if execution should be serial or concurrent.\n * Callers should not need to use this directly.\n */\nvar LDExecution;\n(function (LDExecution) {\n /**\n * Execution will be serial. One read method will be executed fully before\n * the other read method.\n */\n LDExecution[LDExecution[\"Serial\"] = 0] = \"Serial\";\n /**\n * Execution will be concurrent. The execution of the read methods will be\n * started and then resolved concurrently.\n */\n LDExecution[LDExecution[\"Concurrent\"] = 1] = \"Concurrent\";\n})(LDExecution || (exports.LDExecution = LDExecution = {}));\n/**\n * Configuration class for configuring serial execution of a migration.\n */\nclass LDSerialExecution {\n constructor(ordering) {\n this.ordering = ordering;\n this.type = LDExecution.Serial;\n }\n}\nexports.LDSerialExecution = LDSerialExecution;\n/**\n * Configuration class for configuring concurrent execution of a migration.\n */\nclass LDConcurrentExecution {\n constructor() {\n this.type = LDExecution.Concurrent;\n }\n}\nexports.LDConcurrentExecution = LDConcurrentExecution;\n//# sourceMappingURL=LDMigrationOptions.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isCustomOptions = exports.isPollingOnlyOptions = exports.isStreamingOnlyOptions = exports.isStandardOptions = void 0;\nfunction isStandardOptions(u) {\n return u.dataSourceOptionsType === 'standard';\n}\nexports.isStandardOptions = isStandardOptions;\nfunction isStreamingOnlyOptions(u) {\n return u.dataSourceOptionsType === 'streamingOnly';\n}\nexports.isStreamingOnlyOptions = isStreamingOnlyOptions;\nfunction isPollingOnlyOptions(u) {\n return u.dataSourceOptionsType === 'pollingOnly';\n}\nexports.isPollingOnlyOptions = isPollingOnlyOptions;\nfunction isCustomOptions(u) {\n return u.dataSourceOptionsType === 'custom';\n}\nexports.isCustomOptions = isCustomOptions;\n//# sourceMappingURL=LDDataSystemOptions.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./LDBigSegmentsOptions\"), exports);\n__exportStar(require(\"./LDOptions\"), exports);\n__exportStar(require(\"./LDProxyOptions\"), exports);\n__exportStar(require(\"./LDTLSOptions\"), exports);\n__exportStar(require(\"./LDMigrationOptions\"), exports);\n__exportStar(require(\"./LDDataSystemOptions\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDClient.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDMigration.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=DataKind.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDFeatureStore.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDTransactionalFeatureStore.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDWaitForInitializationOptions.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=FileDataSourceOptions.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=Hook.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./FileDataSourceOptions\"), exports);\n__exportStar(require(\"./Hook\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=BigSegmentStore.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=BigSegmentStoreMembership.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=BigSegmentStoreMetadata.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=BigSegmentStoreStatus.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=DataCollection.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=FullDataSet.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=KeyedItems.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=VersionedData.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=BigSegmentStoreStatusProvider.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=index.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./BigSegmentStore\"), exports);\n__exportStar(require(\"./BigSegmentStoreMembership\"), exports);\n__exportStar(require(\"./BigSegmentStoreMetadata\"), exports);\n__exportStar(require(\"./BigSegmentStoreStatus\"), exports);\n__exportStar(require(\"./DataCollection\"), exports);\n__exportStar(require(\"./DataKind\"), exports);\n__exportStar(require(\"./FullDataSet\"), exports);\n__exportStar(require(\"./KeyedItems\"), exports);\n__exportStar(require(\"./VersionedData\"), exports);\n__exportStar(require(\"./BigSegmentStoreStatusProvider\"), exports);\n__exportStar(require(\"./persistent_store\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDDataSourceUpdates.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDFeatureRequestor.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=LDTransactionalDataSourceUpdates.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\n__exportStar(require(\"./LDDataSourceUpdates\"), exports);\n__exportStar(require(\"./LDFeatureRequestor\"), exports);\n__exportStar(require(\"./LDFeatureStore\"), exports);\n__exportStar(require(\"./LDTransactionalDataSourceUpdates\"), exports);\n__exportStar(require(\"./LDTransactionalFeatureStore\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.subsystems = exports.interfaces = exports.integrations = void 0;\n__exportStar(require(\"./data\"), exports);\n__exportStar(require(\"./options\"), exports);\n__exportStar(require(\"./LDClient\"), exports);\n__exportStar(require(\"./LDMigration\"), exports);\n__exportStar(require(\"./interfaces/DataKind\"), exports);\n__exportStar(require(\"./subsystems/LDFeatureStore\"), exports);\n__exportStar(require(\"./subsystems/LDTransactionalFeatureStore\"), exports);\n__exportStar(require(\"./LDWaitForInitializationOptions\"), exports);\n// These are items that should be less frequently used, and therefore they\n// are namespaced to reduce clutter amongst the top level exports.\n// Integrations was overwritten by the exports of index.ts. On a major version\n// we should consider removing this and exporting integrations differently.\nexports.integrations = require(\"./integrations\");\nexports.interfaces = require(\"./interfaces\");\nexports.subsystems = require(\"./subsystems\");\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @internal\n */\nclass LruCache {\n constructor(options) {\n this._keyMap = new Map();\n this._head = 0;\n this._tail = 0;\n this._size = 0;\n const { max } = options;\n this._max = max;\n // This is effectively a struct-of-arrays implementation\n // of a linked list. All the nodes exist statically and then\n // the links between them are changed by updating the previous/next\n // arrays.\n this._values = new Array(max);\n this._keys = new Array(max);\n this._next = new Uint32Array(max);\n this._prev = new Uint32Array(max);\n if (options.maxAge) {\n this._lastUpdated = new Array(max).fill(0);\n this._maxAge = options.maxAge;\n }\n else {\n // To please linting.\n this._lastUpdated = [];\n this._maxAge = 0;\n }\n }\n set(key, val) {\n let index = this._keyMap.get(key);\n if (index === undefined) {\n index = this._index();\n this._keys[index] = key;\n this._keyMap.set(key, index);\n this._next[this._tail] = index;\n this._prev[index] = this._tail;\n this._tail = index;\n this._size += 1;\n }\n else {\n this._setTail(index);\n }\n this._values[index] = val;\n if (this._maxAge) {\n this._lastUpdated[index] = Date.now();\n }\n }\n get(key) {\n const index = this._keyMap.get(key);\n if (index !== undefined) {\n if (this._maxAge) {\n const lastUpdated = this._lastUpdated[index];\n if (Date.now() - lastUpdated > this._maxAge) {\n // The oldest items are always the head, so they get incrementally\n // replaced. This would not be the case if we supported per item TTL.\n return undefined;\n }\n }\n this._setTail(index);\n if (this._maxAge) {\n this._lastUpdated[index] = Date.now();\n }\n return this._values[index];\n }\n return undefined;\n }\n clear() {\n this._head = 0;\n this._tail = 0;\n this._size = 0;\n this._values.fill(undefined);\n this._keys.fill(undefined);\n this._next.fill(0);\n this._prev.fill(0);\n this._keyMap.clear();\n }\n _index() {\n if (this._size === 0) {\n return this._tail;\n }\n if (this._size === this._max) {\n return this._evict();\n }\n // The initial list is being populated, so we can just continue increasing size.\n return this._size;\n }\n _evict() {\n const { _head: head } = this;\n const k = this._keys[head];\n this._head = this._next[head];\n this._keyMap.delete(k);\n this._size -= 1;\n return head;\n }\n _link(p, n) {\n this._prev[n] = p;\n this._next[p] = n;\n }\n _setTail(index) {\n // If it is already the tail, then there is nothing to do.\n if (index !== this._tail) {\n // If this is the head, then we change the next item\n // to the head.\n if (index === this._head) {\n this._head = this._next[index];\n }\n else {\n // Link the previous item to the next item, effectively removing\n // the current node.\n this._link(this._prev[index], this._next[index]);\n }\n // Connect the current tail to this node.\n this._link(this._tail, index);\n this._tail = index;\n }\n }\n}\nexports.default = LruCache;\n//# sourceMappingURL=LruCache.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst BigSegmentStatusProviderImpl_1 = require(\"./BigSegmentStatusProviderImpl\");\nconst LruCache_1 = require(\"./cache/LruCache\");\nconst DEFAULT_STALE_AFTER_SECONDS = 120;\nconst DEFAULT_STATUS_POLL_INTERVAL_SECONDS = 5;\nconst DEFAULT_USER_CACHE_SIZE = 1000;\nconst DEFAULT_USER_CACHE_TIME_SECONDS = 5;\nclass BigSegmentsManager {\n constructor(_store, \n // The store will have been created before the manager is instantiated, so we do not need\n // it in the options at this stage.\n config, _logger, _crypto) {\n this._store = _store;\n this._logger = _logger;\n this._crypto = _crypto;\n this.statusProvider = new BigSegmentStatusProviderImpl_1.default(async () => this._pollStoreAndUpdateStatus());\n this._staleTimeMs =\n (js_sdk_common_1.TypeValidators.Number.is(config.staleAfter) && config.staleAfter > 0\n ? config.staleAfter\n : DEFAULT_STALE_AFTER_SECONDS) * 1000;\n const pollIntervalMs = (js_sdk_common_1.TypeValidators.Number.is(config.statusPollInterval) && config.statusPollInterval > 0\n ? config.statusPollInterval\n : DEFAULT_STATUS_POLL_INTERVAL_SECONDS) * 1000;\n this._pollHandle = _store\n ? setInterval(() => this._pollStoreAndUpdateStatus(), pollIntervalMs)\n : null;\n if (_store) {\n this._cache = new LruCache_1.default({\n max: config.userCacheSize || DEFAULT_USER_CACHE_SIZE,\n maxAge: (config.userCacheTime || DEFAULT_USER_CACHE_TIME_SECONDS) * 1000,\n });\n }\n }\n close() {\n if (this._pollHandle) {\n clearInterval(this._pollHandle);\n this._pollHandle = undefined;\n }\n if (this._store) {\n this._store.close();\n }\n }\n async getUserMembership(userKey) {\n var _a, _b, _c;\n if (!this._store) {\n return undefined;\n }\n const memberCache = (_a = this._cache) === null || _a === void 0 ? void 0 : _a.get(userKey);\n let membership;\n if (!memberCache) {\n try {\n membership = await this._store.getUserMembership(this._hashForUserKey(userKey));\n const cacheItem = { membership };\n (_b = this._cache) === null || _b === void 0 ? void 0 : _b.set(userKey, cacheItem);\n }\n catch (err) {\n (_c = this._logger) === null || _c === void 0 ? void 0 : _c.error(`Big Segment store membership query returned error: ${err}`);\n return [null, 'STORE_ERROR'];\n }\n }\n else {\n membership = memberCache.membership;\n }\n if (!this.statusProvider.getStatus()) {\n await this._pollStoreAndUpdateStatus();\n }\n // Status will be present, because polling is done earlier in this method if it is not.\n const lastStatus = this.statusProvider.getStatus();\n if (!lastStatus.available) {\n return [membership || null, 'STORE_ERROR'];\n }\n return [membership || null, lastStatus.stale ? 'STALE' : 'HEALTHY'];\n }\n async _pollStoreAndUpdateStatus() {\n var _a, _b, _c;\n if (!this._store) {\n this.statusProvider.setStatus({ available: false, stale: false });\n return;\n }\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Querying Big Segment store status');\n let newStatus;\n try {\n const metadata = await this._store.getMetadata();\n newStatus = {\n available: true,\n stale: !metadata || !metadata.lastUpToDate || this._isStale(metadata.lastUpToDate),\n };\n }\n catch (err) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error(`Big Segment store status query returned error: ${err}`);\n newStatus = { available: false, stale: false };\n }\n const lastStatus = this.statusProvider.getStatus();\n if (!lastStatus ||\n lastStatus.available !== newStatus.available ||\n lastStatus.stale !== newStatus.stale) {\n (_c = this._logger) === null || _c === void 0 ? void 0 : _c.debug('Big Segment store status changed from %s to %s', JSON.stringify(lastStatus), JSON.stringify(newStatus));\n this.statusProvider.setStatus(newStatus);\n this.statusProvider.notify();\n }\n }\n _hashForUserKey(userKey) {\n const hasher = this._crypto.createHash('sha256');\n hasher.update(userKey);\n if (!hasher.digest) {\n // This represents an error in platform implementation.\n throw new Error('Platform must implement digest or asyncDigest');\n }\n return hasher.digest('base64');\n }\n _isStale(timestamp) {\n return Date.now() - timestamp >= this._staleTimeMs;\n }\n}\nexports.default = BigSegmentsManager;\n//# sourceMappingURL=BigSegmentsManager.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createPluginEnvironmentMetadata = void 0;\nfunction createPluginEnvironmentMetadata(_platform, _sdkKey, config) {\n const environmentMetadata = {\n sdk: {\n name: _platform.info.sdkData().userAgentBase,\n version: _platform.info.sdkData().version,\n },\n sdkKey: _sdkKey,\n };\n if (_platform.info.sdkData().wrapperName) {\n environmentMetadata.sdk.wrapperName = _platform.info.sdkData().wrapperName;\n }\n if (_platform.info.sdkData().wrapperVersion) {\n environmentMetadata.sdk.wrapperVersion = _platform.info.sdkData().wrapperVersion;\n }\n if (config.applicationInfo) {\n environmentMetadata.application = config.applicationInfo;\n }\n return environmentMetadata;\n}\nexports.createPluginEnvironmentMetadata = createPluginEnvironmentMetadata;\n//# sourceMappingURL=createPluginEnvironmentMetadata.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createPayloadListener = void 0;\nconst namespaceForKind = (kind) => {\n switch (kind) {\n case 'flag':\n return 'features';\n case 'segment':\n return 'segments';\n default:\n return kind;\n }\n};\nconst createPayloadListener = (dataSourceUpdates, logger, initializedCallback = () => { }) => (dataContainer) => {\n const { initMetadata, payload } = dataContainer;\n if (payload.basis) {\n logger === null || logger === void 0 ? void 0 : logger.debug('Initializing all data');\n }\n else if (payload.updates.length > 0) {\n logger === null || logger === void 0 ? void 0 : logger.debug('Applying updates');\n }\n else {\n logger === null || logger === void 0 ? void 0 : logger.debug('Payload had no updates, ignoring.');\n return;\n }\n // convert to LDFeatureStoreDataStorage structure\n const converted = {};\n payload.updates.forEach((it) => {\n const namespace = namespaceForKind(it.kind);\n if (converted[namespace]) {\n // entry for kind already exists, add key\n converted[namespace][it.key] = Object.assign(Object.assign({ version: it.version }, (it.deleted && { deleted: it.deleted })), it.object);\n }\n else {\n // entry for kind doesn't exist, add kind and key\n converted[namespace] = {\n [it.key]: Object.assign(Object.assign({ version: it.version }, (it.deleted && { deleted: it.deleted })), it.object),\n };\n }\n if (it.deleted) {\n logger === null || logger === void 0 ? void 0 : logger.debug(`Deleting ${it.key} in ${it.kind}`);\n }\n else {\n logger === null || logger === void 0 ? void 0 : logger.debug(`Updating ${it.key} in ${it.kind}`);\n }\n });\n // TODO: SDK-1209 - SUpport initMetadata in FDv2 datasources\n dataSourceUpdates.applyChanges(payload.basis, converted, () => {\n if (payload.state !== '') {\n // NOTE: The only condition that we will consider a valid basis\n // is when there is a valid selector. Currently, the only data source that does not have a\n // valid selector is the file data initializer, which will have a blank selector.\n initializedCallback();\n }\n }, initMetadata, payload.state);\n};\nexports.createPayloadListener = createPayloadListener;\n//# sourceMappingURL=createPayloadListenerFDv2.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass VersionedDataKinds {\n static getKeyFromPath(kind, path) {\n return path.startsWith(kind.streamApiPath)\n ? path.substring(kind.streamApiPath.length)\n : undefined;\n }\n}\nVersionedDataKinds.Features = {\n namespace: 'features',\n streamApiPath: '/flags/',\n};\nVersionedDataKinds.Segments = {\n namespace: 'segments',\n streamApiPath: '/segments/',\n};\nexports.default = VersionedDataKinds;\n//# sourceMappingURL=VersionedDataKinds.js.map","\"use strict\";\n// The deserialization will be updating parameter values, so we don't need this\n// warning in this file.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.deserializeSegment = exports.serializeSegment = exports.deserializeFlag = exports.serializeFlag = exports.deserializeDelete = exports.deserializePatch = exports.deserializePoll = exports.deserializeAll = exports.reviveFullPayload = exports.processSegment = exports.processFlag = exports.replacer = exports.nullReplacer = void 0;\n/* eslint-disable no-param-reassign */\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst VersionedDataKinds_1 = require(\"./VersionedDataKinds\");\n// The max size where we use an array instead of a set.\nconst TARGET_LIST_ARRAY_CUTOFF = 100;\n/**\n * Performs deep removal of null values.\n *\n * Does not remove null values from arrays.\n *\n * Note: This is a non-recursive implementation for performance and to avoid\n * potential stack overflows.\n *\n * @param target The target to remove null values from.\n * @param excludeKeys A list of top-level keys to exclude from null removal.\n */\nfunction nullReplacer(target, excludeKeys) {\n const stack = [];\n if (target === null || target === undefined) {\n return;\n }\n const filteredEntries = Object.entries(target).filter(([key, _value]) => !(excludeKeys === null || excludeKeys === void 0 ? void 0 : excludeKeys.includes(key)));\n stack.push(...filteredEntries.map(([key, value]) => ({\n key,\n value,\n parent: target,\n })));\n while (stack.length) {\n const item = stack.pop();\n // Do not remove items from arrays.\n if (item.value === null && !Array.isArray(item.parent)) {\n delete item.parent[item.key];\n }\n else if (typeof item.value === 'object' && item.value !== null) {\n // Add all the children to the stack. This includes array children.\n // The items in the array could themselves be objects which need nulls\n // removed from them.\n stack.push(...Object.entries(item.value).map(([key, value]) => ({\n key,\n value,\n parent: item.value,\n })));\n }\n }\n}\nexports.nullReplacer = nullReplacer;\n/**\n * For use when serializing flags/segments. This will ensure local types\n * are converted to the appropriate JSON representation.\n * @param this The scope containing the key/value.\n * @param key The key of the item being visited.\n * @param value The value of the item being visited.\n * @returns A transformed value for serialization.\n *\n * @internal\n */\nfunction replacer(key, value) {\n if (value instanceof js_sdk_common_1.AttributeReference) {\n return undefined;\n }\n if (Array.isArray(value)) {\n if (value[0] && value[0] instanceof js_sdk_common_1.AttributeReference) {\n return undefined;\n }\n }\n // Allow null/undefined values to pass through without modification.\n if (value === null || value === undefined) {\n return value;\n }\n if (value.generated_includedSet) {\n value.included = [...value.generated_includedSet];\n delete value.generated_includedSet;\n }\n if (value.generated_excludedSet) {\n value.excluded = [...value.generated_excludedSet];\n delete value.generated_excludedSet;\n }\n if (value.includedContexts) {\n value.includedContexts.forEach((target) => {\n if (target.generated_valuesSet) {\n target.values = [...target.generated_valuesSet];\n }\n delete target.generated_valuesSet;\n });\n }\n if (value.excludedContexts) {\n value.excludedContexts.forEach((target) => {\n if (target.generated_valuesSet) {\n target.values = [...target.generated_valuesSet];\n }\n delete target.generated_valuesSet;\n });\n }\n return value;\n}\nexports.replacer = replacer;\nfunction processRollout(rollout) {\n if (rollout && rollout.bucketBy) {\n rollout.bucketByAttributeReference = new js_sdk_common_1.AttributeReference(rollout.bucketBy, !rollout.contextKind);\n }\n}\n/**\n * @internal\n */\nfunction processFlag(flag) {\n var _a;\n nullReplacer(flag, ['variations']);\n if (flag.fallthrough && flag.fallthrough.rollout) {\n const rollout = flag.fallthrough.rollout;\n processRollout(rollout);\n }\n (_a = flag === null || flag === void 0 ? void 0 : flag.rules) === null || _a === void 0 ? void 0 : _a.forEach((rule) => {\n var _a;\n processRollout(rule.rollout);\n (_a = rule === null || rule === void 0 ? void 0 : rule.clauses) === null || _a === void 0 ? void 0 : _a.forEach((clause) => {\n if (clause && clause.attribute) {\n // Clauses before U2C would have had literals for attributes.\n // So use the contextKind to indicate if this is new or old data.\n clause.attributeReference = new js_sdk_common_1.AttributeReference(clause.attribute, !clause.contextKind);\n }\n else if (clause) {\n clause.attributeReference = js_sdk_common_1.AttributeReference.InvalidReference;\n }\n });\n });\n}\nexports.processFlag = processFlag;\n/**\n * @internal\n */\nfunction processSegment(segment) {\n var _a, _b, _c, _d, _e;\n nullReplacer(segment);\n if (((_a = segment === null || segment === void 0 ? void 0 : segment.included) === null || _a === void 0 ? void 0 : _a.length) && segment.included.length > TARGET_LIST_ARRAY_CUTOFF) {\n segment.generated_includedSet = new Set(segment.included);\n delete segment.included;\n }\n if (((_b = segment === null || segment === void 0 ? void 0 : segment.excluded) === null || _b === void 0 ? void 0 : _b.length) && segment.excluded.length > TARGET_LIST_ARRAY_CUTOFF) {\n segment.generated_excludedSet = new Set(segment.excluded);\n delete segment.excluded;\n }\n if ((_c = segment === null || segment === void 0 ? void 0 : segment.includedContexts) === null || _c === void 0 ? void 0 : _c.length) {\n segment.includedContexts.forEach((target) => {\n var _a;\n if (((_a = target === null || target === void 0 ? void 0 : target.values) === null || _a === void 0 ? void 0 : _a.length) && target.values.length > TARGET_LIST_ARRAY_CUTOFF) {\n target.generated_valuesSet = new Set(target.values);\n // Currently typing is non-optional, so we don't delete it.\n target.values = [];\n }\n });\n }\n if ((_d = segment === null || segment === void 0 ? void 0 : segment.excludedContexts) === null || _d === void 0 ? void 0 : _d.length) {\n segment.excludedContexts.forEach((target) => {\n var _a;\n if (((_a = target === null || target === void 0 ? void 0 : target.values) === null || _a === void 0 ? void 0 : _a.length) && target.values.length > TARGET_LIST_ARRAY_CUTOFF) {\n target.generated_valuesSet = new Set(target.values);\n // Currently typing is non-optional, so we don't delete it.\n target.values = [];\n }\n });\n }\n (_e = segment === null || segment === void 0 ? void 0 : segment.rules) === null || _e === void 0 ? void 0 : _e.forEach((rule) => {\n var _a;\n if (rule.bucketBy) {\n // Rules before U2C would have had literals for attributes.\n // So use the rolloutContextKind to indicate if this is new or old data.\n rule.bucketByAttributeReference = new js_sdk_common_1.AttributeReference(rule.bucketBy, !rule.rolloutContextKind);\n }\n (_a = rule === null || rule === void 0 ? void 0 : rule.clauses) === null || _a === void 0 ? void 0 : _a.forEach((clause) => {\n if (clause && clause.attribute) {\n // Clauses before U2C would have had literals for attributes.\n // So use the contextKind to indicate if this is new or old data.\n clause.attributeReference = new js_sdk_common_1.AttributeReference(clause.attribute, !clause.contextKind);\n }\n else if (clause) {\n clause.attributeReference = js_sdk_common_1.AttributeReference.InvalidReference;\n }\n });\n });\n}\nexports.processSegment = processSegment;\nfunction tryParse(data) {\n try {\n return JSON.parse(data);\n }\n catch (_a) {\n return undefined;\n }\n}\n/**\n * This function is intended for usage inside LaunchDarkly SDKs.\n * This function should NOT be used by customer applications.\n * This function may be changed or removed without a major version.\n *\n * @param payload Payload data from launchdarkly.\n * @returns The revived and processed data.\n */\nfunction reviveFullPayload(payload) {\n const flagsAndSegments = payload;\n Object.values((flagsAndSegments === null || flagsAndSegments === void 0 ? void 0 : flagsAndSegments.flags) || []).forEach((flag) => {\n processFlag(flag);\n });\n Object.values((flagsAndSegments === null || flagsAndSegments === void 0 ? void 0 : flagsAndSegments.segments) || []).forEach((segment) => {\n processSegment(segment);\n });\n return flagsAndSegments;\n}\nexports.reviveFullPayload = reviveFullPayload;\n/**\n * @internal\n */\nfunction deserializeAll(data) {\n // The reviver lacks the context of where a different key exists, being as it\n // starts at the deepest level and works outward. As a result attributes are\n // translated into references after the initial parsing. That way we can be sure\n // they are the correct ones. For instance if we added 'attribute' as a new field to\n // the schema for something that was NOT an attribute reference, then we wouldn't\n // want to construct an attribute reference out of it.\n const parsed = tryParse(data);\n if (!parsed) {\n return undefined;\n }\n reviveFullPayload(parsed === null || parsed === void 0 ? void 0 : parsed.data);\n return parsed;\n}\nexports.deserializeAll = deserializeAll;\n/**\n * This function is intended for usage inside LaunchDarkly SDKs.\n * This function should NOT be used by customer applications.\n * This function may be changed or removed without a major version.\n *\n * @param data String data from launchdarkly.\n * @returns The parsed and processed data.\n */\nfunction deserializePoll(data) {\n const parsed = tryParse(data);\n if (!parsed) {\n return undefined;\n }\n reviveFullPayload(parsed);\n return parsed;\n}\nexports.deserializePoll = deserializePoll;\n/**\n * @internal\n */\nfunction deserializePatch(data) {\n const parsed = tryParse(data);\n if (!parsed) {\n return undefined;\n }\n if (parsed.path.startsWith(VersionedDataKinds_1.default.Features.streamApiPath)) {\n processFlag(parsed.data);\n parsed.kind = VersionedDataKinds_1.default.Features;\n }\n else if (parsed.path.startsWith(VersionedDataKinds_1.default.Segments.streamApiPath)) {\n processSegment(parsed.data);\n parsed.kind = VersionedDataKinds_1.default.Segments;\n }\n return parsed;\n}\nexports.deserializePatch = deserializePatch;\n/**\n * @internal\n */\nfunction deserializeDelete(data) {\n const parsed = tryParse(data);\n if (!parsed) {\n return undefined;\n }\n if (parsed.path.startsWith(VersionedDataKinds_1.default.Features.streamApiPath)) {\n parsed.kind = VersionedDataKinds_1.default.Features;\n }\n else if (parsed.path.startsWith(VersionedDataKinds_1.default.Segments.streamApiPath)) {\n parsed.kind = VersionedDataKinds_1.default.Segments;\n }\n return parsed;\n}\nexports.deserializeDelete = deserializeDelete;\n/**\n * Serialize a single flag. Used for persistent data stores.\n *\n * @internal\n */\nfunction serializeFlag(flag) {\n return JSON.stringify(flag, replacer);\n}\nexports.serializeFlag = serializeFlag;\n/**\n * Deserialize a single flag. Used for persistent data stores.\n *\n * @internal\n */\nfunction deserializeFlag(data) {\n const parsed = tryParse(data);\n if (!parsed) {\n return undefined;\n }\n processFlag(parsed);\n return parsed;\n}\nexports.deserializeFlag = deserializeFlag;\n/**\n * Serialize a single segment. Used for persistent data stores.\n *\n * @internal\n */\nfunction serializeSegment(segment) {\n return JSON.stringify(segment, replacer);\n}\nexports.serializeSegment = serializeSegment;\n/**\n * Deserialize a single segment. Used for persistent data stores.\n *\n * @internal\n */\nfunction deserializeSegment(data) {\n const parsed = tryParse(data);\n if (!parsed) {\n return undefined;\n }\n processSegment(parsed);\n return parsed;\n}\nexports.deserializeSegment = deserializeSegment;\n//# sourceMappingURL=serialization.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createStreamListeners = exports.createDeleteListener = exports.createPatchListener = exports.createPutListener = void 0;\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst serialization_1 = require(\"../store/serialization\");\nconst VersionedDataKinds_1 = require(\"../store/VersionedDataKinds\");\nconst { initMetadataFromHeaders } = js_sdk_common_1.internal;\nconst createPutListener = (dataSourceUpdates, logger, onPutCompleteHandler = () => { }) => ({\n deserializeData: serialization_1.deserializeAll,\n processJson: async ({ data: { flags, segments } }, initHeaders) => {\n const initData = {\n [VersionedDataKinds_1.default.Features.namespace]: flags,\n [VersionedDataKinds_1.default.Segments.namespace]: segments,\n };\n logger === null || logger === void 0 ? void 0 : logger.debug('Initializing all data');\n dataSourceUpdates.init(initData, onPutCompleteHandler, initMetadataFromHeaders(initHeaders));\n },\n});\nexports.createPutListener = createPutListener;\nconst createPatchListener = (dataSourceUpdates, logger, onPatchCompleteHandler = () => { }) => ({\n deserializeData: serialization_1.deserializePatch,\n processJson: async ({ data, kind, path }) => {\n if (kind) {\n const key = VersionedDataKinds_1.default.getKeyFromPath(kind, path);\n if (key) {\n logger === null || logger === void 0 ? void 0 : logger.debug(`Updating ${key} in ${kind.namespace}`);\n dataSourceUpdates.upsert(kind, data, onPatchCompleteHandler);\n }\n }\n },\n});\nexports.createPatchListener = createPatchListener;\nconst createDeleteListener = (dataSourceUpdates, logger, onDeleteCompleteHandler = () => { }) => ({\n deserializeData: serialization_1.deserializeDelete,\n processJson: async ({ kind, path, version }) => {\n if (kind) {\n const key = VersionedDataKinds_1.default.getKeyFromPath(kind, path);\n if (key) {\n logger === null || logger === void 0 ? void 0 : logger.debug(`Deleting ${key} in ${kind.namespace}`);\n dataSourceUpdates.upsert(kind, {\n key,\n version,\n deleted: true,\n }, onDeleteCompleteHandler);\n }\n }\n },\n});\nexports.createDeleteListener = createDeleteListener;\nconst createStreamListeners = (dataSourceUpdates, logger, onCompleteHandlers) => {\n const listeners = new Map();\n listeners.set('put', (0, exports.createPutListener)(dataSourceUpdates, logger, onCompleteHandlers === null || onCompleteHandlers === void 0 ? void 0 : onCompleteHandlers.put));\n listeners.set('patch', (0, exports.createPatchListener)(dataSourceUpdates, logger, onCompleteHandlers === null || onCompleteHandlers === void 0 ? void 0 : onCompleteHandlers.patch));\n listeners.set('delete', (0, exports.createDeleteListener)(dataSourceUpdates, logger, onCompleteHandlers === null || onCompleteHandlers === void 0 ? void 0 : onCompleteHandlers.delete));\n return listeners;\n};\nexports.createStreamListeners = createStreamListeners;\n//# sourceMappingURL=createStreamListeners.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @internal\n */\nclass NamespacedDataSet {\n constructor() {\n this._itemsByNamespace = {};\n }\n get(namespace, key) {\n var _a;\n return (_a = this._itemsByNamespace[namespace]) === null || _a === void 0 ? void 0 : _a[key];\n }\n set(namespace, key, value) {\n if (!(namespace in this._itemsByNamespace)) {\n this._itemsByNamespace[namespace] = {};\n }\n this._itemsByNamespace[namespace][key] = value;\n }\n remove(namespace, key) {\n const items = this._itemsByNamespace[namespace];\n if (items) {\n delete items[key];\n }\n }\n removeAll() {\n this._itemsByNamespace = {};\n }\n enumerate(callback) {\n Object.entries(this._itemsByNamespace).forEach(([namespace, values]) => {\n Object.entries(values).forEach(([key, value]) => {\n callback(namespace, key, value);\n });\n });\n }\n mergeFrom(other) {\n other.enumerate(this.set.bind(this));\n }\n}\nexports.default = NamespacedDataSet;\n//# sourceMappingURL=NamespacedDataSet.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst NamespacedDataSet_1 = require(\"./NamespacedDataSet\");\n/**\n * @internal\n */\nclass DependencyTracker {\n constructor() {\n this._dependenciesFrom = new NamespacedDataSet_1.default();\n this._dependenciesTo = new NamespacedDataSet_1.default();\n }\n updateDependenciesFrom(namespace, key, newDependencySet) {\n const oldDependencySet = this._dependenciesFrom.get(namespace, key);\n oldDependencySet === null || oldDependencySet === void 0 ? void 0 : oldDependencySet.enumerate((depNs, depKey) => {\n const depsToThisDep = this._dependenciesTo.get(depNs, depKey);\n depsToThisDep === null || depsToThisDep === void 0 ? void 0 : depsToThisDep.remove(namespace, key);\n });\n this._dependenciesFrom.set(namespace, key, newDependencySet);\n newDependencySet === null || newDependencySet === void 0 ? void 0 : newDependencySet.enumerate((depNs, depKey) => {\n let depsToThisDep = this._dependenciesTo.get(depNs, depKey);\n if (!depsToThisDep) {\n depsToThisDep = new NamespacedDataSet_1.default();\n this._dependenciesTo.set(depNs, depKey, depsToThisDep);\n }\n depsToThisDep.set(namespace, key, true);\n });\n }\n updateModifiedItems(inDependencySet, modifiedNamespace, modifiedKey) {\n if (!inDependencySet.get(modifiedNamespace, modifiedKey)) {\n inDependencySet.set(modifiedNamespace, modifiedKey, true);\n const affectedItems = this._dependenciesTo.get(modifiedNamespace, modifiedKey);\n affectedItems === null || affectedItems === void 0 ? void 0 : affectedItems.enumerate((namespace, key) => {\n this.updateModifiedItems(inDependencySet, namespace, key);\n });\n }\n }\n reset() {\n this._dependenciesFrom.removeAll();\n this._dependenciesTo.removeAll();\n }\n}\nexports.default = DependencyTracker;\n//# sourceMappingURL=DependencyTracker.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.computeDependencies = void 0;\nconst VersionedDataKinds_1 = require(\"../store/VersionedDataKinds\");\nconst DependencyTracker_1 = require(\"./DependencyTracker\");\nconst NamespacedDataSet_1 = require(\"./NamespacedDataSet\");\nfunction computeDependencies(namespace, item) {\n var _a, _b;\n const ret = new NamespacedDataSet_1.default();\n const isFlag = namespace === VersionedDataKinds_1.default.Features.namespace;\n const isSegment = namespace === VersionedDataKinds_1.default.Segments.namespace;\n if (isFlag) {\n const flag = item;\n (_a = flag === null || flag === void 0 ? void 0 : flag.prerequisites) === null || _a === void 0 ? void 0 : _a.forEach((prereq) => {\n ret.set(namespace, prereq.key, true);\n });\n }\n if (isFlag || isSegment) {\n const itemWithRuleClauses = item;\n (_b = itemWithRuleClauses === null || itemWithRuleClauses === void 0 ? void 0 : itemWithRuleClauses.rules) === null || _b === void 0 ? void 0 : _b.forEach((rule) => {\n var _a;\n (_a = rule.clauses) === null || _a === void 0 ? void 0 : _a.forEach((clause) => {\n if (clause.op === 'segmentMatch') {\n clause.values.forEach((value) => {\n ret.set(VersionedDataKinds_1.default.Segments.namespace, value, true);\n });\n }\n });\n });\n }\n return ret;\n}\nexports.computeDependencies = computeDependencies;\n/**\n * @internal\n */\nclass DataSourceUpdates {\n constructor(_featureStore, _hasEventListeners, _onChange) {\n this._featureStore = _featureStore;\n this._hasEventListeners = _hasEventListeners;\n this._onChange = _onChange;\n this._dependencyTracker = new DependencyTracker_1.default();\n }\n init(allData, callback, initMetadata) {\n const checkForChanges = this._hasEventListeners();\n const doInit = (oldData) => {\n this._featureStore.init(allData, () => {\n // Defer change events so they execute after the callback.\n Promise.resolve().then(() => {\n this._dependencyTracker.reset();\n Object.entries(allData).forEach(([namespace, items]) => {\n Object.keys(items || {}).forEach((key) => {\n const item = items[key];\n this._dependencyTracker.updateDependenciesFrom(namespace, key, computeDependencies(namespace, item));\n });\n });\n if (checkForChanges) {\n const updatedItems = new NamespacedDataSet_1.default();\n Object.keys(allData).forEach((namespace) => {\n const oldDataForKind = (oldData === null || oldData === void 0 ? void 0 : oldData[namespace]) || {};\n const newDataForKind = allData[namespace];\n const mergedData = Object.assign(Object.assign({}, oldDataForKind), newDataForKind);\n Object.keys(mergedData).forEach((key) => {\n this.addIfModified(namespace, key, oldDataForKind && oldDataForKind[key], newDataForKind && newDataForKind[key], updatedItems);\n });\n });\n this.sendChangeEvents(updatedItems);\n }\n });\n callback === null || callback === void 0 ? void 0 : callback();\n }, initMetadata);\n };\n if (checkForChanges) {\n this._featureStore.all(VersionedDataKinds_1.default.Features, (oldFlags) => {\n this._featureStore.all(VersionedDataKinds_1.default.Segments, (oldSegments) => {\n const oldData = {\n [VersionedDataKinds_1.default.Features.namespace]: oldFlags,\n [VersionedDataKinds_1.default.Segments.namespace]: oldSegments,\n };\n doInit(oldData);\n });\n });\n }\n else {\n doInit();\n }\n }\n upsert(kind, data, callback) {\n const { key } = data;\n const checkForChanges = this._hasEventListeners();\n const doUpsert = (oldItem) => {\n this._featureStore.upsert(kind, data, () => {\n // Defer change events so they execute after the callback.\n Promise.resolve().then(() => {\n this._dependencyTracker.updateDependenciesFrom(kind.namespace, key, computeDependencies(kind.namespace, data));\n if (checkForChanges) {\n const updatedItems = new NamespacedDataSet_1.default();\n this.addIfModified(kind.namespace, key, oldItem, data, updatedItems);\n this.sendChangeEvents(updatedItems);\n }\n });\n callback === null || callback === void 0 ? void 0 : callback();\n });\n };\n if (checkForChanges) {\n this._featureStore.get(kind, key, doUpsert);\n }\n else {\n doUpsert();\n }\n }\n addIfModified(namespace, key, oldValue, newValue, toDataSet) {\n if (newValue && oldValue && newValue.version <= oldValue.version) {\n return;\n }\n this._dependencyTracker.updateModifiedItems(toDataSet, namespace, key);\n }\n sendChangeEvents(dataSet) {\n dataSet.enumerate((namespace, key) => {\n if (namespace === VersionedDataKinds_1.default.Features.namespace) {\n this._onChange(key);\n }\n });\n }\n}\nexports.default = DataSourceUpdates;\n//# sourceMappingURL=DataSourceUpdates.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * A debounced file load/watcher for use with the {@link FileDataSource}.\n *\n * The file loader will load all files specified and keep the string representations in memory.\n * Whenever a change is made to any of the files, then that file will be reloaded and the in\n * memory version updated.\n *\n * Updates to many files, which occur within 10ms of each other, will be coalesced into\n * a single callback.\n *\n * @internal\n */\nclass FileLoader {\n constructor(_filesystem, _paths, _watch, _callback) {\n this._filesystem = _filesystem;\n this._paths = _paths;\n this._watch = _watch;\n this._callback = _callback;\n this._watchers = [];\n this._fileData = {};\n this._fileTimestamps = {};\n }\n /**\n * Load all the files and start watching them if watching is enabled.\n */\n async loadAndWatch() {\n const promises = this._paths.map(async (path) => {\n const data = await this._filesystem.readFile(path);\n const timeStamp = await this._filesystem.getFileTimestamp(path);\n return { data, path, timeStamp };\n });\n // This promise could be rejected, let the caller handle it.\n const results = await Promise.all(promises);\n results.forEach((res) => {\n this._fileData[res.path] = res.data;\n this._fileTimestamps[res.path] = res.timeStamp;\n });\n this._callback(results);\n // If we are watching, then setup watchers and notify of any changes.\n if (this._watch) {\n this._paths.forEach((path) => {\n const watcher = this._filesystem.watch(path, async (_, updatePath) => {\n const timeStamp = await this._filesystem.getFileTimestamp(updatePath);\n // The modification time is the same, so we are going to ignore this update.\n // In some implementations watch might be triggered multiple times for a single update.\n if (timeStamp === this._fileTimestamps[updatePath]) {\n return;\n }\n this._fileTimestamps[updatePath] = timeStamp;\n const data = await this._filesystem.readFile(updatePath);\n this._fileData[updatePath] = data;\n this._debounceCallback();\n });\n this._watchers.push(watcher);\n });\n }\n }\n close() {\n this._watchers.forEach((watcher) => watcher.close());\n }\n _debounceCallback() {\n // If there is a handle, then we have already started the debounce process.\n if (!this._debounceHandle) {\n this._debounceHandle = setTimeout(() => {\n this._debounceHandle = undefined;\n this._callback(Object.entries(this._fileData).reduce((acc, [path, data]) => {\n acc.push({ path, data });\n return acc;\n }, []));\n }, 10);\n // The 10ms delay above is arbitrary - we just don't want to have the number be zero,\n // because in a case where multiple watch events are fired off one after another,\n // we want the reload to happen only after all of the event handlers have executed.\n }\n }\n}\nexports.default = FileLoader;\n//# sourceMappingURL=FileLoader.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst serialization_1 = require(\"../store/serialization\");\nconst FileLoader_1 = require(\"./FileLoader\");\n/**\n * @internal\n */\nclass FileDataInitializerFDv2 {\n constructor(options, platform, logger) {\n this._validateInputs(options, platform);\n this._paths = options.paths;\n this._logger = logger;\n this._filesystem = platform.fileSystem;\n this._yamlParser = options.yamlParser;\n }\n _validateInputs(options, platform) {\n if (!options.paths || options.paths.length === 0) {\n throw new Error('FileDataInitializerFDv2: paths are required');\n }\n if (!platform.fileSystem) {\n throw new Error('FileDataInitializerFDv2: file system is required');\n }\n }\n start(dataCallback, statusCallback) {\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Initializing);\n const initMetadata = js_sdk_common_1.internal.initMetadataFromHeaders(undefined);\n const payloadProcessor = new js_sdk_common_1.internal.PayloadProcessor({\n flag: (flag) => {\n (0, serialization_1.processFlag)(flag);\n return flag;\n },\n segment: (segment) => {\n (0, serialization_1.processSegment)(segment);\n return segment;\n },\n }, (errorKind, message) => {\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Interrupted, new js_sdk_common_1.LDPollingError(errorKind, message));\n }, this._logger);\n const adaptor = js_sdk_common_1.internal.FDv1PayloadAdaptor(payloadProcessor);\n this._fileLoader = new FileLoader_1.default(this._filesystem, this._paths, false, // autoupdate is always false for initializer\n (results) => {\n var _a;\n try {\n const parsedData = this._processFileData(results);\n payloadProcessor.addPayloadListener((payload) => {\n // NOTE: file data initializer will never have a valid basis, so we always pass false\n dataCallback(false, { initMetadata, payload });\n });\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Valid);\n adaptor.processFullTransfer(parsedData);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed);\n }\n catch (err) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error('File contained invalid data', err);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.InvalidData, 'Malformed data in file response'));\n }\n });\n this._fileLoader.loadAndWatch().catch((err) => {\n var _a;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error('Error loading files', err);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.NetworkError, `Failed to load files: ${err instanceof Error ? err.message : String(err)}`));\n });\n }\n _processFileData(results) {\n const combined = results.reduce((acc, curr) => {\n var _a, _b;\n let parsed;\n if (curr.path.endsWith('.yml') || curr.path.endsWith('.yaml')) {\n if (this._yamlParser) {\n parsed = this._yamlParser(curr.data);\n }\n else {\n throw new Error(`Attempted to parse yaml file (${curr.path}) without parser.`);\n }\n }\n else {\n parsed = JSON.parse(curr.data);\n }\n return {\n segments: Object.assign(Object.assign({}, acc.segments), ((_a = parsed.segments) !== null && _a !== void 0 ? _a : {})),\n flags: Object.assign(Object.assign({}, acc.flags), ((_b = parsed.flags) !== null && _b !== void 0 ? _b : {})),\n };\n }, {\n segments: {},\n flags: {},\n });\n return combined;\n }\n stop() {\n if (this._fileLoader) {\n this._fileLoader.close();\n }\n }\n}\nexports.default = FileDataInitializerFDv2;\n//# sourceMappingURL=fileDataInitilizerFDv2.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst serialization_1 = require(\"../store/serialization\");\n/**\n * @internal\n */\nclass OneShotInitializerFDv2 {\n constructor(_requestor, _logger) {\n this._requestor = _requestor;\n this._logger = _logger;\n this._stopped = false;\n }\n start(dataCallback, statusCallback) {\n var _a;\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Initializing);\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Performing initialization request to LaunchDarkly for feature flag data.');\n this._requestor.requestAllData((err, body, headers) => {\n var _a, _b, _c;\n if (this._stopped) {\n return;\n }\n if (err) {\n const { status } = err;\n const message = (0, js_sdk_common_1.httpErrorMessage)(err, 'initializer', 'initializer does not retry');\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error(message);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, message, status));\n return;\n }\n if (!body) {\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.InvalidData, 'One shot initializer response missing body.'));\n return;\n }\n const initMetadata = js_sdk_common_1.internal.initMetadataFromHeaders(headers);\n try {\n const parsed = JSON.parse(body);\n const payloadProcessor = new js_sdk_common_1.internal.PayloadProcessor({\n flag: (flag) => {\n (0, serialization_1.processFlag)(flag);\n return flag;\n },\n segment: (segment) => {\n (0, serialization_1.processSegment)(segment);\n return segment;\n },\n }, (errorKind, message) => {\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Interrupted, new js_sdk_common_1.LDPollingError(errorKind, message));\n }, this._logger);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Valid);\n payloadProcessor.addPayloadListener((payload) => {\n dataCallback(payload.basis, { initMetadata, payload });\n });\n payloadProcessor.processEvents(parsed.events);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed);\n }\n catch (error) {\n // We could not parse this JSON. Report the problem.\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error('Response contained invalid data');\n (_c = this._logger) === null || _c === void 0 ? void 0 : _c.debug(`${err} - Body follows: ${body}`);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.InvalidData, 'Malformed data in polling response'));\n }\n });\n }\n stop() {\n this._stopped = true;\n }\n}\nexports.default = OneShotInitializerFDv2;\n//# sourceMappingURL=OneShotInitializerFDv2.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * A basic wrapper to make async methods with callbacks into promises.\n *\n * @param method\n * @returns A promisified version of the method.\n */\nfunction promisify(method) {\n return new Promise((resolve) => {\n method((val) => {\n resolve(val);\n });\n });\n}\nexports.default = promisify;\n//# sourceMappingURL=promisify.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst promisify_1 = require(\"../async/promisify\");\n/**\n * Provides an async interface to a feature store.\n *\n * This allows for using a store using async/await instead of callbacks.\n *\n */\nclass AsyncStoreFacade {\n constructor(store) {\n this._store = store;\n }\n async get(kind, key) {\n return (0, promisify_1.default)((cb) => {\n this._store.get(kind, key, cb);\n });\n }\n async all(kind) {\n return (0, promisify_1.default)((cb) => {\n this._store.all(kind, cb);\n });\n }\n async init(allData, initMetadata) {\n return (0, promisify_1.default)((cb) => {\n this._store.init(allData, cb, initMetadata);\n });\n }\n async delete(kind, key, version) {\n return (0, promisify_1.default)((cb) => {\n this._store.delete(kind, key, version, cb);\n });\n }\n async upsert(kind, data) {\n return (0, promisify_1.default)((cb) => {\n this._store.upsert(kind, data, cb);\n });\n }\n async initialized() {\n return (0, promisify_1.default)((cb) => {\n this._store.initialized(cb);\n });\n }\n close() {\n this._store.close();\n }\n getInitMetadata() {\n var _a, _b;\n return (_b = (_a = this._store).getInitMetaData) === null || _b === void 0 ? void 0 : _b.call(_a);\n }\n}\nexports.default = AsyncStoreFacade;\n//# sourceMappingURL=AsyncStoreFacade.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst promisify_1 = require(\"../async/promisify\");\n/**\n * Provides an async interface to a feature store.\n *\n * This allows for using a store using async/await instead of callbacks.\n *\n */\nclass AsyncTransactionalStoreFacade {\n constructor(store) {\n this._store = store;\n }\n async get(kind, key) {\n return (0, promisify_1.default)((cb) => {\n this._store.get(kind, key, cb);\n });\n }\n async all(kind) {\n return (0, promisify_1.default)((cb) => {\n this._store.all(kind, cb);\n });\n }\n async init(allData, initMetadata) {\n return (0, promisify_1.default)((cb) => {\n this._store.init(allData, cb, initMetadata);\n });\n }\n async delete(kind, key, version) {\n return (0, promisify_1.default)((cb) => {\n this._store.delete(kind, key, version, cb);\n });\n }\n async upsert(kind, data) {\n return (0, promisify_1.default)((cb) => {\n this._store.upsert(kind, data, cb);\n });\n }\n async initialized() {\n return (0, promisify_1.default)((cb) => {\n this._store.initialized(cb);\n });\n }\n async applyChanges(basis, data, initMetadata, selector) {\n return (0, promisify_1.default)((cb) => {\n this._store.applyChanges(basis, data, cb, initMetadata, selector);\n });\n }\n close() {\n this._store.close();\n }\n getInitMetadata() {\n var _a, _b;\n return (_b = (_a = this._store).getInitMetaData) === null || _b === void 0 ? void 0 : _b.call(_a);\n }\n}\nexports.default = AsyncTransactionalStoreFacade;\n//# sourceMappingURL=AsyncTransactionalStoreFacade.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction isStale(record) {\n return Date.now() > record.expiration;\n}\n/**\n * A basic TTL cache with configurable TTL and check interval.\n */\nclass TtlCache {\n constructor(_options) {\n this._options = _options;\n this._storage = new Map();\n this._checkIntervalHandle = setInterval(() => {\n this._purgeStale();\n }, _options.checkInterval * 1000);\n }\n /**\n * Get a value from the cache.\n * @param key The key to get a value for.\n * @returns The value for the key, or undefined if the key was not added, or\n * if the value has expired.\n */\n get(key) {\n const record = this._storage.get(key);\n if (record && isStale(record)) {\n this._storage.delete(key);\n return undefined;\n }\n return record === null || record === void 0 ? void 0 : record.value;\n }\n /**\n * Set an item in the cache. It will expire after the TTL specified\n * in the cache configuration.\n * @param key The key for the value.\n * @param value The value to set.\n */\n set(key, value) {\n this._storage.set(key, {\n value,\n expiration: Date.now() + this._options.ttl * 1000,\n });\n }\n /**\n * Delete the item with the specific key. If the item does not exist,\n * then there will be no change to the cache.\n * @param key The key of the value to delete.\n */\n delete(key) {\n this._storage.delete(key);\n }\n /**\n * Clear the items that are in the cache.\n */\n clear() {\n this._storage.clear();\n }\n /**\n * Indicate that you are no longer going to use the cache. The cache will be\n * cleared and it will stop checking for stale items.\n */\n close() {\n this.clear();\n if (this._checkIntervalHandle) {\n clearInterval(this._checkIntervalHandle);\n this._checkIntervalHandle = null;\n }\n }\n _purgeStale() {\n this._storage.forEach((record, key) => {\n if (isStale(record)) {\n this._storage.delete(key);\n }\n });\n }\n /**\n * This is for testing.\n * @internal\n */\n get size() {\n return this._storage.size;\n }\n}\nexports.default = TtlCache;\n//# sourceMappingURL=TtlCache.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.persistentStoreKinds = void 0;\nconst serialization_1 = require(\"./serialization\");\nconst VersionedDataKinds_1 = require(\"./VersionedDataKinds\");\n/**\n * Map namespace to a persistent store kind.\n */\nexports.persistentStoreKinds = {\n segments: {\n namespace: VersionedDataKinds_1.default.Segments.namespace,\n deserialize: (data) => {\n const segment = (0, serialization_1.deserializeSegment)(data);\n if (segment) {\n return {\n version: segment.version,\n item: segment,\n };\n }\n return undefined;\n },\n serialize: (data) => {\n const serializedItem = (0, serialization_1.serializeSegment)(data);\n return {\n version: data.version,\n deleted: data.deleted,\n serializedItem,\n };\n },\n priority: 0,\n },\n features: {\n namespace: VersionedDataKinds_1.default.Features.namespace,\n deserialize: (data) => {\n const flag = (0, serialization_1.deserializeFlag)(data);\n if (flag) {\n return {\n version: flag.version,\n item: flag,\n };\n }\n return undefined;\n },\n serialize: (data) => {\n const serializedItem = (0, serialization_1.serializeFlag)(data);\n return {\n version: data.version,\n deleted: data.deleted,\n serializedItem,\n };\n },\n priority: 1,\n },\n};\n//# sourceMappingURL=persistentStoreKinds.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst persistentStoreKinds_1 = require(\"./persistentStoreKinds\");\nfunction getDependencyKeys(flag) {\n if (!flag.prerequisites || !flag.prerequisites.length) {\n return [];\n }\n return flag.prerequisites.map((preReq) => preReq.key);\n}\n/**\n * Do a topological sort using a depth-first search.\n * https://en.wikipedia.org/wiki/Topological_sorting\n */\nfunction topologicalSort(kind, itemsMap) {\n const sortedItems = [];\n const unvisitedItems = new Set(Object.keys(itemsMap));\n const visit = (key) => {\n if (!unvisitedItems.has(key)) {\n return;\n }\n // Typically in a depth-first search this would be done later, and there\n // would be a temporary mark to detect that this was not an directed acylic graph.\n // Removing it here will mean we cannot do that detection, but we also will\n // not infinitely recurse.\n unvisitedItems.delete(key);\n const item = itemsMap[key];\n if (kind.namespace === 'features') {\n getDependencyKeys(item).forEach((prereqKey) => {\n visit(prereqKey);\n });\n }\n sortedItems.push({\n key,\n item: kind.serialize(item),\n });\n };\n while (unvisitedItems.size > 0) {\n // Visit the next item, the order we visit doesn't matter.\n const key = unvisitedItems.values().next().value;\n visit(key);\n }\n return sortedItems;\n}\n/**\n * For non-atomic stores we want to insert items in an order that no items exist\n * in the store before their dependencies. Segments before flags, because flags\n * are dependent on segments. For flags we want to insert them such that no flags are\n * added before the prerequisites of those flags.\n *\n * Segments can also depend on other segments, but a segment will not be accessed\n * if there are no flags.\n */\nfunction sortDataSet(dataMap) {\n // We use a different type for collecting the results so that we have access\n // to the serialization methods and priorities.\n const result = [];\n Object.keys(dataMap).forEach((kindNamespace) => {\n const kind = persistentStoreKinds_1.persistentStoreKinds[kindNamespace];\n result.push({ key: kind, item: topologicalSort(kind, dataMap[kindNamespace]) });\n });\n result.sort((i1, i2) => i1.key.priority - i2.key.priority);\n return result;\n}\nexports.default = sortDataSet;\n//# sourceMappingURL=sortDataSet.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass UpdateQueue {\n constructor() {\n this._queue = [];\n }\n enqueue(updateFn, cb) {\n this._queue.push([updateFn, cb]);\n if (this._queue.length === 1) {\n // If this is the only item in the queue, then there is not a series\n // of updates already in progress. So we can start executing those updates.\n this.executePendingUpdates();\n }\n }\n executePendingUpdates() {\n if (this._queue.length > 0) {\n const [fn, cb] = this._queue[0];\n const newCb = () => {\n // We just completed work, so remove it from the queue.\n // Don't remove it before the work is done, because then the\n // count could hit 0, and overlapping execution chains could be started.\n this._queue.shift();\n // There is more work to do, so schedule an update.\n if (this._queue.length > 0) {\n setTimeout(() => this.executePendingUpdates(), 0);\n }\n // Call the original callback.\n cb === null || cb === void 0 ? void 0 : cb();\n };\n fn(newCb);\n }\n }\n}\nexports.default = UpdateQueue;\n//# sourceMappingURL=UpdateQueue.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst TtlCache_1 = require(\"../cache/TtlCache\");\nconst persistentStoreKinds_1 = require(\"./persistentStoreKinds\");\nconst sortDataSet_1 = require(\"./sortDataSet\");\nconst UpdateQueue_1 = require(\"./UpdateQueue\");\nfunction cacheKey(kind, key) {\n return `${kind.namespace}:${key}`;\n}\nfunction allForKindCacheKey(kind) {\n return `$all:${kind.namespace}`;\n}\n// This key will be set in the cache if we have checked that a store was\n// initialized and found that it was not. If we do not become initialized\n// within the TTL period, then the key will expire, and the next initialization\n// check will pass through to the store. Once we are initialized, then the key\n// will never be checked again.\nconst initializationCheckedKey = '$checkedInit';\n// The interval to check items in the TTL cache to purge expired items.\n// Expired items which are not purged, will be reactively purged when they are\n// accessed.\nconst defaultCheckInterval = 600;\nfunction itemIfNotDeleted(item) {\n return !item || item.item.deleted ? null : item.item;\n}\nfunction deletedDescriptor(version) {\n return {\n version,\n item: { version, deleted: true },\n };\n}\n/**\n * Deserialize a {@link SerializedItemDescriptor}\n * @param kind The persistent store data kind to deserialize.\n * @param descriptor The serialized descriptor we want to deserialize.\n * @returns An item descriptor for the deserialized item.\n */\nfunction deserialize(kind, descriptor) {\n if (descriptor.deleted || !descriptor.serializedItem) {\n return deletedDescriptor(descriptor.version);\n }\n const deserializedItem = kind.deserialize(descriptor.serializedItem);\n if (deserializedItem === undefined) {\n // This would only happen if the JSON is invalid.\n return deletedDescriptor(descriptor.version);\n }\n if (deserializedItem.version === 0 ||\n deserializedItem.version === descriptor.version ||\n deserializedItem.item === undefined) {\n return deserializedItem;\n }\n // There was a mismatch between the version of the serialized descriptor and the deserialized\n // descriptor. So we are going to trust the version of the serialized descriptor.\n return {\n version: descriptor.version,\n item: deserializedItem.item,\n };\n}\n/**\n * Internal implementation of {@link LDFeatureStore} that delegates the basic functionality to an\n * instance of {@link PersistentDataStore}. It provides optional caching behavior and other logic\n * that would otherwise be repeated in every data store implementation. This makes it easier to\n * create new database integrations by implementing only the database-specific logic.\n */\nclass PersistentDataStoreWrapper {\n constructor(_core, ttl) {\n this._core = _core;\n this._isInitialized = false;\n /**\n * Used to preserve order of operations of async requests.\n */\n this._queue = new UpdateQueue_1.default();\n if (ttl) {\n this._itemCache = new TtlCache_1.default({\n ttl,\n checkInterval: defaultCheckInterval,\n });\n this._allItemsCache = new TtlCache_1.default({\n ttl,\n checkInterval: defaultCheckInterval,\n });\n }\n }\n init(allData, callback) {\n this._queue.enqueue((cb) => {\n const afterStoreInit = () => {\n this._isInitialized = true;\n if (this._itemCache) {\n this._itemCache.clear();\n this._allItemsCache.clear();\n Object.keys(allData).forEach((kindNamespace) => {\n const kind = persistentStoreKinds_1.persistentStoreKinds[kindNamespace];\n const items = allData[kindNamespace];\n this._allItemsCache.set(allForKindCacheKey(kind), items);\n Object.keys(items).forEach((key) => {\n const itemForKey = items[key];\n const itemDescriptor = {\n version: itemForKey.version,\n item: itemForKey,\n };\n this._itemCache.set(cacheKey(kind, key), itemDescriptor);\n });\n });\n }\n cb();\n };\n this._core.init((0, sortDataSet_1.default)(allData), afterStoreInit);\n }, callback);\n }\n get(kind, key, callback) {\n if (this._itemCache) {\n const item = this._itemCache.get(cacheKey(kind, key));\n if (item) {\n callback(itemIfNotDeleted(item));\n return;\n }\n }\n const persistKind = persistentStoreKinds_1.persistentStoreKinds[kind.namespace];\n this._core.get(persistKind, key, (descriptor) => {\n var _a;\n if (descriptor && descriptor.serializedItem) {\n const value = deserialize(persistKind, descriptor);\n (_a = this._itemCache) === null || _a === void 0 ? void 0 : _a.set(cacheKey(kind, key), value);\n callback(itemIfNotDeleted(value));\n return;\n }\n callback(null);\n });\n }\n initialized(callback) {\n var _a;\n if (this._isInitialized) {\n callback(true);\n }\n else if ((_a = this._itemCache) === null || _a === void 0 ? void 0 : _a.get(initializationCheckedKey)) {\n callback(false);\n }\n else {\n this._core.initialized((storeInitialized) => {\n var _a;\n this._isInitialized = storeInitialized;\n if (!this._isInitialized) {\n (_a = this._itemCache) === null || _a === void 0 ? void 0 : _a.set(initializationCheckedKey, true);\n }\n callback(this._isInitialized);\n });\n }\n }\n all(kind, callback) {\n var _a;\n const items = (_a = this._allItemsCache) === null || _a === void 0 ? void 0 : _a.get(allForKindCacheKey(kind));\n if (items) {\n callback(items);\n return;\n }\n const persistKind = persistentStoreKinds_1.persistentStoreKinds[kind.namespace];\n this._core.getAll(persistKind, (storeItems) => {\n var _a;\n if (!storeItems) {\n callback({});\n return;\n }\n const filteredItems = {};\n storeItems.forEach(({ key, item }) => {\n const deserializedItem = deserialize(persistKind, item);\n const filteredItem = itemIfNotDeleted(deserializedItem);\n if (filteredItem) {\n filteredItems[key] = filteredItem;\n }\n });\n (_a = this._allItemsCache) === null || _a === void 0 ? void 0 : _a.set(allForKindCacheKey(kind), filteredItems);\n callback(filteredItems);\n });\n }\n upsert(kind, data, callback) {\n this._queue.enqueue((cb) => {\n // Clear the caches which contain all the values of a specific kind.\n if (this._allItemsCache) {\n this._allItemsCache.clear();\n }\n const persistKind = persistentStoreKinds_1.persistentStoreKinds[kind.namespace];\n this._core.upsert(persistKind, data.key, persistKind.serialize(data), (err, updatedDescriptor) => {\n var _a, _b;\n if (!err && updatedDescriptor) {\n if (updatedDescriptor.serializedItem) {\n const value = deserialize(persistKind, updatedDescriptor);\n (_a = this._itemCache) === null || _a === void 0 ? void 0 : _a.set(cacheKey(kind, data.key), value);\n }\n else if (updatedDescriptor.deleted) {\n // Deleted and there was not a serialized representation.\n (_b = this._itemCache) === null || _b === void 0 ? void 0 : _b.set(data.key, {\n key: data.key,\n version: updatedDescriptor.version,\n deleted: true,\n });\n }\n }\n cb();\n });\n }, callback);\n }\n delete(kind, key, version, callback) {\n this.upsert(kind, { key, version, deleted: true }, callback);\n }\n close() {\n var _a, _b;\n (_a = this._itemCache) === null || _a === void 0 ? void 0 : _a.close();\n (_b = this._allItemsCache) === null || _b === void 0 ? void 0 : _b.close();\n this._core.close();\n }\n getDescription() {\n return this._core.getDescription();\n }\n}\nexports.default = PersistentDataStoreWrapper;\n//# sourceMappingURL=PersistentDataStoreWrapper.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass InMemoryFeatureStore {\n constructor() {\n this._allData = {};\n this._initCalled = false;\n }\n get(kind, key, callback) {\n const items = this._allData[kind.namespace];\n if (items) {\n if (Object.prototype.hasOwnProperty.call(items, key)) {\n const item = items[key];\n if (item && !item.deleted) {\n return callback === null || callback === void 0 ? void 0 : callback(item);\n }\n }\n }\n return callback === null || callback === void 0 ? void 0 : callback(null);\n }\n all(kind, callback) {\n var _a;\n const result = {};\n const items = (_a = this._allData[kind.namespace]) !== null && _a !== void 0 ? _a : {};\n Object.entries(items).forEach(([key, item]) => {\n if (item && !item.deleted) {\n result[key] = item;\n }\n });\n callback === null || callback === void 0 ? void 0 : callback(result);\n }\n init(allData, callback, initMetadata) {\n this.applyChanges(true, allData, callback, initMetadata);\n }\n delete(kind, key, version, callback) {\n const item = { key, version, deleted: true };\n this.applyChanges(false, {\n [kind.namespace]: {\n [key]: item,\n },\n }, callback);\n }\n upsert(kind, data, callback) {\n this.applyChanges(false, {\n [kind.namespace]: {\n [data.key]: data,\n },\n }, callback);\n }\n applyChanges(basis, data, callback, initMetadata, selector) {\n if (basis) {\n this._initCalled = true;\n this._allData = data;\n this._initMetadata = initMetadata;\n }\n else {\n const tempData = {};\n // shallow copy to protect against concurrent read\n Object.entries(this._allData).forEach(([namespace, items]) => {\n tempData[namespace] = Object.assign({}, items);\n });\n Object.entries(data).forEach(([namespace, items]) => {\n Object.keys(items || {}).forEach((key) => {\n let existingItems = tempData[namespace];\n if (!existingItems) {\n existingItems = {};\n tempData[namespace] = existingItems;\n }\n const item = items[key];\n if (Object.hasOwnProperty.call(existingItems, key)) {\n const old = existingItems[key];\n // TODO: SDK-1046 - Determine if version check should be removed\n if (!old || old.version < item.version) {\n existingItems[key] = Object.assign({ key }, item);\n }\n }\n else {\n existingItems[key] = Object.assign({ key }, item);\n }\n });\n });\n this._allData = tempData;\n }\n this._selector = selector;\n callback === null || callback === void 0 ? void 0 : callback();\n }\n initialized(callback) {\n return callback === null || callback === void 0 ? void 0 : callback(this._initCalled);\n }\n /* eslint-disable class-methods-use-this */\n close() {\n // For the memory store this is a no-op.\n }\n getDescription() {\n return 'memory';\n }\n getInitMetaData() {\n return this._initMetadata;\n }\n getSelector() {\n return this._selector;\n }\n}\nexports.default = InMemoryFeatureStore;\n//# sourceMappingURL=InMemoryFeatureStore.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst InMemoryFeatureStore_1 = require(\"./InMemoryFeatureStore\");\n/**\n * This decorator can take a non-transactional {@link LDFeatureStore} implementation\n * and adapt it to be transactional through the use of an in-memory store acting as\n * cache.\n */\nclass TransactionalFeatureStore {\n constructor(_nonTransPersistenceStore) {\n this._nonTransPersistenceStore = _nonTransPersistenceStore;\n // persistence store is inital active store\n this._activeStore = this._nonTransPersistenceStore;\n this._memoryStore = new InMemoryFeatureStore_1.default();\n }\n get(kind, key, callback) {\n this._activeStore.get(kind, key, callback);\n }\n all(kind, callback) {\n this._activeStore.all(kind, callback);\n }\n init(allData, callback) {\n // adapt to applyChanges for common handling\n this.applyChanges(true, allData, callback);\n }\n delete(kind, key, version, callback) {\n // adapt to applyChanges for common handling\n const item = { key, version, deleted: true };\n this.applyChanges(false, {\n [kind.namespace]: {\n [key]: item,\n },\n }, callback);\n }\n upsert(kind, data, callback) {\n // adapt to applyChanges for common handling\n this.applyChanges(false, {\n [kind.namespace]: {\n [data.key]: data,\n },\n }, callback);\n }\n applyChanges(basis, data, callback, initMetadata, selector) {\n this._memoryStore.applyChanges(basis, data, () => {\n // TODO: SDK-1047 conditional propgation to persistence based on parameter\n if (basis) {\n // basis causes memory store to become the active store\n this._activeStore = this._memoryStore;\n this._nonTransPersistenceStore.init(data, callback);\n }\n else {\n const params = [];\n Object.entries(data).forEach(([namespace, items]) => {\n Object.keys(items || {}).forEach((key) => {\n params.push({ dataKind: { namespace }, item: Object.assign({ key }, items[key]) });\n });\n });\n params\n .reduce((previousPromise, nextParams) => previousPromise.then(() => new Promise((resolve) => {\n this._nonTransPersistenceStore.upsert(nextParams.dataKind, nextParams.item, resolve);\n })), Promise.resolve())\n .then(callback);\n }\n }, initMetadata, selector);\n }\n initialized(callback) {\n // this is valid because the active store will only switch to the in memory store\n // after it has already been initialized itself\n this._activeStore.initialized(callback);\n }\n close() {\n this._nonTransPersistenceStore.close();\n this._memoryStore.close();\n }\n getDescription() {\n return 'transactional persistent store';\n }\n}\nexports.default = TransactionalFeatureStore;\n//# sourceMappingURL=TransactionalFeatureStore.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.reviveFullPayload = exports.deserializePoll = exports.TransactionalFeatureStore = exports.PersistentDataStoreWrapper = exports.AsyncTransactionalStoreFacade = exports.AsyncStoreFacade = void 0;\nconst AsyncStoreFacade_1 = require(\"./AsyncStoreFacade\");\nexports.AsyncStoreFacade = AsyncStoreFacade_1.default;\nconst AsyncTransactionalStoreFacade_1 = require(\"./AsyncTransactionalStoreFacade\");\nexports.AsyncTransactionalStoreFacade = AsyncTransactionalStoreFacade_1.default;\nconst PersistentDataStoreWrapper_1 = require(\"./PersistentDataStoreWrapper\");\nexports.PersistentDataStoreWrapper = PersistentDataStoreWrapper_1.default;\nconst serialization_1 = require(\"./serialization\");\nObject.defineProperty(exports, \"deserializePoll\", { enumerable: true, get: function () { return serialization_1.deserializePoll; } });\nObject.defineProperty(exports, \"reviveFullPayload\", { enumerable: true, get: function () { return serialization_1.reviveFullPayload; } });\nconst TransactionalFeatureStore_1 = require(\"./TransactionalFeatureStore\");\nexports.TransactionalFeatureStore = TransactionalFeatureStore_1.default;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst store_1 = require(\"../store\");\nconst VersionedDataKinds_1 = require(\"../store/VersionedDataKinds\");\nconst { initMetadataFromHeaders } = js_sdk_common_1.internal;\n/**\n * @internal\n */\nclass PollingProcessor {\n constructor(_requestor, _pollInterval, _featureStore, _logger, _initSuccessHandler = () => { }, _errorHandler) {\n this._requestor = _requestor;\n this._pollInterval = _pollInterval;\n this._featureStore = _featureStore;\n this._logger = _logger;\n this._initSuccessHandler = _initSuccessHandler;\n this._errorHandler = _errorHandler;\n this._stopped = false;\n }\n _poll() {\n var _a;\n if (this._stopped) {\n return;\n }\n const reportJsonError = (data) => {\n var _a, _b, _c;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error('Polling received invalid data');\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.debug(`Invalid JSON follows: ${data}`);\n (_c = this._errorHandler) === null || _c === void 0 ? void 0 : _c.call(this, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.InvalidData, 'Malformed JSON data in polling response'));\n };\n const startTime = Date.now();\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Polling LaunchDarkly for feature flag updates');\n this._requestor.requestAllData((err, body, headers) => {\n var _a, _b, _c, _d;\n const elapsed = Date.now() - startTime;\n const sleepFor = Math.max(this._pollInterval * 1000 - elapsed, 0);\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Elapsed: %d ms, sleeping for %d ms', elapsed, sleepFor);\n if (err) {\n const { status } = err;\n if (status && !(0, js_sdk_common_1.isHttpRecoverable)(status)) {\n const message = (0, js_sdk_common_1.httpErrorMessage)(err, 'polling request');\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error(message);\n (_c = this._errorHandler) === null || _c === void 0 ? void 0 : _c.call(this, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, message, status));\n // It is not recoverable, return and do not trigger another\n // poll.\n return;\n }\n (_d = this._logger) === null || _d === void 0 ? void 0 : _d.warn((0, js_sdk_common_1.httpErrorMessage)(err, 'polling request', 'will retry'));\n }\n else if (body) {\n const parsed = (0, store_1.deserializePoll)(body);\n if (!parsed) {\n // We could not parse this JSON. Report the problem and fallthrough to\n // start another poll.\n reportJsonError(body);\n }\n else {\n const initData = {\n [VersionedDataKinds_1.default.Features.namespace]: parsed.flags,\n [VersionedDataKinds_1.default.Segments.namespace]: parsed.segments,\n };\n this._featureStore.init(initData, () => {\n this._initSuccessHandler();\n // Triggering the next poll after the init has completed.\n this._timeoutHandle = setTimeout(() => {\n this._poll();\n }, sleepFor);\n }, initMetadataFromHeaders(headers));\n // The poll will be triggered by the feature store initialization\n // completing.\n return;\n }\n }\n // Falling through, there was some type of error and we need to trigger\n // a new poll.\n this._timeoutHandle = setTimeout(() => {\n this._poll();\n }, sleepFor);\n });\n }\n start() {\n this._poll();\n }\n stop() {\n if (this._timeoutHandle) {\n clearTimeout(this._timeoutHandle);\n this._timeoutHandle = undefined;\n }\n this._stopped = true;\n }\n close() {\n this.stop();\n }\n}\nexports.default = PollingProcessor;\n//# sourceMappingURL=PollingProcessor.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst serialization_1 = require(\"../store/serialization\");\nfunction selectorAsQueryParams(selector) {\n if (!selector) {\n return [];\n }\n return [\n {\n key: 'basis',\n value: selector,\n },\n ];\n}\n// helper function to transform FDv1 response data into events the PayloadProcessor can parse\nfunction processFDv1FlagsAndSegments(payloadProcessor, data) {\n const adaptor = js_sdk_common_1.internal.FDv1PayloadAdaptor(payloadProcessor);\n adaptor.useSelector('FDv1Fallback').processFullTransfer(data);\n}\n/**\n * @internal\n */\nclass PollingProcessorFDv2 {\n /**\n * @param _requestor to fetch flags\n * @param _pollInterval in seconds controlling how frequently polling request is made\n * @param _logger for logging\n * @param _processResponseAsFDv1 defaults to false, but if set to true, this data source will process\n * the response body as FDv1 and convert it into a FDv2 payload.\n */\n constructor(_requestor, _pollInterval = 30, _logger, _processResponseAsFDv1 = false) {\n this._requestor = _requestor;\n this._pollInterval = _pollInterval;\n this._logger = _logger;\n this._processResponseAsFDv1 = _processResponseAsFDv1;\n this._stopped = false;\n }\n _poll(dataCallback, statusCallback, selectorGetter) {\n var _a;\n if (this._stopped) {\n return;\n }\n const startTime = Date.now();\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Polling LaunchDarkly for feature flag updates');\n this._requestor.requestAllData((err, body, headers) => {\n var _a, _b, _c, _d, _e, _f, _g;\n if (this._stopped) {\n return;\n }\n const elapsed = Date.now() - startTime;\n const sleepFor = Math.max(this._pollInterval * 1000 - elapsed, 0);\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Elapsed: %d ms, sleeping for %d ms', elapsed, sleepFor);\n if (err) {\n const { status } = err;\n // this is a short term error and will be removed once FDv2 adoption is sufficient.\n if (err instanceof js_sdk_common_1.LDFlagDeliveryFallbackError) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error(err.message);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, err);\n // It is not recoverable, return and do not trigger another poll.\n return;\n }\n if (status && !(0, js_sdk_common_1.isHttpRecoverable)(status)) {\n const message = (0, js_sdk_common_1.httpErrorMessage)(err, 'polling request');\n (_c = this._logger) === null || _c === void 0 ? void 0 : _c.error(message);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, message, status, false));\n // It is not recoverable, return and do not trigger another poll.\n return;\n }\n const message = (0, js_sdk_common_1.httpErrorMessage)(err, 'polling request', 'will retry');\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Interrupted, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, message, status));\n (_d = this._logger) === null || _d === void 0 ? void 0 : _d.warn(message);\n // schedule poll\n this._timeoutHandle = setTimeout(() => {\n this._poll(dataCallback, statusCallback, selectorGetter);\n }, sleepFor);\n return;\n }\n const initMetadata = js_sdk_common_1.internal.initMetadataFromHeaders(headers);\n if (body) {\n try {\n const payloadProcessor = new js_sdk_common_1.internal.PayloadProcessor({\n flag: (flag) => {\n (0, serialization_1.processFlag)(flag);\n return flag;\n },\n segment: (segment) => {\n (0, serialization_1.processSegment)(segment);\n return segment;\n },\n }, (errorKind, message) => {\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Interrupted, new js_sdk_common_1.LDPollingError(errorKind, message));\n }, this._logger);\n payloadProcessor.addPayloadListener((payload) => {\n dataCallback(payload.basis, { initMetadata, payload });\n });\n (_e = this._logger) === null || _e === void 0 ? void 0 : _e.debug(`Got body: ${body}`);\n if (!this._processResponseAsFDv1) {\n // FDv2 case\n const parsed = JSON.parse(body);\n payloadProcessor.processEvents(parsed.events);\n }\n else {\n // FDv1 case\n const parsed = JSON.parse(body);\n processFDv1FlagsAndSegments(payloadProcessor, parsed);\n }\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Valid);\n }\n catch (_h) {\n // We could not parse this JSON. Report the problem and fallthrough to\n // start another poll.\n (_f = this._logger) === null || _f === void 0 ? void 0 : _f.error('Response contained invalid data');\n (_g = this._logger) === null || _g === void 0 ? void 0 : _g.debug(`${err} - Body follows: ${body}`);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Interrupted, new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.InvalidData, 'Malformed data in polling response'));\n }\n }\n // schedule poll\n this._timeoutHandle = setTimeout(() => {\n this._poll(dataCallback, statusCallback, selectorGetter);\n }, sleepFor);\n }, selectorAsQueryParams(selectorGetter === null || selectorGetter === void 0 ? void 0 : selectorGetter()));\n }\n start(dataCallback, statusCallback, selectorGetter) {\n this._statusCallback = statusCallback; // hold reference for usage in stop()\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Initializing);\n this._poll(dataCallback, statusCallback, selectorGetter);\n }\n stop() {\n var _a;\n if (this._timeoutHandle) {\n clearTimeout(this._timeoutHandle);\n this._timeoutHandle = undefined;\n }\n (_a = this._statusCallback) === null || _a === void 0 ? void 0 : _a.call(this, js_sdk_common_1.subsystem.DataSourceState.Closed);\n this._stopped = true;\n this._statusCallback = undefined;\n }\n}\nexports.default = PollingProcessorFDv2;\n//# sourceMappingURL=PollingProcessorFDv2.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\n/**\n * @internal\n */\nclass Requestor {\n constructor(config, _requests, baseHeaders, _path = '/sdk/latest-all', _logger) {\n this._requests = _requests;\n this._path = _path;\n this._logger = _logger;\n this._eTagCache = {};\n this._headers = Object.assign({}, baseHeaders);\n this._serviceEndpoints = config.serviceEndpoints;\n }\n /**\n * Perform a request and utilize the ETag cache. The ETags are cached in the\n * requestor instance.\n */\n async _requestWithETagCache(requestUrl, options) {\n const cacheEntry = this._eTagCache[requestUrl];\n const cachedETag = cacheEntry === null || cacheEntry === void 0 ? void 0 : cacheEntry.etag;\n const updatedOptions = cachedETag\n ? Object.assign(Object.assign({}, options), { headers: Object.assign(Object.assign({}, options.headers), { 'if-none-match': cachedETag }) }) : options;\n const res = await this._requests.fetch(requestUrl, updatedOptions);\n if (res.status === 304 && cacheEntry) {\n return { res, body: cacheEntry.body };\n }\n const etag = res.headers.get('etag');\n const body = await res.text();\n if (etag) {\n this._eTagCache[requestUrl] = { etag, body };\n }\n return { res, body };\n }\n async requestAllData(cb, queryParams = []) {\n var _a, _b;\n const options = {\n method: 'GET',\n headers: this._headers,\n };\n const uri = (0, js_sdk_common_1.getPollingUri)(this._serviceEndpoints, this._path, queryParams);\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug(`Requestor making request to uri: ${uri}`);\n try {\n const { res, body } = await this._requestWithETagCache(uri, options);\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.debug(`Requestor got (possibly cached) body: ${JSON.stringify(body)}`);\n if (res.headers.get(`x-ld-fd-fallback`) === `true`) {\n const err = new js_sdk_common_1.LDFlagDeliveryFallbackError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, `Response header indicates to fallback to FDv1.`, res.status);\n return cb(err, undefined, undefined);\n }\n if (res.status !== 200 && res.status !== 304) {\n const err = new js_sdk_common_1.LDPollingError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, `Unexpected status code: ${res.status}`, res.status);\n return cb(err, undefined, undefined);\n }\n return cb(undefined, res.status === 304 ? null : body, Object.fromEntries(res.headers.entries()));\n }\n catch (err) {\n return cb(err, undefined, undefined);\n }\n }\n}\nexports.default = Requestor;\n//# sourceMappingURL=Requestor.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst reportJsonError = (type, data, logger, errorHandler) => {\n logger === null || logger === void 0 ? void 0 : logger.error(`Stream received invalid data in \"${type}\" message`);\n logger === null || logger === void 0 ? void 0 : logger.debug(`Invalid JSON follows: ${data}`);\n errorHandler === null || errorHandler === void 0 ? void 0 : errorHandler(new js_sdk_common_1.LDStreamingError(js_sdk_common_1.DataSourceErrorKind.InvalidData, 'Malformed JSON data in event stream'));\n};\nclass StreamingProcessor {\n constructor(clientContext, streamUriPath, parameters, _listeners, baseHeaders, _diagnosticsManager, _errorHandler, _streamInitialReconnectDelay = 1) {\n this._listeners = _listeners;\n this._diagnosticsManager = _diagnosticsManager;\n this._errorHandler = _errorHandler;\n this._streamInitialReconnectDelay = _streamInitialReconnectDelay;\n const { basicConfiguration, platform } = clientContext;\n const { logger } = basicConfiguration;\n const { requests } = platform;\n this._headers = Object.assign({}, baseHeaders);\n this._logger = logger;\n this._requests = requests;\n this._streamUri = (0, js_sdk_common_1.getStreamingUri)(basicConfiguration.serviceEndpoints, streamUriPath, parameters);\n }\n _logConnectionStarted() {\n this._connectionAttemptStartTime = Date.now();\n }\n _logConnectionResult(success) {\n if (this._connectionAttemptStartTime && this._diagnosticsManager) {\n this._diagnosticsManager.recordStreamInit(this._connectionAttemptStartTime, !success, Date.now() - this._connectionAttemptStartTime);\n }\n this._connectionAttemptStartTime = undefined;\n }\n /**\n * This is a wrapper around the passed errorHandler which adds additional\n * diagnostics and logging logic.\n *\n * @param err The error to be logged and handled.\n * @return boolean whether to retry the connection.\n *\n * @private\n */\n _retryAndHandleError(err) {\n var _a, _b, _c;\n if (!(0, js_sdk_common_1.shouldRetry)(err)) {\n this._logConnectionResult(false);\n (_a = this._errorHandler) === null || _a === void 0 ? void 0 : _a.call(this, new js_sdk_common_1.LDStreamingError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, err.message, err.status));\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error((0, js_sdk_common_1.httpErrorMessage)(err, 'streaming request'));\n return false;\n }\n (_c = this._logger) === null || _c === void 0 ? void 0 : _c.warn((0, js_sdk_common_1.httpErrorMessage)(err, 'streaming request', 'will retry'));\n this._logConnectionResult(false);\n this._logConnectionStarted();\n return true;\n }\n start() {\n this._logConnectionStarted();\n // TLS is handled by the platform implementation.\n const eventSource = this._requests.createEventSource(this._streamUri, {\n headers: this._headers,\n errorFilter: (error) => this._retryAndHandleError(error),\n initialRetryDelayMillis: 1000 * this._streamInitialReconnectDelay,\n readTimeoutMillis: 5 * 60 * 1000,\n retryResetIntervalMillis: 60 * 1000,\n });\n this._eventSource = eventSource;\n eventSource.onclose = () => {\n var _a;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.info('Closed LaunchDarkly stream connection');\n };\n eventSource.onerror = () => {\n // The work is done by `errorFilter`.\n };\n eventSource.onopen = (e) => {\n var _a;\n this._initHeaders = e.headers;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.info('Opened LaunchDarkly stream connection');\n };\n eventSource.onretrying = (e) => {\n var _a;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.info(`Will retry stream connection in ${e.delayMillis} milliseconds`);\n };\n this._listeners.forEach(({ deserializeData, processJson }, eventName) => {\n eventSource.addEventListener(eventName, (event) => {\n var _a, _b;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug(`Received ${eventName} event`);\n if (event === null || event === void 0 ? void 0 : event.data) {\n this._logConnectionResult(true);\n const { data } = event;\n const dataJson = deserializeData(data);\n if (!dataJson) {\n reportJsonError(eventName, data, this._logger, this._errorHandler);\n return;\n }\n processJson(dataJson, this._initHeaders);\n }\n else {\n (_b = this._errorHandler) === null || _b === void 0 ? void 0 : _b.call(this, new js_sdk_common_1.LDStreamingError(js_sdk_common_1.DataSourceErrorKind.Unknown, 'Unexpected payload from event stream'));\n }\n });\n });\n }\n stop() {\n var _a;\n (_a = this._eventSource) === null || _a === void 0 ? void 0 : _a.close();\n this._eventSource = undefined;\n }\n close() {\n this.stop();\n }\n}\nexports.default = StreamingProcessor;\n//# sourceMappingURL=StreamingProcessor.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst serialization_1 = require(\"../store/serialization\");\nclass StreamingProcessorFDv2 {\n constructor(clientContext, _streamUriPath, _parameters, baseHeaders, _diagnosticsManager, _streamInitialReconnectDelay = 1) {\n this._streamUriPath = _streamUriPath;\n this._parameters = _parameters;\n this._diagnosticsManager = _diagnosticsManager;\n this._streamInitialReconnectDelay = _streamInitialReconnectDelay;\n const { basicConfiguration, platform } = clientContext;\n const { logger, serviceEndpoints } = basicConfiguration;\n const { requests } = platform;\n this._headers = Object.assign({}, baseHeaders);\n this._serviceEndpoints = serviceEndpoints;\n this._logger = logger;\n this._requests = requests;\n }\n _logConnectionAttempt() {\n this._connectionAttemptStartTime = Date.now();\n }\n _logConnectionResult(success) {\n if (this._connectionAttemptStartTime && this._diagnosticsManager) {\n this._diagnosticsManager.recordStreamInit(this._connectionAttemptStartTime, !success, Date.now() - this._connectionAttemptStartTime);\n }\n this._connectionAttemptStartTime = undefined;\n }\n /**\n * This is a wrapper around the passed errorHandler which adds additional\n * diagnostics and logging logic.\n *\n * @param err The error to be logged and handled.\n * @return boolean whether to retry the connection.\n *\n * @private\n */\n _retryAndHandleError(err, statusCallback) {\n var _a, _b, _c;\n // this is a short term error and will be removed once FDv2 adoption is sufficient.\n if (((_a = err.headers) === null || _a === void 0 ? void 0 : _a[`x-ld-fd-fallback`]) === `true`) {\n const fallbackErr = new js_sdk_common_1.LDFlagDeliveryFallbackError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, `Response header indicates to fallback to FDv1`, err.status);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, fallbackErr);\n return false;\n }\n if (!(0, js_sdk_common_1.shouldRetry)(err)) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error((0, js_sdk_common_1.httpErrorMessage)(err, 'streaming request'));\n this._logConnectionResult(false);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed, new js_sdk_common_1.LDStreamingError(js_sdk_common_1.DataSourceErrorKind.ErrorResponse, err.message, err.status, false));\n return false;\n }\n (_c = this._logger) === null || _c === void 0 ? void 0 : _c.warn((0, js_sdk_common_1.httpErrorMessage)(err, 'streaming request', 'will retry'));\n this._logConnectionResult(false);\n this._logConnectionAttempt();\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Interrupted);\n return true;\n }\n start(dataCallback, statusCallback, selectorGetter) {\n var _a;\n this._logConnectionAttempt();\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Initializing);\n const selector = selectorGetter === null || selectorGetter === void 0 ? void 0 : selectorGetter();\n const params = selector\n ? [...this._parameters, { key: 'basis', value: selector }] // if selector exists add basis parameter\n : this._parameters; // otherwise use params as is\n const uri = (0, js_sdk_common_1.getStreamingUri)(this._serviceEndpoints, this._streamUriPath, params);\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug(`Streaming processor opening event source to uri: ${uri}`);\n const eventSource = this._requests.createEventSource(uri, {\n headers: this._headers,\n errorFilter: (error) => this._retryAndHandleError(error, statusCallback),\n initialRetryDelayMillis: 1000 * this._streamInitialReconnectDelay,\n readTimeoutMillis: 5 * 60 * 1000,\n retryResetIntervalMillis: 60 * 1000,\n });\n this._eventSource = eventSource;\n const payloadReader = new js_sdk_common_1.internal.PayloadStreamReader(eventSource, {\n flag: (flag) => {\n (0, serialization_1.processFlag)(flag);\n return flag;\n },\n segment: (segment) => {\n (0, serialization_1.processSegment)(segment);\n return segment;\n },\n }, (errorKind, message) => {\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Interrupted, new js_sdk_common_1.LDStreamingError(errorKind, message));\n // parsing error was encountered, defensively close the data source\n this.stop();\n }, this._logger);\n payloadReader.addPayloadListener((payload) => {\n this._logConnectionResult(true);\n dataCallback(payload.basis, { initMetadata: this._initMetadata, payload });\n });\n eventSource.onclose = () => {\n var _a;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.info('Closed LaunchDarkly stream connection');\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Closed);\n };\n eventSource.onerror = () => {\n // The work is done by `errorFilter`.\n };\n eventSource.onopen = (e) => {\n var _a;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.info('Opened LaunchDarkly stream connection');\n this._initMetadata = js_sdk_common_1.internal.initMetadataFromHeaders(e.headers);\n statusCallback(js_sdk_common_1.subsystem.DataSourceState.Valid);\n };\n eventSource.onretrying = (e) => {\n var _a;\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.info(`Will retry stream connection in ${e.delayMillis} milliseconds`);\n };\n }\n stop() {\n var _a;\n (_a = this._eventSource) === null || _a === void 0 ? void 0 : _a.close();\n this._eventSource = undefined;\n }\n close() {\n this.stop();\n }\n}\nexports.default = StreamingProcessorFDv2;\n//# sourceMappingURL=StreamingProcessorFDv2.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst VersionedDataKinds_1 = require(\"../store/VersionedDataKinds\");\nconst DataSourceUpdates_1 = require(\"./DataSourceUpdates\");\nconst DependencyTracker_1 = require(\"./DependencyTracker\");\nconst NamespacedDataSet_1 = require(\"./NamespacedDataSet\");\n/**\n * @internal\n */\nclass TransactionalDataSourceUpdates {\n constructor(_featureStore, _hasEventListeners, _onChange) {\n this._featureStore = _featureStore;\n this._hasEventListeners = _hasEventListeners;\n this._onChange = _onChange;\n this._dependencyTracker = new DependencyTracker_1.default();\n }\n init(allData, callback, initMetadata) {\n this.applyChanges(true, allData, callback, initMetadata); // basis is true for init\n }\n upsert(kind, data, callback) {\n this.applyChanges(false, // basis is false for upserts\n {\n [kind.namespace]: {\n [data.key]: data,\n },\n }, callback);\n }\n applyChanges(basis, data, callback, initMetadata, selector) {\n const checkForChanges = this._hasEventListeners();\n const doApplyChanges = (oldData) => {\n this._featureStore.applyChanges(basis, data, () => {\n // Defer change events so they execute after the callback.\n Promise.resolve().then(() => {\n if (basis) {\n this._dependencyTracker.reset();\n }\n Object.entries(data).forEach(([namespace, items]) => {\n Object.keys(items || {}).forEach((key) => {\n const item = items[key];\n this._dependencyTracker.updateDependenciesFrom(namespace, key, (0, DataSourceUpdates_1.computeDependencies)(namespace, item));\n });\n });\n if (checkForChanges) {\n const updatedItems = new NamespacedDataSet_1.default();\n Object.keys(data).forEach((namespace) => {\n const oldDataForKind = oldData[namespace];\n const newDataForKind = data[namespace];\n let iterateData;\n if (basis) {\n // for basis, need to iterate on all keys\n iterateData = Object.assign(Object.assign({}, oldDataForKind), newDataForKind);\n }\n else {\n // for non basis, only need to iterate on keys in incoming data\n iterateData = Object.assign({}, newDataForKind);\n }\n Object.keys(iterateData).forEach((key) => {\n this.addIfModified(namespace, key, oldDataForKind && oldDataForKind[key], newDataForKind && newDataForKind[key], updatedItems);\n });\n });\n this.sendChangeEvents(updatedItems);\n }\n });\n callback === null || callback === void 0 ? void 0 : callback();\n }, initMetadata, selector);\n };\n let oldData = {};\n if (checkForChanges) {\n // record old data before making changes to use for change calculations\n this._featureStore.all(VersionedDataKinds_1.default.Features, (oldFlags) => {\n this._featureStore.all(VersionedDataKinds_1.default.Segments, (oldSegments) => {\n oldData = {\n [VersionedDataKinds_1.default.Features.namespace]: oldFlags,\n [VersionedDataKinds_1.default.Segments.namespace]: oldSegments,\n };\n });\n });\n }\n doApplyChanges(oldData);\n }\n addIfModified(namespace, key, oldValue, newValue, toDataSet) {\n if (newValue && oldValue && newValue.version <= oldValue.version) {\n return;\n }\n this._dependencyTracker.updateModifiedItems(toDataSet, namespace, key);\n }\n sendChangeEvents(dataSet) {\n dataSet.enumerate((namespace, key) => {\n if (namespace === VersionedDataKinds_1.default.Features.namespace) {\n this._onChange(key);\n }\n });\n }\n}\nexports.default = TransactionalDataSourceUpdates;\n//# sourceMappingURL=TransactionalDataSourceUpdates.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.defaultValues = exports.DEFAULT_STREAM_RECONNECT_DELAY = exports.DEFAULT_POLL_INTERVAL = void 0;\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst LDDataSystemOptions_1 = require(\"../api/options/LDDataSystemOptions\");\nconst InMemoryFeatureStore_1 = require(\"../store/InMemoryFeatureStore\");\n// Once things are internal to the implementation of the SDK we can depend on\n// types. Calls to the SDK could contain anything without any regard to typing.\n// So, data we take from external sources must be normalized into something\n// that can be trusted.\n/**\n * These perform cursory validations. Complex objects are implemented with classes\n * and these should allow for conditional construction.\n */\nconst validations = {\n baseUri: js_sdk_common_1.TypeValidators.String,\n streamUri: js_sdk_common_1.TypeValidators.String,\n eventsUri: js_sdk_common_1.TypeValidators.String,\n timeout: js_sdk_common_1.TypeValidators.Number,\n capacity: js_sdk_common_1.TypeValidators.Number,\n logger: js_sdk_common_1.TypeValidators.Object,\n featureStore: js_sdk_common_1.TypeValidators.ObjectOrFactory,\n dataSystem: js_sdk_common_1.TypeValidators.Object,\n bigSegments: js_sdk_common_1.TypeValidators.Object,\n updateProcessor: js_sdk_common_1.TypeValidators.ObjectOrFactory,\n flushInterval: js_sdk_common_1.TypeValidators.Number,\n pollInterval: js_sdk_common_1.TypeValidators.numberWithMin(30),\n proxyOptions: js_sdk_common_1.TypeValidators.Object,\n offline: js_sdk_common_1.TypeValidators.Boolean,\n stream: js_sdk_common_1.TypeValidators.Boolean,\n streamInitialReconnectDelay: js_sdk_common_1.TypeValidators.Number,\n useLdd: js_sdk_common_1.TypeValidators.Boolean,\n sendEvents: js_sdk_common_1.TypeValidators.Boolean,\n allAttributesPrivate: js_sdk_common_1.TypeValidators.Boolean,\n privateAttributes: js_sdk_common_1.TypeValidators.StringArray,\n contextKeysCapacity: js_sdk_common_1.TypeValidators.Number,\n contextKeysFlushInterval: js_sdk_common_1.TypeValidators.Number,\n tlsParams: js_sdk_common_1.TypeValidators.Object,\n diagnosticOptOut: js_sdk_common_1.TypeValidators.Boolean,\n diagnosticRecordingInterval: js_sdk_common_1.TypeValidators.numberWithMin(60),\n wrapperName: js_sdk_common_1.TypeValidators.String,\n wrapperVersion: js_sdk_common_1.TypeValidators.String,\n application: js_sdk_common_1.TypeValidators.Object,\n payloadFilterKey: js_sdk_common_1.TypeValidators.stringMatchingRegex(/^[a-zA-Z0-9](\\w|\\.|-)*$/),\n hooks: js_sdk_common_1.TypeValidators.createTypeArray('Hook[]', {}),\n enableEventCompression: js_sdk_common_1.TypeValidators.Boolean,\n dataSourceOptionsType: js_sdk_common_1.TypeValidators.String,\n};\nexports.DEFAULT_POLL_INTERVAL = 30;\nexports.DEFAULT_STREAM_RECONNECT_DELAY = 1;\nconst defaultStandardDataSourceOptions = {\n dataSourceOptionsType: 'standard',\n streamInitialReconnectDelay: exports.DEFAULT_STREAM_RECONNECT_DELAY,\n pollInterval: exports.DEFAULT_POLL_INTERVAL,\n};\nconst defaultStreamingDataSourceOptions = {\n dataSourceOptionsType: 'streamingOnly',\n streamInitialReconnectDelay: exports.DEFAULT_STREAM_RECONNECT_DELAY,\n};\nconst defaultPollingDataSourceOptions = {\n dataSourceOptionsType: 'pollingOnly',\n pollInterval: exports.DEFAULT_POLL_INTERVAL,\n};\nconst defaultDataSystemOptions = {\n dataSource: defaultStandardDataSourceOptions,\n};\n/**\n * @internal\n */\nexports.defaultValues = {\n baseUri: 'https://sdk.launchdarkly.com',\n streamUri: 'https://stream.launchdarkly.com',\n eventsUri: js_sdk_common_1.ServiceEndpoints.DEFAULT_EVENTS,\n stream: true,\n streamInitialReconnectDelay: exports.DEFAULT_STREAM_RECONNECT_DELAY,\n sendEvents: true,\n timeout: 5,\n capacity: 10000,\n flushInterval: 5,\n pollInterval: exports.DEFAULT_POLL_INTERVAL,\n offline: false,\n useLdd: false,\n allAttributesPrivate: false,\n privateAttributes: [],\n contextKeysCapacity: 1000,\n contextKeysFlushInterval: 300,\n diagnosticOptOut: false,\n diagnosticRecordingInterval: 900,\n featureStore: () => new InMemoryFeatureStore_1.default(),\n enableEventCompression: false,\n dataSystem: defaultDataSystemOptions,\n};\nfunction validateTypesAndNames(options, defaults) {\n const errors = [];\n const validatedOptions = Object.assign({}, defaults);\n Object.keys(options).forEach((optionName) => {\n var _a;\n // We need to tell typescript it doesn't actually know what options are.\n // If we don't then it complains we are doing crazy things with it.\n const optionValue = options[optionName];\n const validator = validations[optionName];\n if (validator) {\n if (!validator.is(optionValue)) {\n if (validator.getType() === 'boolean') {\n errors.push(js_sdk_common_1.OptionMessages.wrongOptionTypeBoolean(optionName, typeof optionValue));\n validatedOptions[optionName] = !!optionValue;\n }\n else if (validator instanceof js_sdk_common_1.NumberWithMinimum &&\n js_sdk_common_1.TypeValidators.Number.is(optionValue)) {\n const { min } = validator;\n errors.push(js_sdk_common_1.OptionMessages.optionBelowMinimum(optionName, optionValue, min));\n validatedOptions[optionName] = min;\n }\n else {\n errors.push(js_sdk_common_1.OptionMessages.wrongOptionType(optionName, validator.getType(), typeof optionValue));\n validatedOptions[optionName] = exports.defaultValues[optionName];\n }\n }\n else {\n validatedOptions[optionName] = optionValue;\n }\n }\n else {\n (_a = options.logger) === null || _a === void 0 ? void 0 : _a.warn(js_sdk_common_1.OptionMessages.unknownOption(optionName));\n }\n });\n return { errors, validatedOptions };\n}\nfunction validateEndpoints(options, validatedOptions) {\n var _a, _b, _c;\n const { baseUri, streamUri, eventsUri } = options;\n const streamingEndpointSpecified = streamUri !== undefined && streamUri !== null;\n const pollingEndpointSpecified = baseUri !== undefined && baseUri !== null;\n const eventEndpointSpecified = eventsUri !== undefined && eventsUri !== null;\n if (streamingEndpointSpecified === pollingEndpointSpecified &&\n streamingEndpointSpecified === eventEndpointSpecified) {\n // Either everything is default, or everything is set.\n return;\n }\n if (!streamingEndpointSpecified && validatedOptions.stream) {\n (_a = validatedOptions.logger) === null || _a === void 0 ? void 0 : _a.warn(js_sdk_common_1.OptionMessages.partialEndpoint('streamUri'));\n }\n if (!pollingEndpointSpecified) {\n (_b = validatedOptions.logger) === null || _b === void 0 ? void 0 : _b.warn(js_sdk_common_1.OptionMessages.partialEndpoint('baseUri'));\n }\n if (!eventEndpointSpecified && validatedOptions.sendEvents) {\n (_c = validatedOptions.logger) === null || _c === void 0 ? void 0 : _c.warn(js_sdk_common_1.OptionMessages.partialEndpoint('eventsUri'));\n }\n}\nfunction validateDataSystemOptions(options) {\n const allErrors = [];\n const validatedOptions = Object.assign({}, options);\n if (options.persistentStore && !js_sdk_common_1.TypeValidators.ObjectOrFactory.is(options.persistentStore)) {\n validatedOptions.persistentStore = undefined; // default is to not use this\n allErrors.push(js_sdk_common_1.OptionMessages.wrongOptionType('persistentStore', 'LDFeatureStore', typeof options.persistentStore));\n }\n if (options.dataSource) {\n let errors;\n let validatedDataSourceOptions;\n if ((0, LDDataSystemOptions_1.isStandardOptions)(options.dataSource)) {\n ({ errors, validatedOptions: validatedDataSourceOptions } = validateTypesAndNames(options.dataSource, defaultStandardDataSourceOptions));\n }\n else if ((0, LDDataSystemOptions_1.isStreamingOnlyOptions)(options.dataSource)) {\n ({ errors, validatedOptions: validatedDataSourceOptions } = validateTypesAndNames(options.dataSource, defaultStreamingDataSourceOptions));\n }\n else if ((0, LDDataSystemOptions_1.isPollingOnlyOptions)(options.dataSource)) {\n ({ errors, validatedOptions: validatedDataSourceOptions } = validateTypesAndNames(options.dataSource, defaultPollingDataSourceOptions));\n }\n else if ((0, LDDataSystemOptions_1.isCustomOptions)(options.dataSource)) {\n validatedDataSourceOptions = options.dataSource;\n errors = [];\n }\n else {\n // provided datasource options don't fit any expected form, drop them and use defaults\n validatedDataSourceOptions = defaultStandardDataSourceOptions;\n errors = [\n js_sdk_common_1.OptionMessages.wrongOptionType('dataSource', 'DataSourceOptions', typeof options.dataSource),\n ];\n }\n validatedOptions.dataSource = validatedDataSourceOptions;\n allErrors.push(...errors);\n }\n else {\n // use default datasource options if no datasource was specified\n validatedOptions.dataSource = defaultStandardDataSourceOptions;\n }\n return { errors: allErrors, validatedOptions };\n}\n/**\n * Configuration options for the LDClient.\n *\n * @internal\n */\nclass Configuration {\n constructor(options = {}, internalOptions = {}) {\n var _a;\n // The default will handle undefined, but not null.\n // Because we can be called from JS we need to be extra defensive.\n // eslint-disable-next-line no-param-reassign\n options = options || {};\n // If there isn't a valid logger from the platform, then logs would go nowhere.\n this.logger = options.logger;\n const { errors, validatedOptions: topLevelResult } = validateTypesAndNames(options, exports.defaultValues);\n const validatedOptions = topLevelResult;\n errors.forEach((error) => {\n var _a;\n (_a = this.logger) === null || _a === void 0 ? void 0 : _a.warn(error);\n });\n validateEndpoints(options, validatedOptions);\n if (options.dataSystem) {\n // validate the data system options, this will also apply reasonable defaults\n const { errors: dsErrors, validatedOptions: dsResult } = validateDataSystemOptions(options.dataSystem);\n const validatedDSOptions = dsResult;\n this.dataSystem = {\n dataSource: validatedDSOptions.dataSource,\n useLdd: validatedDSOptions.useLdd,\n // @ts-ignore\n featureStoreFactory: (clientContext) => {\n if (validatedDSOptions.persistentStore === undefined) {\n // the persistent store provided was either undefined or invalid, default to memory store\n return new InMemoryFeatureStore_1.default();\n }\n if (js_sdk_common_1.TypeValidators.Function.is(validatedDSOptions.persistentStore)) {\n return validatedDSOptions.persistentStore(clientContext);\n }\n return validatedDSOptions.persistentStore;\n },\n };\n dsErrors.forEach((error) => {\n var _a;\n (_a = this.logger) === null || _a === void 0 ? void 0 : _a.warn(error);\n });\n }\n this.serviceEndpoints = new js_sdk_common_1.ServiceEndpoints(validatedOptions.streamUri, validatedOptions.baseUri, validatedOptions.eventsUri, internalOptions.analyticsEventPath, internalOptions.diagnosticEventPath, internalOptions.includeAuthorizationHeader, validatedOptions.payloadFilterKey);\n this.eventsCapacity = validatedOptions.capacity;\n this.timeout = validatedOptions.timeout;\n this.bigSegments = validatedOptions.bigSegments;\n this.flushInterval = validatedOptions.flushInterval;\n this.pollInterval = validatedOptions.pollInterval;\n this.proxyOptions = validatedOptions.proxyOptions;\n this.offline = validatedOptions.offline;\n this.stream = validatedOptions.stream;\n this.streamInitialReconnectDelay = validatedOptions.streamInitialReconnectDelay;\n this.useLdd = validatedOptions.useLdd;\n this.sendEvents = validatedOptions.sendEvents;\n this.allAttributesPrivate = validatedOptions.allAttributesPrivate;\n this.privateAttributes = validatedOptions.privateAttributes;\n this.contextKeysCapacity = validatedOptions.contextKeysCapacity;\n this.contextKeysFlushInterval = validatedOptions.contextKeysFlushInterval;\n this.tlsParams = validatedOptions.tlsParams;\n this.diagnosticOptOut = validatedOptions.diagnosticOptOut;\n this.wrapperName = validatedOptions.wrapperName;\n this.payloadFilterKey = validatedOptions.payloadFilterKey;\n this.wrapperVersion = validatedOptions.wrapperVersion;\n this.tags = new js_sdk_common_1.ApplicationTags(validatedOptions);\n this.diagnosticRecordingInterval = validatedOptions.diagnosticRecordingInterval;\n if (js_sdk_common_1.TypeValidators.Function.is(validatedOptions.updateProcessor)) {\n // @ts-ignore\n this.updateProcessorFactory = validatedOptions.updateProcessor;\n }\n else {\n // The processor is already created, just have the method return it.\n // @ts-ignore\n this.updateProcessorFactory = () => validatedOptions.updateProcessor;\n }\n if (js_sdk_common_1.TypeValidators.Function.is(validatedOptions.featureStore)) {\n // @ts-ignore\n this.featureStoreFactory = validatedOptions.featureStore;\n }\n else {\n // The store is already created, just have the method return it.\n // @ts-ignore\n this.featureStoreFactory = () => validatedOptions.featureStore;\n }\n this.hooks = validatedOptions.hooks;\n this.enableEventCompression = validatedOptions.enableEventCompression;\n this.getImplementationHooks = (_a = internalOptions.getImplementationHooks) !== null && _a !== void 0 ? _a : (() => []);\n this.applicationInfo = validatedOptions.application;\n }\n}\nexports.default = Configuration;\n//# sourceMappingURL=Configuration.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst api_1 = require(\"../api\");\nconst Configuration_1 = require(\"../options/Configuration\");\nconst createDiagnosticsInitConfig = (config, platform, featureStore) => {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;\n let pollingIntervalMillis;\n if ((_a = config.dataSystem) === null || _a === void 0 ? void 0 : _a.dataSource) {\n if (((0, api_1.isStandardOptions)(config.dataSystem.dataSource) ||\n (0, api_1.isPollingOnlyOptions)(config.dataSystem.dataSource)) &&\n config.dataSystem.dataSource.pollInterval) {\n pollingIntervalMillis = (0, js_sdk_common_1.secondsToMillis)(config.dataSystem.dataSource.pollInterval);\n }\n }\n else {\n pollingIntervalMillis = (0, js_sdk_common_1.secondsToMillis)(config.pollInterval);\n }\n let reconnectTimeMillis;\n if ((_b = config.dataSystem) === null || _b === void 0 ? void 0 : _b.dataSource) {\n if (((0, api_1.isStandardOptions)(config.dataSystem.dataSource) ||\n (0, api_1.isStreamingOnlyOptions)(config.dataSystem.dataSource)) &&\n config.dataSystem.dataSource.streamInitialReconnectDelay) {\n reconnectTimeMillis = (0, js_sdk_common_1.secondsToMillis)(config.dataSystem.dataSource.streamInitialReconnectDelay);\n }\n }\n else {\n reconnectTimeMillis = (0, js_sdk_common_1.secondsToMillis)(config.streamInitialReconnectDelay);\n }\n let streamDisabled;\n if ((_c = config.dataSystem) === null || _c === void 0 ? void 0 : _c.dataSource) {\n streamDisabled = (0, api_1.isPollingOnlyOptions)((_d = config.dataSystem) === null || _d === void 0 ? void 0 : _d.dataSource);\n }\n else {\n streamDisabled = !config.stream;\n }\n return Object.assign(Object.assign(Object.assign({ customBaseURI: config.serviceEndpoints.polling !== Configuration_1.defaultValues.baseUri, customStreamURI: config.serviceEndpoints.streaming !== Configuration_1.defaultValues.streamUri, customEventsURI: config.serviceEndpoints.events !== Configuration_1.defaultValues.eventsUri, eventsCapacity: config.eventsCapacity, \n // Node doesn't distinguish between these two kinds of timeouts. It is unlikely other web\n // based implementations would be able to either.\n connectTimeoutMillis: (0, js_sdk_common_1.secondsToMillis)(config.timeout), socketTimeoutMillis: (0, js_sdk_common_1.secondsToMillis)(config.timeout), eventsFlushIntervalMillis: (0, js_sdk_common_1.secondsToMillis)(config.flushInterval) }, (pollingIntervalMillis ? { pollingIntervalMillis } : null)), (reconnectTimeMillis ? { reconnectTimeMillis } : null)), { contextKeysFlushIntervalMillis: (0, js_sdk_common_1.secondsToMillis)(config.contextKeysFlushInterval), diagnosticRecordingIntervalMillis: (0, js_sdk_common_1.secondsToMillis)(config.diagnosticRecordingInterval), streamingDisabled: streamDisabled, usingRelayDaemon: (_f = (_e = config.dataSystem) === null || _e === void 0 ? void 0 : _e.useLdd) !== null && _f !== void 0 ? _f : config.useLdd, offline: config.offline, allAttributesPrivate: config.allAttributesPrivate, contextKeysCapacity: config.contextKeysCapacity, usingProxy: !!((_h = (_g = platform.requests).usingProxy) === null || _h === void 0 ? void 0 : _h.call(_g)), usingProxyAuthenticator: !!((_k = (_j = platform.requests).usingProxyAuth) === null || _k === void 0 ? void 0 : _k.call(_j)), dataStoreType: (_m = (_l = featureStore.getDescription) === null || _l === void 0 ? void 0 : _l.call(featureStore)) !== null && _m !== void 0 ? _m : 'memory' });\n};\nexports.default = createDiagnosticsInitConfig;\n//# sourceMappingURL=createDiagnosticsInitConfig.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.allAsync = exports.firstSeriesAsync = exports.allSeriesAsync = exports.firstResult = void 0;\n/**\n * Iterate a collection any apply the specified operation. The first operation which\n * returns a value will be returned and iteration will stop.\n *\n * @param collection The collection to enumerate.\n * @param operator The operation to apply to each item.\n * @returns The result of the first successful operation.\n */\nfunction firstResult(collection, operator) {\n let res;\n collection === null || collection === void 0 ? void 0 : collection.some((item, index) => {\n res = operator(item, index);\n return !!res;\n });\n return res;\n}\nexports.firstResult = firstResult;\nconst ITERATION_RECURSION_LIMIT = 50;\nfunction seriesAsync(collection, check, all, index, cb) {\n if (!collection) {\n cb(false);\n return;\n }\n if (index < (collection === null || collection === void 0 ? void 0 : collection.length)) {\n check(collection[index], index, (res) => {\n if (all) {\n if (!res) {\n cb(false);\n return;\n }\n }\n else if (res) {\n cb(true);\n return;\n }\n if (collection.length > ITERATION_RECURSION_LIMIT) {\n // When we hit the recursion limit we defer execution\n // by using a resolved promise. This is similar to using setImmediate\n // but more portable.\n Promise.resolve().then(() => {\n seriesAsync(collection, check, all, index + 1, cb);\n });\n }\n else {\n seriesAsync(collection, check, all, index + 1, cb);\n }\n });\n }\n else {\n cb(all);\n }\n}\n/**\n * Iterate a collection in series awaiting each check operation.\n * @param collection The collection to iterate.\n * @param check The check to perform for each item in the container.\n * @param cb Called with true if all items pass the check.\n */\nfunction allSeriesAsync(collection, check, cb) {\n seriesAsync(collection, check, true, 0, cb);\n}\nexports.allSeriesAsync = allSeriesAsync;\n/**\n * Iterate a collection in series awaiting each check operation.\n * @param collection The collection to iterate.\n * @param check The check to perform for each item in the container.\n * @param cb called with true on the first item that passes the check. False\n * means no items passed the check.\n */\nfunction firstSeriesAsync(collection, check, cb) {\n seriesAsync(collection, check, false, 0, cb);\n}\nexports.firstSeriesAsync = firstSeriesAsync;\n/**\n * Iterate a collection and execute the the given check operation\n * for all items concurrently.\n * @param collection The collection to iterate.\n * @param check The check to run for each item.\n * @param cb Callback executed when all items have been checked. The callback\n * will be called with true if each item resulted in true, otherwise it will\n * be called with false.\n */\nfunction allAsync(collection, check, cb) {\n if (!collection) {\n cb(false);\n return;\n }\n Promise.all(collection === null || collection === void 0 ? void 0 : collection.map((item) => new Promise((resolve) => {\n check(item, resolve);\n }))).then((results) => {\n cb(results.every((success) => success));\n });\n}\nexports.allAsync = allAsync;\n//# sourceMappingURL=collection.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * A set of static evaluation reasons and methods for creating specific reason instances.\n *\n * @internal\n */\nclass Reasons {\n static prerequisiteFailed(prerequisiteKey) {\n return { kind: 'PREREQUISITE_FAILED', prerequisiteKey };\n }\n static ruleMatch(ruleId, ruleIndex) {\n return { kind: 'RULE_MATCH', ruleId, ruleIndex };\n }\n}\nReasons.Fallthrough = { kind: 'FALLTHROUGH' };\nReasons.Off = { kind: 'OFF' };\nReasons.TargetMatch = { kind: 'TARGET_MATCH' };\nexports.default = Reasons;\n//# sourceMappingURL=Reasons.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst Reasons_1 = require(\"./Reasons\");\n/**\n * A class which encapsulates the result of an evaluation. It allows for differentiating between\n * successful and error result types.\n *\n * @internal\n */\nclass EvalResult {\n constructor(isError, detail, message) {\n this.isError = isError;\n this.detail = detail;\n this.message = message;\n this.isError = isError;\n this.detail = detail;\n this.message = message;\n }\n get isOff() {\n return this.detail.reason.kind === Reasons_1.default.Off.kind;\n }\n setDefault(def) {\n this.detail.value = def;\n }\n static forError(errorKind, message, def) {\n return new EvalResult(true, {\n value: def !== null && def !== void 0 ? def : null,\n variationIndex: null,\n reason: { kind: 'ERROR', errorKind },\n }, message);\n }\n static forSuccess(value, reason, variationIndex) {\n return new EvalResult(false, {\n value,\n variationIndex: variationIndex === undefined ? null : variationIndex,\n reason,\n });\n }\n}\nexports.default = EvalResult;\n//# sourceMappingURL=EvalResult.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Bucketing can be done by string or integer values. The need to be converted to a string\n * for the hashing process.\n * @param value The value to get a bucketable value for.\n * @returns The value as a string, or null if the value cannot be used for bucketing.\n */\nfunction valueForBucketing(value) {\n if (typeof value === 'string') {\n return value;\n }\n if (Number.isInteger(value)) {\n return String(value);\n }\n return null;\n}\nclass Bucketer {\n constructor(crypto) {\n this._crypto = crypto;\n }\n _sha1Hex(value) {\n const hash = this._crypto.createHash('sha1');\n hash.update(value);\n if (!hash.digest) {\n // This represents an error in platform implementation.\n throw new Error('Platform must implement digest or asyncDigest');\n }\n return hash.digest('hex');\n }\n /**\n * Bucket the provided context using the provided parameters.\n * @param context The context to bucket. Can be a 'multi' kind context, but\n * the bucketing will be by a specific contained kind.\n * @param key A key to use in hashing. Typically the flag key or the segment key.\n * @param attr The attribute to use for bucketing.\n * @param salt A salt to use in hashing.\n * @param kindForRollout The kind to use for bucketing.\n * @param seed A seed to use in hashing.\n *\n * @returns A tuple where the first value is the bucket, and the second value indicates if there\n * was a context for the value specified by `kindForRollout`. If there was not a context for the\n * specified kind, then the `inExperiment` attribute should be `false`.\n */\n bucket(context, key, attr, salt, kindForRollout = 'user', seed) {\n const value = context.valueForKind(attr, kindForRollout);\n const bucketableValue = valueForBucketing(value);\n // Bucketing cannot be done by the specified attribute value.\n if (bucketableValue === null) {\n // If we got a value, then we know there was a context, but if we didn't get a value, then\n // it could either be there wasn't an attribute, the attribute was undefined/null, or there\n // was not a context. So here check for the context.\n const hadContext = context.kinds.indexOf(kindForRollout) >= 0;\n return [0, hadContext];\n }\n const prefix = seed ? Number(seed) : `${key}.${salt}`;\n const hashKey = `${prefix}.${bucketableValue}`;\n const hashVal = parseInt(this._sha1Hex(hashKey).substring(0, 15), 16);\n // This is how this has worked in previous implementations, but it is not\n // ideal.\n // The maximum safe integer representation in JS is 2^53 - 1.\n // eslint-disable-next-line @typescript-eslint/no-loss-of-precision\n return [hashVal / 0xfffffffffffffff, true];\n }\n}\nexports.default = Bucketer;\n//# sourceMappingURL=Bucketer.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getBucketBy = exports.getOffVariation = exports.getVariation = void 0;\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst EvalResult_1 = require(\"./EvalResult\");\nconst { ErrorKinds } = js_sdk_common_1.internal;\nconst KEY_ATTR_REF = new js_sdk_common_1.AttributeReference('key');\n/**\n * Attempt to get an evaluation result for the specific variation/flag combination.\n * @param flag The flag to get a variation from.\n * @param index The index of the flag.\n * @param reason The initial evaluation reason. If there is a valid variation, then this reason\n * will be returned in the EvalResult.\n * @returns An evaluation result containing the successful evaluation, or an error if there is\n * a problem accessing the variation.\n *\n * @internal\n */\nfunction getVariation(flag, index, reason) {\n if (js_sdk_common_1.TypeValidators.Number.is(index) && index >= 0 && index < flag.variations.length) {\n return EvalResult_1.default.forSuccess(flag.variations[index], reason, index);\n }\n return EvalResult_1.default.forError(ErrorKinds.MalformedFlag, 'Invalid variation index in flag');\n}\nexports.getVariation = getVariation;\n/**\n * Attempt to get an off result for the specified flag.\n * @param flag The flag to get the off variation for.\n * @param reason The initial reason for the evaluation result.\n * @returns A successful evaluation result, or an error result if there is a problem accessing\n * the off variation. Flags which do not have an off variation specified will get a `null` flag\n * value with an `undefined` variation.\n *\n * @internal\n */\nfunction getOffVariation(flag, reason) {\n if (!js_sdk_common_1.TypeValidators.Number.is(flag.offVariation)) {\n return EvalResult_1.default.forSuccess(null, reason);\n }\n return getVariation(flag, flag.offVariation, reason);\n}\nexports.getOffVariation = getOffVariation;\nfunction getBucketBy(isExperiment, bucketByAttributeReference) {\n var _a;\n return (_a = (isExperiment ? undefined : bucketByAttributeReference)) !== null && _a !== void 0 ? _a : KEY_ATTR_REF;\n}\nexports.getBucketBy = getBucketBy;\n//# sourceMappingURL=variations.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst collection_1 = require(\"./collection\");\nconst Reasons_1 = require(\"./Reasons\");\nconst variations_1 = require(\"./variations\");\nfunction evalTarget(flag, target, context) {\n const contextKey = context.key(target.contextKind);\n if (contextKey !== undefined) {\n const found = target.values.indexOf(contextKey) >= 0;\n if (found) {\n return (0, variations_1.getVariation)(flag, target.variation, Reasons_1.default.TargetMatch);\n }\n }\n return undefined;\n}\n/**\n * Evaluate the targets of the specified flag against the given context.\n * @param flag The flag to evaluate targets for.\n * @param context The context to evaluate those targets against.\n * @returns An evaluation result if there is a target match/error or undefined if there is not.\n *\n * @internal\n */\nfunction evalTargets(flag, context) {\n var _a;\n if (!((_a = flag.contextTargets) === null || _a === void 0 ? void 0 : _a.length)) {\n // There are not context targets, so we are going to evaluate the user targets.\n return (0, collection_1.firstResult)(flag.targets, (target) => evalTarget(flag, target, context));\n }\n return (0, collection_1.firstResult)(flag.contextTargets, (target) => {\n if (!target.contextKind || target.contextKind === js_sdk_common_1.Context.UserKind) {\n // When a context target is for a user, then use a user target with the same variation.\n const userTarget = (flag.targets || []).find((ut) => ut.variation === target.variation);\n if (userTarget) {\n return evalTarget(flag, userTarget, context);\n }\n return undefined;\n }\n return evalTarget(flag, target, context);\n });\n}\nexports.default = evalTargets;\n//# sourceMappingURL=evalTargets.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @internal\n */\nfunction makeBigSegmentRef(segment) {\n // The format of Big Segment references is independent of what store implementation is being\n // used; the store implementation receives only this string and does not know the details of\n // the data model. The Relay Proxy will use the same format when writing to the store.\n return `${segment.key}.g${segment.generation}`;\n}\nexports.default = makeBigSegmentRef;\n//# sourceMappingURL=makeBigSegmentRef.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst semver_1 = require(\"semver\");\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst VERSION_COMPONENTS_REGEX = /^\\d+(\\.\\d+)?(\\.\\d+)?/;\nfunction parseSemver(input) {\n // A leading 'v' is not supported by the standard, but may be by the semver library.\n if (js_sdk_common_1.TypeValidators.String.is(input) && !input.startsWith('v')) {\n // If the input is able to be parsed, then return that.\n const parsed = (0, semver_1.parse)(input);\n if (parsed) {\n return parsed;\n }\n // If not, then we are going to make some exceptions to the format.\n // Specifically semver requires 3 components, but we allow versions with\n // less. For instance we allow '1' to be equivalent to '1.0.0'.\n const components = VERSION_COMPONENTS_REGEX.exec(input);\n if (components) {\n let transformed = components[0];\n // Start after the match.\n for (let i = 1; i < components.length; i += 1) {\n // The regex will return a match followed by each group.\n // Unmatched groups are 'undefined'.\n // So we will always have 3 entries, the match and 2 groups.\n // For each missing group we need to append a '.0' until we have the\n // standard 3.\n if (components[i] === undefined) {\n transformed += '.0';\n }\n }\n // If the original version contains pre-release information like '-beta.1',\n // then this will re-incorporate that into the string.\n transformed += input.substring(components[0].length);\n return (0, semver_1.parse)(transformed);\n }\n }\n return null;\n}\nfunction semVerOperator(fn) {\n return (a, b) => {\n const aVer = parseSemver(a);\n const bVer = parseSemver(b);\n return !!(aVer && bVer && fn(aVer, bVer));\n };\n}\nfunction makeOperator(fn, validator, converter) {\n return (a, b) => {\n if (validator.is(a) && validator.is(b)) {\n if (converter) {\n return fn(converter(a), converter(b));\n }\n return fn(a, b);\n }\n return false;\n };\n}\nfunction parseDate(input) {\n // Before calling this function we know the value is a date in a number\n // or as a string.\n if (typeof input === 'number') {\n return input;\n }\n return Date.parse(input);\n}\nfunction safeRegexMatch(pattern, value) {\n try {\n return new RegExp(pattern).test(value);\n }\n catch (_a) {\n return false;\n }\n}\nconst operators = {\n in: (a, b) => a === b,\n endsWith: makeOperator((a, b) => a.endsWith(b), js_sdk_common_1.TypeValidators.String),\n startsWith: makeOperator((a, b) => a.startsWith(b), js_sdk_common_1.TypeValidators.String),\n matches: makeOperator((value, pattern) => safeRegexMatch(pattern, value), js_sdk_common_1.TypeValidators.String),\n contains: makeOperator((a, b) => a.indexOf(b) > -1, js_sdk_common_1.TypeValidators.String),\n lessThan: makeOperator((a, b) => a < b, js_sdk_common_1.TypeValidators.Number),\n lessThanOrEqual: makeOperator((a, b) => a <= b, js_sdk_common_1.TypeValidators.Number),\n greaterThan: makeOperator((a, b) => a > b, js_sdk_common_1.TypeValidators.Number),\n greaterThanOrEqual: makeOperator((a, b) => a >= b, js_sdk_common_1.TypeValidators.Number),\n before: makeOperator((a, b) => a < b, js_sdk_common_1.TypeValidators.Date, parseDate),\n after: makeOperator((a, b) => a > b, js_sdk_common_1.TypeValidators.Date, parseDate),\n semVerEqual: semVerOperator((a, b) => a.compare(b) === 0),\n semVerLessThan: semVerOperator((a, b) => a.compare(b) < 0),\n semVerGreaterThan: semVerOperator((a, b) => a.compare(b) > 0),\n};\n/**\n * Allows checking if a specific operator is defined and allows execution of an operator on data.\n *\n * @internal\n */\nclass Operators {\n static is(op) {\n return Object.prototype.hasOwnProperty.call(operators, op);\n }\n static execute(op, a, b) {\n var _a, _b;\n return (_b = (_a = operators[op]) === null || _a === void 0 ? void 0 : _a.call(operators, a, b)) !== null && _b !== void 0 ? _b : false;\n }\n}\nexports.default = Operators;\n//# sourceMappingURL=Operations.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.maybeNegate = void 0;\nconst Operations_1 = require(\"./Operations\");\nfunction maybeNegate(clause, value) {\n if (clause.negate) {\n return !value;\n }\n return value;\n}\nexports.maybeNegate = maybeNegate;\nfunction matchAny(op, value, values) {\n return values.some((testValue) => Operations_1.default.execute(op, value, testValue));\n}\n/**\n * Match a clause against a context.\n * @param clause The clause to match against a context.\n * @param context The context to match.\n * @returns True if the clause matches.\n *\n * @internal\n */\nfunction matchClauseWithoutSegmentOperations(clause, context) {\n const contextValue = context.valueForKind(clause.attributeReference, clause.contextKind);\n if (contextValue === null || contextValue === undefined) {\n return false;\n }\n if (Array.isArray(contextValue)) {\n return maybeNegate(clause, contextValue.some((value) => matchAny(clause.op, value, clause.values)));\n }\n return maybeNegate(clause, matchAny(clause.op, contextValue, clause.values));\n}\nexports.default = matchClauseWithoutSegmentOperations;\n//# sourceMappingURL=matchClause.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nfunction segmentSearch(context, contextTargets, userTargets, userTargetSet) {\n if (contextTargets) {\n for (let targetIndex = 0; targetIndex < contextTargets.length; targetIndex += 1) {\n const target = contextTargets[targetIndex];\n const key = context.key(target.contextKind);\n if (key) {\n if (target.generated_valuesSet) {\n // Only check generated_valuesSet if present.\n if (target.generated_valuesSet.has(key)) {\n return true;\n }\n }\n else if (target.values.includes(key)) {\n return true;\n }\n }\n }\n }\n if (userTargetSet) {\n const userKey = context.key('user');\n if (userKey) {\n if (userTargetSet.has(userKey)) {\n return true;\n }\n }\n }\n else if (userTargets) {\n const userKey = context.key('user');\n if (userKey) {\n if (userTargets.includes(userKey)) {\n return true;\n }\n }\n }\n return false;\n}\nfunction matchSegmentTargets(segment, context) {\n const included = segmentSearch(context, segment.includedContexts, segment.included, segment.generated_includedSet);\n if (included) {\n return true;\n }\n const excluded = segmentSearch(context, segment.excludedContexts, segment.excluded, segment.generated_excludedSet);\n if (excluded) {\n // The match was an exclusion, so it should be negated.\n return !excluded;\n }\n return undefined;\n}\nexports.default = matchSegmentTargets;\n//# sourceMappingURL=matchSegmentTargets.js.map","\"use strict\";\n/* eslint-disable class-methods-use-this */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/* eslint-disable max-classes-per-file */\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst Bucketer_1 = require(\"./Bucketer\");\nconst collection_1 = require(\"./collection\");\nconst EvalResult_1 = require(\"./EvalResult\");\nconst evalTargets_1 = require(\"./evalTargets\");\nconst makeBigSegmentRef_1 = require(\"./makeBigSegmentRef\");\nconst matchClause_1 = require(\"./matchClause\");\nconst matchSegmentTargets_1 = require(\"./matchSegmentTargets\");\nconst Reasons_1 = require(\"./Reasons\");\nconst variations_1 = require(\"./variations\");\nconst { ErrorKinds } = js_sdk_common_1.internal;\nconst bigSegmentsStatusPriority = {\n HEALTHY: 1,\n STALE: 2,\n STORE_ERROR: 3,\n NOT_CONFIGURED: 4,\n};\nfunction getBigSegmentsStatusPriority(status) {\n if (status !== undefined) {\n return bigSegmentsStatusPriority[status] || 0;\n }\n return 0;\n}\n/**\n * Given two big segment statuses return the one with the higher priority.\n * @returns The status with the higher priority.\n */\nfunction computeUpdatedBigSegmentsStatus(old, latest) {\n if (old !== undefined &&\n getBigSegmentsStatusPriority(old) > getBigSegmentsStatusPriority(latest)) {\n return old;\n }\n return latest;\n}\nfunction makeMatch(match) {\n return { error: false, isMatch: match, result: undefined };\n}\nfunction makeError(result) {\n return { error: true, isMatch: false, result };\n}\n/**\n * @internal\n */\nclass Evaluator {\n constructor(platform, queries) {\n this._queries = queries;\n this._bucketer = new Bucketer_1.default(platform.crypto);\n }\n async evaluate(flag, context, eventFactory) {\n return new Promise((resolve) => {\n this.evaluateCb(flag, context, resolve, eventFactory);\n });\n }\n evaluateCb(flag, context, cb, eventFactory) {\n const state = {};\n this._evaluateInternal(flag, context, state, [], (res) => {\n if (state.bigSegmentsStatus) {\n res.detail.reason = Object.assign(Object.assign({}, res.detail.reason), { bigSegmentsStatus: state.bigSegmentsStatus });\n }\n if (state.prerequisites) {\n res.prerequisites = state.prerequisites;\n }\n res.events = state.events;\n cb(res);\n }, true, eventFactory);\n }\n /**\n * Evaluate the given flag against the given context. This internal method is entered\n * initially from the external evaluation method, but may be recursively executed during\n * prerequisite evaluations.\n * @param flag The flag to evaluate.\n * @param context The context to evaluate the flag against.\n * @param state The current evaluation state.\n * @param visitedFlags The flags that have been visited during this evaluation.\n * This is not part of the state, because it needs to be forked during prerequisite evaluations.\n * @param topLevel True when this function is being called in the direct evaluation of a flag,\n * versus the evaluataion of a prerequisite.\n */\n _evaluateInternal(flag, context, state, visitedFlags, cb, topLevel, eventFactory) {\n if (!flag.on) {\n cb((0, variations_1.getOffVariation)(flag, Reasons_1.default.Off));\n return;\n }\n this._checkPrerequisites(flag, context, state, visitedFlags, (res) => {\n // If there is a prereq result, then prereqs have failed, or there was\n // an error.\n if (res) {\n cb(res);\n return;\n }\n const targetRes = (0, evalTargets_1.default)(flag, context);\n if (targetRes) {\n cb(targetRes);\n return;\n }\n this._evaluateRules(flag, context, state, (evalRes) => {\n if (evalRes) {\n cb(evalRes);\n return;\n }\n cb(this._variationForContext(flag.fallthrough, context, flag, Reasons_1.default.Fallthrough));\n });\n }, topLevel, eventFactory);\n }\n /**\n * Evaluate the prerequisite flags for the given flag.\n * @param flag The flag to evaluate prerequisites for.\n * @param context The context to evaluate the prerequisites against.\n * @param state used to accumulate prerequisite events.\n * @param visitedFlags Used to detect cycles in prerequisite evaluation.\n * @param cb A callback which is executed when prerequisite checks are complete it is called with\n * an {@link EvalResult} containing an error result or `undefined` if the prerequisites\n * are met.\n * @param topLevel True when this function is being called in the direct evaluation of a flag,\n * versus the evaluataion of a prerequisite.\n */\n _checkPrerequisites(flag, context, state, visitedFlags, cb, topLevel, eventFactory) {\n let prereqResult;\n if (!flag.prerequisites || !flag.prerequisites.length) {\n cb(undefined);\n return;\n }\n // On any error conditions the prereq result will be set, so we do not need\n // the result of the series evaluation.\n (0, collection_1.allSeriesAsync)(flag.prerequisites, (prereq, _index, iterCb) => {\n if (visitedFlags.indexOf(prereq.key) !== -1) {\n prereqResult = EvalResult_1.default.forError(ErrorKinds.MalformedFlag, `Prerequisite of ${flag.key} causing a circular reference.` +\n ' This is probably a temporary condition due to an incomplete update.');\n iterCb(true);\n return;\n }\n const updatedVisitedFlags = [...visitedFlags, prereq.key];\n this._queries.getFlag(prereq.key, (prereqFlag) => {\n if (!prereqFlag) {\n prereqResult = (0, variations_1.getOffVariation)(flag, Reasons_1.default.prerequisiteFailed(prereq.key));\n iterCb(false);\n return;\n }\n this._evaluateInternal(prereqFlag, context, state, updatedVisitedFlags, (res) => {\n var _a, _b;\n // eslint-disable-next-line no-param-reassign\n (_a = state.events) !== null && _a !== void 0 ? _a : (state.events = []);\n if (topLevel) {\n // eslint-disable-next-line no-param-reassign\n (_b = state.prerequisites) !== null && _b !== void 0 ? _b : (state.prerequisites = []);\n state.prerequisites.push(prereqFlag.key);\n }\n if (eventFactory) {\n state.events.push(eventFactory.evalEventServer(prereqFlag, context, res.detail, null, flag));\n }\n if (res.isError) {\n prereqResult = res;\n return iterCb(false);\n }\n if (res.isOff || res.detail.variationIndex !== prereq.variation) {\n prereqResult = (0, variations_1.getOffVariation)(flag, Reasons_1.default.prerequisiteFailed(prereq.key));\n return iterCb(false);\n }\n return iterCb(true);\n }, false, // topLevel false evaluating the prerequisite.\n eventFactory);\n });\n }, () => {\n cb(prereqResult);\n });\n }\n /**\n * Evaluate the rules for a flag and return an {@link EvalResult} if there is\n * a match or error.\n * @param flag The flag to evaluate rules for.\n * @param context The context to evaluate the rules against.\n * @param state The current evaluation state.\n * @param cb Callback called when rule evaluation is complete, it will be called with either\n * an {@link EvalResult} or 'undefined'.\n */\n _evaluateRules(flag, context, state, cb) {\n let ruleResult;\n (0, collection_1.firstSeriesAsync)(flag.rules, (rule, ruleIndex, iterCb) => {\n this._ruleMatchContext(flag, rule, ruleIndex, context, state, [], (res) => {\n ruleResult = res;\n iterCb(!!res);\n });\n }, () => cb(ruleResult));\n }\n _clauseMatchContext(clause, context, segmentsVisited, state, cb) {\n let errorResult;\n if (clause.op === 'segmentMatch') {\n (0, collection_1.firstSeriesAsync)(clause.values, (value, _index, iterCb) => {\n this._queries.getSegment(value, (segment) => {\n if (segment) {\n if (segmentsVisited.includes(segment.key)) {\n errorResult = EvalResult_1.default.forError(ErrorKinds.MalformedFlag, `Segment rule referencing segment ${segment.key} caused a circular reference. ` +\n 'This is probably a temporary condition due to an incomplete update');\n // There was an error, so stop checking further segments.\n iterCb(true);\n return;\n }\n const newVisited = [...segmentsVisited, segment === null || segment === void 0 ? void 0 : segment.key];\n this.segmentMatchContext(segment, context, state, newVisited, (res) => {\n if (res.error) {\n errorResult = res.result;\n }\n iterCb(res.error || res.isMatch);\n });\n }\n else {\n iterCb(false);\n }\n });\n }, (match) => {\n if (errorResult) {\n return cb(makeError(errorResult));\n }\n return cb(makeMatch((0, matchClause_1.maybeNegate)(clause, match)));\n });\n return;\n }\n // This is after segment matching, which does not use the reference.\n if (!clause.attributeReference.isValid) {\n cb(makeError(EvalResult_1.default.forError(ErrorKinds.MalformedFlag, 'Invalid attribute reference in clause')));\n return;\n }\n cb(makeMatch((0, matchClause_1.default)(clause, context)));\n }\n /**\n * Evaluate a flag rule against the given context.\n * @param flag The flag the rule is part of.\n * @param rule The rule to match.\n * @param rule The index of the rule.\n * @param context The context to match the rule against.\n * @param cb Called when matching is complete with an {@link EvalResult} or `undefined` if there\n * are no matches or errors.\n */\n _ruleMatchContext(flag, rule, ruleIndex, context, state, segmentsVisited, cb) {\n if (!rule.clauses) {\n cb(undefined);\n return;\n }\n let errorResult;\n (0, collection_1.allSeriesAsync)(rule.clauses, (clause, _index, iterCb) => {\n this._clauseMatchContext(clause, context, segmentsVisited, state, (res) => {\n errorResult = res.result;\n return iterCb(res.error || res.isMatch);\n });\n }, (match) => {\n if (errorResult) {\n return cb(errorResult);\n }\n if (match) {\n return cb(this._variationForContext(rule, context, flag, Reasons_1.default.ruleMatch(rule.id, ruleIndex)));\n }\n return cb(undefined);\n });\n }\n _variationForContext(varOrRollout, context, flag, reason) {\n if (varOrRollout === undefined) {\n // By spec this field should be defined, but better to be overly cautious.\n return EvalResult_1.default.forError(ErrorKinds.MalformedFlag, 'Fallthrough variation undefined');\n }\n if (varOrRollout.variation !== undefined) {\n // 0 would be false.\n return (0, variations_1.getVariation)(flag, varOrRollout.variation, reason);\n }\n if (varOrRollout.rollout) {\n const { rollout } = varOrRollout;\n const { variations } = rollout;\n const isExperiment = rollout.kind === 'experiment';\n if (variations && variations.length) {\n const bucketBy = (0, variations_1.getBucketBy)(isExperiment, rollout.bucketByAttributeReference);\n if (!bucketBy.isValid) {\n return EvalResult_1.default.forError(ErrorKinds.MalformedFlag, 'Invalid attribute reference for bucketBy in rollout');\n }\n const [bucket, hadContext] = this._bucketer.bucket(context, flag.key, bucketBy, flag.salt || '', rollout.contextKind, rollout.seed);\n const updatedReason = Object.assign({}, reason);\n let sum = 0;\n for (let i = 0; i < variations.length; i += 1) {\n const variate = variations[i];\n sum += variate.weight / 100000.0;\n if (bucket < sum) {\n if (isExperiment && hadContext && !variate.untracked) {\n updatedReason.inExperiment = true;\n }\n return (0, variations_1.getVariation)(flag, variate.variation, updatedReason);\n }\n }\n // The context's bucket value was greater than or equal to the end of\n // the last bucket. This could happen due to a rounding error, or due to\n // the fact that we are scaling to 100000 rather than 99999, or the flag\n // data could contain buckets that don't actually add up to 100000.\n // Rather than returning an error in this case (or changing the scaling,\n // which would potentially change the results for *all* users), we will\n // simply put the context in the last bucket.\n const lastVariate = variations[variations.length - 1];\n if (isExperiment && !lastVariate.untracked) {\n updatedReason.inExperiment = true;\n }\n return (0, variations_1.getVariation)(flag, lastVariate.variation, updatedReason);\n }\n }\n return EvalResult_1.default.forError(ErrorKinds.MalformedFlag, 'Variation/rollout object with no variation or rollout');\n }\n segmentRuleMatchContext(segment, rule, context, state, segmentsVisited, cb) {\n let errorResult;\n (0, collection_1.allSeriesAsync)(rule.clauses, (clause, _index, iterCb) => {\n this._clauseMatchContext(clause, context, segmentsVisited, state, (res) => {\n errorResult = res.result;\n iterCb(res.error || res.isMatch);\n });\n }, (match) => {\n if (errorResult) {\n return cb(makeError(errorResult));\n }\n if (match) {\n if (rule.weight === undefined) {\n return cb(makeMatch(match));\n }\n const bucketBy = (0, variations_1.getBucketBy)(false, rule.bucketByAttributeReference);\n if (!bucketBy.isValid) {\n return cb(makeError(EvalResult_1.default.forError(ErrorKinds.MalformedFlag, 'Invalid attribute reference in clause')));\n }\n const [bucket] = this._bucketer.bucket(context, segment.key, bucketBy, segment.salt || '', rule.rolloutContextKind);\n return cb(makeMatch(bucket < rule.weight / 100000.0));\n }\n return cb(makeMatch(false));\n });\n }\n // eslint-disable-next-line class-methods-use-this\n simpleSegmentMatchContext(segment, context, state, segmentsVisited, cb) {\n if (!segment.unbounded) {\n const includeExclude = (0, matchSegmentTargets_1.default)(segment, context);\n if (includeExclude !== undefined) {\n cb(makeMatch(includeExclude));\n return;\n }\n }\n let evalResult;\n (0, collection_1.firstSeriesAsync)(segment.rules, (rule, _index, iterCb) => {\n this.segmentRuleMatchContext(segment, rule, context, state, segmentsVisited, (res) => {\n evalResult = res.result;\n return iterCb(res.error || res.isMatch);\n });\n }, (matched) => {\n if (evalResult) {\n return cb(makeError(evalResult));\n }\n return cb(makeMatch(matched));\n });\n }\n segmentMatchContext(segment, context, state, segmentsVisited, cb) {\n if (!segment.unbounded) {\n this.simpleSegmentMatchContext(segment, context, state, segmentsVisited, cb);\n return;\n }\n const bigSegmentKind = segment.unboundedContextKind || 'user';\n const keyForBigSegment = context.key(bigSegmentKind);\n if (!keyForBigSegment) {\n cb(makeMatch(false));\n return;\n }\n if (!segment.generation) {\n // Big Segment queries can only be done if the generation is known. If it's unset,\n // that probably means the data store was populated by an older SDK that doesn't know\n // about the generation property and therefore dropped it from the JSON data. We'll treat\n // that as a \"not configured\" condition.\n // eslint-disable-next-line no-param-reassign\n state.bigSegmentsStatus = computeUpdatedBigSegmentsStatus(state.bigSegmentsStatus, 'NOT_CONFIGURED');\n cb(makeMatch(false));\n return;\n }\n if (state.bigSegmentsMembership && state.bigSegmentsMembership[keyForBigSegment]) {\n // We've already done the query at some point during the flag evaluation and stored\n // the result (if any) in stateOut.bigSegmentsMembership, so we don't need to do it\n // again. Even if multiple Big Segments are being referenced, the membership includes\n // *all* of the user's segment memberships.\n this.bigSegmentMatchContext(state.bigSegmentsMembership[keyForBigSegment], segment, context, state).then(cb);\n return;\n }\n this._queries.getBigSegmentsMembership(keyForBigSegment).then((result) => {\n // eslint-disable-next-line no-param-reassign\n state.bigSegmentsMembership = state.bigSegmentsMembership || {};\n if (result) {\n const [membership, status] = result;\n // eslint-disable-next-line no-param-reassign\n state.bigSegmentsMembership[keyForBigSegment] = membership;\n // eslint-disable-next-line no-param-reassign\n state.bigSegmentsStatus = computeUpdatedBigSegmentsStatus(state.bigSegmentsStatus, status);\n }\n else {\n // eslint-disable-next-line no-param-reassign\n state.bigSegmentsStatus = computeUpdatedBigSegmentsStatus(state.bigSegmentsStatus, 'NOT_CONFIGURED');\n }\n /* eslint-enable no-param-reassign */\n this.bigSegmentMatchContext(state.bigSegmentsMembership[keyForBigSegment], segment, context, state).then(cb);\n });\n }\n bigSegmentMatchContext(membership, segment, context, state) {\n const segmentRef = (0, makeBigSegmentRef_1.default)(segment);\n const included = membership === null || membership === void 0 ? void 0 : membership[segmentRef];\n return new Promise((resolve) => {\n // Typically null is not checked because we filter it from the data\n // we get in flag updates. Here it is checked because big segment data\n // will be contingent on the store that implements it.\n if (included !== undefined && included !== null) {\n resolve(makeMatch(included));\n return;\n }\n this.simpleSegmentMatchContext(segment, context, state, [], resolve);\n });\n }\n}\nexports.default = Evaluator;\n//# sourceMappingURL=Evaluator.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst LruCache_1 = require(\"../cache/LruCache\");\nclass ContextDeduplicator {\n constructor(options) {\n this._contextKeysCache = new LruCache_1.default({ max: options.contextKeysCapacity });\n this.flushInterval = options.contextKeysFlushInterval;\n }\n processContext(context) {\n const { canonicalKey } = context;\n const inCache = this._contextKeysCache.get(canonicalKey);\n this._contextKeysCache.set(canonicalKey, true);\n // If it is in the cache, then we do not want to add an event.\n return !inCache;\n }\n flush() {\n this._contextKeysCache.clear();\n }\n}\nexports.default = ContextDeduplicator;\n//# sourceMappingURL=ContextDeduplicator.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @internal\n */\nfunction isExperiment(flag, reason) {\n if (reason) {\n // If the reason says we're in an experiment, we are. Otherwise, apply\n // the legacy rule exclusion logic.\n if (reason.inExperiment) {\n return true;\n }\n switch (reason.kind) {\n case 'RULE_MATCH': {\n const index = reason.ruleIndex;\n if (index !== undefined) {\n const rules = flag.rules || [];\n return index >= 0 && index < rules.length && !!rules[index].trackEvents;\n }\n break;\n }\n case 'FALLTHROUGH':\n return !!flag.trackEventsFallthrough;\n default:\n // No action needed.\n }\n }\n return false;\n}\nexports.default = isExperiment;\n//# sourceMappingURL=isExperiment.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst isExperiment_1 = require(\"./isExperiment\");\n/**\n * @internal\n */\nclass EventFactory extends js_sdk_common_1.internal.EventFactoryBase {\n evalEventServer(flag, context, detail, defaultVal, prereqOfFlag) {\n var _a;\n const addExperimentData = (0, isExperiment_1.default)(flag, detail.reason);\n return super.evalEvent({\n addExperimentData,\n context,\n debugEventsUntilDate: flag.debugEventsUntilDate,\n defaultVal,\n excludeFromSummaries: flag.excludeFromSummaries,\n flagKey: flag.key,\n prereqOfFlagKey: prereqOfFlag === null || prereqOfFlag === void 0 ? void 0 : prereqOfFlag.key,\n reason: detail.reason,\n samplingRatio: flag.samplingRatio,\n trackEvents: flag.trackEvents || addExperimentData,\n value: detail.value,\n variation: (_a = detail.variationIndex) !== null && _a !== void 0 ? _a : undefined,\n version: flag.version,\n });\n }\n}\nexports.default = EventFactory;\n//# sourceMappingURL=EventFactory.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass FlagsStateBuilder {\n constructor(_valid, _withReasons) {\n this._valid = _valid;\n this._withReasons = _withReasons;\n this._flagValues = {};\n this._flagMetadata = {};\n }\n addFlag(flag, value, variation, reason, trackEvents, trackReason, detailsOnlyIfTracked, prerequisites) {\n this._flagValues[flag.key] = value;\n const meta = {};\n if (variation !== undefined) {\n meta.variation = variation;\n }\n const omitDetails = detailsOnlyIfTracked &&\n !trackEvents &&\n !trackReason &&\n flag.debugEventsUntilDate === undefined; // 0 probably doesn't matter.\n if (!omitDetails) {\n meta.version = flag.version;\n }\n if (reason && (trackReason || (this._withReasons && !omitDetails))) {\n meta.reason = reason;\n }\n if (trackEvents) {\n meta.trackEvents = true;\n }\n if (trackReason) {\n meta.trackReason = true;\n }\n if (flag.debugEventsUntilDate !== undefined) {\n meta.debugEventsUntilDate = flag.debugEventsUntilDate;\n }\n if (prerequisites && prerequisites.length) {\n meta.prerequisites = prerequisites;\n }\n this._flagMetadata[flag.key] = meta;\n }\n build() {\n return {\n valid: this._valid,\n allValues: () => this._flagValues,\n getFlagValue: (key) => this._flagValues[key],\n getFlagReason: (key) => { var _a; return (_a = (this._flagMetadata[key] ? this._flagMetadata[key].reason : null)) !== null && _a !== void 0 ? _a : null; },\n toJSON: () => (Object.assign(Object.assign({}, this._flagValues), { $flagsState: this._flagMetadata, $valid: this._valid })),\n };\n }\n}\nexports.default = FlagsStateBuilder;\n//# sourceMappingURL=FlagsStateBuilder.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst BEFORE_EVALUATION_STAGE_NAME = 'beforeEvaluation';\nconst AFTER_EVALUATION_STAGE_NAME = 'afterEvaluation';\nconst UNKNOWN_HOOK_NAME = 'unknown hook';\nclass HookRunner {\n constructor(_logger, hooks) {\n this._logger = _logger;\n this._hooks = [];\n this._hooks.push(...hooks);\n }\n async withEvaluationSeries(key, context, defaultValue, methodName, method, environmentId) {\n // This early return is here to avoid the extra async/await associated with\n // using withHooksDataWithDetail.\n if (this._hooks.length === 0) {\n return method();\n }\n return this.withEvaluationSeriesExtraDetail(key, context, defaultValue, methodName, async () => {\n const detail = await method();\n return { detail };\n }, environmentId).then(({ detail }) => detail);\n }\n /**\n * This function allows extra information to be returned with the detail for situations like\n * migrations where a tracker is returned with the detail.\n */\n async withEvaluationSeriesExtraDetail(key, context, defaultValue, methodName, method, environmentId) {\n if (this._hooks.length === 0) {\n return method();\n }\n const { hooks, hookContext } = this._prepareHooks(key, context, defaultValue, methodName, environmentId);\n const hookData = this._executeBeforeEvaluation(hooks, hookContext);\n const result = await method();\n this._executeAfterEvaluation(hooks, hookContext, hookData, result.detail);\n return result;\n }\n _tryExecuteStage(method, hookName, stage) {\n var _a;\n try {\n return stage();\n }\n catch (err) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error(`An error was encountered in \"${method}\" of the \"${hookName}\" hook: ${err}`);\n return {};\n }\n }\n _hookName(hook) {\n var _a, _b;\n try {\n return (_a = hook === null || hook === void 0 ? void 0 : hook.getMetadata().name) !== null && _a !== void 0 ? _a : UNKNOWN_HOOK_NAME;\n }\n catch (_c) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error(`Exception thrown getting metadata for hook. Unable to get hook name.`);\n return UNKNOWN_HOOK_NAME;\n }\n }\n _executeAfterEvaluation(hooks, hookContext, updatedData, result) {\n var _a;\n // This iterates in reverse, versus reversing a shallow copy of the hooks,\n // for efficiency.\n for (let hookIndex = hooks.length - 1; hookIndex >= 0; hookIndex -= 1) {\n const hook = hooks[hookIndex];\n const data = (_a = updatedData[hookIndex]) !== null && _a !== void 0 ? _a : {};\n this._tryExecuteStage(AFTER_EVALUATION_STAGE_NAME, this._hookName(hook), () => { var _a, _b; return (_b = (_a = hook === null || hook === void 0 ? void 0 : hook.afterEvaluation) === null || _a === void 0 ? void 0 : _a.call(hook, hookContext, data, result)) !== null && _b !== void 0 ? _b : {}; });\n }\n }\n _executeBeforeEvaluation(hooks, hookContext) {\n return hooks.map((hook) => this._tryExecuteStage(BEFORE_EVALUATION_STAGE_NAME, this._hookName(hook), () => { var _a, _b; return (_b = (_a = hook === null || hook === void 0 ? void 0 : hook.beforeEvaluation) === null || _a === void 0 ? void 0 : _a.call(hook, hookContext, {})) !== null && _b !== void 0 ? _b : {}; }));\n }\n _prepareHooks(key, context, defaultValue, methodName, environmentId) {\n // Copy the hooks to use a consistent set during evaluation. Hooks could be added and we want\n // to ensure all correct stages for any give hook execute. Not for instance the afterEvaluation\n // stage without beforeEvaluation having been called on that hook.\n const hooks = [...this._hooks];\n const hookContext = {\n flagKey: key,\n context,\n defaultValue,\n method: methodName,\n environmentId,\n };\n return { hooks, hookContext };\n }\n addHook(hook) {\n this._hooks.push(hook);\n }\n}\nexports.default = HookRunner;\n//# sourceMappingURL=HookRunner.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nfunction isOperation(value) {\n if (!js_sdk_common_1.TypeValidators.String.is(value)) {\n return false;\n }\n return value === 'read' || value === 'write';\n}\nfunction isLatencyMeasurement(value) {\n return value.key === 'latency_ms';\n}\nfunction isErrorMeasurement(value) {\n return value.key === 'error';\n}\nfunction isInvokedMeasurement(value) {\n return value.key === 'invoked';\n}\nfunction isConsistencyMeasurement(value) {\n return value.key === 'consistent';\n}\nfunction areValidNumbers(values) {\n const oldValue = values.old;\n const newValue = values.new;\n if (oldValue !== undefined && !js_sdk_common_1.TypeValidators.Number.is(oldValue)) {\n return false;\n }\n if (newValue !== undefined && !js_sdk_common_1.TypeValidators.Number.is(newValue)) {\n return false;\n }\n return true;\n}\nfunction areValidBooleans(values) {\n const oldValue = values.old;\n const newValue = values.new;\n if (oldValue !== undefined && !js_sdk_common_1.TypeValidators.Boolean.is(oldValue)) {\n return false;\n }\n if (newValue !== undefined && !js_sdk_common_1.TypeValidators.Boolean.is(newValue)) {\n return false;\n }\n return true;\n}\nfunction validateMeasurement(measurement) {\n // Here we are protecting ourselves from JS callers. TypeScript says that\n // it cannot be an empty string, but those using JS can do what they want.\n // @ts-ignore\n if (!js_sdk_common_1.TypeValidators.String.is(measurement.key) || measurement.key === '') {\n return undefined;\n }\n if (isLatencyMeasurement(measurement)) {\n if (!js_sdk_common_1.TypeValidators.Object.is(measurement.values)) {\n return undefined;\n }\n if (!areValidNumbers(measurement.values)) {\n return undefined;\n }\n return {\n key: measurement.key,\n values: {\n old: measurement.values.old,\n new: measurement.values.new,\n },\n };\n }\n if (isErrorMeasurement(measurement)) {\n if (!js_sdk_common_1.TypeValidators.Object.is(measurement.values)) {\n return undefined;\n }\n if (!areValidBooleans(measurement.values)) {\n return undefined;\n }\n return {\n key: measurement.key,\n values: {\n old: measurement.values.old,\n new: measurement.values.new,\n },\n };\n }\n if (isConsistencyMeasurement(measurement)) {\n if (!js_sdk_common_1.TypeValidators.Boolean.is(measurement.value) ||\n !js_sdk_common_1.TypeValidators.Number.is(measurement.samplingRatio)) {\n return undefined;\n }\n return {\n key: measurement.key,\n value: measurement.value,\n samplingRatio: measurement.samplingRatio,\n };\n }\n if (isInvokedMeasurement(measurement)) {\n if (!js_sdk_common_1.TypeValidators.Object.is(measurement.values)) {\n return undefined;\n }\n if (!areValidBooleans(measurement.values)) {\n return undefined;\n }\n return {\n key: measurement.key,\n values: {\n old: measurement.values.old,\n new: measurement.values.new,\n },\n };\n }\n // Not a supported measurement type.\n return undefined;\n}\nfunction validateMeasurements(measurements) {\n return measurements\n .map(validateMeasurement)\n .filter((value) => value !== undefined);\n}\nfunction validateEvaluation(evaluation) {\n if (!js_sdk_common_1.TypeValidators.String.is(evaluation.key) || evaluation.key === '') {\n return undefined;\n }\n if (!js_sdk_common_1.TypeValidators.Object.is(evaluation.reason)) {\n return undefined;\n }\n if (!js_sdk_common_1.TypeValidators.String.is(evaluation.reason.kind) || evaluation.reason.kind === '') {\n return undefined;\n }\n const validated = {\n key: evaluation.key,\n value: evaluation.value,\n default: evaluation.default,\n reason: {\n kind: evaluation.reason.kind,\n },\n };\n const inReason = evaluation.reason;\n const outReason = validated.reason;\n if (js_sdk_common_1.TypeValidators.String.is(inReason.errorKind)) {\n outReason.errorKind = inReason.errorKind;\n }\n if (js_sdk_common_1.TypeValidators.String.is(inReason.ruleId)) {\n outReason.ruleId = inReason.ruleId;\n }\n if (js_sdk_common_1.TypeValidators.String.is(inReason.prerequisiteKey)) {\n outReason.prerequisiteKey = inReason.prerequisiteKey;\n }\n if (js_sdk_common_1.TypeValidators.Boolean.is(inReason.inExperiment)) {\n outReason.inExperiment = inReason.inExperiment;\n }\n if (js_sdk_common_1.TypeValidators.Number.is(inReason.ruleIndex)) {\n outReason.ruleIndex = inReason.ruleIndex;\n }\n if (js_sdk_common_1.TypeValidators.String.is(inReason.bigSegmentsStatus)) {\n outReason.bigSegmentsStatus = inReason.bigSegmentsStatus;\n }\n if (evaluation.variation !== undefined && js_sdk_common_1.TypeValidators.Number.is(evaluation.variation)) {\n validated.variation = evaluation.variation;\n }\n if (evaluation.version !== undefined && js_sdk_common_1.TypeValidators.Number.is(evaluation.version)) {\n validated.version = evaluation.version;\n }\n return validated;\n}\n/**\n * Migration events can be generated directly in user code and may not follow the shape\n * expected by the TypeScript definitions. So we do some validation on these events, as well\n * as copying the data out of them, to reduce the amount of invalid data we may send.\n *\n * @param inEvent The event to process.\n * @returns An event, or undefined if it could not be converted.\n */\nfunction MigrationOpEventToInputEvent(inEvent) {\n var _a;\n // The sampling ratio is omitted and needs populated by the track migration method.\n if (inEvent.kind !== 'migration_op') {\n return undefined;\n }\n if (!isOperation(inEvent.operation)) {\n return undefined;\n }\n if (!js_sdk_common_1.TypeValidators.Number.is(inEvent.creationDate)) {\n return undefined;\n }\n const contextKeysOrContext = {};\n if (js_sdk_common_1.TypeValidators.Object.is(inEvent.context)) {\n const context = js_sdk_common_1.Context.fromLDContext(inEvent.context);\n if (context.valid) {\n contextKeysOrContext.context = context;\n }\n }\n else if (js_sdk_common_1.TypeValidators.Object.is(inEvent.contextKeys)) {\n if (Object.keys(inEvent.contextKeys).every((key) => js_sdk_common_1.TypeValidators.Kind.is(key)) &&\n Object.values(inEvent.contextKeys).every((value) => js_sdk_common_1.TypeValidators.String.is(value) && value !== '')) {\n contextKeysOrContext.contextKeys = Object.assign({}, inEvent.contextKeys);\n }\n }\n if (!contextKeysOrContext.context && !contextKeysOrContext.contextKeys) {\n return undefined;\n }\n const samplingRatio = (_a = inEvent.samplingRatio) !== null && _a !== void 0 ? _a : 1;\n if (!js_sdk_common_1.TypeValidators.Number.is(samplingRatio)) {\n return undefined;\n }\n const evaluation = validateEvaluation(inEvent.evaluation);\n if (!evaluation) {\n return undefined;\n }\n return Object.assign(Object.assign({ kind: inEvent.kind, operation: inEvent.operation, creationDate: inEvent.creationDate }, contextKeysOrContext), { measurements: validateMeasurements(inEvent.measurements), evaluation,\n samplingRatio });\n}\nexports.default = MigrationOpEventToInputEvent;\n//# sourceMappingURL=MigrationOpEventConversion.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst data_1 = require(\"./api/data\");\nfunction isPopulated(data) {\n return !Number.isNaN(data);\n}\nclass MigrationOpTracker {\n constructor(_flagKey, _context, _defaultStage, _stage, _reason, _checkRatio, _variation, _version, _samplingRatio, _logger) {\n this._flagKey = _flagKey;\n this._context = _context;\n this._defaultStage = _defaultStage;\n this._stage = _stage;\n this._reason = _reason;\n this._checkRatio = _checkRatio;\n this._variation = _variation;\n this._version = _version;\n this._samplingRatio = _samplingRatio;\n this._logger = _logger;\n this._errors = {\n old: false,\n new: false,\n };\n this._wasInvoked = {\n old: false,\n new: false,\n };\n this._consistencyCheck = data_1.LDConsistencyCheck.NotChecked;\n this._latencyMeasurement = {\n old: NaN,\n new: NaN,\n };\n }\n op(op) {\n this._operation = op;\n }\n error(origin) {\n this._errors[origin] = true;\n }\n consistency(check) {\n var _a, _b;\n if (js_sdk_common_1.internal.shouldSample((_a = this._checkRatio) !== null && _a !== void 0 ? _a : 1)) {\n try {\n const res = check();\n this._consistencyCheck = res\n ? data_1.LDConsistencyCheck.Consistent\n : data_1.LDConsistencyCheck.Inconsistent;\n }\n catch (exception) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error('Exception when executing consistency check function for migration' +\n ` '${this._flagKey}' the consistency check will not be included in the generated migration` +\n ` op event. Exception: ${exception}`);\n }\n }\n }\n latency(origin, value) {\n this._latencyMeasurement[origin] = value;\n }\n invoked(origin) {\n this._wasInvoked[origin] = true;\n }\n createEvent() {\n var _a, _b, _c, _d, _e;\n if (!js_sdk_common_1.TypeValidators.String.is(this._flagKey) || this._flagKey === '') {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error('The flag key for a migration operation must be a non-empty string.');\n return undefined;\n }\n if (!this._operation) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error('The operation must be set using \"op\" before an event can be created.');\n return undefined;\n }\n if (!js_sdk_common_1.Context.fromLDContext(this._context).valid) {\n (_c = this._logger) === null || _c === void 0 ? void 0 : _c.error('The migration was not done against a valid context and cannot generate an event.');\n return undefined;\n }\n if (!this._wasInvoked.old && !this._wasInvoked.new) {\n (_d = this._logger) === null || _d === void 0 ? void 0 : _d.error('The migration invoked neither the \"old\" or \"new\" implementation and' +\n 'an event cannot be generated');\n return undefined;\n }\n if (!this._measurementConsistencyCheck()) {\n return undefined;\n }\n const measurements = [];\n this._populateInvoked(measurements);\n this._populateConsistency(measurements);\n this._populateLatency(measurements);\n this._populateErrors(measurements);\n return {\n kind: 'migration_op',\n operation: this._operation,\n creationDate: Date.now(),\n context: this._context,\n evaluation: {\n key: this._flagKey,\n value: this._stage,\n default: this._defaultStage,\n reason: this._reason,\n variation: this._variation,\n version: this._version,\n },\n measurements,\n samplingRatio: (_e = this._samplingRatio) !== null && _e !== void 0 ? _e : 1,\n };\n }\n _logTag() {\n return `For migration ${this._operation}-${this._flagKey}:`;\n }\n _latencyConsistencyMessage(origin) {\n return `Latency measurement for \"${origin}\", but \"${origin}\" was not invoked.`;\n }\n _errorConsistencyMessage(origin) {\n return `Error occurred for \"${origin}\", but \"${origin}\" was not invoked.`;\n }\n _consistencyCheckConsistencyMessage(origin) {\n return (`Consistency check was done, but \"${origin}\" was not invoked.` +\n 'Both \"old\" and \"new\" must be invoked to do a consistency check.');\n }\n _checkOriginEventConsistency(origin) {\n var _a, _b, _c;\n if (this._wasInvoked[origin]) {\n return true;\n }\n // If the specific origin was not invoked, but it contains measurements, then\n // that is a problem. Check each measurement and log a message if it is present.\n if (!Number.isNaN(this._latencyMeasurement[origin])) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error(`${this._logTag()} ${this._latencyConsistencyMessage(origin)}`);\n return false;\n }\n if (this._errors[origin]) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error(`${this._logTag()} ${this._errorConsistencyMessage(origin)}`);\n return false;\n }\n if (this._consistencyCheck !== data_1.LDConsistencyCheck.NotChecked) {\n (_c = this._logger) === null || _c === void 0 ? void 0 : _c.error(`${this._logTag()} ${this._consistencyCheckConsistencyMessage(origin)}`);\n return false;\n }\n return true;\n }\n /**\n * Check that the latency, error, consistency and invoked measurements are self-consistent.\n */\n _measurementConsistencyCheck() {\n return this._checkOriginEventConsistency('old') && this._checkOriginEventConsistency('new');\n }\n _populateInvoked(measurements) {\n var _a;\n const measurement = {\n key: 'invoked',\n values: {},\n };\n if (!this._wasInvoked.old && !this._wasInvoked.new) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.error('Migration op completed without executing any origins (old/new).');\n }\n if (this._wasInvoked.old) {\n measurement.values.old = true;\n }\n if (this._wasInvoked.new) {\n measurement.values.new = true;\n }\n measurements.push(measurement);\n }\n _populateConsistency(measurements) {\n var _a;\n if (this._consistencyCheck !== undefined &&\n this._consistencyCheck !== data_1.LDConsistencyCheck.NotChecked) {\n measurements.push({\n key: 'consistent',\n value: this._consistencyCheck === data_1.LDConsistencyCheck.Consistent,\n samplingRatio: (_a = this._checkRatio) !== null && _a !== void 0 ? _a : 1,\n });\n }\n }\n _populateErrors(measurements) {\n if (this._errors.new || this._errors.old) {\n const measurement = {\n key: 'error',\n values: {},\n };\n if (this._errors.new) {\n measurement.values.new = true;\n }\n if (this._errors.old) {\n measurement.values.old = true;\n }\n measurements.push(measurement);\n }\n }\n _populateLatency(measurements) {\n const newIsPopulated = isPopulated(this._latencyMeasurement.new);\n const oldIsPopulated = isPopulated(this._latencyMeasurement.old);\n if (newIsPopulated || oldIsPopulated) {\n const values = {};\n if (newIsPopulated) {\n values.new = this._latencyMeasurement.new;\n }\n if (oldIsPopulated) {\n values.old = this._latencyMeasurement.old;\n }\n measurements.push({\n key: 'latency_ms',\n values,\n });\n }\n }\n}\nexports.default = MigrationOpTracker;\n//# sourceMappingURL=MigrationOpTracker.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/* eslint-disable class-methods-use-this */\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst api_1 = require(\"./api\");\nconst LDDataSystemOptions_1 = require(\"./api/options/LDDataSystemOptions\");\nconst BigSegmentsManager_1 = require(\"./BigSegmentsManager\");\nconst createPluginEnvironmentMetadata_1 = require(\"./createPluginEnvironmentMetadata\");\nconst createPayloadListenerFDv2_1 = require(\"./data_sources/createPayloadListenerFDv2\");\nconst createStreamListeners_1 = require(\"./data_sources/createStreamListeners\");\nconst DataSourceUpdates_1 = require(\"./data_sources/DataSourceUpdates\");\nconst fileDataInitilizerFDv2_1 = require(\"./data_sources/fileDataInitilizerFDv2\");\nconst OneShotInitializerFDv2_1 = require(\"./data_sources/OneShotInitializerFDv2\");\nconst PollingProcessor_1 = require(\"./data_sources/PollingProcessor\");\nconst PollingProcessorFDv2_1 = require(\"./data_sources/PollingProcessorFDv2\");\nconst Requestor_1 = require(\"./data_sources/Requestor\");\nconst StreamingProcessor_1 = require(\"./data_sources/StreamingProcessor\");\nconst StreamingProcessorFDv2_1 = require(\"./data_sources/StreamingProcessorFDv2\");\nconst TransactionalDataSourceUpdates_1 = require(\"./data_sources/TransactionalDataSourceUpdates\");\nconst createDiagnosticsInitConfig_1 = require(\"./diagnostics/createDiagnosticsInitConfig\");\nconst collection_1 = require(\"./evaluation/collection\");\nconst EvalResult_1 = require(\"./evaluation/EvalResult\");\nconst Evaluator_1 = require(\"./evaluation/Evaluator\");\nconst ContextDeduplicator_1 = require(\"./events/ContextDeduplicator\");\nconst EventFactory_1 = require(\"./events/EventFactory\");\nconst isExperiment_1 = require(\"./events/isExperiment\");\nconst FlagsStateBuilder_1 = require(\"./FlagsStateBuilder\");\nconst HookRunner_1 = require(\"./hooks/HookRunner\");\nconst MigrationOpEventConversion_1 = require(\"./MigrationOpEventConversion\");\nconst MigrationOpTracker_1 = require(\"./MigrationOpTracker\");\nconst Configuration_1 = require(\"./options/Configuration\");\nconst VersionedDataKinds_1 = require(\"./store/VersionedDataKinds\");\nconst { ClientMessages, ErrorKinds, NullEventProcessor } = js_sdk_common_1.internal;\nvar InitState;\n(function (InitState) {\n InitState[InitState[\"Initializing\"] = 0] = \"Initializing\";\n InitState[InitState[\"Initialized\"] = 1] = \"Initialized\";\n InitState[InitState[\"Failed\"] = 2] = \"Failed\";\n})(InitState || (InitState = {}));\nconst HIGH_TIMEOUT_THRESHOLD = 60;\nconst BOOL_VARIATION_METHOD_NAME = 'LDClient.boolVariation';\nconst NUMBER_VARIATION_METHOD_NAME = 'LDClient.numberVariation';\nconst STRING_VARIATION_METHOD_NAME = 'LDClient.stringVariation';\nconst JSON_VARIATION_METHOD_NAME = 'LDClient.jsonVariation';\nconst VARIATION_METHOD_NAME = 'LDClient.variation';\nconst MIGRATION_VARIATION_METHOD_NAME = 'LDClient.migrationVariation';\nconst BOOL_VARIATION_DETAIL_METHOD_NAME = 'LDClient.boolVariationDetail';\nconst NUMBER_VARIATION_DETAIL_METHOD_NAME = 'LDClient.numberVariationDetail';\nconst STRING_VARIATION_DETAIL_METHOD_NAME = 'LDClient.stringVariationDetail';\nconst JSON_VARIATION_DETAIL_METHOD_NAME = 'LDClient.jsonVariationDetail';\nconst VARIATION_METHOD_DETAIL_NAME = 'LDClient.variationDetail';\nfunction constructFDv1(sdkKey, platform, config, callbacks, initSuccess, dataSourceErrorHandler, hooks) {\n var _a, _b, _c, _d, _e;\n const { onUpdate, hasEventListeners } = callbacks;\n const hookRunner = new HookRunner_1.default(config.logger, hooks);\n if (!sdkKey && !config.offline) {\n throw new Error('You must configure the client with an SDK key');\n }\n const { logger } = config;\n const baseHeaders = (0, js_sdk_common_1.defaultHeaders)(sdkKey, platform.info, config.tags);\n const clientContext = new js_sdk_common_1.ClientContext(sdkKey, config, platform);\n const featureStore = config.featureStoreFactory(clientContext);\n const dataSourceUpdates = new DataSourceUpdates_1.default(featureStore, hasEventListeners, onUpdate);\n let diagnosticsManager;\n if (config.sendEvents && !config.offline && !config.diagnosticOptOut) {\n diagnosticsManager = new js_sdk_common_1.internal.DiagnosticsManager(sdkKey, platform, (0, createDiagnosticsInitConfig_1.default)(config, platform, featureStore));\n }\n let eventProcessor;\n if (!config.sendEvents || config.offline) {\n eventProcessor = new NullEventProcessor();\n }\n else {\n eventProcessor = new js_sdk_common_1.internal.EventProcessor(config, clientContext, baseHeaders, new ContextDeduplicator_1.default(config), diagnosticsManager);\n }\n const bigSegmentsManager = new BigSegmentsManager_1.default((_b = (_a = config.bigSegments) === null || _a === void 0 ? void 0 : _a.store) === null || _b === void 0 ? void 0 : _b.call(_a, clientContext), (_c = config.bigSegments) !== null && _c !== void 0 ? _c : {}, config.logger, platform.crypto);\n const queries = {\n getFlag(key, cb) {\n featureStore.get(VersionedDataKinds_1.default.Features, key, (item) => cb(item));\n },\n getSegment(key, cb) {\n featureStore.get(VersionedDataKinds_1.default.Segments, key, (item) => cb(item));\n },\n getBigSegmentsMembership(userKey) {\n return bigSegmentsManager.getUserMembership(userKey);\n },\n };\n const evaluator = new Evaluator_1.default(platform, queries);\n const listeners = (0, createStreamListeners_1.createStreamListeners)(dataSourceUpdates, logger, {\n put: initSuccess,\n });\n const makeDefaultProcessor = () => config.stream\n ? new StreamingProcessor_1.default(clientContext, '/all', [], listeners, baseHeaders, diagnosticsManager, dataSourceErrorHandler, config.streamInitialReconnectDelay)\n : new PollingProcessor_1.default(new Requestor_1.default(config, platform.requests, baseHeaders), config.pollInterval, dataSourceUpdates, config.logger, initSuccess, dataSourceErrorHandler);\n let updateProcessor;\n if (!(config.offline || config.useLdd)) {\n updateProcessor =\n (_e = (_d = config.updateProcessorFactory) === null || _d === void 0 ? void 0 : _d.call(config, clientContext, dataSourceUpdates, initSuccess, dataSourceErrorHandler)) !== null && _e !== void 0 ? _e : makeDefaultProcessor();\n }\n return {\n config,\n logger,\n evaluator,\n featureStore,\n updateProcessor,\n eventProcessor,\n bigSegmentsManager,\n hookRunner,\n onError: callbacks.onError,\n onFailed: callbacks.onFailed,\n onReady: callbacks.onReady,\n };\n}\nfunction constructFDv2(sdkKey, platform, config, callbacks, initSuccess, hooks) {\n var _a, _b, _c, _d;\n const { onUpdate, hasEventListeners } = callbacks;\n const hookRunner = new HookRunner_1.default(config.logger, hooks);\n if (!sdkKey && !config.offline) {\n throw new Error('You must configure the client with an SDK key');\n }\n const { logger } = config;\n const baseHeaders = (0, js_sdk_common_1.defaultHeaders)(sdkKey, platform.info, config.tags);\n const clientContext = new js_sdk_common_1.ClientContext(sdkKey, config, platform);\n const dataSystem = config.dataSystem; // dataSystem must be defined to get into this construct function\n const featureStore = dataSystem.featureStoreFactory(clientContext);\n const dataSourceUpdates = new TransactionalDataSourceUpdates_1.default(featureStore, hasEventListeners, onUpdate);\n let diagnosticsManager;\n if (config.sendEvents && !config.offline && !config.diagnosticOptOut) {\n diagnosticsManager = new js_sdk_common_1.internal.DiagnosticsManager(sdkKey, platform, (0, createDiagnosticsInitConfig_1.default)(config, platform, featureStore));\n }\n let eventProcessor;\n if (!config.sendEvents || config.offline) {\n eventProcessor = new NullEventProcessor();\n }\n else {\n eventProcessor = new js_sdk_common_1.internal.EventProcessor(config, clientContext, baseHeaders, new ContextDeduplicator_1.default(config), diagnosticsManager);\n }\n const bigSegmentsManager = new BigSegmentsManager_1.default((_b = (_a = config.bigSegments) === null || _a === void 0 ? void 0 : _a.store) === null || _b === void 0 ? void 0 : _b.call(_a, clientContext), (_c = config.bigSegments) !== null && _c !== void 0 ? _c : {}, config.logger, platform.crypto);\n const queries = {\n getFlag(key, cb) {\n featureStore.get(VersionedDataKinds_1.default.Features, key, (item) => cb(item));\n },\n getSegment(key, cb) {\n featureStore.get(VersionedDataKinds_1.default.Segments, key, (item) => cb(item));\n },\n getBigSegmentsMembership(userKey) {\n return bigSegmentsManager.getUserMembership(userKey);\n },\n };\n const evaluator = new Evaluator_1.default(platform, queries);\n let dataSource;\n let payloadListener;\n if (!(config.offline || config.dataSystem.useLdd)) {\n // make the FDv2 composite datasource with initializers/synchronizers\n const initializers = [];\n const synchronizers = [];\n const fdv1FallbackSynchronizers = [];\n if ((0, LDDataSystemOptions_1.isCustomOptions)(dataSystem.dataSource)) {\n const { initializers: initializerConfigs = [], synchronizers: synchronizerConfigs = [] } = dataSystem.dataSource;\n initializerConfigs.forEach((initializerConfig) => {\n switch (initializerConfig.type) {\n case 'file': {\n initializers.push(() => new fileDataInitilizerFDv2_1.default(initializerConfig, platform, config.logger));\n break;\n }\n case 'polling': {\n initializers.push(() => new OneShotInitializerFDv2_1.default(new Requestor_1.default(config, platform.requests, baseHeaders, '/sdk/poll', config.logger), config.logger));\n break;\n }\n default: {\n throw new Error('Unsupported initializer type');\n }\n }\n });\n synchronizerConfigs.forEach((synchronizerConfig) => {\n switch (synchronizerConfig.type) {\n case 'streaming': {\n const { streamInitialReconnectDelay = Configuration_1.DEFAULT_STREAM_RECONNECT_DELAY } = synchronizerConfig;\n synchronizers.push(() => new StreamingProcessorFDv2_1.default(clientContext, '/sdk/stream', [], baseHeaders, diagnosticsManager, streamInitialReconnectDelay));\n break;\n }\n case 'polling': {\n const { pollInterval = Configuration_1.DEFAULT_POLL_INTERVAL } = synchronizerConfig;\n synchronizers.push(() => new PollingProcessorFDv2_1.default(new Requestor_1.default(config, platform.requests, baseHeaders, '/sdk/poll', config.logger), pollInterval, config.logger));\n break;\n }\n default: {\n throw new Error('Unsupported synchronizer type');\n }\n }\n });\n }\n else {\n // use one shot initializer for performance and cost if we can do a combination of polling and streaming\n if ((0, LDDataSystemOptions_1.isStandardOptions)(dataSystem.dataSource)) {\n initializers.push(() => new OneShotInitializerFDv2_1.default(new Requestor_1.default(config, platform.requests, baseHeaders, '/sdk/poll', config.logger), config.logger));\n }\n // if streaming is configured, add streaming synchronizer\n if ((0, LDDataSystemOptions_1.isStandardOptions)(dataSystem.dataSource) ||\n (0, LDDataSystemOptions_1.isStreamingOnlyOptions)(dataSystem.dataSource)) {\n const reconnectDelay = dataSystem.dataSource.streamInitialReconnectDelay;\n synchronizers.push(() => new StreamingProcessorFDv2_1.default(clientContext, '/sdk/stream', [], baseHeaders, diagnosticsManager, reconnectDelay));\n }\n let pollingInterval = Configuration_1.DEFAULT_POLL_INTERVAL;\n // if polling is configured, add polling synchronizer\n if ((0, LDDataSystemOptions_1.isStandardOptions)(dataSystem.dataSource) || (0, LDDataSystemOptions_1.isPollingOnlyOptions)(dataSystem.dataSource)) {\n pollingInterval = (_d = dataSystem.dataSource.pollInterval) !== null && _d !== void 0 ? _d : Configuration_1.DEFAULT_POLL_INTERVAL;\n synchronizers.push(() => new PollingProcessorFDv2_1.default(new Requestor_1.default(config, platform.requests, baseHeaders, '/sdk/poll', logger), pollingInterval, logger));\n }\n }\n // This is short term handling and will be removed once FDv2 adoption is sufficient.\n fdv1FallbackSynchronizers.push(() => {\n var _a;\n return new PollingProcessorFDv2_1.default(new Requestor_1.default(config, platform.requests, baseHeaders, '/sdk/latest-all', config.logger), (_a = config.pollInterval) !== null && _a !== void 0 ? _a : Configuration_1.DEFAULT_POLL_INTERVAL, config.logger, true);\n });\n dataSource = new js_sdk_common_1.CompositeDataSource(initializers, synchronizers, fdv1FallbackSynchronizers, logger);\n payloadListener = (0, createPayloadListenerFDv2_1.createPayloadListener)(dataSourceUpdates, logger, initSuccess);\n }\n return {\n config,\n logger,\n evaluator,\n featureStore,\n dataSource,\n payloadListener,\n eventProcessor,\n bigSegmentsManager,\n hookRunner,\n onError: callbacks.onError,\n onFailed: callbacks.onFailed,\n onReady: callbacks.onReady,\n };\n}\n/**\n * @ignore\n */\nclass LDClientImpl {\n get logger() {\n return this._logger;\n }\n constructor(_sdkKey, _platform, options, callbacks, internalOptions) {\n this._sdkKey = _sdkKey;\n this._platform = _platform;\n this._initState = InitState.Initializing;\n this._eventFactoryDefault = new EventFactory_1.default(false);\n this._eventFactoryWithReasons = new EventFactory_1.default(true);\n const config = new Configuration_1.default(options, internalOptions);\n this.environmentMetadata = (0, createPluginEnvironmentMetadata_1.createPluginEnvironmentMetadata)(_platform, _sdkKey, config);\n const hooks = [];\n if (config.hooks) {\n hooks.push(...config.hooks);\n }\n config.getImplementationHooks(this.environmentMetadata).forEach((hook) => {\n hooks.push(hook);\n });\n if (!config.dataSystem) {\n // setup for FDv1\n ({\n config: this._config,\n logger: this._logger,\n evaluator: this._evaluator,\n featureStore: this._featureStore,\n updateProcessor: this._updateProcessor,\n eventProcessor: this._eventProcessor,\n bigSegmentsManager: this._bigSegmentsManager,\n hookRunner: this._hookRunner,\n onError: this._onError,\n onFailed: this._onFailed,\n onReady: this._onReady,\n } = constructFDv1(_sdkKey, _platform, config, callbacks, () => this._initSuccess(), (e) => this._dataSourceErrorHandler(e), hooks));\n this.bigSegmentStatusProviderInternal = this._bigSegmentsManager\n .statusProvider;\n if (this._updateProcessor) {\n this._updateProcessor.start();\n }\n else {\n // Deferring the start callback should allow client construction to complete before we start\n // emitting events. Allowing the client an opportunity to register events.\n setTimeout(() => this._initSuccess(), 0);\n }\n }\n else {\n // setup for FDv2\n let transactionalStore;\n let payloadListener;\n ({\n config: this._config,\n logger: this._logger,\n evaluator: this._evaluator,\n featureStore: transactionalStore,\n dataSource: this._dataSource,\n payloadListener,\n eventProcessor: this._eventProcessor,\n bigSegmentsManager: this._bigSegmentsManager,\n hookRunner: this._hookRunner,\n onError: this._onError,\n onFailed: this._onFailed,\n onReady: this._onReady,\n } = constructFDv2(_sdkKey, _platform, config, callbacks, () => this._initSuccess(), hooks));\n this._featureStore = transactionalStore;\n this.bigSegmentStatusProviderInternal = this._bigSegmentsManager\n .statusProvider;\n if (this._dataSource) {\n this._dataSource.start((_, payload) => {\n payloadListener === null || payloadListener === void 0 ? void 0 : payloadListener(payload);\n }, (state, err) => {\n if (state === js_sdk_common_1.subsystem.DataSourceState.Closed && err) {\n this._dataSourceErrorHandler(err);\n }\n }, () => { var _a; return (_a = transactionalStore.getSelector) === null || _a === void 0 ? void 0 : _a.call(transactionalStore); });\n }\n else {\n // Deferring the start callback should allow client construction to complete before we start\n // emitting events. Allowing the client an opportunity to register events.\n setTimeout(() => this._initSuccess(), 0);\n }\n }\n }\n initialized() {\n return this._initState === InitState.Initialized;\n }\n waitForInitialization(options) {\n // An initialization promise is only created if someone is going to use that promise.\n // If we always created an initialization promise, and there was no call waitForInitialization\n // by the time the promise was rejected, then that would result in an unhandled promise\n // rejection.\n var _a, _b;\n // If there is no update processor, then there is functionally no initialization\n // so it is fine not to wait.\n if ((options === null || options === void 0 ? void 0 : options.timeout) === undefined &&\n (this._updateProcessor !== undefined || this._dataSource !== undefined)) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.warn('The waitForInitialization function was called without a timeout specified.' +\n ' In a future version a default timeout will be applied.');\n }\n if ((options === null || options === void 0 ? void 0 : options.timeout) !== undefined &&\n (options === null || options === void 0 ? void 0 : options.timeout) > HIGH_TIMEOUT_THRESHOLD &&\n (this._updateProcessor !== undefined || this._dataSource !== undefined)) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.warn('The waitForInitialization function was called with a timeout greater than ' +\n `${HIGH_TIMEOUT_THRESHOLD} seconds. We recommend a timeout of less than ` +\n `${HIGH_TIMEOUT_THRESHOLD} seconds.`);\n }\n // Initialization promise was created by a previous call to waitForInitialization.\n if (this._initializedPromise) {\n // This promise may already be resolved/rejected, but it doesn't hurt to wrap it in a timeout.\n return this._clientWithTimeout(this._initializedPromise, options === null || options === void 0 ? void 0 : options.timeout, this._logger);\n }\n // Initialization completed before waitForInitialization was called, so we have completed\n // and there was no promise. So we make a resolved promise and return it.\n if (this._initState === InitState.Initialized) {\n this._initializedPromise = Promise.resolve(this);\n // Already initialized, no need to timeout.\n return this._initializedPromise;\n }\n // Initialization failed before waitForInitialization was called, so we have completed\n // and there was no promise. So we make a rejected promise and return it.\n if (this._initState === InitState.Failed) {\n // Already failed, no need to timeout.\n this._initializedPromise = Promise.reject(this._rejectionReason);\n return this._initializedPromise;\n }\n if (!this._initializedPromise) {\n this._initializedPromise = new Promise((resolve, reject) => {\n this._initResolve = resolve;\n this._initReject = reject;\n });\n }\n return this._clientWithTimeout(this._initializedPromise, options === null || options === void 0 ? void 0 : options.timeout, this._logger);\n }\n variation(key, context, defaultValue, callback) {\n var _a, _b, _c;\n return this._hookRunner\n .withEvaluationSeries(key, context, defaultValue, VARIATION_METHOD_NAME, () => new Promise((resolve) => {\n this._evaluateIfPossible(key, context, defaultValue, this._eventFactoryDefault, (res) => {\n resolve(res.detail);\n });\n }), (_c = (_b = (_a = this._featureStore).getInitMetaData) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c.environmentId)\n .then((detail) => {\n callback === null || callback === void 0 ? void 0 : callback(null, detail.value);\n return detail.value;\n });\n }\n variationDetail(key, context, defaultValue, callback) {\n var _a, _b, _c;\n return this._hookRunner.withEvaluationSeries(key, context, defaultValue, VARIATION_METHOD_DETAIL_NAME, () => new Promise((resolve) => {\n this._evaluateIfPossible(key, context, defaultValue, this._eventFactoryWithReasons, (res) => {\n resolve(res.detail);\n callback === null || callback === void 0 ? void 0 : callback(null, res.detail);\n });\n }), (_c = (_b = (_a = this._featureStore).getInitMetaData) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c.environmentId);\n }\n _typedEval(key, context, defaultValue, eventFactory, methodName, typeChecker) {\n var _a, _b, _c;\n return this._hookRunner.withEvaluationSeries(key, context, defaultValue, methodName, () => new Promise((resolve) => {\n this._evaluateIfPossible(key, context, defaultValue, eventFactory, (res) => {\n const typedRes = {\n value: res.detail.value,\n reason: res.detail.reason,\n variationIndex: res.detail.variationIndex,\n };\n resolve(typedRes);\n }, typeChecker);\n }), (_c = (_b = (_a = this._featureStore).getInitMetaData) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c.environmentId);\n }\n async boolVariation(key, context, defaultValue) {\n return (await this._typedEval(key, context, defaultValue, this._eventFactoryDefault, BOOL_VARIATION_METHOD_NAME, (value) => [js_sdk_common_1.TypeValidators.Boolean.is(value), js_sdk_common_1.TypeValidators.Boolean.getType()])).value;\n }\n async numberVariation(key, context, defaultValue) {\n return (await this._typedEval(key, context, defaultValue, this._eventFactoryDefault, NUMBER_VARIATION_METHOD_NAME, (value) => [js_sdk_common_1.TypeValidators.Number.is(value), js_sdk_common_1.TypeValidators.Number.getType()])).value;\n }\n async stringVariation(key, context, defaultValue) {\n return (await this._typedEval(key, context, defaultValue, this._eventFactoryDefault, STRING_VARIATION_METHOD_NAME, (value) => [js_sdk_common_1.TypeValidators.String.is(value), js_sdk_common_1.TypeValidators.String.getType()])).value;\n }\n jsonVariation(key, context, defaultValue) {\n var _a, _b, _c;\n return this._hookRunner\n .withEvaluationSeries(key, context, defaultValue, JSON_VARIATION_METHOD_NAME, () => new Promise((resolve) => {\n this._evaluateIfPossible(key, context, defaultValue, this._eventFactoryDefault, (res) => {\n resolve(res.detail);\n });\n }), (_c = (_b = (_a = this._featureStore).getInitMetaData) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c.environmentId)\n .then((detail) => detail.value);\n }\n boolVariationDetail(key, context, defaultValue) {\n return this._typedEval(key, context, defaultValue, this._eventFactoryWithReasons, BOOL_VARIATION_DETAIL_METHOD_NAME, (value) => [js_sdk_common_1.TypeValidators.Boolean.is(value), js_sdk_common_1.TypeValidators.Boolean.getType()]);\n }\n numberVariationDetail(key, context, defaultValue) {\n return this._typedEval(key, context, defaultValue, this._eventFactoryWithReasons, NUMBER_VARIATION_DETAIL_METHOD_NAME, (value) => [js_sdk_common_1.TypeValidators.Number.is(value), js_sdk_common_1.TypeValidators.Number.getType()]);\n }\n stringVariationDetail(key, context, defaultValue) {\n return this._typedEval(key, context, defaultValue, this._eventFactoryWithReasons, STRING_VARIATION_DETAIL_METHOD_NAME, (value) => [js_sdk_common_1.TypeValidators.String.is(value), js_sdk_common_1.TypeValidators.String.getType()]);\n }\n jsonVariationDetail(key, context, defaultValue) {\n var _a, _b, _c;\n return this._hookRunner.withEvaluationSeries(key, context, defaultValue, JSON_VARIATION_DETAIL_METHOD_NAME, () => new Promise((resolve) => {\n this._evaluateIfPossible(key, context, defaultValue, this._eventFactoryWithReasons, (res) => {\n resolve(res.detail);\n });\n }), (_c = (_b = (_a = this._featureStore).getInitMetaData) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c.environmentId);\n }\n async _migrationVariationInternal(key, context, defaultValue) {\n var _a;\n const res = await new Promise((resolve) => {\n this._evaluateIfPossible(key, context, defaultValue, this._eventFactoryWithReasons, ({ detail }, flag) => {\n if (!(0, api_1.IsMigrationStage)(detail.value)) {\n const error = new Error(`Unrecognized MigrationState for \"${key}\"; returning default value.`);\n this._onError(error);\n const reason = {\n kind: 'ERROR',\n errorKind: ErrorKinds.WrongType,\n };\n resolve({\n detail: {\n value: defaultValue,\n reason,\n },\n flag,\n });\n return;\n }\n resolve({ detail, flag });\n });\n });\n const { detail, flag } = res;\n const checkRatio = (_a = flag === null || flag === void 0 ? void 0 : flag.migration) === null || _a === void 0 ? void 0 : _a.checkRatio;\n const samplingRatio = flag === null || flag === void 0 ? void 0 : flag.samplingRatio;\n return {\n detail,\n migration: {\n value: detail.value,\n tracker: new MigrationOpTracker_1.default(key, context, defaultValue, detail.value, detail.reason, checkRatio, \n // Can be null for compatibility reasons.\n detail.variationIndex === null ? undefined : detail.variationIndex, flag === null || flag === void 0 ? void 0 : flag.version, samplingRatio, this._logger),\n },\n };\n }\n async migrationVariation(key, context, defaultValue) {\n var _a, _b, _c;\n const res = await this._hookRunner.withEvaluationSeriesExtraDetail(key, context, defaultValue, MIGRATION_VARIATION_METHOD_NAME, () => this._migrationVariationInternal(key, context, defaultValue), (_c = (_b = (_a = this._featureStore).getInitMetaData) === null || _b === void 0 ? void 0 : _b.call(_a)) === null || _c === void 0 ? void 0 : _c.environmentId);\n return res.migration;\n }\n allFlagsState(context, options, callback) {\n var _a, _b, _c;\n if (this._config.offline) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.info('allFlagsState() called in offline mode. Returning empty state.');\n const allFlagState = new FlagsStateBuilder_1.default(false, false).build();\n callback === null || callback === void 0 ? void 0 : callback(null, allFlagState);\n return Promise.resolve(allFlagState);\n }\n const evalContext = js_sdk_common_1.Context.fromLDContext(context);\n if (!evalContext.valid) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.info(`${(_c = evalContext.message) !== null && _c !== void 0 ? _c : 'Invalid context.'}. Returning empty state.`);\n return Promise.resolve(new FlagsStateBuilder_1.default(false, false).build());\n }\n return new Promise((resolve) => {\n const doEval = (valid) => this._featureStore.all(VersionedDataKinds_1.default.Features, (allFlags) => {\n const builder = new FlagsStateBuilder_1.default(valid, !!(options === null || options === void 0 ? void 0 : options.withReasons));\n const clientOnly = !!(options === null || options === void 0 ? void 0 : options.clientSideOnly);\n const detailsOnlyIfTracked = !!(options === null || options === void 0 ? void 0 : options.detailsOnlyForTrackedFlags);\n (0, collection_1.allAsync)(Object.values(allFlags), (storeItem, iterCb) => {\n var _a;\n const flag = storeItem;\n if (clientOnly && !((_a = flag.clientSideAvailability) === null || _a === void 0 ? void 0 : _a.usingEnvironmentId)) {\n iterCb(true);\n return;\n }\n this._evaluator.evaluateCb(flag, evalContext, (res) => {\n var _a;\n if (res.isError) {\n this._onError(new Error(`Error for feature flag \"${flag.key}\" while evaluating all flags: ${res.message}`));\n }\n const requireExperimentData = (0, isExperiment_1.default)(flag, res.detail.reason);\n builder.addFlag(flag, res.detail.value, (_a = res.detail.variationIndex) !== null && _a !== void 0 ? _a : undefined, res.detail.reason, flag.trackEvents || requireExperimentData, requireExperimentData, detailsOnlyIfTracked, res.prerequisites);\n iterCb(true);\n });\n }, () => {\n const res = builder.build();\n callback === null || callback === void 0 ? void 0 : callback(null, res);\n resolve(res);\n });\n });\n if (!this.initialized()) {\n this._featureStore.initialized((storeInitialized) => {\n var _a, _b;\n let valid = true;\n if (storeInitialized) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.warn('Called allFlagsState before client initialization; using last known' +\n ' values from data store');\n }\n else {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.warn('Called allFlagsState before client initialization. Data store not available; ' +\n 'returning empty state');\n valid = false;\n }\n doEval(valid);\n });\n }\n else {\n doEval(true);\n }\n });\n }\n secureModeHash(context) {\n const checkedContext = js_sdk_common_1.Context.fromLDContext(context);\n const key = checkedContext.valid ? checkedContext.canonicalKey : undefined;\n if (!this._platform.crypto.createHmac) {\n // This represents an error in platform implementation.\n throw new Error('Platform must implement createHmac');\n }\n const hmac = this._platform.crypto.createHmac('sha256', this._sdkKey);\n if (key === undefined) {\n throw new js_sdk_common_1.LDClientError('Could not generate secure mode hash for invalid context');\n }\n hmac.update(key);\n return hmac.digest('hex');\n }\n close() {\n var _a, _b;\n this._eventProcessor.close();\n (_a = this._updateProcessor) === null || _a === void 0 ? void 0 : _a.close();\n (_b = this._dataSource) === null || _b === void 0 ? void 0 : _b.stop();\n this._featureStore.close();\n this._bigSegmentsManager.close();\n }\n isOffline() {\n return this._config.offline;\n }\n track(key, context, data, metricValue) {\n var _a, _b;\n const checkedContext = js_sdk_common_1.Context.fromLDContext(context);\n if (!checkedContext.valid) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.warn(ClientMessages.MissingContextKeyNoEvent);\n return;\n }\n // 0 is valid, so do not truthy check the metric value\n if (metricValue !== undefined && !js_sdk_common_1.TypeValidators.Number.is(metricValue)) {\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.warn(ClientMessages.invalidMetricValue(typeof metricValue));\n }\n this._eventProcessor.sendEvent(this._eventFactoryDefault.customEvent(key, checkedContext, data, metricValue));\n }\n trackMigration(event) {\n const converted = (0, MigrationOpEventConversion_1.default)(event);\n if (!converted) {\n return;\n }\n this._eventProcessor.sendEvent(converted);\n }\n identify(context) {\n var _a;\n const checkedContext = js_sdk_common_1.Context.fromLDContext(context);\n if (!checkedContext.valid) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.warn(ClientMessages.MissingContextKeyNoEvent);\n return;\n }\n this._eventProcessor.sendEvent(this._eventFactoryDefault.identifyEvent(checkedContext));\n }\n async flush(callback) {\n try {\n await this._eventProcessor.flush();\n }\n catch (err) {\n return callback === null || callback === void 0 ? void 0 : callback(err, false);\n }\n return callback === null || callback === void 0 ? void 0 : callback(null, true);\n }\n addHook(hook) {\n this._hookRunner.addHook(hook);\n }\n _variationInternal(flagKey, context, defaultValue, eventFactory, cb, typeChecker) {\n var _a, _b;\n if (this._config.offline) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.info('Variation called in offline mode. Returning default value.');\n cb(EvalResult_1.default.forError(ErrorKinds.ClientNotReady, undefined, defaultValue));\n return;\n }\n const evalContext = js_sdk_common_1.Context.fromLDContext(context);\n if (!evalContext.valid) {\n this._onError(new js_sdk_common_1.LDClientError(`${(_b = evalContext.message) !== null && _b !== void 0 ? _b : 'Context not valid;'} returning default value.`));\n cb(EvalResult_1.default.forError(ErrorKinds.UserNotSpecified, undefined, defaultValue));\n return;\n }\n this._featureStore.get(VersionedDataKinds_1.default.Features, flagKey, (item) => {\n const flag = item;\n if (!flag) {\n const error = new js_sdk_common_1.LDClientError(`Unknown feature flag \"${flagKey}\"; returning default value`);\n this._onError(error);\n const result = EvalResult_1.default.forError(ErrorKinds.FlagNotFound, undefined, defaultValue);\n this._eventProcessor.sendEvent(this._eventFactoryDefault.unknownFlagEvent(flagKey, defaultValue, evalContext));\n cb(result);\n return;\n }\n this._evaluator.evaluateCb(flag, evalContext, (evalRes) => {\n var _a;\n if (evalRes.detail.variationIndex === undefined ||\n evalRes.detail.variationIndex === null) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.debug('Result value is null in variation');\n evalRes.setDefault(defaultValue);\n }\n if (typeChecker) {\n const [matched, type] = typeChecker(evalRes.detail.value);\n if (!matched) {\n const errorRes = EvalResult_1.default.forError(ErrorKinds.WrongType, `Did not receive expected type (${type}) evaluating feature flag \"${flagKey}\"`, defaultValue);\n this._sendEvalEvent(errorRes, eventFactory, flag, evalContext, defaultValue);\n cb(errorRes, flag);\n return;\n }\n }\n this._sendEvalEvent(evalRes, eventFactory, flag, evalContext, defaultValue);\n cb(evalRes, flag);\n }, eventFactory);\n });\n }\n _sendEvalEvent(evalRes, eventFactory, flag, evalContext, defaultValue) {\n var _a;\n (_a = evalRes.events) === null || _a === void 0 ? void 0 : _a.forEach((event) => {\n this._eventProcessor.sendEvent(Object.assign({}, event));\n });\n this._eventProcessor.sendEvent(eventFactory.evalEventServer(flag, evalContext, evalRes.detail, defaultValue, undefined));\n }\n _evaluateIfPossible(flagKey, context, defaultValue, eventFactory, cb, typeChecker) {\n if (!this.initialized()) {\n this._featureStore.initialized((storeInitialized) => {\n var _a, _b;\n if (storeInitialized) {\n (_a = this._logger) === null || _a === void 0 ? void 0 : _a.warn('Variation called before LaunchDarkly client initialization completed' +\n \" (did you wait for the 'ready' event?) - using last known values from feature store\");\n this._variationInternal(flagKey, context, defaultValue, eventFactory, cb, typeChecker);\n return;\n }\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.warn('Variation called before LaunchDarkly client initialization completed (did you wait for the' +\n \"'ready' event?) - using default value\");\n cb(EvalResult_1.default.forError(ErrorKinds.ClientNotReady, undefined, defaultValue));\n });\n return;\n }\n this._variationInternal(flagKey, context, defaultValue, eventFactory, cb, typeChecker);\n }\n _dataSourceErrorHandler(e) {\n var _a;\n const error = e.code === 401 ? new Error('Authentication failed. Double check your SDK key.') : e;\n this._onError(error);\n this._onFailed(error);\n if (!this.initialized()) {\n this._initState = InitState.Failed;\n this._rejectionReason = error;\n (_a = this._initReject) === null || _a === void 0 ? void 0 : _a.call(this, error);\n }\n }\n _initSuccess() {\n var _a;\n if (!this.initialized()) {\n this._initState = InitState.Initialized;\n (_a = this._initResolve) === null || _a === void 0 ? void 0 : _a.call(this, this);\n this._onReady();\n }\n }\n /**\n * Apply a timeout promise to a base promise. This is for use with waitForInitialization.\n * Currently it returns a LDClient. In the future it should return a status.\n *\n * The client isn't always the expected type of the consumer. It returns an LDClient interface\n * which is less capable than, for example, the node client interface.\n *\n * @param basePromise The promise to race against a timeout.\n * @param timeout The timeout in seconds.\n * @param logger A logger to log when the timeout expires.\n * @returns\n */\n _clientWithTimeout(basePromise, timeout, logger) {\n if (timeout) {\n const cancelableTimeout = (0, js_sdk_common_1.cancelableTimedPromise)(timeout, 'waitForInitialization');\n return Promise.race([\n basePromise.then(() => this),\n cancelableTimeout.promise.then(() => this),\n ])\n .catch((reason) => {\n if (reason instanceof js_sdk_common_1.LDTimeoutError) {\n logger === null || logger === void 0 ? void 0 : logger.error(reason.message);\n }\n throw reason;\n })\n .finally(() => cancelableTimeout.cancel());\n }\n return basePromise;\n }\n}\nexports.default = LDClientImpl;\n//# sourceMappingURL=LDClientImpl.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createMigration = exports.LDMigrationError = exports.LDMigrationSuccess = void 0;\nconst api_1 = require(\"./api\");\nconst LDMigrationOptions_1 = require(\"./api/options/LDMigrationOptions\");\nasync function safeCall(method) {\n try {\n // Awaiting to allow catching.\n const res = await method();\n return res;\n }\n catch (error) {\n return {\n success: false,\n error,\n };\n }\n}\n/**\n * Report a successful migration operation from `readNew`, `readOld`, `writeNew` or `writeOld`.\n *\n * ```\n * readNew: async () => {\n * const myResult = doMyOldRead();\n * if(myResult.wasGood) {\n * return LDMigrationSuccess(myResult);\n * }\n * return LDMigrationError(myResult.error)\n * }\n * ```\n *\n * @param result The result of the operation.\n * @returns An {@link LDMethodResult}\n */\nfunction LDMigrationSuccess(result) {\n return {\n success: true,\n result,\n };\n}\nexports.LDMigrationSuccess = LDMigrationSuccess;\n/**\n * Report a failed migration operation from `readNew`, `readOld`, `writeNew` or `writeOld`.\n *\n * ```\n * readNew: async () => {\n * const myResult = doMyOldRead();\n * if(myResult.wasGood) {\n * return LDMigrationSuccess(myResult);\n * }\n * return LDMigrationError(myResult.error)\n * }\n * ```\n *\n * @param result The result of the operations.\n * @returns An {@link LDMethodResult}\n */\nfunction LDMigrationError(error) {\n return {\n success: false,\n error,\n };\n}\nexports.LDMigrationError = LDMigrationError;\n/**\n * Class which allows performing technology migrations.\n */\nclass Migration {\n constructor(_client, _config) {\n var _a, _b;\n this._client = _client;\n this._config = _config;\n this._readTable = {\n [api_1.LDMigrationStage.Off]: async (context) => this._doSingleOp(context, 'old', this._config.readOld.bind(this._config)),\n [api_1.LDMigrationStage.DualWrite]: async (context) => this._doSingleOp(context, 'old', this._config.readOld.bind(this._config)),\n [api_1.LDMigrationStage.Shadow]: async (context) => {\n const { fromOld, fromNew } = await this._doRead(context);\n this._trackConsistency(context, fromOld, fromNew);\n return fromOld;\n },\n [api_1.LDMigrationStage.Live]: async (context) => {\n const { fromNew, fromOld } = await this._doRead(context);\n this._trackConsistency(context, fromOld, fromNew);\n return fromNew;\n },\n [api_1.LDMigrationStage.RampDown]: async (context) => this._doSingleOp(context, 'new', this._config.readNew.bind(this._config)),\n [api_1.LDMigrationStage.Complete]: async (context) => this._doSingleOp(context, 'new', this._config.readNew.bind(this._config)),\n };\n this._writeTable = {\n [api_1.LDMigrationStage.Off]: async (context) => ({\n authoritative: await this._doSingleOp(context, 'old', this._config.writeOld.bind(this._config)),\n }),\n [api_1.LDMigrationStage.DualWrite]: async (context) => {\n const fromOld = await this._doSingleOp(context, 'old', this._config.writeOld.bind(this._config));\n if (!fromOld.success) {\n return {\n authoritative: fromOld,\n };\n }\n const fromNew = await this._doSingleOp(context, 'new', this._config.writeNew.bind(this._config));\n return {\n authoritative: fromOld,\n nonAuthoritative: fromNew,\n };\n },\n [api_1.LDMigrationStage.Shadow]: async (context) => {\n const fromOld = await this._doSingleOp(context, 'old', this._config.writeOld.bind(this._config));\n if (!fromOld.success) {\n return {\n authoritative: fromOld,\n };\n }\n const fromNew = await this._doSingleOp(context, 'new', this._config.writeNew.bind(this._config));\n return {\n authoritative: fromOld,\n nonAuthoritative: fromNew,\n };\n },\n [api_1.LDMigrationStage.Live]: async (context) => {\n const fromNew = await this._doSingleOp(context, 'new', this._config.writeNew.bind(this._config));\n if (!fromNew.success) {\n return {\n authoritative: fromNew,\n };\n }\n const fromOld = await this._doSingleOp(context, 'old', this._config.writeOld.bind(this._config));\n return {\n authoritative: fromNew,\n nonAuthoritative: fromOld,\n };\n },\n [api_1.LDMigrationStage.RampDown]: async (context) => {\n const fromNew = await this._doSingleOp(context, 'new', this._config.writeNew.bind(this._config));\n if (!fromNew.success) {\n return {\n authoritative: fromNew,\n };\n }\n const fromOld = await this._doSingleOp(context, 'old', this._config.writeOld.bind(this._config));\n return {\n authoritative: fromNew,\n nonAuthoritative: fromOld,\n };\n },\n [api_1.LDMigrationStage.Complete]: async (context) => ({\n authoritative: await this._doSingleOp(context, 'new', this._config.writeNew.bind(this._config)),\n }),\n };\n if (this._config.execution) {\n this._execution = this._config.execution;\n }\n else {\n this._execution = new LDMigrationOptions_1.LDConcurrentExecution();\n }\n this._latencyTracking = (_a = this._config.latencyTracking) !== null && _a !== void 0 ? _a : true;\n this._errorTracking = (_b = this._config.errorTracking) !== null && _b !== void 0 ? _b : true;\n }\n async read(key, context, defaultStage, payload) {\n const stage = await this._client.migrationVariation(key, context, defaultStage);\n const res = await this._readTable[stage.value]({\n payload,\n tracker: stage.tracker,\n });\n stage.tracker.op('read');\n this._sendEvent(stage.tracker);\n return res;\n }\n async write(key, context, defaultStage, payload) {\n const stage = await this._client.migrationVariation(key, context, defaultStage);\n const res = await this._writeTable[stage.value]({\n payload,\n tracker: stage.tracker,\n });\n stage.tracker.op('write');\n this._sendEvent(stage.tracker);\n return res;\n }\n _sendEvent(tracker) {\n const event = tracker.createEvent();\n if (event) {\n this._client.trackMigration(event);\n }\n }\n _trackConsistency(context, oldValue, newValue) {\n if (!this._config.check) {\n return;\n }\n if (oldValue.success && newValue.success) {\n // Check is validated before this point, so it is force unwrapped.\n context.tracker.consistency(() => this._config.check(oldValue.result, newValue.result));\n }\n }\n async _readSequentialFixed(context) {\n const fromOld = await this._doSingleOp(context, 'old', this._config.readOld.bind(this._config));\n const fromNew = await this._doSingleOp(context, 'new', this._config.readNew.bind(this._config));\n return { fromOld, fromNew };\n }\n async _readConcurrent(context) {\n const fromOldPromise = this._doSingleOp(context, 'old', this._config.readOld.bind(this._config));\n const fromNewPromise = this._doSingleOp(context, 'new', this._config.readNew.bind(this._config));\n const [fromOld, fromNew] = await Promise.all([fromOldPromise, fromNewPromise]);\n return { fromOld, fromNew };\n }\n async _readSequentialRandom(context) {\n // This number is not used for a purpose requiring cryptographic security.\n const randomIndex = Math.floor(Math.random() * 2);\n // Effectively flip a coin and do it on one order or the other.\n if (randomIndex === 0) {\n const fromOld = await this._doSingleOp(context, 'old', this._config.readOld.bind(this._config));\n const fromNew = await this._doSingleOp(context, 'new', this._config.readNew.bind(this._config));\n return { fromOld, fromNew };\n }\n const fromNew = await this._doSingleOp(context, 'new', this._config.readNew.bind(this._config));\n const fromOld = await this._doSingleOp(context, 'old', this._config.readOld.bind(this._config));\n return { fromOld, fromNew };\n }\n async _doRead(context) {\n var _a;\n if (((_a = this._execution) === null || _a === void 0 ? void 0 : _a.type) === LDMigrationOptions_1.LDExecution.Serial) {\n const serial = this._execution;\n if (serial.ordering === LDMigrationOptions_1.LDExecutionOrdering.Fixed) {\n return this._readSequentialFixed(context);\n }\n return this._readSequentialRandom(context);\n }\n return this._readConcurrent(context);\n }\n async _doSingleOp(context, origin, method) {\n context.tracker.invoked(origin);\n const res = await this._trackLatency(context.tracker, origin, () => safeCall(() => method(context.payload)));\n if (!res.success && this._errorTracking) {\n context.tracker.error(origin);\n }\n return Object.assign({ origin }, res);\n }\n async _trackLatency(tracker, origin, method) {\n if (!this._latencyTracking) {\n return method();\n }\n let start;\n let end;\n let result;\n // TODO: Need to validate performance existence check with edge SDKs.\n if (typeof performance !== 'undefined') {\n start = performance.now();\n result = await method();\n end = performance.now();\n }\n else {\n start = Date.now();\n result = await method();\n end = Date.now();\n }\n // Performance timer is in ms, but may have a microsecond resolution\n // fractional component.\n const latency = end - start;\n tracker.latency(origin, latency);\n return result;\n }\n}\nfunction createMigration(client, config) {\n return new Migration(client, config);\n}\nexports.createMigration = createMigration;\n//# sourceMappingURL=Migration.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst serialization_1 = require(\"../store/serialization\");\nconst VersionedDataKinds_1 = require(\"../store/VersionedDataKinds\");\nconst FileLoader_1 = require(\"./FileLoader\");\nfunction makeFlagWithValue(key, value, version) {\n return {\n key,\n on: true,\n fallthrough: { variation: 0 },\n variations: [value],\n version,\n };\n}\nclass FileDataSource {\n /**\n * This is internal because we want instances to only be created with the\n * factory.\n * @internal\n */\n constructor(options, filesystem, _featureStore, _initSuccessHandler = () => { }, _errorHandler) {\n var _a;\n this._featureStore = _featureStore;\n this._initSuccessHandler = _initSuccessHandler;\n this._errorHandler = _errorHandler;\n this._allData = {};\n this._fileLoader = new FileLoader_1.default(filesystem, options.paths, (_a = options.autoUpdate) !== null && _a !== void 0 ? _a : false, (results) => {\n var _a, _b;\n // Whenever changes are detected we re-process all of the data.\n // The FileLoader will have handled debouncing for us.\n try {\n this._processFileData(results);\n }\n catch (err) {\n // If this was during start, then the initCallback will be present.\n (_a = this._errorHandler) === null || _a === void 0 ? void 0 : _a.call(this, err);\n (_b = this._logger) === null || _b === void 0 ? void 0 : _b.error(`Error processing files: ${err}`);\n }\n });\n this._logger = options.logger;\n this._yamlParser = options.yamlParser;\n }\n start() {\n // Use an immediately invoked function expression to allow handling of the\n // async loading without making start async itself.\n (async () => {\n var _a;\n try {\n await this._fileLoader.loadAndWatch();\n }\n catch (err) {\n // There was an issue loading/watching the files.\n // Report back to the caller.\n (_a = this._errorHandler) === null || _a === void 0 ? void 0 : _a.call(this, err);\n }\n })();\n }\n stop() {\n this._fileLoader.close();\n }\n close() {\n this.stop();\n }\n _addItem(kind, item) {\n if (!this._allData[kind.namespace]) {\n this._allData[kind.namespace] = {};\n }\n if (this._allData[kind.namespace][item.key]) {\n throw new Error(`found duplicate key: \"${item.key}\"`);\n }\n else {\n this._allData[kind.namespace][item.key] = item;\n }\n }\n _processFileData(fileData) {\n // Clear any existing data before re-populating it.\n const oldData = this._allData;\n this._allData = {};\n // We let the parsers throw, and the caller can handle the rejection.\n fileData.forEach((fd) => {\n let parsed;\n if (fd.path.endsWith('.yml') || fd.path.endsWith('.yaml')) {\n if (this._yamlParser) {\n parsed = this._yamlParser(fd.data);\n }\n else {\n throw new Error(`Attempted to parse yaml file (${fd.path}) without parser.`);\n }\n }\n else {\n parsed = JSON.parse(fd.data);\n }\n this._processParsedData(parsed, oldData);\n });\n this._featureStore.init(this._allData, () => {\n // Call the init callback if present.\n // Then clear the callback so we cannot call it again.\n this._initSuccessHandler();\n this._initSuccessHandler = () => { };\n });\n }\n _processParsedData(parsed, oldData) {\n Object.keys(parsed.flags || {}).forEach((key) => {\n (0, serialization_1.processFlag)(parsed.flags[key]);\n this._addItem(VersionedDataKinds_1.default.Features, parsed.flags[key]);\n });\n Object.keys(parsed.flagValues || {}).forEach((key) => {\n var _a, _b;\n const previousInstance = (_a = oldData[VersionedDataKinds_1.default.Features.namespace]) === null || _a === void 0 ? void 0 : _a[key];\n let { version } = previousInstance !== null && previousInstance !== void 0 ? previousInstance : { version: 1 };\n // If the data is different, then we want to increment the version.\n if (previousInstance &&\n JSON.stringify(parsed.flagValues[key]) !== JSON.stringify((_b = previousInstance === null || previousInstance === void 0 ? void 0 : previousInstance.variations) === null || _b === void 0 ? void 0 : _b[0])) {\n version += 1;\n }\n const flag = makeFlagWithValue(key, parsed.flagValues[key], version);\n (0, serialization_1.processFlag)(flag);\n this._addItem(VersionedDataKinds_1.default.Features, flag);\n });\n Object.keys(parsed.segments || {}).forEach((key) => {\n (0, serialization_1.processSegment)(parsed.segments[key]);\n this._addItem(VersionedDataKinds_1.default.Segments, parsed.segments[key]);\n });\n }\n}\nexports.default = FileDataSource;\n//# sourceMappingURL=FileDataSource.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst FileDataSource_1 = require(\"../data_sources/FileDataSource\");\n/**\n * Class for creating file data sources.\n */\nclass FileDataSourceFactory {\n constructor(_options) {\n this._options = _options;\n }\n /**\n * Method for creating instances of the file data source. This method is intended to be used\n * by the SDK.\n *\n * @param config SDK configuration required by the file data source.\n * @param filesystem Platform abstraction used for filesystem access.\n * @returns a {@link FileDataSource}\n *\n * @internal\n */\n create(ldClientContext, featureStore, initSuccessHandler, errorHandler) {\n const updatedOptions = {\n paths: this._options.paths,\n autoUpdate: this._options.autoUpdate,\n logger: this._options.logger || ldClientContext.basicConfiguration.logger,\n yamlParser: this._options.yamlParser,\n };\n return new FileDataSource_1.default(updatedOptions, ldClientContext.platform.fileSystem, featureStore, initSuccessHandler, errorHandler);\n }\n getFactory() {\n return (ldClientContext, featureStore, initSuccessHandler, errorHandler) => this.create(ldClientContext, featureStore, initSuccessHandler, errorHandler);\n }\n}\nexports.default = FileDataSourceFactory;\n//# sourceMappingURL=FileDataSourceFactory.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.variationForBoolean = exports.FALSE_VARIATION_INDEX = exports.TRUE_VARIATION_INDEX = void 0;\nexports.TRUE_VARIATION_INDEX = 0;\nexports.FALSE_VARIATION_INDEX = 1;\n/**\n * @internal\n */\nfunction variationForBoolean(val) {\n return val ? exports.TRUE_VARIATION_INDEX : exports.FALSE_VARIATION_INDEX;\n}\nexports.variationForBoolean = variationForBoolean;\n//# sourceMappingURL=booleanVariation.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst booleanVariation_1 = require(\"./booleanVariation\");\n/**\n * A builder for feature flag rules to be used with {@link TestDataFlagBuilder}.\n *\n * In the LaunchDarkly model, a flag can have any number of rules, and\n * a rule can have any number of clauses. A clause is an individual test\n * such as \"name is 'X'\". A rule matches a user if all of the rule's\n * clauses match the user.\n *\n * To start defining a rule, use one of the flag builder's matching methods\n * such as `ifMatch`. This defines the first clause for the rule. Optionally,\n * you may add more clauses with the rule builder's methods such as `andMatch`.\n * Finally, call `thenReturn` to finish defining the rule.\n */\nclass TestDataRuleBuilder {\n /**\n * @internal\n */\n constructor(_flagBuilder, clauses, variation) {\n this._flagBuilder = _flagBuilder;\n this._clauses = [];\n if (clauses) {\n this._clauses = [...clauses];\n }\n if (variation !== undefined) {\n this._variation = variation;\n }\n }\n /**\n * Adds another clause using the \"is one of\" operator.\n *\n * For example, this creates a rule that returns `true` if the name is\n * \"Patsy\" and the country is \"gb\":\n *\n * testData.flag('flag')\n * .ifMatch('name', 'Patsy')\n * .andMatch('country', 'gb')\n * .thenReturn(true)\n *\n * @param contextKind the kind of the context\n * @param attribute the user attribute to match against\n * @param values values to compare to\n * @return the flag rule builder\n */\n andMatch(contextKind, attribute, ...values) {\n this._clauses.push({\n contextKind,\n attribute,\n attributeReference: new js_sdk_common_1.AttributeReference(attribute),\n op: 'in',\n values,\n negate: false,\n });\n return this;\n }\n /**\n * Adds another clause using the \"is not one of\" operator.\n *\n * For example, this creates a rule that returns `true` if the name is\n * \"Patsy\" and the country is not \"gb\":\n *\n * testData.flag('flag')\n * .ifMatch('name', 'Patsy')\n * .andNotMatch('country', 'gb')\n * .thenReturn(true)\n *\n * @param contextKind the kind of the context\n * @param attribute the user attribute to match against\n * @param values values to compare to\n * @return the flag rule builder\n */\n andNotMatch(contextKind, attribute, ...values) {\n this._clauses.push({\n contextKind,\n attribute,\n attributeReference: new js_sdk_common_1.AttributeReference(attribute),\n op: 'in',\n values,\n negate: true,\n });\n return this;\n }\n /**\n * Finishes defining the rule, specifying the result value as either a boolean or an index\n *\n * If the variation is a boolean value and the flag was not already a boolean\n * flag, this also changes it to be a boolean flag.\n *\n * If the variation is an integer, it specifies a variation out of whatever\n * variation values have already been defined.\n *\n * @param variation\n * either `true` or `false` or the index of the desired variation:\n * 0 for the first, 1 for the second, etc.\n * @return the flag rule builder\n */\n thenReturn(variation) {\n if (js_sdk_common_1.TypeValidators.Boolean.is(variation)) {\n this._flagBuilder.booleanFlag();\n return this.thenReturn((0, booleanVariation_1.variationForBoolean)(variation));\n }\n this._variation = variation;\n this._flagBuilder.addRule(this);\n return this._flagBuilder;\n }\n /**\n * @internal\n */\n build(id) {\n return {\n id: `rule${id}`,\n variation: this._variation,\n clauses: this._clauses,\n };\n }\n /**\n * @internal\n */\n clone() {\n return new TestDataRuleBuilder(this._flagBuilder, this._clauses, this._variation);\n }\n}\nexports.default = TestDataRuleBuilder;\n//# sourceMappingURL=TestDataRuleBuilder.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst js_sdk_common_1 = require(\"@launchdarkly/js-sdk-common\");\nconst booleanVariation_1 = require(\"./booleanVariation\");\nconst TestDataRuleBuilder_1 = require(\"./TestDataRuleBuilder\");\n/**\n * A builder for feature flag configurations to be used with {@link TestData}.\n */\nclass TestDataFlagBuilder {\n /**\n * @internal\n */\n constructor(_key, data) {\n this._key = _key;\n this._data = {\n on: true,\n variations: [],\n };\n if (data) {\n // Not the fastest way to deep copy, but this is a testing mechanism.\n this._data = {\n on: data.on,\n variations: [...data.variations],\n };\n if (data.offVariation !== undefined) {\n this._data.offVariation = data.offVariation;\n }\n if (data.fallthroughVariation !== undefined) {\n this._data.fallthroughVariation = data.fallthroughVariation;\n }\n if (data.targetsByVariation) {\n this._data.targetsByVariation = JSON.parse(JSON.stringify(data.targetsByVariation));\n }\n if (data.rules) {\n this._data.rules = [];\n data.rules.forEach((rule) => {\n var _a;\n (_a = this._data.rules) === null || _a === void 0 ? void 0 : _a.push(rule.clone());\n });\n }\n }\n }\n get _isBooleanFlag() {\n return (this._data.variations.length === 2 &&\n this._data.variations[booleanVariation_1.TRUE_VARIATION_INDEX] === true &&\n this._data.variations[booleanVariation_1.FALSE_VARIATION_INDEX] === false);\n }\n /**\n * A shortcut for setting the flag to use the standard boolean configuration.\n *\n * This is the default for all new flags created with {@link TestData.flag}. The\n * flag will have two variations, `true` and `false` (in that order). It\n * will return `false` whenever targeting is off and `true` when targeting\n * is on unless other settings specify otherwise.\n *\n * @return the flag builder\n */\n booleanFlag() {\n if (this._isBooleanFlag) {\n return this;\n }\n // Change this flag into a boolean flag.\n return this.variations(true, false)\n .fallthroughVariation(booleanVariation_1.TRUE_VARIATION_INDEX)\n .offVariation(booleanVariation_1.FALSE_VARIATION_INDEX);\n }\n /**\n * Sets the allowable variation values for the flag.\n *\n * The values may be of any JSON-compatible type: boolean, number, string, array,\n * or object. For instance, a boolean flag normally has `variations(true, false)`;\n * a string-valued flag might have `variations(\"red\", \"green\")`; etc.\n *\n * @param values any number of variation values\n * @return the flag builder\n */\n variations(...values) {\n this._data.variations = [...values];\n return this;\n }\n /**\n * Sets targeting to be on or off for this flag.\n *\n * The effect of this depends on the rest of the flag configuration, just\n * as it does on the real LaunchDarkly dashboard. In the default configuration\n * that you get from calling {@link TestData.flag} with a new flag key, the flag\n * will return `false` whenever targeting is off and `true` when targeting\n * is on.\n *\n * @param targetingOn true if targeting should be on\n * @return the flag builder\n */\n on(targetingOn) {\n this._data.on = targetingOn;\n return this;\n }\n /**\n * Specifies the fallthrough variation for a flag. The fallthrough is\n * the value that is returned if targeting is on and the user was not\n * matched by a more specific target or rule.\n *\n * If a boolean is supplied, and the flag was previously configured with\n * other variations, this also changes it to a boolean flag.\n *\n * @param variation\n * either `true` or `false` or the index of the desired fallthrough\n * variation: 0 for the first, 1 for the second, etc.\n * @return the flag builder\n */\n fallthroughVariation(variation) {\n if (js_sdk_common_1.TypeValidators.Boolean.is(variation)) {\n return this.booleanFlag().fallthroughVariation((0, booleanVariation_1.variationForBoolean)(variation));\n }\n this._data.fallthroughVariation = variation;\n return this;\n }\n /**\n * Specifies the off variation for a flag. This is the variation that is\n * returned whenever targeting is off.\n *\n * If a boolean is supplied, and the flag was previously configured with\n * other variations, this also changes it to a boolean flag.\n *\n * @param variation\n * either `true` or `false` or the index of the desired off\n * variation: 0 for the first, 1 for the second, etc.\n * @return the flag builder\n */\n offVariation(variation) {\n if (js_sdk_common_1.TypeValidators.Boolean.is(variation)) {\n return this.booleanFlag().offVariation((0, booleanVariation_1.variationForBoolean)(variation));\n }\n this._data.offVariation = variation;\n return this;\n }\n /**\n * Sets the flag to always return the specified variation for all contexts.\n *\n * Targeting is switched on, any existing targets or rules are removed,\n * and the fallthrough variation is set to the specified value. The off\n * variation is left unchanged.\n *\n * If a boolean is supplied, and the flag was previously configured with\n * other variations, this also changes it to a boolean flag.\n *\n * @param varation\n * either `true` or `false` or the index of the desired variation:\n * 0 for the first, 1 for the second, etc.\n * @return the flag builder\n */\n variationForAll(variation) {\n return this.on(true).clearRules().clearAllTargets().fallthroughVariation(variation);\n }\n /**\n * Sets the flag to always return the specified variation value for all contexts.\n *\n * The value may be of any valid JSON type. This method changes the flag to have\n * only a single variation, which is this value, and to return the same variation\n * regardless of whether targeting is on or off. Any existing targets or rules\n * are removed.\n *\n * @param value The desired value to be returned for all contexts.\n * @return the flag builder\n */\n valueForAll(value) {\n return this.variations(value).variationForAll(0);\n }\n /**\n * Sets the flag to return the specified variation for a specific context key\n * when targeting is on. The context kind for contexts created with this method\n * will be 'user'.\n *\n * This has no effect when targeting is turned off for the flag.\n *\n * If the variation is a boolean value and the flag was not already a boolean\n * flag, this also changes it to be a boolean flag.\n *\n * If the variation is an integer, it specifies a variation out of whatever\n * variation values have already been defined.\n *\n * @param contextKey a context key\n * @param variation\n * either `true` or `false` or the index of the desired variation:\n * 0 for the first, 1 for the second, etc.\n * @return the flag builder\n */\n variationForUser(contextKey, variation) {\n return this.variationForContext('user', contextKey, variation);\n }\n /**\n * Sets the flag to return the specified variation for a specific context key\n * when targeting is on.\n *\n * This has no effect when targeting is turned off for the flag.\n *\n * If the variation is a boolean value and the flag was not already a boolean\n * flag, this also changes it to be a boolean flag.\n *\n * If the variation is an integer, it specifies a variation out of whatever\n * variation values have already been defined.\n *\n * @param contextKind a context kind\n * @param contextKey a context key\n * @param variation\n * either `true` or `false` or the index of the desired variation:\n * 0 for the first, 1 for the second, etc.\n * @return the flag builder\n */\n variationForContext(contextKind, contextKey, variation) {\n if (js_sdk_common_1.TypeValidators.Boolean.is(variation)) {\n return this.booleanFlag().variationForContext(contextKind, contextKey, (0, booleanVariation_1.variationForBoolean)(variation));\n }\n if (!this._data.targetsByVariation) {\n this._data.targetsByVariation = {};\n }\n this._data.variations.forEach((_, i) => {\n if (i === variation) {\n // If there is nothing set at the current variation then set it to the empty array\n const targetsForVariation = this._data.targetsByVariation[i] || {};\n if (!(contextKind in targetsForVariation)) {\n targetsForVariation[contextKind] = [];\n }\n const exists = targetsForVariation[contextKind].indexOf(contextKey) !== -1;\n // Add context to current variation set if they aren't already there\n if (!exists) {\n targetsForVariation[contextKind].push(contextKey);\n }\n this._data.targetsByVariation[i] = targetsForVariation;\n }\n else {\n // remove user from other variation set if necessary\n const targetsForVariation = this._data.targetsByVariation[i];\n if (targetsForVariation) {\n const targetsForContextKind = targetsForVariation[contextKind];\n if (targetsForContextKind) {\n const targetIndex = targetsForContextKind.indexOf(contextKey);\n if (targetIndex !== -1) {\n targetsForContextKind.splice(targetIndex, 1);\n if (!targetsForContextKind.length) {\n delete targetsForVariation[contextKind];\n }\n }\n }\n if (!Object.keys(targetsForVariation).length) {\n delete this._data.targetsByVariation[i];\n }\n }\n }\n });\n return this;\n }\n /**\n * Removes any existing rules from the flag. This undoes the effect of methods\n * like {@link ifMatch}.\n *\n * @return the same flag builder\n */\n clearRules() {\n delete this._data.rules;\n return this;\n }\n /**\n * Removes any existing targets from the flag. This undoes the effect of\n * methods like {@link variationForContext}.\n *\n * @return the same flag builder\n */\n clearAllTargets() {\n delete this._data.targetsByVariation;\n return this;\n }\n /**\n * Starts defining a flag rule using the \"is one of\" operator.\n *\n * For example, this creates a rule that returnes `true` if the name is\n * \"Patsy\" or \"Edina\":\n *\n * testData.flag('flag')\n * .ifMatch('user', name', 'Patsy', 'Edina')\n * .thenReturn(true)\n *\n * @param contextKind the kind of the context\n * @param attribute the context attribute to match against\n * @param values values to compare to\n * @return\n * a flag rule builder; call `thenReturn` to finish the rule\n * or add more tests with another method like `andMatch`\n */\n ifMatch(contextKind, attribute, ...values) {\n const flagRuleBuilder = new TestDataRuleBuilder_1.default(this);\n return flagRuleBuilder.andMatch(contextKind, attribute, ...values);\n }\n /**\n * Starts defining a flag rule using the \"is not one of\" operator.\n *\n * For example, this creates a rule that returns `true` if the name is\n * neither \"Saffron\" nor \"Bubble\":\n *\n * testData.flag('flag')\n * .ifNotMatch('user', 'name', 'Saffron', 'Bubble')\n * .thenReturn(true)\n *\n * @param contextKind the kind of the context\n * @param attribute the user attribute to match against\n * @param values values to compare to\n * @return\n * a flag rule builder; call `thenReturn` to finish the rule\n * or add more tests with another method like `andNotMatch`\n */\n ifNotMatch(contextKind, attribute, ...values) {\n const flagRuleBuilder = new TestDataRuleBuilder_1.default(this);\n return flagRuleBuilder.andNotMatch(contextKind, attribute, ...values);\n }\n checkRatio(ratio) {\n var _a;\n this._data.migration = (_a = this._data.migration) !== null && _a !== void 0 ? _a : {};\n this._data.migration.checkRatio = ratio;\n return this;\n }\n samplingRatio(ratio) {\n this._data.samplingRatio = ratio;\n return this;\n }\n /**\n * @internal\n */\n addRule(flagRuleBuilder) {\n if (!this._data.rules) {\n this._data.rules = [];\n }\n this._data.rules.push(flagRuleBuilder);\n }\n /**\n * @internal\n */\n build(version) {\n const baseFlagObject = {\n key: this._key,\n version,\n on: this._data.on,\n offVariation: this._data.offVariation,\n fallthrough: {\n variation: this._data.fallthroughVariation,\n },\n variations: [...this._data.variations],\n migration: this._data.migration,\n samplingRatio: this._data.samplingRatio,\n };\n if (this._data.targetsByVariation) {\n const contextTargets = [];\n const userTargets = [];\n Object.entries(this._data.targetsByVariation).forEach(([variation, contextTargetsForVariation]) => {\n Object.entries(contextTargetsForVariation).forEach(([contextKind, values]) => {\n const numberVariation = parseInt(variation, 10);\n contextTargets.push({\n contextKind,\n values: contextKind === 'user' ? [] : values,\n // Iterating the object it will be a string.\n variation: numberVariation,\n });\n if (contextKind === 'user') {\n userTargets.push({ values, variation: numberVariation });\n }\n });\n });\n baseFlagObject.targets = userTargets;\n baseFlagObject.contextTargets = contextTargets;\n }\n if (this._data.rules) {\n baseFlagObject.rules = this._data.rules.map((rule, i) => rule.build(String(i)));\n }\n return baseFlagObject;\n }\n /**\n * @internal\n */\n clone() {\n return new TestDataFlagBuilder(this._key, this._data);\n }\n /**\n * @internal\n */\n getKey() {\n return this._key;\n }\n}\nexports.default = TestDataFlagBuilder;\n//# sourceMappingURL=TestDataFlagBuilder.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @internal\n */\nclass TestDataSource {\n constructor(_featureStore, initialFlags, initialSegments, _onStop, _listeners) {\n this._featureStore = _featureStore;\n this._onStop = _onStop;\n this._listeners = _listeners;\n // make copies of these objects to decouple them from the originals\n // so updates made to the originals don't affect these internal data.\n this._flags = Object.assign({}, initialFlags);\n this._segments = Object.assign({}, initialSegments);\n }\n async start() {\n this._listeners.forEach(({ processJson }) => {\n const dataJson = { data: { flags: this._flags, segments: this._segments } };\n processJson(dataJson);\n });\n }\n stop() {\n this._onStop(this);\n }\n close() {\n this.stop();\n }\n async upsert(kind, value) {\n return this._featureStore.upsert(kind, value);\n }\n}\nexports.default = TestDataSource;\n//# sourceMappingURL=TestDataSource.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst createStreamListeners_1 = require(\"../../data_sources/createStreamListeners\");\nconst AsyncStoreFacade_1 = require(\"../../store/AsyncStoreFacade\");\nconst serialization_1 = require(\"../../store/serialization\");\nconst VersionedDataKinds_1 = require(\"../../store/VersionedDataKinds\");\nconst TestDataFlagBuilder_1 = require(\"./TestDataFlagBuilder\");\nconst TestDataSource_1 = require(\"./TestDataSource\");\n/**\n * A mechanism for providing dynamically updatable feature flag state in a simplified form to an SDK\n * client in test scenarios.\n *\n * Unlike `FileData`, this mechanism does not use any external resources. It provides only the\n * data that the application has put into it using the {@link TestData.update} method.\n *\n * ```\n * // Import TestData from the integrations package of the SDK you are using.\n * // This is a common implementation and may be used in multiple SDKs.\n *\n * const td = TestData();\n * testData.update(td.flag(\"flag-key-1\").booleanFlag().variationForAll(true));\n * // Use the initialization mechanism specified by your SDK.\n * const client = LDClient.init(sdkKey, { updateProcessor: td.getFactory() });\n *\n * // flags can be updated at any time:\n * td.update(td.flag(\"flag-key-2\")\n * .variationForContext(\"user\", \"some-user-key\", true)\n * .fallthroughVariation(false));\n * ```\n *\n * The above example uses a simple boolean flag, but more complex configurations are possible using\n * the methods of the {@link TestDataFlagBuilder} that is returned by {@link TestData.flag}.\n * {@link TestDataFlagBuilder} supports many of the ways a flag can be configured on the\n * LaunchDarkly dashboard, but does not currently support\n * 1. rule operators other than \"in\" and \"not in\", or\n * 2. percentage rollouts.\n *\n * If the same `TestData` instance is used to configure multiple `LDClient` instances,\n * any changes made to the data will propagate to all of the `LDClient`s.\n */\nclass TestData {\n constructor() {\n this._currentFlags = {};\n this._currentSegments = {};\n this._dataSources = [];\n this._flagBuilders = {};\n }\n /**\n * Get a factory for update processors that will be attached to this TestData instance.\n * @returns An update processor factory.\n */\n getFactory() {\n // Provides an arrow function to prevent needed to bind the method to\n // maintain `this`.\n return (clientContext, featureStore, initSuccessHandler, _errorHandler) => {\n const listeners = (0, createStreamListeners_1.createStreamListeners)(featureStore, clientContext.basicConfiguration.logger, {\n put: initSuccessHandler,\n });\n const newSource = new TestDataSource_1.default(new AsyncStoreFacade_1.default(featureStore), this._currentFlags, this._currentSegments, (tds) => {\n this._dataSources.splice(this._dataSources.indexOf(tds));\n }, listeners);\n this._dataSources.push(newSource);\n return newSource;\n };\n }\n /**\n * Creates or copies a {@link TestDataFlagBuilder} for building a test flag configuration.\n *\n * If the flag key has already been defined in this `TestData` instance,\n * then the builder starts with the same configuration that was last\n * provided for this flag.\n *\n * Otherwise, it starts with a new default configuration in which the flag\n * has `true` and `false` variations, is `true` for all users when targeting\n * is turned on and `false` otherwise, and currently has targeting turned on.\n * You can change any of those properties and provide more complex behavior\n * using the `TestDataFlagBuilder` methods.\n *\n * Once you have set the desired configuration, pass the builder to\n * {@link TestData.update}.\n *\n * @param key the flag key\n * @returns a flag configuration builder\n *\n */\n flag(key) {\n if (this._flagBuilders[key]) {\n return this._flagBuilders[key].clone();\n }\n return new TestDataFlagBuilder_1.default(key).booleanFlag();\n }\n /**\n * Updates the test data with the specified flag configuration.\n *\n * This has the same effect as if a flag were added or modified in the\n * LaunchDarkly dashboard. It immediately propagates the flag changes to\n * any `LDClient` instance(s) that you have already configured to use\n * this `TestData`. If no `LDClient` has been started yet, it simply adds\n * this flag to the test data which will be provided to any `LDClient`\n * that you subsequently configure.\n *\n * Any subsequent changes to this `TestDataFlagBuilder` instance do not affect\n * the test data unless you call `update` again.\n *\n * @param flagBuilder a flag configuration builder\n * @return a promise that will resolve when the feature stores are updated\n */\n update(flagBuilder) {\n const flagKey = flagBuilder.getKey();\n const oldItem = this._currentFlags[flagKey];\n const oldVersion = oldItem ? oldItem.version : 0;\n const newFlag = flagBuilder.build(oldVersion + 1);\n this._currentFlags[flagKey] = newFlag;\n this._flagBuilders[flagKey] = flagBuilder.clone();\n return Promise.all(this._dataSources.map((impl) => impl.upsert(VersionedDataKinds_1.default.Features, newFlag)));\n }\n /**\n * Copies a full feature flag data model object into the test data.\n *\n * It immediately propagates the flag change to any `LDClient` instance(s) that you have already\n * configured to use this `TestData`. If no `LDClient` has been started yet, it simply adds this\n * flag to the test data which will be provided to any LDClient that you subsequently configure.\n *\n * Use this method if you need to use advanced flag configuration properties that are not\n * supported by the simplified {@link TestDataFlagBuilder} API. Otherwise it is recommended to use\n * the regular {@link flag}/{@link update} mechanism to avoid dependencies on details of the data\n * model.\n *\n * You cannot make incremental changes with {@link flag}/{@link update} to a flag that has been\n * added in this way; you can only replace it with an entirely new flag configuration.\n *\n * @param flagConfig the flag configuration as a JSON object\n * @return a promise that will resolve when the feature stores are updated\n */\n usePreconfiguredFlag(inConfig) {\n // We need to do things like process attribute reference, and\n // we do not want to modify the passed in value.\n const flagConfig = JSON.parse(JSON.stringify(inConfig));\n const oldItem = this._currentFlags[flagConfig.key];\n const newItem = Object.assign(Object.assign({}, flagConfig), { version: oldItem ? oldItem.version + 1 : flagConfig.version });\n (0, serialization_1.processFlag)(newItem);\n this._currentFlags[flagConfig.key] = newItem;\n return Promise.all(this._dataSources.map((impl) => impl.upsert(VersionedDataKinds_1.default.Features, newItem)));\n }\n /**\n * Copies a full segment data model object into the test data.\n *\n * It immediately propagates the change to any `LDClient` instance(s) that you have already\n * configured to use this `TestData`. If no `LDClient` has been started yet, it simply adds\n * this segment to the test data which will be provided to any LDClient that you subsequently\n * configure.\n *\n * This method is currently the only way to inject segment data, since there is no builder\n * API for segments. It is mainly intended for the SDK's own tests of segment functionality,\n * since application tests that need to produce a desired evaluation state could do so more easily\n * by just setting flag values.\n *\n * @param segmentConfig the segment configuration as a JSON object\n * @return a promise that will resolve when the feature stores are updated\n */\n usePreconfiguredSegment(inConfig) {\n const segmentConfig = JSON.parse(JSON.stringify(inConfig));\n const oldItem = this._currentSegments[segmentConfig.key];\n const newItem = Object.assign(Object.assign({}, segmentConfig), { version: oldItem ? oldItem.version + 1 : segmentConfig.version });\n (0, serialization_1.processSegment)(newItem);\n this._currentSegments[segmentConfig.key] = newItem;\n return Promise.all(this._dataSources.map((impl) => impl.upsert(VersionedDataKinds_1.default.Segments, newItem)));\n }\n}\nexports.default = TestData;\n//# sourceMappingURL=TestData.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TestDataRuleBuilder = exports.TestDataFlagBuilder = exports.TestData = void 0;\nconst TestData_1 = require(\"./TestData\");\nexports.TestData = TestData_1.default;\nconst TestDataFlagBuilder_1 = require(\"./TestDataFlagBuilder\");\nexports.TestDataFlagBuilder = TestDataFlagBuilder_1.default;\nconst TestDataRuleBuilder_1 = require(\"./TestDataRuleBuilder\");\nexports.TestDataRuleBuilder = TestDataRuleBuilder_1.default;\n//# sourceMappingURL=index.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.FileDataSourceFactory = void 0;\nconst FileDataSourceFactory_1 = require(\"./FileDataSourceFactory\");\nexports.FileDataSourceFactory = FileDataSourceFactory_1.default;\n__exportStar(require(\"./test_data\"), exports);\n// Api exported integrations, but it was overwritten by the more specific\n// integrations from index.ts.\n__exportStar(require(\"../api/integrations\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass NullEventSource {\n constructor(url, options) {\n this.handlers = {};\n this.closed = false;\n this.url = url;\n this.options = options;\n }\n addEventListener(type, listener) {\n this.handlers[type] = listener;\n }\n close() {\n this.closed = true;\n }\n simulateError(error) {\n const shouldRetry = this.options.errorFilter(error);\n if (!shouldRetry) {\n this.closed = true;\n }\n }\n}\nexports.default = NullEventSource;\n//# sourceMappingURL=NullEventSource.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.NullEventSource = void 0;\nconst NullEventSource_1 = require(\"./NullEventSource\");\nexports.NullEventSource = NullEventSource_1.default;\n//# sourceMappingURL=index.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TtlCache = void 0;\nconst TtlCache_1 = require(\"../cache/TtlCache\");\nexports.TtlCache = TtlCache_1.default;\n//# sourceMappingURL=index.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createMigration = exports.LDMigrationSuccess = exports.LDMigrationError = exports.BigSegmentStoreStatusProviderImpl = exports.LDClientImpl = exports.internalServer = exports.platform = exports.integrations = void 0;\nconst BigSegmentStatusProviderImpl_1 = require(\"./BigSegmentStatusProviderImpl\");\nexports.BigSegmentStoreStatusProviderImpl = BigSegmentStatusProviderImpl_1.default;\nconst LDClientImpl_1 = require(\"./LDClientImpl\");\nexports.LDClientImpl = LDClientImpl_1.default;\nconst Migration_1 = require(\"./Migration\");\nObject.defineProperty(exports, \"createMigration\", { enumerable: true, get: function () { return Migration_1.createMigration; } });\nObject.defineProperty(exports, \"LDMigrationError\", { enumerable: true, get: function () { return Migration_1.LDMigrationError; } });\nObject.defineProperty(exports, \"LDMigrationSuccess\", { enumerable: true, get: function () { return Migration_1.LDMigrationSuccess; } });\nexports.integrations = require(\"./integrations\");\nexports.platform = require(\"@launchdarkly/js-sdk-common\");\n__exportStar(require(\"./api\"), exports);\n__exportStar(require(\"./store\"), exports);\n__exportStar(require(\"./events\"), exports);\n__exportStar(require(\"@launchdarkly/js-sdk-common\"), exports);\nexports.internalServer = require(\"./internal\");\n//# sourceMappingURL=index.js.map","import CryptoJS from 'crypto-js';\nexport default class CryptoJSHasher {\n constructor(algorithm) {\n let algo;\n switch (algorithm) {\n case 'sha1':\n algo = CryptoJS.algo.SHA1;\n break;\n case 'sha256':\n algo = CryptoJS.algo.SHA256;\n break;\n default:\n throw new Error('unsupported hash algorithm. Only sha1 and sha256 are supported.');\n }\n this._cryptoJSHasher = algo.create();\n }\n digest(encoding) {\n const result = this._cryptoJSHasher.finalize();\n let enc;\n switch (encoding) {\n case 'base64':\n enc = CryptoJS.enc.Base64;\n break;\n case 'hex':\n enc = CryptoJS.enc.Hex;\n break;\n default:\n throw new Error('unsupported output encoding. Only base64 and hex are supported.');\n }\n return result.toString(enc);\n }\n update(data) {\n this._cryptoJSHasher.update(data);\n return this;\n }\n}\n//# sourceMappingURL=cryptoJSHasher.js.map","import CryptoJS from 'crypto-js';\nexport default class CryptoJSHmac {\n constructor(algorithm, key) {\n let algo;\n switch (algorithm) {\n case 'sha1':\n algo = CryptoJS.algo.SHA1;\n break;\n case 'sha256':\n algo = CryptoJS.algo.SHA256;\n break;\n default:\n throw new Error('unsupported hash algorithm. Only sha1 and sha256 are supported.');\n }\n this._cryptoJSHmac = CryptoJS.algo.HMAC.create(algo, key);\n }\n digest(encoding) {\n const result = this._cryptoJSHmac.finalize();\n if (encoding === 'base64') {\n return result.toString(CryptoJS.enc.Base64);\n }\n if (encoding === 'hex') {\n return result.toString(CryptoJS.enc.Hex);\n }\n throw new Error('unsupported output encoding. Only base64 and hex are supported.');\n }\n update(data) {\n this._cryptoJSHmac.update(data);\n return this;\n }\n}\n//# sourceMappingURL=cryptoJSHmac.js.map","import CryptoJSHasher from './cryptoJSHasher';\nimport CryptoJSHmac from './cryptoJSHmac';\n/**\n * Uses crypto-js as substitute to node:crypto because the latter\n * is not yet supported in some runtimes.\n * https://cryptojs.gitbook.io/docs/\n */\nexport default class EdgeCrypto {\n createHash(algorithm) {\n return new CryptoJSHasher(algorithm);\n }\n createHmac(algorithm, key) {\n return new CryptoJSHmac(algorithm, key);\n }\n randomUUID() {\n return crypto.randomUUID();\n }\n}\n//# sourceMappingURL=index.js.map","import { NullEventSource } from '@launchdarkly/js-server-sdk-common';\nexport default class EdgeRequests {\n fetch(url, options = {}) {\n // @ts-ignore\n return fetch(url, options);\n }\n createEventSource(url, eventSourceInitDict) {\n return new NullEventSource(url, eventSourceInitDict);\n }\n getEventSourceCapabilities() {\n return {\n readTimeout: false,\n headers: false,\n customMethod: false,\n };\n }\n}\n//# sourceMappingURL=requests.js.map","import EdgeCrypto from './crypto';\nimport EdgeRequests from './requests';\nexport default class EdgePlatform {\n constructor(info) {\n this.crypto = new EdgeCrypto();\n this.requests = new EdgeRequests();\n this.info = info;\n }\n}\n//# sourceMappingURL=index.js.map","import { noop } from '@launchdarkly/js-server-sdk-common';\nconst createCallbacks = (emitter, logger) => ({\n onError: (err) => {\n if (emitter.listenerCount('error')) {\n emitter.emit('error', err);\n }\n else {\n logger === null || logger === void 0 ? void 0 : logger.error(err.message);\n }\n },\n onFailed: (err) => {\n emitter.emit('failed', err);\n },\n onReady: () => {\n emitter.emit('ready');\n },\n onUpdate: noop,\n hasEventListeners: () => false,\n});\nexport default createCallbacks;\n//# sourceMappingURL=createCallbacks.js.map","import { BasicLogger } from '@launchdarkly/js-server-sdk-common';\nexport const defaultOptions = {\n stream: false,\n sendEvents: false,\n useLdd: true,\n diagnosticOptOut: true,\n logger: BasicLogger.get(),\n};\nconst createOptions = (options) => (Object.assign(Object.assign({}, defaultOptions), options));\nexport default createOptions;\n//# sourceMappingURL=createOptions.js.map","import { EventEmitter } from 'node:events';\nimport { LDClientImpl } from '@launchdarkly/js-server-sdk-common';\nimport EdgePlatform from '../platform';\nimport createCallbacks from './createCallbacks';\nimport createOptions from './createOptions';\n/**\n * The LaunchDarkly SDK edge client object.\n */\nexport default class LDClient extends LDClientImpl {\n // clientSideID is only used to query the edge key-value store and send analytics, not to initialize with LD servers\n constructor(clientSideID, platformInfo, options) {\n const em = new EventEmitter();\n const platform = new EdgePlatform(platformInfo);\n const internalOptions = {\n analyticsEventPath: `/events/bulk/${clientSideID}`,\n diagnosticEventPath: `/events/diagnostic/${clientSideID}`,\n includeAuthorizationHeader: false,\n };\n const finalOptions = createOptions(options);\n super(clientSideID, platform, finalOptions, createCallbacks(em, finalOptions.logger), internalOptions);\n this.emitter = em;\n }\n}\n//# sourceMappingURL=LDClient.js.map","import { deserializePoll, noop, reviveFullPayload } from '@launchdarkly/js-server-sdk-common';\nexport class EdgeFeatureStore {\n constructor(_edgeProvider, sdkKey, _description, _logger, _cache) {\n this._edgeProvider = _edgeProvider;\n this._description = _description;\n this._logger = _logger;\n this._cache = _cache;\n // unused\n this.delete = noop;\n this.upsert = noop;\n this._rootKey = `LD-Env-${sdkKey}`;\n }\n async get(kind, dataKey, callback) {\n const { namespace } = kind;\n const kindKey = namespace === 'features' ? 'flags' : namespace;\n this._logger.debug(`Requesting ${dataKey} from ${this._rootKey}.${kindKey}`);\n try {\n const storePayload = await this._getStorePayload();\n switch (namespace) {\n case 'features':\n callback(storePayload.flags[dataKey]);\n break;\n case 'segments':\n callback(storePayload.segments[dataKey]);\n break;\n default:\n callback(null);\n }\n }\n catch (err) {\n this._logger.error(err);\n callback(null);\n }\n }\n async all(kind, callback = noop) {\n const { namespace } = kind;\n const kindKey = namespace === 'features' ? 'flags' : namespace;\n this._logger.debug(`Requesting all from ${this._rootKey}.${kindKey}`);\n try {\n const storePayload = await this._getStorePayload();\n switch (namespace) {\n case 'features':\n callback(storePayload.flags);\n break;\n case 'segments':\n callback(storePayload.segments);\n break;\n default:\n callback({});\n }\n }\n catch (err) {\n this._logger.error(err);\n callback({});\n }\n }\n /**\n * This method is used to retrieve the environment payload from the edge\n * provider. If a cache is provided, it will serve from that.\n */\n async _getStorePayload() {\n var _a, _b;\n let payload = (_a = this._cache) === null || _a === void 0 ? void 0 : _a.get(this._rootKey);\n if (payload !== undefined) {\n return payload;\n }\n const providerData = await this._edgeProvider.get(this._rootKey);\n if (!providerData) {\n throw new Error(`${this._rootKey} is not found in KV.`);\n }\n payload =\n typeof providerData === 'string'\n ? deserializePoll(providerData)\n : reviveFullPayload(providerData);\n if (!payload) {\n throw new Error(`Error deserializing ${this._rootKey}`);\n }\n (_b = this._cache) === null || _b === void 0 ? void 0 : _b.set(this._rootKey, payload);\n return payload;\n }\n async initialized(callback = noop) {\n const config = await this._edgeProvider.get(this._rootKey);\n const result = config !== null;\n this._logger.debug(`Is ${this._rootKey} initialized? ${result}`);\n callback(result);\n }\n init(allData, callback) {\n callback();\n }\n getDescription() {\n return this._description;\n }\n close() {\n var _a;\n return (_a = this._cache) === null || _a === void 0 ? void 0 : _a.close();\n }\n}\n//# sourceMappingURL=EdgeFeatureStore.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nconst validateOptions = (sdkKey, options) => {\n const { featureStore, logger, sendEvents } = options, rest = __rest(options, [\"featureStore\", \"logger\", \"sendEvents\"]);\n if (!sdkKey) {\n throw new Error('You must configure the client with a client key');\n }\n if (!featureStore || typeof featureStore !== 'object' || !featureStore.get) {\n throw new Error('You must configure the client with a feature store');\n }\n if (!logger) {\n throw new Error('You must configure the client with a logger');\n }\n if (JSON.stringify(rest) !== '{}') {\n throw new Error(`Invalid configuration: ${Object.keys(rest).toString()} not supported`);\n }\n return true;\n};\nexport default validateOptions;\n//# sourceMappingURL=validateOptions.js.map","import type { Info, PlatformData, SdkData } from '@launchdarkly/js-server-sdk-common-edge';\n\nconst name = '@launchdarkly/cloudflare-server-sdk';\nconst version = '2.7.13'; // x-release-please-version\n\nclass CloudflarePlatformInfo implements Info {\n platformData(): PlatformData {\n return {\n name: 'Cloudflare',\n };\n }\n\n sdkData(): SdkData {\n return {\n name,\n version,\n userAgentBase: 'CloudflareEdgeSDK',\n };\n }\n}\n\nconst createPlatformInfo = (): CloudflarePlatformInfo => new CloudflarePlatformInfo();\n\nexport default createPlatformInfo;\n","/**\n * This is the API reference for the Cloudflare LaunchDarkly SDK.\n *\n * In typical usage, you will call {@link init} once at startup time to obtain an instance of\n * {@link LDClient}, which provides access to all of the SDK's functionality.\n *\n * For more information, see the SDK reference guide.\n *\n * @packageDocumentation\n */\nimport type { KVNamespace } from '@cloudflare/workers-types';\n\nimport {\n BasicLogger,\n EdgeFeatureStore,\n init as initEdge,\n internalServer,\n type LDClient,\n type LDOptions as LDOptionsCommon,\n} from '@launchdarkly/js-server-sdk-common-edge';\n\nimport createPlatformInfo from './createPlatformInfo';\n\nexport {\n createMigration,\n BasicLogger,\n type BasicLoggerOptions,\n type Cache,\n EdgeFeatureStore,\n type EdgeProvider,\n integrations,\n IsMigrationStage,\n type LDBigSegmentsOptions,\n type LDClient,\n type LDClientContext,\n type LDContext,\n LDConcurrentExecution,\n type LDEvaluationDetail,\n type LDEvaluationDetailTyped,\n type LDFeatureStore,\n type LDFlagValue,\n type LDFlagsState,\n type LDFlagsStateOptions,\n type LDLogger,\n type LDMigration,\n type LDMethodResult,\n type LDMigrationOptions,\n type LDMigrationOpEvent,\n type LDMigrationOrigin,\n type LDMigrationReadResult,\n type LDMigrationResult,\n LDMigrationStage,\n LDMigrationSuccess,\n type LDMigrationWriteResult,\n type LDMigrationVariation,\n type LDProxyOptions,\n type LDTLSOptions,\n type LDWaitForInitializationOptions,\n} from '@launchdarkly/js-server-sdk-common-edge';\n\nexport type TtlCacheOptions = internalServer.TtlCacheOptions;\n\n/**\n * The Launchdarkly Edge SDKs configuration options.\n */\nexport type LDOptions = {\n /**\n * Optional TTL cache configuration which allows for caching feature flags in\n * memory.\n */\n cache?: TtlCacheOptions;\n} & LDOptionsCommon;\n\n/**\n * Creates an instance of the Cloudflare LaunchDarkly client.\n *\n * Applications should instantiate a single instance for the lifetime of the worker.\n * The client will begin attempting to connect to the configured Cloudflare KV as\n * soon as it is created. To determine when it is ready to use, call {@link LDClient.waitForInitialization}.\n *\n * **Important:** Do **not** try to instantiate `LDClient` with its constructor\n * (`new LDClient()/new LDClientImpl()/new LDClient()`); the SDK does not currently support\n * this.\n *\n * @param clientSideID\n * The client side ID. This is only used to query the kvNamespace above,\n * not to connect with LaunchDarkly servers.\n * @param kvNamespace\n * The Cloudflare KV configured for LaunchDarkly.\n * @param options\n * Optional configuration settings.\n * @return\n * The new {@link LDClient} instance.\n */\nexport const init = (\n clientSideID: string,\n kvNamespace: KVNamespace,\n options: LDOptions = {},\n): LDClient => {\n const logger = options.logger ?? BasicLogger.get();\n\n const { cache: _cacheOptions, ...rest } = options;\n const cache = options.cache ? new internalServer.TtlCache(options.cache) : undefined;\n return initEdge(clientSideID, createPlatformInfo(), {\n featureStore: new EdgeFeatureStore(kvNamespace, clientSideID, 'Cloudflare', logger, cache),\n logger,\n ...rest,\n });\n};\n","import { EdgeFeatureStore, LDClient } from './api';\nimport validateOptions from './utils/validateOptions';\nexport * from '@launchdarkly/js-server-sdk-common';\nexport { EdgeFeatureStore };\n/**\n * Do not use this function directly.\n *\n * This is an internal API to be used directly only by LaunchDarkly Edge SDKs.\n */\nexport const init = (clientSideID, platformInfo, options) => {\n // this throws if options are invalid\n validateOptions(clientSideID, options);\n return new LDClient(clientSideID, platformInfo, options);\n};\n//# sourceMappingURL=index.js.map"],"names":["Object","defineProperty","BigSegmentStatusProviderImpl","value","default","constructor","_onRequestStatus","this","getStatus","_lastStatus","requireStatus","notify","_a","_listener","call","setListener","listener","setStatus","status","unescape","ref","indexOf","replace","AttributeReference","refOrLiteral","literal","literalVal","_components","isValid","redactionName","startsWith","match","reference","isLiteral","slice","substring","split","map","component","getComponents","get","target","components","current","index","length","prototype","hasOwnProperty","Array","isArray","getComponent","depth","isKind","compare","other","every","InvalidReference","FactoryOrInstance","is","factoryOrInstance","typeOfFactory","getType","Type","typeName","example","_typeName","typeOf","u","TypeArray","val","NumberWithMinimum","min","super","StringMatchingRegex","expression","Function","NullableBoolean","DATE_REGEX","DateValidator","test","KindValidator","TypeValidators","createTypeArray","numberWithMin","stringMatchingRegex","isSingleKind","context","String","kind","isMultiKind","isLegacyUser","undefined","canonicalize","object","visited","JSON","stringify","includes","Error","item","join","keys","sort","key","filter","Number","ObjectOrFactory","StringArray","Boolean","Date","Kind","DEFAULT_KIND","encodeKey","validKind","validKey","processPrivateAttributes","privateAttributes","literals","privateAttribute","Context","valid","message","_isMulti","_isUser","_wasLegacy","_contexts","_contextForError","_getValueFromContext","anonymous","_contextForKind","_context","_fromMultiKindContext","kinds","kindsValid","contextsAreObjects","contexts","reduce","acc","singleContext","kindOrContext","_meta","values","part","created","_privateAttributeReferences","_fromSingleKindContext","kindValid","keyValid","privateAttributeReferences","_fromLegacyUser","user","singleKindContext","custom","name","ip","firstName","lastName","email","avatar","country","privateAttributeNames","legacyToSingleKind","fromLDContext","toLDContext","getContexts","result","forEach","kindAndContext","nestedContext","valueForKind","canonicalKey","kindsAndKeys","entries","legacy","canonicalUnfilteredJson","_cachedCanonicalJson","UserKind","protectedAttributes","str","legacyTopLevelCopyAttributes","ContextFilter","_allAttributesPrivate","_privateAttributes","redactAnonymousAttributes","_filterSingleKind","filteredMulti","single","_getAttributesToFilter","redactAllAttributes","k","attr","some","protectedAttr","cloned","excluded","references","stack","push","ptr","source","parent","pop","redactRef","find","a","b","cloneWithRedactions","redactedAttributes","DefaultBackoff","initialRetryDelayMillis","_retryResetIntervalMillis","_random","Math","random","_retryCount","_initialRetryDelayMillis","max","_maxExponent","ceil","log2","_backoff","exponent","delay","_jitter","computedDelayMillis","trunc","success","timeStampMs","now","_activeSince","fail","CallbackHandler","_dataCallback","_statusCallback","_disabled","disable","dataHandler","basis","data","statusHandler","err","DataSourceState","DataSourceList","circular","initialList","_list","_circular","_pos","next","input","remove","element","splice","reset","pos","clear","LDFileDataSourceError","LDPollingError","recoverable","LDStreamingError","code","LDFlagDeliveryFallbackError","DataSourceErrorKind","AutoEnvAttributes","LDEventType","LDDeliveryStatus","exports","index$1","freeze","__proto__","tryStringify","toString","error","TypeError","escapes","s","d","toNumber","i","parseInt","toInt","f","parseFloat","toFloat","j","o","O","c","format","args","formatString","shift","out","char","charAt","nextChar","LogPriority","LEVEL_NAMES","BasicLogger","options","_logLevel","level","info","_name","_formatter","formatter","destination","_destinations","debug","warn","_tryFormat","_tryWrite","msg","console","_log","prefix","loggerRequirements","SafeLogger","logger","fallback","validator","_logger","_fallback","OptionMessages","deprecated","oldName","newName","optionBelowMinimum","unknownOption","wrongOptionType","expectedType","actualType","wrongOptionTypeBoolean","invalidTagValue","tagValueTooLong","partialEndpoint","regexValidator","tagValidator","canonicalizeUri","uri","canonicalizePath","path","ServiceEndpoints","streaming","polling","events","DEFAULT_EVENTS","analyticsEventPath","diagnosticEventPath","includeAuthorizationHeader","payloadFilterKey","getWithParams","parameters","getEventsUri","endpoints","canonicalizedPath","LDUnexpectedResponseError","LDClientError","LDTimeoutError","isHttpRecoverable","isHttpLocallyRecoverable","deepCompact","obj","ignoreKeys","isEmptyObject","httpErrorMessage","retryMessage","desc","sleep","async","delayMillis","Promise","resolve","setTimeout","ErrorKinds","ErrorKinds$1","ClientMessages","invalidMetricValue","badType","MissingContextKeyNoEvent","EventSender","clientContext","baseHeaders","basicConfiguration","platform","serviceEndpoints","crypto","requests","_defaultHeaders","_eventsUri","_diagnosticEventsUri","_requests","_crypto","_tryPostingEvents","payloadId","canRetry","tryRes","Succeeded","headers","resHeaders","fetch","body","compressBodyIfPossible","method","keepalive","serverDate","parse","serverTime","Failed","FailedAndMustShutDown","sendEventData","type","AnalyticsEvents","randomUUID","isFeature","SummaryCounter","count","defValue","version","variation","increment","EventSummarizer","_singleContext","_contextFilter","_startDate","_endDate","_counters","_contextKinds","summarizeEvent","event","excludeFromSummaries","countKey","counterKey","counter","Set","add","creationDate","getSummary","features","flagSummary","counters","contextKinds","counterOut","unknown","startDate","endDate","_clearSummary","LDInvalidSDKKeyError","MultiEventSummarizer","_summarizers","summarizer","getSummaries","summarizersToFlush","shouldSample","ratio","truncated","floor","InputCustomEvent","metricValue","samplingRatio","url","InputEvalEvent","withReasons","trackEvents","prereqOf","reason","debugEventsUntilDate","InputIdentifyEvent","PAYLOAD_ID","PayloadProcessor","_objProcessors","_errorHandler","_listeners","_tempId","_tempBasis","_tempUpdates","_processServerIntent","_resetAll","payloads","payload","intentCode","_processIntentNone","id","_processPutObject","_processObj","_processDeleteObject","deleted","intent","updates","it","_resetAfterEmission","_processPayloadTransferred","state","_processGoodbye","_processError","_resetAfterError","addPayloadListener","removePayloadListener","processEvents","jsonObj","UNKNOWN_PLUGIN_NAME","safeGetName","plugin","getMetadata","DiagnosticsManager","sdkKey","_platform","_diagnosticInitConfig","_streamInits","_startTime","_dataSinceDate","_id","diagnosticId","sdkKeySuffix","createInitEvent","sdkData","platformData","sdk","configuration","osArch","os","arch","osName","osVersion","additional","recordStreamInit","timestamp","failed","durationMillis","createStatsEventAndReset","droppedEvents","deduplicatedUsers","eventsInLastBatch","currentTime","evt","dataSinceDate","streamInits","EventFactoryBase","_withReasons","evalEvent","e","flagKey","defaultVal","addExperimentData","prereqOfFlagKey","unknownFlagEvent","defVal","identifyEvent","customEvent","EventProcessor","_config","_contextDeduplicator","_diagnosticsManager","start","summariesPerContext","_queue","_lastKnownPastTime","_droppedEvents","_deduplicatedUsers","_exceededCapacity","_eventsInLastBatch","_shutdown","_flushUsersTimer","_capacity","eventsCapacity","_eventSender","allAttributesPrivate","_summarizer","flushInterval","setInterval","flush","_flushTimer","initEvent","_postDiagnosticEvent","_diagnosticsTimer","statsEvent","diagnosticRecordingInterval","DiagnosticEvent","close","clearInterval","eventsToFlush","summary","sendEvent","inputEvent","migrationEvent","_enqueue","isFeatureEvent","addFullEvent","addDebugEvent","_shouldDebugEvent","isIdentifyEvent","isIdentify","shouldNotDeduplicate","processContext","_makeOutputEvent","contextKeys","selector","res","FDv1PayloadAdaptor","processor","_processor","_selector","useSelector","processFullTransfer","flags","flag","segments","segment","NullEventProcessor","PayloadStreamReader","eventStream","_attachHandler","_payloadProcessor","stream","eventName","addEventListener","InvalidData","Unknown","initMetadataFromHeaders","initHeaders","envIdKey","toLowerCase","environmentId","safeGetHooks","environmentMetadata","plugins","hooks","pluginHooks","getHooks","safeRegisterPlugins","client","register","ApplicationTags","tags","application","tagKeys","flatMap","ClientContext","offline","CompositeDataSource","initializers","synchronizers","fdv1Synchronizers","_transitionConditions","Valid","durationMS","transition","Interrupted","_stopped","_cancelTokens","_cancellableDelay","delayMS","timeout","promise","_","cancel","clearTimeout","_externalTransitionPromise","resolveTransition","_externalTransitionResolve","_initPhaseActive","_initFactories","_syncFactories","_fdv1Synchronizers","dataCallback","statusCallback","selectorGetter","sanitizedStatusCallback","_wrapStatusCallbackWithSanitizer","lastTransition","Initializing","dataSource","currentDS","isPrimary","cullDSFactory","_pickDataSource","internalTransitionPromise","transitionResolve","lastState","cancelScheduledTransition","callbackHandler","_consumeCancelToken","Closed","condition","_lookupTransitionCondition","then","transitionRequest","race","stop","cancelDelay","delayedTransition","_reset","tr","factory","excludeRecover","lastStatus","lastErr","alreadyReportedInitializing","sanitized","base64UrlEncode","encoding","btoa","cancelableTimedPromise","t","taskName","_res","reject","clone","createSafeLogger","basicLogger","debounce","fn","delayMs","timer","defaultHeaders","userAgentHeaderName","userAgentBase","wrapperName","wrapperVersion","authorization","fastDeepEqual","Map","size","has","ArrayBuffer","isView","RegExp","valueOf","getPollingUri","combinedParameters","getStreamingUri","internal","noop","secondsToMillis","sec","shouldRetry","subsystem","timedPromise","LDFlagsStateOptions","LDFlagsState","LDMigrationStage","LDMigrationStage_1","IsMigrationStage","LDMigrationOpEvent","LDConsistencyCheck","__createBinding","__exportStar","LDMigrationVariation","create","m","k2","getOwnPropertyDescriptor","__esModule","writable","configurable","enumerable","p","require$$0","require$$1","require$$2","require$$3","require$$4","LDBigSegmentsOptions","LDOptions","LDProxyOptions","LDTLSOptions","LDExecutionOrdering","LDExecution","LDMigrationOptions","LDConcurrentExecution","LDSerialExecution","ordering","Serial","Concurrent","LDDataSystemOptions","isCustomOptions","isStreamingOnlyOptions","isStandardOptions","dataSourceOptionsType","isPollingOnlyOptions","require$$5","LDClient","LDMigration","DataKind","LDFeatureStore","LDTransactionalFeatureStore","LDWaitForInitializationOptions","FileDataSourceOptions","Hook","BigSegmentStore","BigSegmentStoreMembership","BigSegmentStoreMetadata","BigSegmentStoreStatus","DataCollection","FullDataSet","KeyedItems","VersionedData","BigSegmentStoreStatusProvider","persistent_store","require$$6","require$$7","require$$8","require$$9","require$$10","LDDataSourceUpdates","LDFeatureRequestor","LDTransactionalDataSourceUpdates","subsystems","interfaces","integrations","LruCache_1","_keyMap","_head","_tail","_size","_max","_values","_keys","_next","Uint32Array","_prev","maxAge","_lastUpdated","fill","_maxAge","set","_index","_setTail","lastUpdated","_evict","head","delete","_link","n","BigSegmentsManager_1","js_sdk_common_1","BigSegmentStatusProviderImpl_1","_store","config","statusProvider","_pollStoreAndUpdateStatus","_staleTimeMs","staleAfter","pollIntervalMs","statusPollInterval","_pollHandle","_cache","userCacheSize","userCacheTime","getUserMembership","userKey","_b","_c","memberCache","membership","_hashForUserKey","cacheItem","available","stale","newStatus","metadata","lastUpToDate","_isStale","hasher","createHash","update","digest","createPluginEnvironmentMetadata_1","createPluginEnvironmentMetadata","_sdkKey","applicationInfo","createPayloadListenerFDv2","createPayloadListener","dataSourceUpdates","initializedCallback","dataContainer","initMetadata","converted","namespace","namespaceForKind","assign","applyChanges","VersionedDataKinds_1","VersionedDataKinds","getKeyFromPath","streamApiPath","Features","Segments","serialization","deserializeSegment","serializeSegment","deserializeFlag","serializeFlag","deserializeDelete","deserializePatch","deserializePoll","reviveFullPayload","processSegment","processFlag","replacer","nullReplacer","TARGET_LIST_ARRAY_CUTOFF","excludeKeys","filteredEntries","_value","generated_includedSet","included","generated_excludedSet","includedContexts","generated_valuesSet","excludedContexts","processRollout","rollout","bucketBy","bucketByAttributeReference","contextKind","fallthrough","rules","rule","clauses","clause","attribute","attributeReference","_d","_e","rolloutContextKind","tryParse","flagsAndSegments","deserializeAll","parsed","createStreamListeners","createDeleteListener","createPatchListener","createPutListener","serialization_1","onPutCompleteHandler","deserializeData","processJson","initData","init","onPatchCompleteHandler","upsert","onDeleteCompleteHandler","onCompleteHandlers","listeners","put","patch","NamespacedDataSet_1","_itemsByNamespace","items","removeAll","enumerate","callback","mergeFrom","bind","DependencyTracker_1","_dependenciesFrom","_dependenciesTo","updateDependenciesFrom","newDependencySet","oldDependencySet","depNs","depKey","depsToThisDep","updateModifiedItems","inDependencySet","modifiedNamespace","modifiedKey","affectedItems","DataSourceUpdates_1","computeDependencies","ret","isFlag","isSegment","prerequisites","prereq","itemWithRuleClauses","op","_featureStore","_hasEventListeners","_onChange","_dependencyTracker","allData","checkForChanges","doInit","oldData","updatedItems","oldDataForKind","newDataForKind","mergedData","addIfModified","sendChangeEvents","all","oldFlags","oldSegments","doUpsert","oldItem","oldValue","newValue","toDataSet","dataSet","FileLoader_1","_filesystem","_paths","_watch","_callback","_watchers","_fileData","_fileTimestamps","loadAndWatch","promises","readFile","timeStamp","getFileTimestamp","results","watcher","watch","updatePath","_debounceCallback","_debounceHandle","fileDataInitilizerFDv2","_validateInputs","paths","fileSystem","_yamlParser","yamlParser","payloadProcessor","errorKind","adaptor","_fileLoader","parsedData","_processFileData","catch","NetworkError","curr","endsWith","OneShotInitializerFDv2_1","_requestor","requestAllData","ErrorResponse","promisify_1","AsyncStoreFacade_1","store","cb","initialized","getInitMetadata","getInitMetaData","AsyncTransactionalStoreFacade_1","isStale","record","expiration","TtlCache_1","_options","_storage","_checkIntervalHandle","_purgeStale","checkInterval","ttl","persistentStoreKinds","deserialize","serialize","serializedItem","priority","sortDataSet_1","persistentStoreKinds_1","topologicalSort","itemsMap","sortedItems","unvisitedItems","visit","preReq","prereqKey","dataMap","kindNamespace","i1","i2","UpdateQueue_1","enqueue","updateFn","executePendingUpdates","PersistentDataStoreWrapper_1","cacheKey","allForKindCacheKey","initializationCheckedKey","itemIfNotDeleted","deletedDescriptor","descriptor","deserializedItem","_core","_isInitialized","_itemCache","_allItemsCache","itemForKey","itemDescriptor","persistKind","storeInitialized","getAll","storeItems","filteredItems","filteredItem","updatedDescriptor","getDescription","InMemoryFeatureStore_1","_allData","_initCalled","_initMetadata","tempData","existingItems","old","getSelector","TransactionalFeatureStore_1","_nonTransPersistenceStore","_activeStore","_memoryStore","params","dataKind","previousPromise","nextParams","TransactionalFeatureStore","PersistentDataStoreWrapper","AsyncTransactionalStoreFacade","AsyncStoreFacade","PollingProcessor_1","store_1","_pollInterval","_initSuccessHandler","_poll","reportJsonError","startTime","elapsed","sleepFor","_timeoutHandle","PollingProcessorFDv2_1","_processResponseAsFDv1","_f","_g","processFDv1FlagsAndSegments","_h","Requestor_1","_path","_eTagCache","_headers","_serviceEndpoints","_requestWithETagCache","requestUrl","cacheEntry","cachedETag","etag","updatedOptions","text","queryParams","fromEntries","StreamingProcessor_1","streamUriPath","_streamInitialReconnectDelay","_streamUri","_logConnectionStarted","_connectionAttemptStartTime","_logConnectionResult","_retryAndHandleError","eventSource","createEventSource","errorFilter","readTimeoutMillis","retryResetIntervalMillis","_eventSource","onclose","onerror","onopen","_initHeaders","onretrying","dataJson","errorHandler","StreamingProcessorFDv2_1","_streamUriPath","_parameters","_logConnectionAttempt","fallbackErr","TransactionalDataSourceUpdates_1","iterateData","doApplyChanges","defaultValues","DEFAULT_STREAM_RECONNECT_DELAY","DEFAULT_POLL_INTERVAL","LDDataSystemOptions_1","validations","baseUri","streamUri","eventsUri","capacity","featureStore","dataSystem","bigSegments","updateProcessor","pollInterval","proxyOptions","streamInitialReconnectDelay","useLdd","sendEvents","contextKeysCapacity","contextKeysFlushInterval","tlsParams","diagnosticOptOut","enableEventCompression","defaultStandardDataSourceOptions","defaultStreamingDataSourceOptions","defaultPollingDataSourceOptions","defaultDataSystemOptions","validateTypesAndNames","defaults","errors","validatedOptions","optionName","optionValue","internalOptions","topLevelResult","streamingEndpointSpecified","pollingEndpointSpecified","eventEndpointSpecified","validateEndpoints","dsErrors","dsResult","allErrors","persistentStore","validatedDataSourceOptions","validateDataSystemOptions","validatedDSOptions","featureStoreFactory","updateProcessorFactory","getImplementationHooks","createDiagnosticsInitConfig_1","api_1","Configuration_1","_j","_k","_l","_m","pollingIntervalMillis","reconnectTimeMillis","streamDisabled","customBaseURI","customStreamURI","customEventsURI","connectTimeoutMillis","socketTimeoutMillis","eventsFlushIntervalMillis","contextKeysFlushIntervalMillis","diagnosticRecordingIntervalMillis","streamingDisabled","usingRelayDaemon","usingProxy","usingProxyAuthenticator","usingProxyAuth","dataStoreType","collection","allAsync","allSeriesAsync","firstResult","operator","seriesAsync","check","firstSeriesAsync","Reasons_1","Reasons","prerequisiteFailed","prerequisiteKey","ruleMatch","ruleId","ruleIndex","Fallthrough","Off","TargetMatch","EvalResult_1","EvalResult","isError","detail","isOff","setDefault","def","forError","variationIndex","forSuccess","Bucketer_1","_sha1Hex","hash","bucket","salt","kindForRollout","seed","bucketableValue","isInteger","valueForBucketing","hashKey","variations","getBucketBy","getOffVariation","getVariation","KEY_ATTR_REF","MalformedFlag","offVariation","isExperiment","evalTargets_1","collection_1","variations_1","evalTarget","contextKey","contextTargets","userTarget","targets","ut","makeBigSegmentRef_1","generation","Operations","semver_1","VERSION_COMPONENTS_REGEX","parseSemver","exec","transformed","semVerOperator","aVer","bVer","makeOperator","converter","parseDate","operators","in","matches","pattern","safeRegexMatch","contains","lessThan","lessThanOrEqual","greaterThan","greaterThanOrEqual","before","after","semVerEqual","semVerLessThan","semVerGreaterThan","execute","matchClause","maybeNegate","Operations_1","negate","matchAny","testValue","contextValue","segmentSearch","userTargets","userTargetSet","targetIndex","matchSegmentTargets_1","Evaluator_1","matchClause_1","bigSegmentsStatusPriority","HEALTHY","STALE","STORE_ERROR","NOT_CONFIGURED","getBigSegmentsStatusPriority","computeUpdatedBigSegmentsStatus","latest","makeMatch","isMatch","makeError","queries","_queries","_bucketer","evaluate","eventFactory","evaluateCb","_evaluateInternal","bigSegmentsStatus","visitedFlags","topLevel","on","_checkPrerequisites","targetRes","_evaluateRules","evalRes","_variationForContext","prereqResult","iterCb","updatedVisitedFlags","getFlag","prereqFlag","evalEventServer","ruleResult","_ruleMatchContext","_clauseMatchContext","segmentsVisited","errorResult","getSegment","newVisited","segmentMatchContext","varOrRollout","hadContext","updatedReason","sum","variate","weight","untracked","inExperiment","lastVariate","segmentRuleMatchContext","simpleSegmentMatchContext","unbounded","includeExclude","evalResult","matched","bigSegmentKind","unboundedContextKind","keyForBigSegment","bigSegmentsMembership","bigSegmentMatchContext","getBigSegmentsMembership","segmentRef","ContextDeduplicator_1","_contextKeysCache","inCache","isExperiment_1","trackEventsFallthrough","EventFactory_1","EventFactory","prereqOfFlag","FlagsStateBuilder_1","_valid","_flagValues","_flagMetadata","addFlag","trackReason","detailsOnlyIfTracked","meta","omitDetails","build","allValues","getFlagValue","getFlagReason","toJSON","$flagsState","$valid","HookRunner_1","UNKNOWN_HOOK_NAME","_hooks","withEvaluationSeries","defaultValue","methodName","withEvaluationSeriesExtraDetail","hookContext","_prepareHooks","hookData","_executeBeforeEvaluation","_executeAfterEvaluation","_tryExecuteStage","hookName","stage","_hookName","hook","updatedData","hookIndex","afterEvaluation","beforeEvaluation","addHook","MigrationOpEventConversion","areValidBooleans","new","validateMeasurement","measurement","areValidNumbers","isErrorMeasurement","isConsistencyMeasurement","isInvokedMeasurement","inEvent","operation","contextKeysOrContext","evaluation","validated","inReason","outReason","validateEvaluation","measurements","MigrationOpTracker_1","data_1","isPopulated","isNaN","_flagKey","_defaultStage","_stage","_reason","_checkRatio","_variation","_version","_samplingRatio","_errors","_wasInvoked","_consistencyCheck","NotChecked","_latencyMeasurement","NaN","_operation","origin","consistency","Consistent","Inconsistent","exception","latency","invoked","createEvent","_measurementConsistencyCheck","_populateInvoked","_populateConsistency","_populateLatency","_populateErrors","_logTag","_latencyConsistencyMessage","_errorConsistencyMessage","_consistencyCheckConsistencyMessage","_checkOriginEventConsistency","newIsPopulated","oldIsPopulated","LDClientImpl_1","createPayloadListenerFDv2_1","createStreamListeners_1","fileDataInitilizerFDv2_1","require$$11","require$$12","require$$13","require$$14","require$$15","require$$16","require$$17","require$$18","require$$19","require$$20","require$$21","require$$22","require$$23","require$$24","MigrationOpEventConversion_1","require$$25","require$$26","require$$27","require$$28","InitState","constructFDv1","callbacks","initSuccess","dataSourceErrorHandler","onUpdate","hasEventListeners","hookRunner","diagnosticsManager","eventProcessor","bigSegmentsManager","evaluator","onError","onFailed","onReady","_initState","_eventFactoryDefault","_eventFactoryWithReasons","transactionalStore","payloadListener","_evaluator","_dataSource","_eventProcessor","_bigSegmentsManager","_hookRunner","_onError","_onFailed","_onReady","fdv1FallbackSynchronizers","initializerConfigs","synchronizerConfigs","initializerConfig","synchronizerConfig","reconnectDelay","pollingInterval","constructFDv2","_initSuccess","bigSegmentStatusProviderInternal","_dataSourceErrorHandler","_updateProcessor","Initialized","waitForInitialization","_initializedPromise","_clientWithTimeout","_rejectionReason","_initResolve","_initReject","_evaluateIfPossible","variationDetail","_typedEval","typeChecker","typedRes","boolVariation","numberVariation","stringVariation","jsonVariation","boolVariationDetail","numberVariationDetail","stringVariationDetail","jsonVariationDetail","_migrationVariationInternal","WrongType","checkRatio","migration","tracker","migrationVariation","allFlagsState","allFlagState","evalContext","doEval","allFlags","builder","clientOnly","clientSideOnly","detailsOnlyForTrackedFlags","storeItem","clientSideAvailability","usingEnvironmentId","requireExperimentData","secureModeHash","checkedContext","createHmac","hmac","isOffline","track","trackMigration","identify","_variationInternal","ClientNotReady","UserNotSpecified","FlagNotFound","errorRes","_sendEvalEvent","basePromise","cancelableTimeout","finally","Migration_1","createMigration","LDMigrationError","LDMigrationSuccess","LDMigrationOptions_1","Migration","_client","_readTable","_doSingleOp","readOld","DualWrite","Shadow","fromOld","fromNew","_doRead","_trackConsistency","Live","RampDown","readNew","Complete","_writeTable","authoritative","writeOld","nonAuthoritative","writeNew","execution","_execution","_latencyTracking","latencyTracking","_errorTracking","errorTracking","read","defaultStage","_sendEvent","write","_readSequentialFixed","_readConcurrent","fromOldPromise","fromNewPromise","_readSequentialRandom","Fixed","_trackLatency","safeCall","end","performance","FileDataSource_1","filesystem","autoUpdate","_addItem","fileData","fd","_processParsedData","flagValues","previousInstance","makeFlagWithValue","FileDataSourceFactory_1","ldClientContext","initSuccessHandler","getFactory","variationForBoolean","FALSE_VARIATION_INDEX","TRUE_VARIATION_INDEX","TestDataRuleBuilder_1","booleanVariation_1","TestDataRuleBuilder","_flagBuilder","_clauses","andMatch","andNotMatch","thenReturn","booleanFlag","addRule","TestDataFlagBuilder_1","TestDataFlagBuilder","_key","_data","fallthroughVariation","targetsByVariation","_isBooleanFlag","targetingOn","variationForAll","clearRules","clearAllTargets","valueForAll","variationForUser","variationForContext","targetsForVariation","targetsForContextKind","ifMatch","ifNotMatch","flagRuleBuilder","baseFlagObject","contextTargetsForVariation","getKey","TestDataSource_1","initialFlags","initialSegments","_onStop","_flags","_segments","TestData_1","_currentFlags","_currentSegments","_dataSources","_flagBuilders","newSource","tds","flagBuilder","oldVersion","newFlag","impl","usePreconfiguredFlag","inConfig","flagConfig","newItem","usePreconfiguredSegment","segmentConfig","test_data","TestData","FileDataSourceFactory","NullEventSource_1","handlers","closed","simulateError","NullEventSource","TtlCache","BigSegmentStoreStatusProviderImpl","LDClientImpl","internalServer","CryptoJSHasher","algorithm","algo","CryptoJS","SHA1","SHA256","_cryptoJSHasher","finalize","enc","Base64","Hex","CryptoJSHmac","_cryptoJSHmac","HMAC","EdgeCrypto","EdgeRequests","eventSourceInitDict","getEventSourceCapabilities","readTimeout","customMethod","EdgePlatform","defaultOptions","clientSideID","platformInfo","em","EventEmitter","finalOptions","createOptions","emitter","listenerCount","emit","EdgeFeatureStore","_edgeProvider","_description","_rootKey","dataKey","kindKey","storePayload","_getStorePayload","providerData","validateOptions","rest","getOwnPropertySymbols","propertyIsEnumerable","__rest","CloudflarePlatformInfo","kvNamespace","__objRest","cache","initEdge","__spreadValues"],"mappings":"yPACAA,OAAOC,eAAeC,EAAS,aAAc,CAAEC,OAAO,IA0CtDD,EAAAE,QAtCA,MACI,WAAAC,CAAYC,GACRC,KAAKD,iBAAmBA,CAChC,CAOI,SAAAE,GACI,OAAOD,KAAKE,WACpB,CAMI,mBAAMC,GAKF,OAJKH,KAAKE,mBACAF,KAAKD,mBAGRC,KAAKE,WACpB,CACI,MAAAE,GACQ,IAAAC,EACAL,KAAKE,cACqB,QAAzBG,EAAKL,KAAKM,iBAAuC,IAAhBD,GAAyBA,EAAGE,KAAKP,KAAMA,KAAKE,aAE1F,CACI,WAAAM,CAAYC,GACRT,KAAKM,UAAYG,CACzB,CACI,SAAAC,CAAUC,GACNX,KAAKE,YAAcS,CAC3B,8BC1BA,SAASC,EAASC,GACd,OAAOA,EAAIC,QAAQ,KAAOD,EAAIE,QAAQ,MAAO,KAAKA,QAAQ,MAAO,KAAOF,CAC5E,CAWA,MAAMG,EAeF,WAAAlB,CAAYmB,EAAcC,GAAU,GAChC,GAAKA,EA2BA,CACD,M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