{"version":3,"file":"index.node.es.min.mjs","sources":["../.build/utils/enums/index.js","../.build/utils/fns/index.js","../.build/logging/logger.js","../.build/error/optimizly_error.js","../.build/message/log_message.gen.js","../.build/message/error_message.gen.js","../.build/message/message_resolver.js","../.build/logging/logger_factory.js","../.build/error/error_notifier.js","../.build/error/error_notifier_factory.js","../.build/core/condition_tree_evaluator/index.js","../.build/project_config/optimizely_config.js","../.build/utils/config_validator/index.js","../.build/odp/odp_config.js","../.build/project_config/project_config.js","../.build/utils/promise/resolvablePromise.js","../.build/service.js","../.build/utils/event_emitter/event_emitter.js","../.build/project_config/project_config_manager.js","../node_modules/tslib/tslib.es6.mjs","../.build/project_config/constant.js","../.build/utils/http_request_handler/http_util.js","../.build/project_config/polling_datafile_manager.js","../.build/utils/repeater/repeater.js","../.build/utils/microtask/index.js","../.build/utils/cache/store_validator.js","../.build/project_config/config_manager_factory.js","../.build/utils/cache/store.js","../.build/event_processor/event_builder/log_event.js","../.build/utils/executor/backoff_retry_runner.js","../.build/utils/id_generator/index.js","../.build/core/decision/index.js","../.build/notification_center/type.js","../.build/shared_types.js","../.build/event_processor/event_builder/user_event.js","../.build/utils/event_tag_utils/index.js","../.build/utils/attributes_validator/index.js","../.build/event_processor/batch_event_processor.js","../.build/utils/executor/serial_runner.js","../.build/event_processor/event_store.js","../.build/event_processor/forwarding_event_processor.js","../.build/event_processor/event_processor_factory.js","../.build/utils/cache/in_memory_lru_cache.js","../.build/odp/event_manager/odp_event_api_manager.js","../.build/odp/constant.js","../.build/odp/event_manager/odp_event_manager.js","../.build/odp/event_manager/odp_event.js","../.build/vuid/vuid.js","../.build/odp/odp_manager.js","../.build/project_config/project_config_schema.js","../.build/odp/segment_manager/odp_response_schema.js","../.build/odp/segment_manager/odp_segment_api_manager.js","../.build/utils/json_schema_validator/index.js","../.build/odp/segment_manager/optimizely_segment_option.js","../.build/odp/segment_manager/odp_segment_manager.js","../.build/odp/odp_manager_factory.js","../.build/vuid/vuid_manager_factory.js","../.build/error/error_reporter.js","../.build/notification_center/index.js","../.build/optimizely_decision/index.js","../.build/optimizely_user_context/index.js","../.build/core/bucketer/bucket_value_generator.js","../.build/core/bucketer/index.js","../.build/utils/semantic_version/index.js","../.build/core/custom_attribute_condition_evaluator/index.js","../.build/core/audience_evaluator/odp_segment_condition_evaluator/index.js","../.build/core/audience_evaluator/index.js","../.build/utils/string_value_validator/index.js","../.build/utils/promise/operation_value.js","../.build/message/error_message.js","../.build/core/decision_service/index.js","../.build/optimizely/index.js","../.build/utils/user_profile_service_validator/index.js","../.build/utils/event_tags_validator/index.js","../.build/core/decision_service/cmab/cmab_client.js","../.build/core/decision_service/cmab/cmab_service.js","../.build/utils/cache/cache.js","../.build/client_factory.js","../.build/utils/http_request_handler/request_handler.node.js","../.build/event_processor/event_dispatcher/default_dispatcher.node.js","../.build/event_processor/event_dispatcher/default_dispatcher.js","../.build/project_config/config_manager_factory.node.js","../.build/event_processor/event_processor_factory.node.js","../.build/odp/odp_manager_factory.node.js","../.build/vuid/vuid_manager_factory.node.js","../.build/index.node.js"],"sourcesContent":["/**\n * Copyright 2016-2026, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport const LOG_LEVEL = {\n    NOTSET: 0,\n    DEBUG: 1,\n    INFO: 2,\n    WARNING: 3,\n    ERROR: 4,\n};\nexport const CONTROL_ATTRIBUTES = {\n    BOT_FILTERING: '$opt_bot_filtering',\n    BUCKETING_ID: '$opt_bucketing_id',\n    STICKY_BUCKETING_KEY: '$opt_experiment_bucket_map',\n    USER_AGENT: '$opt_user_agent',\n};\nexport const JAVASCRIPT_CLIENT_ENGINE = 'javascript-sdk';\nexport const NODE_CLIENT_ENGINE = 'node-sdk';\nexport const REACT_NATIVE_JS_CLIENT_ENGINE = 'react-native-js-sdk';\nexport const CLIENT_VERSION = '6.3.1';\n/*\n * Represents the source of a decision for feature management. When a feature\n * is accessed through isFeatureEnabled or getVariableValue APIs, the decision\n * source is used to decide whether to dispatch an impression event to\n * Optimizely.\n */\nexport const DECISION_SOURCES = {\n    FEATURE_TEST: 'feature-test',\n    ROLLOUT: 'rollout',\n    EXPERIMENT: 'experiment',\n    HOLDOUT: 'holdout',\n};\nexport const AUDIENCE_EVALUATION_TYPES = {\n    RULE: 'rule',\n    EXPERIMENT: 'experiment',\n};\n/*\n * Possible types of variables attached to features\n */\nexport const FEATURE_VARIABLE_TYPES = {\n    BOOLEAN: 'boolean',\n    DOUBLE: 'double',\n    INTEGER: 'integer',\n    STRING: 'string',\n    JSON: 'json',\n};\n/*\n * Supported datafile versions\n */\nexport const DATAFILE_VERSIONS = {\n    V2: '2',\n    V3: '3',\n    V4: '4',\n};\nexport const DECISION_MESSAGES = {\n    SDK_NOT_READY: 'Optimizely SDK not configured properly yet.',\n    FLAG_KEY_INVALID: 'No flag was found for key \"%s\".',\n    VARIABLE_VALUE_INVALID: 'Variable value for key \"%s\" is invalid or wrong type.',\n};\n/**\n * Default milliseconds before request timeout\n */\nexport const REQUEST_TIMEOUT_MS = 60 * 1000; // 1 minute\nexport const DEFAULT_CMAB_CACHE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes\nexport const DEFAULT_CMAB_CACHE_SIZE = 10000;\nexport const DEFAULT_CMAB_RETRIES = 1;\nexport const DEFAULT_CMAB_BACKOFF_MS = 100; // 100 milliseconds\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","/**\n * Copyright 2017, 2019-2020, 2022-2023, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { v4 } from 'uuid';\nconst MAX_SAFE_INTEGER_LIMIT = Math.pow(2, 53);\nexport function currentTimestamp() {\n    return Math.round(new Date().getTime());\n}\nexport function isSafeInteger(number) {\n    return typeof number == 'number' && Math.abs(number) <= MAX_SAFE_INTEGER_LIMIT;\n}\nexport function keyBy(arr, key) {\n    if (!arr)\n        return {};\n    const base = {};\n    assignBy(arr, key, base);\n    return base;\n}\nexport function assignBy(arr, key, base) {\n    if (!arr)\n        return;\n    arr.forEach((e) => {\n        base[e[key]] = e;\n    });\n}\nfunction isNumber(value) {\n    return typeof value === 'number';\n}\nexport function uuid() {\n    return v4();\n}\nexport function getTimestamp() {\n    return new Date().getTime();\n}\nexport function groupBy(arr, grouperFn) {\n    const grouper = {};\n    arr.forEach(item => {\n        const key = grouperFn(item);\n        grouper[key] = grouper[key] || [];\n        grouper[key].push(item);\n    });\n    return objectValues(grouper);\n}\nexport function objectValues(obj) {\n    return Object.keys(obj).map(key => obj[key]);\n}\nexport function objectEntries(obj) {\n    return Object.keys(obj).map(key => [key, obj[key]]);\n}\nexport function find(arr, cond) {\n    let found;\n    for (const item of arr) {\n        if (cond(item)) {\n            found = item;\n            break;\n        }\n    }\n    return found;\n}\n// TODO[OASIS-6649]: Don't use any type\n// eslint-disable-next-line  @typescript-eslint/no-explicit-any\nexport function sprintf(format, ...args) {\n    let i = 0;\n    return format.replace(/%s/g, function () {\n        const arg = args[i++];\n        const type = typeof arg;\n        if (type === 'function') {\n            return arg();\n        }\n        else if (type === 'string') {\n            return arg;\n        }\n        else {\n            return String(arg);\n        }\n    });\n}\n/**\n * Checks two string arrays for equality.\n * @param arrayA First Array to be compared against.\n * @param arrayB Second Array to be compared against.\n * @returns {boolean} True if both arrays are equal, otherwise returns false.\n */\nexport function checkArrayEquality(arrayA, arrayB) {\n    return arrayA.length === arrayB.length && arrayA.every((item, index) => item === arrayB[index]);\n}\nexport default {\n    checkArrayEquality,\n    currentTimestamp,\n    isSafeInteger,\n    keyBy,\n    uuid,\n    isNumber,\n    getTimestamp,\n    groupBy,\n    objectValues,\n    objectEntries,\n    find,\n    sprintf,\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","/**\n * Copyright 2019, 2024, 2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { OptimizelyError } from '../error/optimizly_error';\nimport { sprintf } from '../utils/fns';\nexport var LogLevel;\n(function (LogLevel) {\n    LogLevel[LogLevel[\"Debug\"] = 0] = \"Debug\";\n    LogLevel[LogLevel[\"Info\"] = 1] = \"Info\";\n    LogLevel[LogLevel[\"Warn\"] = 2] = \"Warn\";\n    LogLevel[LogLevel[\"Error\"] = 3] = \"Error\";\n})(LogLevel || (LogLevel = {}));\nexport const LogLevelToUpper = {\n    [LogLevel.Debug]: 'DEBUG',\n    [LogLevel.Info]: 'INFO',\n    [LogLevel.Warn]: 'WARN',\n    [LogLevel.Error]: 'ERROR',\n};\nexport const LogLevelToLower = {\n    [LogLevel.Debug]: 'debug',\n    [LogLevel.Info]: 'info',\n    [LogLevel.Warn]: 'warn',\n    [LogLevel.Error]: 'error',\n};\nexport class ConsoleLogHandler {\n    constructor(prefix) {\n        this.prefix = prefix || '[OPTIMIZELY]';\n    }\n    log(level, message) {\n        const log = `${this.prefix} - ${LogLevelToUpper[level]} ${this.getTime()} ${message}`;\n        this.consoleLog(level, log);\n    }\n    getTime() {\n        return new Date().toISOString();\n    }\n    consoleLog(logLevel, log) {\n        const methodName = LogLevelToLower[logLevel];\n        const method = console[methodName] || console.log;\n        method.call(console, log);\n    }\n}\nexport class OptimizelyLogger {\n    constructor(config) {\n        this.prefix = '';\n        this.logHandler = config.logHandler;\n        this.infoResolver = config.infoMsgResolver;\n        this.errorResolver = config.errorMsgResolver;\n        this.level = config.level;\n        if (config.name) {\n            this.setName(config.name);\n        }\n    }\n    child(name) {\n        return new OptimizelyLogger({\n            logHandler: this.logHandler,\n            infoMsgResolver: this.infoResolver,\n            errorMsgResolver: this.errorResolver,\n            level: this.level,\n            name,\n        });\n    }\n    setName(name) {\n        this.name = name;\n        this.prefix = `${name}: `;\n    }\n    info(message, ...args) {\n        this.log(LogLevel.Info, message, args);\n    }\n    debug(message, ...args) {\n        this.log(LogLevel.Debug, message, args);\n    }\n    warn(message, ...args) {\n        this.log(LogLevel.Warn, message, args);\n    }\n    error(message, ...args) {\n        this.log(LogLevel.Error, message, args);\n    }\n    handleLog(level, message, args) {\n        const log = args.length > 0 ? `${this.prefix}${sprintf(message, ...args)}`\n            : `${this.prefix}${message}`;\n        this.logHandler.log(level, log);\n    }\n    log(level, message, args) {\n        if (level < this.level) {\n            return;\n        }\n        if (message instanceof Error) {\n            if (message instanceof OptimizelyError) {\n                message.setMessage(this.errorResolver);\n            }\n            this.handleLog(level, message.message, []);\n            return;\n        }\n        let resolver = this.errorResolver;\n        if (level < LogLevel.Warn) {\n            if (!this.infoResolver) {\n                return;\n            }\n            resolver = this.infoResolver;\n        }\n        const resolvedMessage = resolver.resolve(message);\n        this.handleLog(level, resolvedMessage, args);\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=logger.js.map","import { sprintf } from \"../utils/fns\";\nexport class OptimizelyError extends Error {\n    constructor(baseMessage, ...params) {\n        super();\n        this.resolved = false;\n        this.name = 'OptimizelyError';\n        this.baseMessage = baseMessage;\n        this.params = params;\n        // this is needed cause instanceof doesn't work for\n        // custom Errors when TS is compiled to es5\n        Object.setPrototypeOf(this, OptimizelyError.prototype);\n    }\n    setMessage(resolver) {\n        if (!this.resolved) {\n            this.message = sprintf(resolver.resolve(this.baseMessage), ...this.params);\n            this.resolved = true;\n        }\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=optimizly_error.js.map","export const ADDING_AUTHORIZATION_HEADER_WITH_BEARER_TOKEN = '0';\nexport const AUDIENCE_EVALUATION_RESULT = '1';\nexport const CMAB_CACHE_ATTRIBUTES_MISMATCH = '2';\nexport const CMAB_CACHE_HIT = '3';\nexport const CMAB_CACHE_MISS = '4';\nexport const EVALUATING_AUDIENCE = '5';\nexport const FAILED_TO_PARSE_REVENUE = '6';\nexport const FAILED_TO_PARSE_VALUE = '7';\nexport const FEATURE_ENABLED_FOR_USER = '8';\nexport const FEATURE_NOT_ENABLED_FOR_USER = '9';\nexport const FEATURE_NOT_ENABLED_RETURN_DEFAULT_VARIABLE_VALUE = '10';\nexport const IGNORE_CMAB_CACHE = '11';\nexport const INVALIDATE_CMAB_CACHE = '12';\nexport const INVALID_CLIENT_ENGINE = '13';\nexport const INVALID_DECIDE_OPTIONS = '14';\nexport const INVALID_DEFAULT_DECIDE_OPTIONS = '15';\nexport const INVALID_EXPERIMENT_KEY_INFO = '16';\nexport const MAKING_DATAFILE_REQ_TO_URL_WITH_HEADERS = '17';\nexport const MISSING_ATTRIBUTE_VALUE = '18';\nexport const NOT_ACTIVATING_USER = '19';\nexport const PARSED_NUMERIC_VALUE = '20';\nexport const PARSED_REVENUE_VALUE = '21';\nexport const RESET_CMAB_CACHE = '22';\nexport const RESPONSE_STATUS_CODE = '23';\nexport const SAVED_LAST_MODIFIED_HEADER_VALUE_FROM_RESPONSE = '24';\nexport const SAVED_USER_VARIATION = '25';\nexport const SAVED_VARIATION_NOT_FOUND = '26';\nexport const SHOULD_NOT_DISPATCH_ACTIVATE = '27';\nexport const SKIPPING_JSON_VALIDATION = '28';\nexport const TRACK_EVENT = '29';\nexport const UNEXPECTED_TYPE_NULL = '30';\nexport const UPDATED_OPTIMIZELY_CONFIG = '31';\nexport const USER_HAS_NO_FORCED_VARIATION = '32';\nexport const USER_HAS_NO_FORCED_VARIATION_FOR_EXPERIMENT = '33';\nexport const USER_MAPPED_TO_FORCED_VARIATION = '34';\nexport const USER_RECEIVED_DEFAULT_VARIABLE_VALUE = '35';\nexport const USER_RECEIVED_VARIABLE_VALUE = '36';\nexport const VALID_BUCKETING_ID = '37';\nexport const VALID_DATAFILE = '38';\nexport const VALID_USER_PROFILE_SERVICE = '39';\nexport const VARIABLE_NOT_USED_RETURN_DEFAULT_VARIABLE_VALUE = '40';\nexport const VARIATION_REMOVED_FOR_USER = '41';\nexport const messages = [\n    \"Adding Authorization header with Bearer Token\",\n    \"Audience \\\"%s\\\" evaluated to %s.\",\n    \"CMAB cache attributes mismatch for user %s and rule %s, fetching new decision.\",\n    \"Cache hit for user %s and rule %s.\",\n    \"Cache miss for user %s and rule %s.\",\n    \"Starting to evaluate audience \\\"%s\\\" with conditions: %s.\",\n    \"Failed to parse revenue value \\\"%s\\\" from event tags.\",\n    \"Failed to parse event value \\\"%s\\\" from event tags.\",\n    \"Feature %s is enabled for user %s.\",\n    \"Feature %s is not enabled for user %s.\",\n    \"Feature \\\"%s\\\" is not enabled for user %s. Returning the default variable value \\\"%s\\\".\",\n    \"Ignoring CMAB cache for user %s and rule %s.\",\n    \"Invalidating CMAB cache for user %s and rule %s.\",\n    \"Invalid client engine passed: %s. Defaulting to node-sdk.\",\n    \"Provided decide options is not an array. Using default decide options.\",\n    \"Provided default decide options is not an array.\",\n    \"Experiment key %s is not in datafile. It is either invalid, paused, or archived.\",\n    \"Making datafile request to url %s with headers: %s\",\n    \"Audience condition %s evaluated to UNKNOWN because no value was passed for user attribute \\\"%s\\\".\",\n    \"Not activating user %s for experiment %s.\",\n    \"Parsed event value \\\"%s\\\" from event tags.\",\n    \"Parsed revenue value \\\"%s\\\" from event tags.\",\n    \"Resetting CMAB cache for user %s and rule %s.\",\n    \"Response status code: %s\",\n    \"Saved last modified header value from response: %s\",\n    \"Saved user profile for user \\\"%s\\\".\",\n    \"User %s was previously bucketed into variation with ID %s for experiment %s, but no matching variation was found.\",\n    \"Experiment %s is not in \\\"Running\\\" state. Not activating user.\",\n    \"Skipping JSON schema validation.\",\n    \"Tracking event %s for user %s.\",\n    \"Audience condition %s evaluated to UNKNOWN because a null value was passed for user attribute \\\"%s\\\".\",\n    \"Updated Optimizely config to revision %s (project id %s)\",\n    \"User %s is not in the forced variation map.\",\n    \"No experiment %s mapped to user %s in the forced variation map.\",\n    \"Set variation %s for experiment %s and user %s in the forced variation map.\",\n    \"User \\\"%s\\\" is not in any variation or rollout rule. Returning default value for variable \\\"%s\\\" of feature flag \\\"%s\\\".\",\n    \"Got variable value \\\"%s\\\" for variable \\\"%s\\\" of feature flag \\\"%s\\\"\",\n    \"BucketingId is valid: \\\"%s\\\"\",\n    \"Datafile is valid.\",\n    \"Valid user profile service provided.\",\n    \"Variable \\\"%s\\\" is not used in variation \\\"%s\\\". Returning default value.\",\n    \"Variation mapped to experiment %s has been removed for user %s.\"\n];\n//# sourceMappingURL=log_message.gen.js.map","export const BUCKETING_ID_NOT_STRING = '0';\nexport const CMAB_FETCH_FAILED = '1';\nexport const CONDITION_EVALUATOR_ERROR = '2';\nexport const DATAFILE_FETCH_REQUEST_FAILED = '3';\nexport const ERROR_FETCHING_DATAFILE = '4';\nexport const EVENT_ACTION_INVALID = '5';\nexport const EVENT_DATA_INVALID = '6';\nexport const EVENT_KEY_NOT_FOUND = '7';\nexport const EVENT_STORE_FULL = '8';\nexport const EXPERIMENT_KEY_NOT_IN_DATAFILE = '9';\nexport const FAILED_TO_DISPATCH_EVENTS = '10';\nexport const FAILED_TO_SEND_ODP_EVENTS = '11';\nexport const FEATURE_NOT_IN_DATAFILE = '12';\nexport const INVALID_ATTRIBUTES = '13';\nexport const INVALID_BUCKETING_ID = '14';\nexport const INVALID_CMAB_FETCH_RESPONSE = '15';\nexport const INVALID_CONFIG = '16';\nexport const INVALID_DATAFILE = '17';\nexport const INVALID_DATAFILE_MALFORMED = '18';\nexport const INVALID_DATAFILE_VERSION = '19';\nexport const INVALID_EVENT_TAGS = '20';\nexport const INVALID_EXPERIMENT_ID = '21';\nexport const INVALID_EXPERIMENT_KEY = '22';\nexport const INVALID_GROUP_ID = '23';\nexport const INVALID_INPUT_FORMAT = '24';\nexport const INVALID_JSON = '25';\nexport const INVALID_USER_ID = '26';\nexport const INVALID_USER_PROFILE_SERVICE = '27';\nexport const INVALID_VARIATION_KEY = '28';\nexport const MISSING_INTEGRATION_KEY = '29';\nexport const NOTIFICATION_LISTENER_EXCEPTION = '30';\nexport const NOT_TRACKING_USER = '31';\nexport const NO_DATAFILE_SPECIFIED = '32';\nexport const NO_EVENT_PROCESSOR = '33';\nexport const NO_JSON_PROVIDED = '34';\nexport const NO_PROJECT_CONFIG_FAILURE = '35';\nexport const NO_STATUS_CODE_IN_RESPONSE = '36';\nexport const NO_VARIATION_FOR_EXPERIMENT_KEY = '37';\nexport const ODP_CONFIG_NOT_AVAILABLE = '38';\nexport const ODP_EVENTS_SHOULD_HAVE_ATLEAST_ONE_KEY_VALUE = '39';\nexport const ODP_EVENT_FAILED = '40';\nexport const ODP_EVENT_MANAGER_STOPPED = '41';\nexport const ODP_MANAGER_MISSING = '42';\nexport const ODP_NOT_INTEGRATED = '43';\nexport const ONLY_POST_REQUESTS_ARE_SUPPORTED = '44';\nexport const OUT_OF_BOUNDS = '45';\nexport const PROMISE_NOT_ALLOWED = '46';\nexport const REQUEST_ERROR = '47';\nexport const REQUEST_TIMEOUT = '48';\nexport const RETRY_CANCELLED = '49';\nexport const SEND_BEACON_FAILED = '50';\nexport const SERVICE_NOT_RUNNING = '51';\nexport const UNABLE_TO_ATTACH_UNLOAD = '52';\nexport const UNABLE_TO_CAST_VALUE = '53';\nexport const UNABLE_TO_GET_VUID_VUID_MANAGER_NOT_AVAILABLE = '54';\nexport const UNABLE_TO_PARSE_AND_SKIPPED_HEADER = '55';\nexport const UNDEFINED_ATTRIBUTE = '56';\nexport const UNEXPECTED_CONDITION_VALUE = '57';\nexport const UNEXPECTED_RESERVED_ATTRIBUTE_PREFIX = '58';\nexport const UNEXPECTED_TYPE = '59';\nexport const UNKNOWN_CONDITION_TYPE = '60';\nexport const UNKNOWN_MATCH_TYPE = '61';\nexport const UNRECOGNIZED_ATTRIBUTE = '62';\nexport const UNRECOGNIZED_DECIDE_OPTION = '63';\nexport const UNSUPPORTED_PROTOCOL = '64';\nexport const USER_NOT_IN_FORCED_VARIATION = '65';\nexport const USER_PROFILE_LOOKUP_ERROR = '66';\nexport const USER_PROFILE_SAVE_ERROR = '67';\nexport const VARIABLE_KEY_NOT_IN_DATAFILE = '68';\nexport const VARIABLE_REQUESTED_WITH_WRONG_TYPE = '69';\nexport const VARIATION_ID_NOT_IN_DATAFILE = '70';\nexport const messages = [\n    \"BucketingID attribute is not a string. Defaulted to userId\",\n    \"CMAB decision fetch failed with status: %s\",\n    \"Error evaluating audience condition of type %s: %s\",\n    \"Datafile fetch request failed with status: %s\",\n    \"Error fetching datafile: %s\",\n    \"Event action invalid.\",\n    \"Event data invalid.\",\n    \"Event key %s is not in datafile.\",\n    \"Event store is full. Not saving event with id %d.\",\n    \"Experiment key %s is not in datafile.\",\n    \"Failed to dispatch events, status: %s\",\n    \"failed to send odp events\",\n    \"Feature key %s is not in datafile.\",\n    \"Provided attributes are in an invalid format.\",\n    \"Unable to generate hash for bucketing ID %s: %s\",\n    \"Invalid CMAB fetch response\",\n    \"Provided Optimizely config is in an invalid format.\",\n    \"Datafile is invalid - property %s: %s\",\n    \"Datafile is invalid because it is malformed.\",\n    \"This version of the JavaScript SDK does not support the given datafile version: %s\",\n    \"Provided event tags are in an invalid format.\",\n    \"Experiment ID %s is not in datafile.\",\n    \"Experiment key %s is not in datafile. It is either invalid, paused, or archived.\",\n    \"Group ID %s is not in datafile.\",\n    \"Provided %s is in an invalid format.\",\n    \"JSON object is not valid.\",\n    \"Provided user ID is in an invalid format.\",\n    \"Provided user profile service instance is in an invalid format: %s.\",\n    \"Provided variation key is in an invalid format.\",\n    \"Integration key missing from datafile. All integrations should include a key.\",\n    \"Notification listener for (%s) threw exception: %s\",\n    \"Not tracking user %s.\",\n    \"No datafile specified. Cannot start optimizely.\",\n    \"No event processor is provided\",\n    \"No JSON object to validate against schema.\",\n    \"No project config available. Failing %s.\",\n    \"No status code in response\",\n    \"No variation key %s defined in datafile for experiment %s.\",\n    \"ODP config is not available.\",\n    \"ODP events should have at least one key-value pair in identifiers.\",\n    \"ODP event send failed.\",\n    \"ODP event manager stopped before it could start\",\n    \"ODP Manager is missing. %s failed.\",\n    \"ODP is not integrated\",\n    \"Only POST requests are supported\",\n    \"Audience condition %s evaluated to UNKNOWN because the number value for user attribute \\\"%s\\\" is not in the range [-2^53, +2^53].\",\n    \"Promise value is not allowed in sync operation\",\n    \"Request error\",\n    \"Request timeout\",\n    \"Retry cancelled\",\n    \"sendBeacon failed\",\n    \"%s not running\",\n    \"unable to bind optimizely.close() to page unload event: \\\"%s\\\"\",\n    \"Unable to cast value %s to type %s, returning null.\",\n    \"Unable to get VUID - VuidManager is not available\",\n    \"Unable to parse & skipped header item\",\n    \"Provided attribute: %s has an undefined value.\",\n    \"Audience condition %s evaluated to UNKNOWN because the condition value is not supported.\",\n    \"Attribute %s unexpectedly has reserved prefix %s; using attribute ID instead of reserved attribute name.\",\n    \"Audience condition %s evaluated to UNKNOWN because a value of type \\\"%s\\\" was passed for user attribute \\\"%s\\\".\",\n    \"Audience condition %s has an unknown condition type. You may need to upgrade to a newer release of the Optimizely SDK.\",\n    \"Audience condition %s uses an unknown match type. You may need to upgrade to a newer release of the Optimizely SDK.\",\n    \"Unrecognized attribute %s provided. Pruning before sending event to Optimizely.\",\n    \"Unrecognized decide option %s provided.\",\n    \"Unsupported protocol: %s\",\n    \"User %s is not in the forced variation map. Cannot remove their forced variation.\",\n    \"Error while looking up user profile for user ID \\\"%s\\\": %s.\",\n    \"Error while saving user profile for user ID \\\"%s\\\": %s.\",\n    \"Variable with key \\\"%s\\\" associated with feature with key \\\"%s\\\" is not in datafile.\",\n    \"Requested variable type \\\"%s\\\", but variable is of type \\\"%s\\\". Use correct API to retrieve value. Returning None.\",\n    \"Variation ID %s is not in the datafile.\"\n];\n//# sourceMappingURL=error_message.gen.js.map","import { messages as infoMessages } from 'log_message';\nimport { messages as errorMessages } from 'error_message';\nexport const infoResolver = {\n    resolve(baseMessage) {\n        const messageNum = parseInt(baseMessage);\n        return infoMessages[messageNum] || baseMessage;\n    }\n};\nexport const errorResolver = {\n    resolve(baseMessage) {\n        const messageNum = parseInt(baseMessage);\n        return errorMessages[messageNum] || baseMessage;\n    }\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=message_resolver.js.map","/**\n * Copyright 2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { ConsoleLogHandler, LogLevel, OptimizelyLogger } from './logger';\nimport { errorResolver, infoResolver } from '../message/message_resolver';\nexport const INVALID_LOG_HANDLER = 'Invalid log handler';\nexport const INVALID_LEVEL_PRESET = 'Invalid level preset';\nconst debugPreset = {\n    level: LogLevel.Debug,\n    infoResolver,\n    errorResolver,\n};\nconst infoPreset = {\n    level: LogLevel.Info,\n    infoResolver,\n    errorResolver,\n};\nconst warnPreset = {\n    level: LogLevel.Warn,\n    errorResolver,\n};\nconst errorPreset = {\n    level: LogLevel.Error,\n    errorResolver,\n};\nconst levelPresetSymbol = Symbol();\nexport const DEBUG = {\n    [levelPresetSymbol]: debugPreset,\n};\nexport const INFO = {\n    [levelPresetSymbol]: infoPreset,\n};\nexport const WARN = {\n    [levelPresetSymbol]: warnPreset,\n};\nexport const ERROR = {\n    [levelPresetSymbol]: errorPreset,\n};\nexport const extractLevelPreset = (preset) => {\n    if (!preset || typeof preset !== 'object' || !preset[levelPresetSymbol]) {\n        throw new Error(INVALID_LEVEL_PRESET);\n    }\n    return preset[levelPresetSymbol];\n};\nconst loggerSymbol = Symbol();\nconst validateLogHandler = (logHandler) => {\n    if (typeof logHandler !== 'object' || typeof logHandler.log !== 'function') {\n        throw new Error(INVALID_LOG_HANDLER);\n    }\n};\nexport const createLogger = (config) => {\n    const { level, infoResolver, errorResolver } = extractLevelPreset(config.level);\n    if (config.logHandler) {\n        validateLogHandler(config.logHandler);\n    }\n    const loggerName = 'Optimizely';\n    return {\n        [loggerSymbol]: new OptimizelyLogger({\n            name: loggerName,\n            level,\n            infoMsgResolver: infoResolver,\n            errorMsgResolver: errorResolver,\n            logHandler: config.logHandler || new ConsoleLogHandler(),\n        }),\n    };\n};\nexport const wrapLogger = (logger) => {\n    return {\n        [loggerSymbol]: logger,\n    };\n};\nexport const extractLogger = (logger) => {\n    if (!logger || typeof logger !== 'object') {\n        return undefined;\n    }\n    return logger[loggerSymbol];\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=logger_factory.js.map","import { OptimizelyError } from \"./optimizly_error\";\nexport class DefaultErrorNotifier {\n    constructor(errorHandler, messageResolver, name) {\n        this.errorHandler = errorHandler;\n        this.messageResolver = messageResolver;\n        this.name = name || '';\n    }\n    notify(error) {\n        if (error instanceof OptimizelyError) {\n            error.setMessage(this.messageResolver);\n        }\n        this.errorHandler.handleError(error);\n    }\n    child(name) {\n        return new DefaultErrorNotifier(this.errorHandler, this.messageResolver, name);\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=error_notifier.js.map","/**\n * Copyright 2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { errorResolver } from \"../message/message_resolver\";\nimport { DefaultErrorNotifier } from \"./error_notifier\";\nexport const INVALID_ERROR_HANDLER = 'Invalid error handler';\nconst errorNotifierSymbol = Symbol();\nconst validateErrorHandler = (errorHandler) => {\n    if (!errorHandler || typeof errorHandler !== 'object' || typeof errorHandler.handleError !== 'function') {\n        throw new Error(INVALID_ERROR_HANDLER);\n    }\n};\nexport const createErrorNotifier = (errorHandler) => {\n    validateErrorHandler(errorHandler);\n    return {\n        [errorNotifierSymbol]: new DefaultErrorNotifier(errorHandler, errorResolver),\n    };\n};\nexport const extractErrorNotifier = (errorNotifier) => {\n    if (!errorNotifier || typeof errorNotifier !== 'object') {\n        return undefined;\n    }\n    return errorNotifier[errorNotifierSymbol];\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=error_notifier_factory.js.map","/****************************************************************************\n * Copyright 2018, 2021, Optimizely, Inc. and contributors                  *\n *                                                                          *\n * Licensed under the Apache License, Version 2.0 (the \"License\");          *\n * you may not use this file except in compliance with the License.         *\n * You may obtain a copy of the License at                                  *\n *                                                                          *\n *    http://www.apache.org/licenses/LICENSE-2.0                            *\n *                                                                          *\n * Unless required by applicable law or agreed to in writing, software      *\n * distributed under the License is distributed on an \"AS IS\" BASIS,        *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and      *\n * limitations under the License.                                           *\n ***************************************************************************/\nconst AND_CONDITION = 'and';\nconst OR_CONDITION = 'or';\nconst NOT_CONDITION = 'not';\nexport const DEFAULT_OPERATOR_TYPES = [AND_CONDITION, OR_CONDITION, NOT_CONDITION];\n/**\n * Top level method to evaluate conditions\n * @param  {ConditionTree<Leaf>}    conditions      Nested array of and/or conditions, or a single leaf\n *                                                  condition value of any type\n *                                                  Example: ['and', '0', ['or', '1', '2']]\n * @param  {LeafEvaluator<Leaf>}    leafEvaluator   Function which will be called to evaluate leaf condition\n *                                                  values\n * @return {?boolean}                               Result of evaluating the conditions using the operator\n *                                                  rules and the leaf evaluator. A return value of null\n *                                                  indicates that the conditions are invalid or unable to be\n *                                                  evaluated.\n */\nexport function evaluate(conditions, leafEvaluator) {\n    if (Array.isArray(conditions)) {\n        let firstOperator = conditions[0];\n        let restOfConditions = conditions.slice(1);\n        if (typeof firstOperator === 'string' && DEFAULT_OPERATOR_TYPES.indexOf(firstOperator) === -1) {\n            // Operator to apply is not explicit - assume 'or'\n            firstOperator = OR_CONDITION;\n            restOfConditions = conditions;\n        }\n        switch (firstOperator) {\n            case AND_CONDITION:\n                return andEvaluator(restOfConditions, leafEvaluator);\n            case NOT_CONDITION:\n                return notEvaluator(restOfConditions, leafEvaluator);\n            default:\n                // firstOperator is OR_CONDITION\n                return orEvaluator(restOfConditions, leafEvaluator);\n        }\n    }\n    const leafCondition = conditions;\n    return leafEvaluator(leafCondition);\n}\n/**\n * Evaluates an array of conditions as if the evaluator had been applied\n * to each entry and the results AND-ed together.\n * @param  {unknown[]}             conditions      Array of conditions ex: [operand_1, operand_2]\n * @param  {LeafEvaluator<Leaf>}   leafEvaluator   Function which will be called to evaluate leaf condition values\n * @return {?boolean}                              Result of evaluating the conditions. A return value of null\n *                                                 indicates that the conditions are invalid or unable to be\n *                                                 evaluated.\n */\nfunction andEvaluator(conditions, leafEvaluator) {\n    let sawNullResult = false;\n    if (Array.isArray(conditions)) {\n        for (let i = 0; i < conditions.length; i++) {\n            const conditionResult = evaluate(conditions[i], leafEvaluator);\n            if (conditionResult === false) {\n                return false;\n            }\n            if (conditionResult === null) {\n                sawNullResult = true;\n            }\n        }\n        return sawNullResult ? null : true;\n    }\n    return null;\n}\n/**\n * Evaluates an array of conditions as if the evaluator had been applied\n * to a single entry and NOT was applied to the result.\n * @param  {unknown[]}             conditions      Array of conditions ex: [operand_1]\n * @param  {LeafEvaluator<Leaf>}   leafEvaluator   Function which will be called to evaluate leaf condition values\n * @return {?boolean}                              Result of evaluating the conditions. A return value of null\n *                                                 indicates that the conditions are invalid or unable to be\n *                                                 evaluated.\n */\nfunction notEvaluator(conditions, leafEvaluator) {\n    if (Array.isArray(conditions) && conditions.length > 0) {\n        const result = evaluate(conditions[0], leafEvaluator);\n        return result === null ? null : !result;\n    }\n    return null;\n}\n/**\n * Evaluates an array of conditions as if the evaluator had been applied\n * to each entry and the results OR-ed together.\n * @param  {unknown[]}             conditions      Array of conditions ex: [operand_1, operand_2]\n * @param  {LeafEvaluator<Leaf>}   leafEvaluator   Function which will be called to evaluate leaf condition values\n * @return {?boolean}                              Result of evaluating the conditions. A return value of null\n *                                                 indicates that the conditions are invalid or unable to be\n *                                                 evaluated.\n */\nfunction orEvaluator(conditions, leafEvaluator) {\n    let sawNullResult = false;\n    if (Array.isArray(conditions)) {\n        for (let i = 0; i < conditions.length; i++) {\n            const conditionResult = evaluate(conditions[i], leafEvaluator);\n            if (conditionResult === true) {\n                return true;\n            }\n            if (conditionResult === null) {\n                sawNullResult = true;\n            }\n        }\n        return sawNullResult ? null : false;\n    }\n    return null;\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","import { DEFAULT_OPERATOR_TYPES } from '../core/condition_tree_evaluator';\n/**\n * The OptimizelyConfig class\n * @param {ProjectConfig} configObj\n * @param {string}        datafile\n */\nexport class OptimizelyConfig {\n    constructor(configObj, datafile, logger) {\n        var _a, _b;\n        this.sdkKey = (_a = configObj.sdkKey) !== null && _a !== void 0 ? _a : '';\n        this.environmentKey = (_b = configObj.environmentKey) !== null && _b !== void 0 ? _b : '';\n        this.attributes = configObj.attributes;\n        this.audiences = OptimizelyConfig.getAudiences(configObj);\n        this.events = configObj.events;\n        this.revision = configObj.revision;\n        const featureIdVariablesMap = (configObj.featureFlags || []).reduce((resultMap, feature) => {\n            resultMap[feature.id] = feature.variables;\n            return resultMap;\n        }, {});\n        const variableIdMap = OptimizelyConfig.getVariableIdMap(configObj);\n        const { experimentsMapById, experimentsMapByKey } = OptimizelyConfig.getExperimentsMap(configObj, featureIdVariablesMap, variableIdMap, logger);\n        this.experimentsMap = experimentsMapByKey;\n        this.featuresMap = OptimizelyConfig.getFeaturesMap(configObj, featureIdVariablesMap, experimentsMapById, variableIdMap);\n        this.datafile = datafile;\n    }\n    /**\n     * Get the datafile\n     * @returns {string} JSON string representation of the datafile that was used to create the current config object\n     */\n    getDatafile() {\n        return this.datafile;\n    }\n    /**\n     * Get Unique audiences list with typedAudiences as priority\n     * @param       {ProjectConfig}              configObj\n     * @returns     {OptimizelyAudience[]}       Array of unique audiences\n     */\n    static getAudiences(configObj) {\n        const audiences = [];\n        const typedAudienceIds = [];\n        (configObj.typedAudiences || []).forEach((typedAudience) => {\n            audiences.push({\n                id: typedAudience.id,\n                conditions: JSON.stringify(typedAudience.conditions),\n                name: typedAudience.name,\n            });\n            typedAudienceIds.push(typedAudience.id);\n        });\n        (configObj.audiences || []).forEach((audience) => {\n            if (typedAudienceIds.indexOf(audience.id) === -1 && audience.id != '$opt_dummy_audience') {\n                audiences.push({\n                    id: audience.id,\n                    conditions: JSON.stringify(audience.conditions),\n                    name: audience.name,\n                });\n            }\n        });\n        return audiences;\n    }\n    /**\n     * Converts list of audience conditions to serialized audiences used in experiment\n     * for examples:\n     * 1. Input: [\"or\", \"1\", \"2\"]\n     * Output: \"\\\"us\\\" OR \\\"female\\\"\"\n     * 2. Input: [\"not\", \"1\"]\n     * Output: \"NOT \\\"us\\\"\"\n     * 3. Input: [\"or\", \"1\"]\n     * Output: \"\\\"us\\\"\"\n     * 4. Input: [\"and\", [\"or\", \"1\", [\"and\", \"2\", \"3\"]], [\"and\", \"11\", [\"or\", \"12\", \"13\"]]]\n     * Output: \"(\\\"us\\\" OR (\\\"female\\\" AND \\\"adult\\\")) AND (\\\"fr\\\" AND (\\\"male\\\" OR \\\"kid\\\"))\"\n     * @param       {Array<string | string[]>}                 conditions\n     * @param       {[id: string]: Audience}                   audiencesById\n     * @returns     {string}                                   Serialized audiences condition string\n     */\n    static getSerializedAudiences(conditions, audiencesById) {\n        let serializedAudience = '';\n        if (conditions) {\n            let cond = '';\n            conditions.forEach((item) => {\n                let subAudience = '';\n                // Checks if item is list of conditions means it is sub audience\n                if (item instanceof Array) {\n                    subAudience = OptimizelyConfig.getSerializedAudiences(item, audiencesById);\n                    subAudience = `(${subAudience})`;\n                }\n                else if (DEFAULT_OPERATOR_TYPES.indexOf(item) > -1) {\n                    cond = item.toUpperCase();\n                }\n                else {\n                    // Checks if item is audience id\n                    const audienceName = audiencesById[item] ? audiencesById[item].name : item;\n                    // if audience condition is \"NOT\" then add \"NOT\" at start. Otherwise check if there is already audience id in serializedAudience then append condition between serializedAudience and item\n                    if (serializedAudience || cond === 'NOT') {\n                        cond = cond === '' ? 'OR' : cond;\n                        if (serializedAudience === '') {\n                            serializedAudience = `${cond} \"${audiencesById[item].name}\"`;\n                        }\n                        else {\n                            serializedAudience = serializedAudience.concat(` ${cond} \"${audienceName}\"`);\n                        }\n                    }\n                    else {\n                        serializedAudience = `\"${audienceName}\"`;\n                    }\n                }\n                // Checks if sub audience is empty or not\n                if (subAudience !== '') {\n                    if (serializedAudience !== '' || cond === 'NOT') {\n                        cond = cond === '' ? 'OR' : cond;\n                        if (serializedAudience === '') {\n                            serializedAudience = `${cond} ${subAudience}`;\n                        }\n                        else {\n                            serializedAudience = serializedAudience.concat(` ${cond} ${subAudience}`);\n                        }\n                    }\n                    else {\n                        serializedAudience = serializedAudience.concat(subAudience);\n                    }\n                }\n            });\n        }\n        return serializedAudience;\n    }\n    /**\n     * Get serialized audience condition string for experiment\n     * @param       {Experiment}                 experiment\n     * @param       {ProjectConfig}              configObj\n     * @returns     {string}                     Serialized audiences condition string\n     */\n    static getExperimentAudiences(experiment, configObj) {\n        if (!experiment.audienceConditions) {\n            return '';\n        }\n        return OptimizelyConfig.getSerializedAudiences(experiment.audienceConditions, configObj.audiencesById);\n    }\n    /**\n     * Make map of featureVariable which are associated with given feature experiment\n     * @param       {FeatureVariablesMap}                 featureIdVariableMap\n     * @param       {[id: string]: FeatureVariable}       variableIdMap\n     * @param       {string}                              featureId\n     * @param       {VariationVariable[] | undefined}     featureVariableUsages\n     * @param       {boolean | undefined}                 isFeatureEnabled\n     * @returns     {OptimizelyVariablesMap}              FeatureVariables mapped by key\n     */\n    static mergeFeatureVariables(featureIdVariableMap, variableIdMap, featureId, featureVariableUsages, isFeatureEnabled) {\n        const variablesMap = (featureIdVariableMap[featureId] || []).reduce((optlyVariablesMap, featureVariable) => {\n            optlyVariablesMap[featureVariable.key] = {\n                id: featureVariable.id,\n                key: featureVariable.key,\n                type: featureVariable.type,\n                value: featureVariable.defaultValue,\n            };\n            return optlyVariablesMap;\n        }, {});\n        (featureVariableUsages || []).forEach((featureVariableUsage) => {\n            const defaultVariable = variableIdMap[featureVariableUsage.id];\n            const optimizelyVariable = {\n                id: featureVariableUsage.id,\n                key: defaultVariable.key,\n                type: defaultVariable.type,\n                value: isFeatureEnabled ? featureVariableUsage.value : defaultVariable.defaultValue,\n            };\n            variablesMap[defaultVariable.key] = optimizelyVariable;\n        });\n        return variablesMap;\n    }\n    /**\n     * Gets Map of all experiment variations and variables including rollouts\n     * @param       {Variation[]}                           variations\n     * @param       {FeatureVariablesMap}                   featureIdVariableMap\n     * @param       {{[id: string]: FeatureVariable}}       variableIdMap\n     * @param       {string}                                featureId\n     * @returns     {[key: string]: Variation}              Variations mapped by key\n     */\n    static getVariationsMap(variations, featureIdVariableMap, variableIdMap, featureId) {\n        let variationsMap = {};\n        variationsMap = variations.reduce((optlyVariationsMap, variation) => {\n            const variablesMap = OptimizelyConfig.mergeFeatureVariables(featureIdVariableMap, variableIdMap, featureId, variation.variables, variation.featureEnabled);\n            optlyVariationsMap[variation.key] = {\n                id: variation.id,\n                key: variation.key,\n                featureEnabled: variation.featureEnabled,\n                variablesMap: variablesMap,\n            };\n            return optlyVariationsMap;\n        }, {});\n        return variationsMap;\n    }\n    /**\n     * Gets Map of FeatureVariable with respect to featureVariableId\n     * @param       {ProjectConfig}                        configObj\n     * @returns     {[id: string]: FeatureVariable}        FeatureVariables mapped by id\n     */\n    static getVariableIdMap(configObj) {\n        let variablesIdMap = {};\n        variablesIdMap = (configObj.featureFlags || []).reduce((resultMap, feature) => {\n            feature.variables.forEach((variable) => {\n                resultMap[variable.id] = variable;\n            });\n            return resultMap;\n        }, {});\n        return variablesIdMap;\n    }\n    /**\n     * Gets list of rollout experiments\n     * @param       {ProjectConfig}                     configObj\n     * @param       {FeatureVariablesMap}               featureVariableIdMap\n     * @param       {string}                            featureId\n     * @param       {Experiment[]}                      experiments\n     * @param       {{[id: string]: FeatureVariable}}   variableIdMap\n     * @returns     {OptimizelyExperiment[]}            List of Optimizely rollout experiments\n     */\n    static getDeliveryRules(configObj, featureVariableIdMap, featureId, experiments, variableIdMap) {\n        return experiments.map((experiment) => {\n            return {\n                id: experiment.id,\n                key: experiment.key,\n                audiences: OptimizelyConfig.getExperimentAudiences(experiment, configObj),\n                variationsMap: OptimizelyConfig.getVariationsMap(experiment.variations, featureVariableIdMap, variableIdMap, featureId),\n            };\n        });\n    }\n    /**\n     * Get Experiment Ids which are part of rollout\n     * @param       {Rollout[]}     rollouts\n     * @returns     {string[]}      Array of experiment Ids\n     */\n    static getRolloutExperimentIds(rollouts) {\n        const experimentIds = [];\n        (rollouts || []).forEach((rollout) => {\n            rollout.experiments.forEach((e) => {\n                experimentIds.push(e.id);\n            });\n        });\n        return experimentIds;\n    }\n    /**\n     * Get experiments mapped by their id's which are not part of a rollout\n     * @param       {ProjectConfig}                           configObj\n     * @param       {FeatureVariablesMap}                     featureIdVariableMap\n     * @param       {{[id: string]: FeatureVariable}}         variableIdMap\n     * @returns     { experimentsMapById: { [id: string]: OptimizelyExperiment }, experimentsMapByKey: OptimizelyExperimentsMap }      Experiments mapped by id and key\n     */\n    static getExperimentsMap(configObj, featureIdVariableMap, variableIdMap, logger) {\n        const rolloutExperimentIds = this.getRolloutExperimentIds(configObj.rollouts);\n        const experimentsMapById = {};\n        const experimentsMapByKey = {};\n        const experiments = configObj.experiments || [];\n        experiments.forEach((experiment) => {\n            if (rolloutExperimentIds.indexOf(experiment.id) !== -1) {\n                return;\n            }\n            const featureIds = configObj.experimentFeatureMap[experiment.id];\n            let featureId = '';\n            if (featureIds && featureIds.length > 0) {\n                featureId = featureIds[0];\n            }\n            const variationsMap = OptimizelyConfig.getVariationsMap(experiment.variations, featureIdVariableMap, variableIdMap, featureId.toString());\n            const optimizelyExperiment = {\n                id: experiment.id,\n                key: experiment.key,\n                audiences: OptimizelyConfig.getExperimentAudiences(experiment, configObj),\n                variationsMap: variationsMap,\n            };\n            experimentsMapById[experiment.id] = optimizelyExperiment;\n            if (experimentsMapByKey[experiment.key] && logger) {\n                logger.warn(`Duplicate experiment keys found in datafile: ${experiment.key}`);\n            }\n            experimentsMapByKey[experiment.key] = optimizelyExperiment;\n        });\n        return { experimentsMapById, experimentsMapByKey };\n    }\n    /**\n     * Get experiments mapped by their keys\n     * @param       {OptimizelyExperimentsMap}     experimentsMapById\n     * @returns     {OptimizelyExperimentsMap}     Experiments mapped by key\n     */\n    static getExperimentsKeyMap(experimentsMapById) {\n        const experimentKeysMap = {};\n        for (const id in experimentsMapById) {\n            const experiment = experimentsMapById[id];\n            experimentKeysMap[experiment.key] = experiment;\n        }\n        return experimentKeysMap;\n    }\n    /**\n     * Gets Map of all FeatureFlags and associated experiment map inside it\n     * @param       {ProjectConfig}                     configObj\n     * @param       {FeatureVariablesMap}               featureVariableIdMap\n     * @param       {OptimizelyExperimentsMap}          experimentsMapById\n     * @param       {{[id: string]: FeatureVariable}}   variableIdMap\n     * @returns     {OptimizelyFeaturesMap}             OptimizelyFeature mapped by key\n     */\n    static getFeaturesMap(configObj, featureVariableIdMap, experimentsMapById, variableIdMap) {\n        const featuresMap = {};\n        configObj.featureFlags.forEach((featureFlag) => {\n            const featureExperimentMap = {};\n            const experimentRules = [];\n            featureFlag.experimentIds.forEach(experimentId => {\n                const experiment = experimentsMapById[experimentId];\n                if (experiment) {\n                    featureExperimentMap[experiment.key] = experiment;\n                }\n                experimentRules.push(experimentsMapById[experimentId]);\n            });\n            const featureVariableMap = (featureFlag.variables || []).reduce((variables, variable) => {\n                variables[variable.key] = {\n                    id: variable.id,\n                    key: variable.key,\n                    type: variable.type,\n                    value: variable.defaultValue,\n                };\n                return variables;\n            }, {});\n            let deliveryRules = [];\n            const rollout = configObj.rolloutIdMap[featureFlag.rolloutId];\n            if (rollout) {\n                deliveryRules = OptimizelyConfig.getDeliveryRules(configObj, featureVariableIdMap, featureFlag.id, rollout.experiments, variableIdMap);\n            }\n            featuresMap[featureFlag.key] = {\n                id: featureFlag.id,\n                key: featureFlag.key,\n                experimentRules: experimentRules,\n                deliveryRules: deliveryRules,\n                experimentsMap: featureExperimentMap,\n                variablesMap: featureVariableMap,\n            };\n        });\n        return featuresMap;\n    }\n}\n/**\n * Create an instance of OptimizelyConfig\n * @param   {ProjectConfig}             configObj\n * @param   {string}                    datafile\n * @returns {OptimizelyConfig}          An instance of OptimizelyConfig\n */\nexport function createOptimizelyConfig(configObj, datafile, logger) {\n    return new OptimizelyConfig(configObj, datafile, logger);\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=optimizely_config.js.map","/**\n * Copyright 2016, 2018-2020, 2022, 2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { DATAFILE_VERSIONS, } from '../enums';\nimport { INVALID_DATAFILE_MALFORMED, INVALID_DATAFILE_VERSION, NO_DATAFILE_SPECIFIED, } from 'error_message';\nimport { OptimizelyError } from '../../error/optimizly_error';\nconst SUPPORTED_VERSIONS = [DATAFILE_VERSIONS.V2, DATAFILE_VERSIONS.V3, DATAFILE_VERSIONS.V4];\n/**\n * Validates the datafile\n * @param {Object|string}  datafile\n * @return {Object} The datafile object if the datafile is valid\n * @throws If the datafile is not valid for any of the following reasons:\n - The datafile string is undefined\n - The datafile string cannot be parsed as a JSON object\n - The datafile version is not supported\n */\n// eslint-disable-next-line\nexport const validateDatafile = function (datafile) {\n    if (!datafile) {\n        throw new OptimizelyError(NO_DATAFILE_SPECIFIED);\n    }\n    if (typeof datafile === 'string') {\n        // Attempt to parse the datafile string\n        try {\n            datafile = JSON.parse(datafile);\n        }\n        catch (ex) {\n            throw new OptimizelyError(INVALID_DATAFILE_MALFORMED);\n        }\n    }\n    if (typeof datafile === 'object' && !Array.isArray(datafile) && datafile !== null) {\n        if (SUPPORTED_VERSIONS.indexOf(datafile['version']) === -1) {\n            throw new OptimizelyError(INVALID_DATAFILE_VERSION, datafile['version']);\n        }\n    }\n    else {\n        throw new OptimizelyError(INVALID_DATAFILE_MALFORMED);\n    }\n    return datafile;\n};\nexport default {\n    validateDatafile: validateDatafile,\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","/**\n * Copyright 2022-2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { checkArrayEquality } from '../utils/fns';\nexport class OdpConfig {\n    constructor(apiKey, apiHost, pixelUrl, segmentsToCheck) {\n        this.apiKey = apiKey;\n        this.apiHost = apiHost;\n        this.pixelUrl = pixelUrl;\n        this.segmentsToCheck = segmentsToCheck;\n    }\n    /**\n     * Detects if there are any changes between the current and incoming ODP Configs\n     * @param configToCompare ODP Configuration to check self against for equality\n     * @returns Boolean based on if the current ODP Config is equivalent to the incoming ODP Config\n     */\n    equals(configToCompare) {\n        return (this.apiHost === configToCompare.apiHost &&\n            this.apiKey === configToCompare.apiKey &&\n            this.pixelUrl === configToCompare.pixelUrl &&\n            checkArrayEquality(this.segmentsToCheck, configToCompare.segmentsToCheck));\n    }\n}\nexport const odpIntegrationsAreEqual = (config1, config2) => {\n    if (config1.integrated !== config2.integrated) {\n        return false;\n    }\n    if (config1.integrated && config2.integrated) {\n        return config1.odpConfig.equals(config2.odpConfig);\n    }\n    return true;\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=odp_config.js.map","/**\n * Copyright 2016-2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { find, objectEntries, objectValues, keyBy, assignBy } from '../utils/fns';\nimport { FEATURE_VARIABLE_TYPES } from '../utils/enums';\nimport configValidator from '../utils/config_validator';\nimport { OdpConfig } from '../odp/odp_config';\nimport { EXPERIMENT_KEY_NOT_IN_DATAFILE, FEATURE_NOT_IN_DATAFILE, INVALID_EXPERIMENT_ID, INVALID_EXPERIMENT_KEY, MISSING_INTEGRATION_KEY, UNABLE_TO_CAST_VALUE, UNEXPECTED_RESERVED_ATTRIBUTE_PREFIX, UNRECOGNIZED_ATTRIBUTE, VARIABLE_KEY_NOT_IN_DATAFILE, VARIATION_ID_NOT_IN_DATAFILE, } from 'error_message';\nimport { SKIPPING_JSON_VALIDATION, VALID_DATAFILE } from 'log_message';\nimport { OptimizelyError } from '../error/optimizly_error';\nconst EXPERIMENT_RUNNING_STATUS = 'Running';\nconst RESERVED_ATTRIBUTE_PREFIX = '$opt_';\n// eslint-disable-next-line  @typescript-eslint/no-explicit-any\nfunction createMutationSafeDatafileCopy(datafile) {\n    var _a, _b;\n    const datafileCopy = Object.assign({}, datafile);\n    datafileCopy.audiences = (datafile.audiences || []).map((audience) => {\n        return Object.assign({}, audience);\n    });\n    datafileCopy.experiments = (datafile.experiments || []).map((experiment) => {\n        return Object.assign({}, experiment);\n    });\n    datafileCopy.featureFlags = (datafile.featureFlags || []).map((featureFlag) => {\n        return Object.assign({}, featureFlag);\n    });\n    datafileCopy.groups = (datafile.groups || []).map((group) => {\n        const groupCopy = Object.assign({}, group);\n        groupCopy.experiments = (group.experiments || []).map(experiment => {\n            return Object.assign({}, experiment);\n        });\n        return groupCopy;\n    });\n    datafileCopy.rollouts = (datafile.rollouts || []).map((rollout) => {\n        const rolloutCopy = Object.assign({}, rollout);\n        rolloutCopy.experiments = (rollout.experiments || []).map(experiment => {\n            return Object.assign({}, experiment);\n        });\n        return rolloutCopy;\n    });\n    datafileCopy.environmentKey = (_a = datafile.environmentKey) !== null && _a !== void 0 ? _a : '';\n    datafileCopy.sdkKey = (_b = datafile.sdkKey) !== null && _b !== void 0 ? _b : '';\n    return datafileCopy;\n}\n/**\n * Creates projectConfig object to be used for quick project property lookup\n * @param  {Object}        datafileObj   JSON datafile representing the project\n * @param  {string|null}   datafileStr   JSON string representation of the datafile\n * @return {ProjectConfig} Object representing project configuration\n */\nexport const createProjectConfig = function (datafileObj, datafileStr = null) {\n    const projectConfig = createMutationSafeDatafileCopy(datafileObj);\n    if (!projectConfig.region) {\n        projectConfig.region = 'US'; // Default to US region if not specified\n    }\n    projectConfig.__datafileStr = datafileStr === null ? JSON.stringify(datafileObj) : datafileStr;\n    /*\n     * Conditions of audiences in projectConfig.typedAudiences are not\n     * expected to be string-encoded as they are here in projectConfig.audiences.\n     */\n    (projectConfig.audiences || []).forEach(audience => {\n        audience.conditions = JSON.parse(audience.conditions);\n    });\n    projectConfig.audiencesById = {};\n    assignBy(projectConfig.audiences, 'id', projectConfig.audiencesById);\n    assignBy(projectConfig.typedAudiences, 'id', projectConfig.audiencesById);\n    projectConfig.attributes = projectConfig.attributes || [];\n    projectConfig.attributeKeyMap = {};\n    projectConfig.attributeIdMap = {};\n    projectConfig.attributes.forEach(attribute => {\n        projectConfig.attributeKeyMap[attribute.key] = attribute;\n        projectConfig.attributeIdMap[attribute.id] = attribute;\n    });\n    projectConfig.eventKeyMap = keyBy(projectConfig.events, 'key');\n    projectConfig.groupIdMap = keyBy(projectConfig.groups, 'id');\n    let experiments;\n    Object.keys(projectConfig.groupIdMap || {}).forEach(Id => {\n        experiments = projectConfig.groupIdMap[Id].experiments;\n        (experiments || []).forEach(experiment => {\n            experiment.groupId = Id;\n            projectConfig.experiments.push(experiment);\n        });\n    });\n    projectConfig.rolloutIdMap = keyBy(projectConfig.rollouts || [], 'id');\n    objectValues(projectConfig.rolloutIdMap || {}).forEach(rollout => {\n        (rollout.experiments || []).forEach(experiment => {\n            experiment.isRollout = true;\n            projectConfig.experiments.push(experiment);\n            // Creates { <variationKey>: <variation> } map inside of the experiment\n            experiment.variationKeyMap = keyBy(experiment.variations, 'key');\n        });\n    });\n    const allSegmentsSet = new Set();\n    Object.keys(projectConfig.audiencesById)\n        .map(audience => getAudienceSegments(projectConfig.audiencesById[audience]))\n        .forEach(audienceSegments => {\n        audienceSegments.forEach(segment => {\n            allSegmentsSet.add(segment);\n        });\n    });\n    const allSegments = Array.from(allSegmentsSet);\n    let odpIntegrated = false;\n    let odpApiHost = '';\n    let odpApiKey = '';\n    let odpPixelUrl = '';\n    if (projectConfig.integrations) {\n        projectConfig.integrationKeyMap = keyBy(projectConfig.integrations, 'key');\n        projectConfig.integrations.forEach(integration => {\n            if (!('key' in integration)) {\n                throw new OptimizelyError(MISSING_INTEGRATION_KEY);\n            }\n            if (integration.key === 'odp') {\n                odpIntegrated = true;\n                odpApiKey = odpApiKey || integration.publicKey || '';\n                odpApiHost = odpApiHost || integration.host || '';\n                odpPixelUrl = odpPixelUrl || integration.pixelUrl || '';\n            }\n        });\n    }\n    if (odpIntegrated) {\n        projectConfig.odpIntegrationConfig = {\n            integrated: true,\n            odpConfig: new OdpConfig(odpApiKey, odpApiHost, odpPixelUrl, allSegments),\n        };\n    }\n    else {\n        projectConfig.odpIntegrationConfig = { integrated: false };\n    }\n    projectConfig.experimentKeyMap = keyBy(projectConfig.experiments, 'key');\n    projectConfig.experimentIdMap = keyBy(projectConfig.experiments, 'id');\n    projectConfig.variationIdMap = {};\n    projectConfig.variationVariableUsageMap = {};\n    (projectConfig.experiments || []).forEach(experiment => {\n        // Creates { <variationKey>: <variation> } map inside of the experiment\n        experiment.variationKeyMap = keyBy(experiment.variations, 'key');\n        assignBy(experiment.variations, 'id', projectConfig.variationIdMap);\n        objectValues(experiment.variationKeyMap || {}).forEach(variation => {\n            if (variation.variables) {\n                projectConfig.variationVariableUsageMap[variation.id] = keyBy(variation.variables, 'id');\n            }\n        });\n    });\n    // Object containing experiment Ids that exist in any feature\n    // for checking that experiment is a feature experiment or not.\n    projectConfig.experimentFeatureMap = {};\n    projectConfig.featureKeyMap = keyBy(projectConfig.featureFlags || [], 'key');\n    objectValues(projectConfig.featureKeyMap || {}).forEach(feature => {\n        // Json type is represented in datafile as a subtype of string for the sake of backwards compatibility.\n        // Converting it to a first-class json type while creating Project Config\n        feature.variables.forEach(variable => {\n            if (variable.type === FEATURE_VARIABLE_TYPES.STRING && variable.subType === FEATURE_VARIABLE_TYPES.JSON) {\n                variable.type = FEATURE_VARIABLE_TYPES.JSON;\n                delete variable.subType;\n            }\n        });\n        feature.variableKeyMap = keyBy(feature.variables, 'key');\n        (feature.experimentIds || []).forEach(experimentId => {\n            // Add this experiment in experiment-feature map.\n            if (projectConfig.experimentFeatureMap[experimentId]) {\n                projectConfig.experimentFeatureMap[experimentId].push(feature.id);\n            }\n            else {\n                projectConfig.experimentFeatureMap[experimentId] = [feature.id];\n            }\n        });\n    });\n    // all rules (experiment rules and delivery rules) for each flag\n    projectConfig.flagRulesMap = {};\n    (projectConfig.featureFlags || []).forEach(featureFlag => {\n        const flagRuleExperiments = [];\n        featureFlag.experimentIds.forEach(experimentId => {\n            const experiment = projectConfig.experimentIdMap[experimentId];\n            if (experiment) {\n                flagRuleExperiments.push(experiment);\n            }\n        });\n        const rollout = projectConfig.rolloutIdMap[featureFlag.rolloutId];\n        if (rollout) {\n            flagRuleExperiments.push(...rollout.experiments);\n        }\n        projectConfig.flagRulesMap[featureFlag.key] = flagRuleExperiments;\n    });\n    // all variations for each flag\n    // - datafile does not contain a separate entity for this.\n    // - we collect variations used in each rule (experiment rules and delivery rules)\n    projectConfig.flagVariationsMap = {};\n    objectEntries(projectConfig.flagRulesMap || {}).forEach(([flagKey, rules]) => {\n        const variations = [];\n        rules.forEach(rule => {\n            rule.variations.forEach(variation => {\n                if (!find(variations, item => item.id === variation.id)) {\n                    variations.push(variation);\n                }\n            });\n        });\n        projectConfig.flagVariationsMap[flagKey] = variations;\n    });\n    parseHoldoutsConfig(projectConfig);\n    return projectConfig;\n};\nconst parseHoldoutsConfig = (projectConfig) => {\n    projectConfig.holdouts = projectConfig.holdouts || [];\n    projectConfig.holdoutIdMap = keyBy(projectConfig.holdouts, 'id');\n    projectConfig.globalHoldouts = [];\n    projectConfig.includedHoldouts = {};\n    projectConfig.excludedHoldouts = {};\n    projectConfig.flagHoldoutsMap = {};\n    const featureFlagIdMap = keyBy(projectConfig.featureFlags, 'id');\n    projectConfig.holdouts.forEach((holdout) => {\n        if (!holdout.includedFlags) {\n            holdout.includedFlags = [];\n        }\n        if (!holdout.excludedFlags) {\n            holdout.excludedFlags = [];\n        }\n        holdout.variationKeyMap = keyBy(holdout.variations, 'key');\n        assignBy(holdout.variations, 'id', projectConfig.variationIdMap);\n        if (holdout.includedFlags.length === 0) {\n            projectConfig.globalHoldouts.push(holdout);\n            holdout.excludedFlags.forEach((flagId) => {\n                const flag = featureFlagIdMap[flagId];\n                if (flag) {\n                    const flagKey = flag.key;\n                    if (!projectConfig.excludedHoldouts[flagKey]) {\n                        projectConfig.excludedHoldouts[flagKey] = [];\n                    }\n                    projectConfig.excludedHoldouts[flagKey].push(holdout);\n                }\n            });\n        }\n        else {\n            holdout.includedFlags.forEach((flagId) => {\n                const flag = featureFlagIdMap[flagId];\n                if (flag) {\n                    const flagKey = flag.key;\n                    if (!projectConfig.includedHoldouts[flagKey]) {\n                        projectConfig.includedHoldouts[flagKey] = [];\n                    }\n                    projectConfig.includedHoldouts[flagKey].push(holdout);\n                }\n            });\n        }\n    });\n};\nexport const getHoldoutsForFlag = (projectConfig, flagKey) => {\n    if (projectConfig.flagHoldoutsMap[flagKey]) {\n        return projectConfig.flagHoldoutsMap[flagKey];\n    }\n    const flagHoldouts = [\n        ...projectConfig.globalHoldouts.filter((holdout) => {\n            return !(projectConfig.excludedHoldouts[flagKey] || []).includes(holdout);\n        }),\n        ...(projectConfig.includedHoldouts[flagKey] || []),\n    ];\n    projectConfig.flagHoldoutsMap[flagKey] = flagHoldouts;\n    return flagHoldouts;\n};\n/**\n * Extract all audience segments used in this audience's conditions\n * @param  {Audience}     audience  Object representing the audience being parsed\n * @return {string[]}               List of all audience segments\n */\nexport const getAudienceSegments = function (audience) {\n    if (!audience.conditions)\n        return [];\n    return getSegmentsFromConditions(audience.conditions);\n};\n// eslint-disable-next-line  @typescript-eslint/no-explicit-any\nconst getSegmentsFromConditions = (condition) => {\n    const segments = [];\n    if (isLogicalOperator(condition)) {\n        return [];\n    }\n    else if (Array.isArray(condition)) {\n        condition.forEach(nextCondition => segments.push(...getSegmentsFromConditions(nextCondition)));\n    }\n    else if (condition['match'] === 'qualified') {\n        segments.push(condition['value']);\n    }\n    return segments;\n};\nfunction isLogicalOperator(condition) {\n    return ['and', 'or', 'not'].includes(condition);\n}\n/**\n * Get experiment ID for the provided experiment key\n * @param  {ProjectConfig}    projectConfig   Object representing project configuration\n * @param  {string}           experimentKey   Experiment key for which ID is to be determined\n * @return {string}                           Experiment ID corresponding to the provided experiment key\n * @throws If experiment key is not in datafile\n */\nexport const getExperimentId = function (projectConfig, experimentKey) {\n    const experiment = projectConfig.experimentKeyMap[experimentKey];\n    if (!experiment) {\n        throw new OptimizelyError(INVALID_EXPERIMENT_KEY, experimentKey);\n    }\n    return experiment.id;\n};\n/**\n * Get layer ID for the provided experiment key\n * @param  {ProjectConfig}    projectConfig   Object representing project configuration\n * @param  {string}           experimentId    Experiment ID for which layer ID is to be determined\n * @return {string}                           Layer ID corresponding to the provided experiment key\n * @throws If experiment key is not in datafile\n */\nexport const getLayerId = function (projectConfig, experimentId) {\n    const experiment = projectConfig.experimentIdMap[experimentId];\n    if (!experiment) {\n        throw new OptimizelyError(INVALID_EXPERIMENT_ID, experimentId);\n    }\n    return experiment.layerId;\n};\n/**\n * Get attribute ID for the provided attribute key\n * @param  {ProjectConfig}   projectConfig    Object representing project configuration\n * @param  {string}          attributeKey     Attribute key for which ID is to be determined\n * @param  {LogHandler}      logger\n * @return {string|null}     Attribute ID corresponding to the provided attribute key. Attribute key if it is a reserved attribute.\n */\nexport const getAttributeId = function (projectConfig, attributeKey, logger) {\n    const attribute = projectConfig.attributeKeyMap[attributeKey];\n    const hasReservedPrefix = attributeKey.indexOf(RESERVED_ATTRIBUTE_PREFIX) === 0;\n    if (attribute) {\n        if (hasReservedPrefix) {\n            logger === null || logger === void 0 ? void 0 : logger.warn(UNEXPECTED_RESERVED_ATTRIBUTE_PREFIX, attributeKey, RESERVED_ATTRIBUTE_PREFIX);\n        }\n        return attribute.id;\n    }\n    else if (hasReservedPrefix) {\n        return attributeKey;\n    }\n    logger === null || logger === void 0 ? void 0 : logger.warn(UNRECOGNIZED_ATTRIBUTE, attributeKey);\n    return null;\n};\n/**\n * Get event ID for the provided\n * @param  {ProjectConfig}   projectConfig  Object representing project configuration\n * @param  {string}          eventKey       Event key for which ID is to be determined\n * @return {string|null}     Event ID corresponding to the provided event key\n */\nexport const getEventId = function (projectConfig, eventKey) {\n    const event = projectConfig.eventKeyMap[eventKey];\n    if (event) {\n        return event.id;\n    }\n    return null;\n};\n/**\n * Get experiment status for the provided experiment key\n * @param  {ProjectConfig}  projectConfig   Object representing project configuration\n * @param  {string}         experimentKey   Experiment key for which status is to be determined\n * @return {string}         Experiment status corresponding to the provided experiment key\n * @throws If experiment key is not in datafile\n */\nexport const getExperimentStatus = function (projectConfig, experimentKey) {\n    const experiment = projectConfig.experimentKeyMap[experimentKey];\n    if (!experiment) {\n        throw new OptimizelyError(INVALID_EXPERIMENT_KEY, experimentKey);\n    }\n    return experiment.status;\n};\n/**\n * Returns whether experiment has a status of 'Running'\n * @param  {ProjectConfig}  projectConfig   Object representing project configuration\n * @param  {string}         experimentKey   Experiment key for which status is to be compared with 'Running'\n * @return {boolean}                        True if experiment status is set to 'Running', false otherwise\n */\nexport const isActive = function (projectConfig, experimentKey) {\n    return getExperimentStatus(projectConfig, experimentKey) === EXPERIMENT_RUNNING_STATUS;\n};\n/**\n * Determine for given experiment if event is running, which determines whether should be dispatched or not\n * @param  {ProjectConfig}  configObj       Object representing project configuration\n * @param  {string}         experimentKey   Experiment key for which the status is to be determined\n * @return {boolean}                        True if the experiment is running\n *                                          False if the experiment is not running\n *\n */\nexport const isRunning = function (projectConfig, experimentKey) {\n    return getExperimentStatus(projectConfig, experimentKey) === EXPERIMENT_RUNNING_STATUS;\n};\n/**\n * Get audience conditions for the experiment\n * @param  {ProjectConfig}  projectConfig   Object representing project configuration\n * @param  {string}         experimentId    Experiment id for which audience conditions are to be determined\n * @return {Array<string|string[]>}         Audience conditions for the experiment - can be an array of audience IDs, or a\n *                                          nested array of conditions\n *                                          Examples: [\"5\", \"6\"], [\"and\", [\"or\", \"1\", \"2\"], \"3\"]\n * @throws If experiment key is not in datafile\n */\nexport const getExperimentAudienceConditions = function (projectConfig, experimentId) {\n    const experiment = projectConfig.experimentIdMap[experimentId];\n    if (!experiment) {\n        throw new OptimizelyError(INVALID_EXPERIMENT_ID, experimentId);\n    }\n    return experiment.audienceConditions || experiment.audienceIds;\n};\n/**\n * Get variation key given experiment key and variation ID\n * @param  {ProjectConfig}  projectConfig   Object representing project configuration\n * @param  {string}         variationId     ID of the variation\n * @return {string|null}    Variation key or null if the variation ID is not found\n */\nexport const getVariationKeyFromId = function (projectConfig, variationId) {\n    if (projectConfig.variationIdMap.hasOwnProperty(variationId)) {\n        return projectConfig.variationIdMap[variationId].key;\n    }\n    return null;\n};\n/**\n * Get variation given variation ID\n * @param  {ProjectConfig}  projectConfig   Object representing project configuration\n * @param  {string}         variationId     ID of the variation\n * @return {Variation|null}    Variation or null if the variation ID is not found\n */\nexport const getVariationFromId = function (projectConfig, variationId) {\n    if (projectConfig.variationIdMap.hasOwnProperty(variationId)) {\n        return projectConfig.variationIdMap[variationId];\n    }\n    return null;\n};\n/**\n * Get the variation ID given the experiment key and variation key\n * @param  {ProjectConfig}  projectConfig   Object representing project configuration\n * @param  {string}         experimentKey   Key of the experiment the variation belongs to\n * @param  {string}         variationKey    The variation key\n * @return {string|null}    Variation ID or null\n */\nexport const getVariationIdFromExperimentAndVariationKey = function (projectConfig, experimentKey, variationKey) {\n    const experiment = projectConfig.experimentKeyMap[experimentKey];\n    if (experiment.variationKeyMap.hasOwnProperty(variationKey)) {\n        return experiment.variationKeyMap[variationKey].id;\n    }\n    return null;\n};\n/**\n * Get experiment from provided experiment key\n * @param  {ProjectConfig}  projectConfig  Object representing project configuration\n * @param  {string}         experimentKey  Event key for which experiment IDs are to be retrieved\n * @return {Experiment}     Experiment\n * @throws If experiment key is not in datafile\n */\nexport const getExperimentFromKey = function (projectConfig, experimentKey) {\n    if (projectConfig.experimentKeyMap.hasOwnProperty(experimentKey)) {\n        const experiment = projectConfig.experimentKeyMap[experimentKey];\n        if (experiment) {\n            return experiment;\n        }\n    }\n    throw new OptimizelyError(EXPERIMENT_KEY_NOT_IN_DATAFILE, experimentKey);\n};\n/**\n * Given an experiment id, returns the traffic allocation within that experiment\n * @param  {ProjectConfig}  projectConfig  Object representing project configuration\n * @param  {string}         experimentId   Id representing the experiment\n * @return {TrafficAllocation[]}           Traffic allocation for the experiment\n * @throws If experiment key is not in datafile\n */\nexport const getTrafficAllocation = function (projectConfig, experimentId) {\n    const experiment = projectConfig.experimentIdMap[experimentId];\n    if (!experiment) {\n        throw new OptimizelyError(INVALID_EXPERIMENT_ID, experimentId);\n    }\n    return experiment.trafficAllocation;\n};\n/**\n * Get experiment from provided experiment id. Log an error if no experiment\n * exists in the project config with the given ID.\n * @param  {ProjectConfig}  projectConfig  Object representing project configuration\n * @param  {string}         experimentId   ID of desired experiment object\n * @param  {LogHandler}     logger\n * @return {Experiment|null}               Experiment object or null\n */\nexport const getExperimentFromId = function (projectConfig, experimentId, logger) {\n    if (projectConfig.experimentIdMap.hasOwnProperty(experimentId)) {\n        const experiment = projectConfig.experimentIdMap[experimentId];\n        if (experiment) {\n            return experiment;\n        }\n    }\n    logger === null || logger === void 0 ? void 0 : logger.error(INVALID_EXPERIMENT_ID, experimentId);\n    return null;\n};\n/**\n * Returns flag variation for specified flagKey and variationKey\n * @param  {flagKey}        string\n * @param  {variationKey}   string\n * @return {Variation|null}\n */\nexport const getFlagVariationByKey = function (projectConfig, flagKey, variationKey) {\n    if (!projectConfig) {\n        return null;\n    }\n    const variations = projectConfig.flagVariationsMap[flagKey];\n    const result = find(variations, item => item.key === variationKey);\n    if (result) {\n        return result;\n    }\n    return null;\n};\n/**\n * Get feature from provided feature key. Log an error if no feature exists in\n * the project config with the given key.\n * @param  {ProjectConfig}    projectConfig\n * @param  {string}           featureKey\n * @param  {LogHandler}       logger\n * @return {FeatureFlag|null} Feature object, or null if no feature with the given\n *                            key exists\n */\nexport const getFeatureFromKey = function (projectConfig, featureKey, logger) {\n    if (projectConfig.featureKeyMap.hasOwnProperty(featureKey)) {\n        const feature = projectConfig.featureKeyMap[featureKey];\n        if (feature) {\n            return feature;\n        }\n    }\n    logger === null || logger === void 0 ? void 0 : logger.error(FEATURE_NOT_IN_DATAFILE, featureKey);\n    return null;\n};\n/**\n * Get the variable with the given key associated with the feature with the\n * given key. If the feature key or the variable key are invalid, log an error\n * message.\n * @param  {ProjectConfig}        projectConfig\n * @param  {string}               featureKey\n * @param  {string}               variableKey\n * @param  {LogHandler}           logger\n * @return {FeatureVariable|null} Variable object, or null one or both of the given\n * feature and variable keys are invalid\n */\nexport const getVariableForFeature = function (projectConfig, featureKey, variableKey, logger) {\n    const feature = projectConfig.featureKeyMap[featureKey];\n    if (!feature) {\n        logger === null || logger === void 0 ? void 0 : logger.error(FEATURE_NOT_IN_DATAFILE, featureKey);\n        return null;\n    }\n    const variable = feature.variableKeyMap[variableKey];\n    if (!variable) {\n        logger === null || logger === void 0 ? void 0 : logger.error(VARIABLE_KEY_NOT_IN_DATAFILE, variableKey, featureKey);\n        return null;\n    }\n    return variable;\n};\n/**\n * Get the value of the given variable for the given variation. If the given\n * variable has no value for the given variation, return null. Log an error message if the variation is invalid. If the\n * variable or variation are invalid, return null.\n * @param  {ProjectConfig}     projectConfig\n * @param  {FeatureVariable}   variable\n * @param  {Variation}         variation\n * @param  {LogHandler}        logger\n * @return {string|null}       The value of the given variable for the given\n * variation, or null if the given variable has no value\n * for the given variation or if the variation or variable are invalid\n */\nexport const getVariableValueForVariation = function (projectConfig, variable, variation, logger) {\n    if (!variable || !variation) {\n        return null;\n    }\n    if (!projectConfig.variationVariableUsageMap.hasOwnProperty(variation.id)) {\n        logger === null || logger === void 0 ? void 0 : logger.error(VARIATION_ID_NOT_IN_DATAFILE, variation.id);\n        return null;\n    }\n    const variableUsages = projectConfig.variationVariableUsageMap[variation.id];\n    const variableUsage = variableUsages[variable.id];\n    return variableUsage ? variableUsage.value : null;\n};\n/**\n * Given a variable value in string form, try to cast it to the argument type.\n * If the type cast succeeds, return the type casted value, otherwise log an\n * error and return null.\n * @param {string}     variableValue  Variable value in string form\n * @param {string}     variableType   Type of the variable whose value was passed\n *                                    in the first argument. Must be one of\n *                                    FEATURE_VARIABLE_TYPES in\n *                                    lib/utils/enums/index.js. The return value's\n *                                    type is determined by this argument (boolean\n *                                    for BOOLEAN, number for INTEGER or DOUBLE,\n *                                    and string for STRING).\n * @param {LogHandler} logger         Logger instance\n * @returns {*}                       Variable value of the appropriate type, or\n *                                    null if the type cast failed\n */\nexport const getTypeCastValue = function (variableValue, variableType, logger) {\n    let castValue;\n    switch (variableType) {\n        case FEATURE_VARIABLE_TYPES.BOOLEAN:\n            if (variableValue !== 'true' && variableValue !== 'false') {\n                logger === null || logger === void 0 ? void 0 : logger.error(UNABLE_TO_CAST_VALUE, variableValue, variableType);\n                castValue = null;\n            }\n            else {\n                castValue = variableValue === 'true';\n            }\n            break;\n        case FEATURE_VARIABLE_TYPES.INTEGER:\n            castValue = parseInt(variableValue, 10);\n            if (isNaN(castValue)) {\n                logger === null || logger === void 0 ? void 0 : logger.error(UNABLE_TO_CAST_VALUE, variableValue, variableType);\n                castValue = null;\n            }\n            break;\n        case FEATURE_VARIABLE_TYPES.DOUBLE:\n            castValue = parseFloat(variableValue);\n            if (isNaN(castValue)) {\n                logger === null || logger === void 0 ? void 0 : logger.error(UNABLE_TO_CAST_VALUE, variableValue, variableType);\n                castValue = null;\n            }\n            break;\n        case FEATURE_VARIABLE_TYPES.JSON:\n            try {\n                castValue = JSON.parse(variableValue);\n            }\n            catch (e) {\n                logger === null || logger === void 0 ? void 0 : logger.error(UNABLE_TO_CAST_VALUE, variableValue, variableType);\n                castValue = null;\n            }\n            break;\n        default:\n            // type is STRING\n            castValue = variableValue;\n            break;\n    }\n    return castValue;\n};\n/**\n * Returns an object containing all audiences in the project config. Keys are audience IDs\n * and values are audience objects.\n * @param   {ProjectConfig}     projectConfig\n * @returns {{ [id: string]: Audience }}\n */\nexport const getAudiencesById = function (projectConfig) {\n    return projectConfig.audiencesById;\n};\n/**\n * Returns true if an event with the given key exists in the datafile, and false otherwise\n * @param   {ProjectConfig}     projectConfig\n * @param   {string}            eventKey\n * @returns {boolean}\n */\nexport const eventWithKeyExists = function (projectConfig, eventKey) {\n    return projectConfig.eventKeyMap.hasOwnProperty(eventKey);\n};\n/**\n * Returns true if experiment belongs to any feature, false otherwise.\n * @param   {ProjectConfig}       projectConfig\n * @param   {string}              experimentId\n * @returns {boolean}\n */\nexport const isFeatureExperiment = function (projectConfig, experimentId) {\n    return projectConfig.experimentFeatureMap.hasOwnProperty(experimentId);\n};\n/**\n * Returns the JSON string representation of the datafile\n * @param   {ProjectConfig}       projectConfig\n * @returns {string}\n */\nexport const toDatafile = function (projectConfig) {\n    return projectConfig.__datafileStr;\n};\n/**\n * @typedef   {Object}\n * @property  {Object|null} configObj\n * @property  {Error|null}  error\n */\n/**\n * Try to create a project config object from the given datafile and\n * configuration properties.\n * Returns a ProjectConfig if successful.\n * Otherwise, throws an error.\n * @param   {Object}         config\n * @param   {Object|string}  config.datafile\n * @param   {Object}         config.jsonSchemaValidator\n * @param   {Object}         config.logger\n * @returns {Object}         ProjectConfig\n * @throws {Error}\n */\nexport const tryCreatingProjectConfig = function (config) {\n    var _a, _b;\n    const newDatafileObj = configValidator.validateDatafile(config.datafile);\n    if (config.jsonSchemaValidator) {\n        config.jsonSchemaValidator(newDatafileObj);\n        (_a = config.logger) === null || _a === void 0 ? void 0 : _a.info(VALID_DATAFILE);\n    }\n    else {\n        (_b = config.logger) === null || _b === void 0 ? void 0 : _b.info(SKIPPING_JSON_VALIDATION);\n    }\n    const createProjectConfigArgs = [newDatafileObj];\n    if (typeof config.datafile === 'string') {\n        // Since config.datafile was validated above, we know that it is a valid JSON string\n        createProjectConfigArgs.push(config.datafile);\n    }\n    const newConfigObj = createProjectConfig(...createProjectConfigArgs);\n    return newConfigObj;\n};\n/**\n * Get the send flag decisions value\n * @param  {ProjectConfig}   projectConfig\n * @return {boolean}         A boolean value that indicates if we should send flag decisions\n */\nexport const getSendFlagDecisionsValue = function (projectConfig) {\n    return !!projectConfig.sendFlagDecisions;\n};\nexport default {\n    createProjectConfig,\n    getExperimentId,\n    getLayerId,\n    getAttributeId,\n    getEventId,\n    getExperimentStatus,\n    isActive,\n    isRunning,\n    getExperimentAudienceConditions,\n    getVariationFromId,\n    getVariationKeyFromId,\n    getVariationIdFromExperimentAndVariationKey,\n    getExperimentFromKey,\n    getExperimentFromId,\n    getFlagVariationByKey,\n    getFeatureFromKey,\n    getVariableForFeature,\n    getVariableValueForVariation,\n    getTypeCastValue,\n    getSendFlagDecisionsValue,\n    getAudiencesById,\n    getAudienceSegments,\n    eventWithKeyExists,\n    isFeatureExperiment,\n    toDatafile,\n    tryCreatingProjectConfig,\n    getTrafficAllocation,\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=project_config.js.map","/**\n * Copyright 2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst noop = () => { };\nexport function resolvablePromise() {\n    let resolve = noop;\n    let reject = noop;\n    const promise = new Promise((res, rej) => {\n        resolve = res;\n        reject = rej;\n    });\n    return { promise, resolve, reject, then: promise.then.bind(promise) };\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=resolvablePromise.js.map","/**\n * Copyright 2024-2025 Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { LogLevelToLower } from './logging/logger';\nimport { resolvablePromise } from \"./utils/promise/resolvablePromise\";\nexport const SERVICE_FAILED_TO_START = '%s failed to start, reason: %s';\nexport const SERVICE_STOPPED_BEFORE_RUNNING = '%s stopped before running';\n/**\n * The service interface represents an object with an operational state,\n * with methods to start and stop. The design of this interface in modelled\n * after Guava Service interface (https://github.com/google/guava/wiki/ServiceExplained).\n */\nexport var ServiceState;\n(function (ServiceState) {\n    ServiceState[ServiceState[\"New\"] = 0] = \"New\";\n    ServiceState[ServiceState[\"Starting\"] = 1] = \"Starting\";\n    ServiceState[ServiceState[\"Running\"] = 2] = \"Running\";\n    ServiceState[ServiceState[\"Stopping\"] = 3] = \"Stopping\";\n    ServiceState[ServiceState[\"Terminated\"] = 4] = \"Terminated\";\n    ServiceState[ServiceState[\"Failed\"] = 5] = \"Failed\";\n})(ServiceState || (ServiceState = {}));\nexport class BaseService {\n    constructor(startupLogs = []) {\n        this.disposable = false;\n        this.state = ServiceState.New;\n        this.startPromise = resolvablePromise();\n        this.stopPromise = resolvablePromise();\n        this.startupLogs = startupLogs;\n        // avoid unhandled promise rejection\n        this.startPromise.promise.catch(() => { });\n        this.stopPromise.promise.catch(() => { });\n    }\n    makeDisposable() {\n        this.disposable = true;\n    }\n    setLogger(logger) {\n        this.logger = logger;\n    }\n    printStartupLogs() {\n        if (!this.logger) {\n            return;\n        }\n        for (const { level, message, params } of this.startupLogs) {\n            const methodName = LogLevelToLower[level];\n            const method = this.logger[methodName];\n            method.call(this.logger, message, ...params);\n        }\n    }\n    onRunning() {\n        return this.startPromise.promise;\n    }\n    onTerminated() {\n        return this.stopPromise.promise;\n    }\n    getState() {\n        return this.state;\n    }\n    isStarting() {\n        return this.state === ServiceState.Starting;\n    }\n    isRunning() {\n        return this.state === ServiceState.Running;\n    }\n    isNew() {\n        return this.state === ServiceState.New;\n    }\n    isDone() {\n        return [\n            ServiceState.Stopping,\n            ServiceState.Terminated,\n            ServiceState.Failed\n        ].includes(this.state);\n    }\n    start() {\n        this.printStartupLogs();\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=service.js.map","/**\n * Copyright 2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport class EventEmitter {\n    constructor() {\n        this.id = 0;\n        this.listeners = {};\n    }\n    on(eventName, listener) {\n        var _a;\n        if (!this.listeners[eventName]) {\n            this.listeners[eventName] = new Map();\n        }\n        const curId = this.id++;\n        (_a = this.listeners[eventName]) === null || _a === void 0 ? void 0 : _a.set(curId, listener);\n        return () => {\n            var _a;\n            (_a = this.listeners[eventName]) === null || _a === void 0 ? void 0 : _a.delete(curId);\n        };\n    }\n    emit(eventName, data) {\n        const listeners = this.listeners[eventName];\n        if (listeners) {\n            listeners.forEach(listener => {\n                listener(data);\n            });\n        }\n    }\n    removeListeners(eventName) {\n        var _a;\n        (_a = this.listeners[eventName]) === null || _a === void 0 ? void 0 : _a.clear();\n    }\n    removeAllListeners() {\n        this.listeners = {};\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=event_emitter.js.map","import { createOptimizelyConfig } from './optimizely_config';\nimport { toDatafile, tryCreatingProjectConfig } from './project_config';\nimport { ServiceState, BaseService } from '../service';\nimport { EventEmitter } from '../utils/event_emitter/event_emitter';\nimport { SERVICE_FAILED_TO_START, SERVICE_STOPPED_BEFORE_RUNNING, } from '../service';\nexport const NO_SDKKEY_OR_DATAFILE = 'sdkKey or datafile must be provided';\nexport const GOT_INVALID_DATAFILE = 'got invalid datafile';\nimport { sprintf } from '../utils/fns';\n/**\n * ProjectConfigManager provides project config objects via its methods\n * getConfig and onUpdate. It uses a DatafileManager to fetch datafile if provided.\n * It is responsible for parsing and validating datafiles, and converting datafile\n * string into project config objects.\n * @param {ProjectConfigManagerConfig}    config\n */\nexport const LOGGER_NAME = 'ProjectConfigManager';\nexport class ProjectConfigManagerImpl extends BaseService {\n    constructor(config) {\n        super();\n        this.eventEmitter = new EventEmitter();\n        this.jsonSchemaValidator = config.jsonSchemaValidator;\n        this.datafile = config.datafile;\n        this.datafileManager = config.datafileManager;\n        if (config.logger) {\n            this.setLogger(config.logger);\n        }\n    }\n    setLogger(logger) {\n        var _a;\n        this.logger = logger;\n        this.logger.setName(LOGGER_NAME);\n        (_a = this.datafileManager) === null || _a === void 0 ? void 0 : _a.setLogger(logger.child());\n    }\n    start() {\n        var _a, _b, _c;\n        if (!this.isNew()) {\n            return;\n        }\n        this.state = ServiceState.Starting;\n        if (!this.datafile && !this.datafileManager) {\n            this.handleInitError(new Error(NO_SDKKEY_OR_DATAFILE));\n            return;\n        }\n        if (this.datafile) {\n            this.handleNewDatafile(this.datafile, true);\n        }\n        (_a = this.datafileManager) === null || _a === void 0 ? void 0 : _a.start();\n        // This handles the case where the datafile manager starts successfully. The \n        // datafile manager will only start successfully when it has downloaded a datafile,\n        // an will fire an onUpdate event.\n        (_b = this.datafileManager) === null || _b === void 0 ? void 0 : _b.onUpdate(this.handleNewDatafile.bind(this));\n        // If the datafile manager runs successfully, it will emit a onUpdate event. We can\n        // handle the success case in the onUpdate handler. Hanlding the error case in the\n        // catch callback\n        (_c = this.datafileManager) === null || _c === void 0 ? void 0 : _c.onRunning().catch((err) => {\n            this.handleDatafileManagerError(err);\n        });\n    }\n    makeDisposable() {\n        var _a;\n        super.makeDisposable();\n        (_a = this.datafileManager) === null || _a === void 0 ? void 0 : _a.makeDisposable();\n    }\n    handleInitError(error) {\n        var _a, _b;\n        (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(error);\n        this.state = ServiceState.Failed;\n        (_b = this.datafileManager) === null || _b === void 0 ? void 0 : _b.stop();\n        this.startPromise.reject(error);\n        this.stopPromise.reject(error);\n    }\n    handleDatafileManagerError(err) {\n        var _a;\n        (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(SERVICE_FAILED_TO_START, 'DatafileManager', err.message);\n        // If datafile manager onRunning() promise is rejected, and the project config manager \n        // is still in starting state, that means a datafile was not provided in cofig or was invalid, \n        // otherwise the state would have already been set to running synchronously.\n        // In this case, we cannot recover.\n        if (this.isStarting()) {\n            this.handleInitError(new Error(sprintf(SERVICE_FAILED_TO_START, 'DatafileManager', err.message)));\n        }\n    }\n    /**\n     * Handle new datafile by attemping to create a new Project Config object. If successful and\n     * the new config object's revision is newer than the current one, sets/updates the project config\n     * and emits onUpdate event. If unsuccessful,\n     * the project config and optimizely config objects will not be updated. If the error\n     * is fatal, handleInitError will be called.\n     */\n    handleNewDatafile(newDatafile, fromConfig = false) {\n        var _a, _b;\n        if (this.isDone()) {\n            return;\n        }\n        try {\n            const config = tryCreatingProjectConfig({\n                datafile: newDatafile,\n                jsonSchemaValidator: this.jsonSchemaValidator,\n                logger: this.logger,\n            });\n            if (this.isStarting()) {\n                this.state = ServiceState.Running;\n                this.startPromise.resolve();\n            }\n            if (((_a = this.projectConfig) === null || _a === void 0 ? void 0 : _a.revision) !== config.revision) {\n                this.projectConfig = config;\n                this.optimizelyConfig = undefined;\n                this.eventEmitter.emit('update', config);\n            }\n        }\n        catch (err) {\n            (_b = this.logger) === null || _b === void 0 ? void 0 : _b.error(err);\n            // if the state is starting and no datafileManager is provided, we cannot recover.\n            // If the state is starting and the datafileManager has emitted a datafile,\n            // that means a datafile was not provided in config or an invalid datafile was provided,\n            // otherwise the state would have already been set to running synchronously.\n            // If the first datafile emitted by the datafileManager is invalid, \n            // we consider this to be an initialization error as well.\n            const fatalError = (this.isStarting() && !this.datafileManager) ||\n                (this.isStarting() && !fromConfig);\n            if (fatalError) {\n                this.handleInitError(new Error(GOT_INVALID_DATAFILE));\n            }\n        }\n    }\n    getConfig() {\n        return this.projectConfig;\n    }\n    getOptimizelyConfig() {\n        if (!this.optimizelyConfig && this.projectConfig) {\n            this.optimizelyConfig = createOptimizelyConfig(this.projectConfig, toDatafile(this.projectConfig), this.logger);\n        }\n        return this.optimizelyConfig;\n    }\n    /**\n     * Add a listener for project config updates. The listener will be called\n     * whenever this instance has a new project config object available.\n     * Returns a dispose function that removes the subscription\n     * @param  {Function} listener\n     * @return {Function}\n     */\n    onUpdate(listener) {\n        return this.eventEmitter.on('update', listener);\n    }\n    stop() {\n        if (this.isDone()) {\n            return;\n        }\n        if (this.isNew() || this.isStarting()) {\n            this.startPromise.reject(new Error(sprintf(SERVICE_STOPPED_BEFORE_RUNNING, 'ProjectConfigManager')));\n        }\n        this.state = ServiceState.Stopping;\n        this.eventEmitter.removeAllListeners();\n        if (!this.datafileManager) {\n            this.state = ServiceState.Terminated;\n            this.stopPromise.resolve();\n            return;\n        }\n        this.datafileManager.stop();\n        this.datafileManager.onTerminated().then(() => {\n            this.state = ServiceState.Terminated;\n            this.stopPromise.resolve();\n        }).catch((err) => {\n            this.state = ServiceState.Failed;\n            this.stopPromise.reject(err);\n        });\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=project_config_manager.js.map","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n  extendStatics = Object.setPrototypeOf ||\n      ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n      function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n  return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n  if (typeof b !== \"function\" && b !== null)\n      throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n  extendStatics(d, b);\n  function __() { this.constructor = d; }\n  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n  __assign = Object.assign || function __assign(t) {\n      for (var s, i = 1, n = arguments.length; i < n; i++) {\n          s = arguments[i];\n          for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n      }\n      return t;\n  }\n  return __assign.apply(this, arguments);\n}\n\nexport function __rest(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}\n\nexport function __decorate(decorators, target, key, desc) {\n  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n  if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n  return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n  return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n  function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n  var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n  var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n  var _, done = false;\n  for (var i = decorators.length - 1; i >= 0; i--) {\n      var context = {};\n      for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n      for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n      context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n      var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n      if (kind === \"accessor\") {\n          if (result === void 0) continue;\n          if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n          if (_ = accept(result.get)) descriptor.get = _;\n          if (_ = accept(result.set)) descriptor.set = _;\n          if (_ = accept(result.init)) initializers.unshift(_);\n      }\n      else if (_ = accept(result)) {\n          if (kind === \"field\") initializers.unshift(_);\n          else descriptor[key] = _;\n      }\n  }\n  if (target) Object.defineProperty(target, contextIn.name, descriptor);\n  done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n  var useValue = arguments.length > 2;\n  for (var i = 0; i < initializers.length; i++) {\n      value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n  }\n  return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n  return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n  if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n  return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n  if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n  return new (P || (P = Promise))(function (resolve, reject) {\n      function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n      function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n      function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n      step((generator = generator.apply(thisArg, _arguments || [])).next());\n  });\n}\n\nexport function __generator(thisArg, body) {\n  var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n  return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n  function verb(n) { return function (v) { return step([n, v]); }; }\n  function step(op) {\n      if (f) throw new TypeError(\"Generator is already executing.\");\n      while (g && (g = 0, op[0] && (_ = 0)), _) try {\n          if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n          if (y = 0, t) op = [op[0] & 2, t.value];\n          switch (op[0]) {\n              case 0: case 1: t = op; break;\n              case 4: _.label++; return { value: op[1], done: false };\n              case 5: _.label++; y = op[1]; op = [0]; continue;\n              case 7: op = _.ops.pop(); _.trys.pop(); continue;\n              default:\n                  if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n                  if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n                  if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n                  if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n                  if (t[2]) _.ops.pop();\n                  _.trys.pop(); continue;\n          }\n          op = body.call(thisArg, _);\n      } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n      if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n  }\n}\n\nexport var __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});\n\nexport function __exportStar(m, o) {\n  for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n  var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n  if (m) return m.call(o);\n  if (o && typeof o.length === \"number\") return {\n      next: function () {\n          if (o && i >= o.length) o = void 0;\n          return { value: o && o[i++], done: !o };\n      }\n  };\n  throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n  var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n  if (!m) return o;\n  var i = m.call(o), r, ar = [], e;\n  try {\n      while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n  }\n  catch (error) { e = { error: error }; }\n  finally {\n      try {\n          if (r && !r.done && (m = i[\"return\"])) m.call(i);\n      }\n      finally { if (e) throw e.error; }\n  }\n  return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n  for (var ar = [], i = 0; i < arguments.length; i++)\n      ar = ar.concat(__read(arguments[i]));\n  return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n  for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n  for (var r = Array(s), k = 0, i = 0; i < il; i++)\n      for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n          r[k] = a[j];\n  return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n      if (ar || !(i in from)) {\n          if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n          ar[i] = from[i];\n      }\n  }\n  return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n  return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n  if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n  var g = generator.apply(thisArg, _arguments || []), i, q = [];\n  return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n  function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n  function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n  function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n  function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n  function fulfill(value) { resume(\"next\", value); }\n  function reject(value) { resume(\"throw\", value); }\n  function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n  var i, p;\n  return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n  function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n  if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n  var m = o[Symbol.asyncIterator], i;\n  return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n  function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n  function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n  if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n  return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n  Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n  o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n  ownKeys = Object.getOwnPropertyNames || function (o) {\n    var ar = [];\n    for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n    return ar;\n  };\n  return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n  if (mod && mod.__esModule) return mod;\n  var result = {};\n  if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n  __setModuleDefault(result, mod);\n  return result;\n}\n\nexport function __importDefault(mod) {\n  return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n  if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n  if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n  return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n  if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n  if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n  if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n  return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n  if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n  return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n  if (value !== null && value !== void 0) {\n    if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n    var dispose, inner;\n    if (async) {\n      if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n      dispose = value[Symbol.asyncDispose];\n    }\n    if (dispose === void 0) {\n      if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n      dispose = value[Symbol.dispose];\n      if (async) inner = dispose;\n    }\n    if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n    if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n    env.stack.push({ value: value, dispose: dispose, async: async });\n  }\n  else if (async) {\n    env.stack.push({ async: true });\n  }\n  return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n  var e = new Error(message);\n  return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n  function fail(e) {\n    env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n    env.hasError = true;\n  }\n  var r, s = 0;\n  function next() {\n    while (r = env.stack.pop()) {\n      try {\n        if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n        if (r.dispose) {\n          var result = r.dispose.call(r.value);\n          if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n        }\n        else s |= 1;\n      }\n      catch (e) {\n        fail(e);\n      }\n    }\n    if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n    if (env.hasError) throw env.error;\n  }\n  return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n  if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n      return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n          return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n      });\n  }\n  return path;\n}\n\nexport default {\n  __extends,\n  __assign,\n  __rest,\n  __decorate,\n  __param,\n  __esDecorate,\n  __runInitializers,\n  __propKey,\n  __setFunctionName,\n  __metadata,\n  __awaiter,\n  __generator,\n  __createBinding,\n  __exportStar,\n  __values,\n  __read,\n  __spread,\n  __spreadArrays,\n  __spreadArray,\n  __await,\n  __asyncGenerator,\n  __asyncDelegator,\n  __asyncValues,\n  __makeTemplateObject,\n  __importStar,\n  __importDefault,\n  __classPrivateFieldGet,\n  __classPrivateFieldSet,\n  __classPrivateFieldIn,\n  __addDisposableResource,\n  __disposeResources,\n  __rewriteRelativeImportExtension,\n};\n","/**\n * Copyright 2022-2023, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst DEFAULT_UPDATE_INTERVAL_MINUTES = 5;\n/** Standard interval (5 minutes in milliseconds) for polling datafile updates.; */\nexport const DEFAULT_UPDATE_INTERVAL = DEFAULT_UPDATE_INTERVAL_MINUTES * 60 * 1000;\nconst MIN_UPDATE_INTERVAL_SECONDS = 30;\n/** Minimum allowed interval (30 seconds in milliseconds) for polling datafile updates. */\nexport const MIN_UPDATE_INTERVAL = MIN_UPDATE_INTERVAL_SECONDS * 1000;\nexport const UPDATE_INTERVAL_BELOW_MINIMUM_MESSAGE = `Polling intervals below ${MIN_UPDATE_INTERVAL_SECONDS} seconds are not recommended.`;\nexport const DEFAULT_URL_TEMPLATE = `https://cdn.optimizely.com/datafiles/%s.json`;\nexport const DEFAULT_AUTHENTICATED_URL_TEMPLATE = `https://config.optimizely.com/datafiles/auth/%s.json`;\nexport const BACKOFF_BASE_WAIT_SECONDS_BY_ERROR_COUNT = [0, 8, 16, 32, 64, 128, 256, 512];\nexport const REQUEST_TIMEOUT_MS = 60 * 1000; // 1 minute\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=constant.js.map","export const isSuccessStatusCode = (statusCode) => {\n    return statusCode >= 200 && statusCode < 400;\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=http_util.js.map","import { __awaiter } from \"tslib\";\n/**\n * Copyright 2022-2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { sprintf } from '../utils/fns';\nimport { EventEmitter } from '../utils/event_emitter/event_emitter';\nimport { DEFAULT_AUTHENTICATED_URL_TEMPLATE, DEFAULT_URL_TEMPLATE } from './constant';\nimport { BaseService, ServiceState } from '../service';\nimport { isSuccessStatusCode } from '../utils/http_request_handler/http_util';\nimport { DATAFILE_FETCH_REQUEST_FAILED, ERROR_FETCHING_DATAFILE, } from 'error_message';\nimport { ADDING_AUTHORIZATION_HEADER_WITH_BEARER_TOKEN, MAKING_DATAFILE_REQ_TO_URL_WITH_HEADERS, RESPONSE_STATUS_CODE, SAVED_LAST_MODIFIED_HEADER_VALUE_FROM_RESPONSE, } from 'log_message';\nexport const LOGGER_NAME = 'PollingDatafileManager';\nimport { SERVICE_STOPPED_BEFORE_RUNNING } from '../service';\nexport const FAILED_TO_FETCH_DATAFILE = 'Failed to fetch datafile';\nexport class PollingDatafileManager extends BaseService {\n    constructor(config) {\n        super(config.startupLogs);\n        const { autoUpdate = false, sdkKey, datafileAccessToken, customHeaders, urlTemplate, cache, initRetry, repeater, requestHandler, logger, } = config;\n        this.cache = cache;\n        this.cacheKey = 'opt-datafile-' + sdkKey;\n        this.sdkKey = sdkKey;\n        this.datafileAccessToken = datafileAccessToken;\n        this.customHeaders = customHeaders;\n        this.requestHandler = requestHandler;\n        this.emitter = new EventEmitter();\n        this.autoUpdate = autoUpdate;\n        this.initRetryRemaining = initRetry;\n        this.repeater = repeater;\n        if (logger) {\n            this.setLogger(logger);\n        }\n        const urlTemplateToUse = urlTemplate ||\n            (datafileAccessToken ? DEFAULT_AUTHENTICATED_URL_TEMPLATE : DEFAULT_URL_TEMPLATE);\n        this.datafileUrl = sprintf(urlTemplateToUse, this.sdkKey);\n    }\n    setLogger(logger) {\n        this.logger = logger;\n        this.logger.setName(LOGGER_NAME);\n    }\n    onUpdate(listener) {\n        return this.emitter.on('update', listener);\n    }\n    get() {\n        return this.currentDatafile;\n    }\n    start() {\n        if (!this.isNew()) {\n            return;\n        }\n        super.start();\n        this.state = ServiceState.Starting;\n        this.setDatafileFromCacheIfAvailable();\n        this.repeater.setTask(this.syncDatafile.bind(this));\n        this.repeater.start(true);\n    }\n    makeDisposable() {\n        var _a;\n        super.makeDisposable();\n        this.initRetryRemaining = Math.min((_a = this.initRetryRemaining) !== null && _a !== void 0 ? _a : 5, 5);\n    }\n    stop() {\n        var _a;\n        if (this.isDone()) {\n            return;\n        }\n        if (this.isNew() || this.isStarting()) {\n            this.startPromise.reject(new Error(sprintf(SERVICE_STOPPED_BEFORE_RUNNING, 'PollingDatafileManager')));\n        }\n        this.state = ServiceState.Terminated;\n        this.repeater.stop();\n        (_a = this.currentRequest) === null || _a === void 0 ? void 0 : _a.abort();\n        this.emitter.removeAllListeners();\n        this.stopPromise.resolve();\n    }\n    handleInitFailure() {\n        this.state = ServiceState.Failed;\n        this.repeater.stop();\n        const error = new Error(FAILED_TO_FETCH_DATAFILE);\n        this.startPromise.reject(error);\n        this.stopPromise.reject(error);\n    }\n    handleError(errorOrStatus) {\n        var _a, _b;\n        if (this.isDone()) {\n            return;\n        }\n        if (errorOrStatus instanceof Error) {\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(ERROR_FETCHING_DATAFILE, errorOrStatus.message, errorOrStatus);\n        }\n        else {\n            (_b = this.logger) === null || _b === void 0 ? void 0 : _b.error(DATAFILE_FETCH_REQUEST_FAILED, errorOrStatus);\n        }\n        if (this.isStarting() && this.initRetryRemaining !== undefined) {\n            if (this.initRetryRemaining === 0) {\n                this.handleInitFailure();\n            }\n            else {\n                this.initRetryRemaining--;\n            }\n        }\n    }\n    onRequestRejected(err) {\n        return __awaiter(this, void 0, void 0, function* () {\n            this.handleError(err);\n            return Promise.reject(err);\n        });\n    }\n    onRequestResolved(response) {\n        return __awaiter(this, void 0, void 0, function* () {\n            if (this.isDone()) {\n                return;\n            }\n            this.saveLastModified(response.headers);\n            if (!isSuccessStatusCode(response.statusCode)) {\n                this.handleError(response.statusCode);\n                return Promise.reject(new Error());\n            }\n            const datafile = this.getDatafileFromResponse(response);\n            if (datafile) {\n                this.handleDatafile(datafile);\n                // if autoUpdate is off, don't need to sync datafile any more\n                // if disposable, stop the repeater after the first successful fetch\n                if (!this.autoUpdate || this.disposable) {\n                    this.repeater.stop();\n                }\n            }\n        });\n    }\n    makeDatafileRequest() {\n        var _a, _b;\n        const headers = Object.assign({}, this.customHeaders);\n        if (this.lastResponseLastModified) {\n            headers['if-modified-since'] = this.lastResponseLastModified;\n        }\n        if (this.datafileAccessToken) {\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(ADDING_AUTHORIZATION_HEADER_WITH_BEARER_TOKEN);\n            headers['Authorization'] = `Bearer ${this.datafileAccessToken}`;\n        }\n        (_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug(MAKING_DATAFILE_REQ_TO_URL_WITH_HEADERS, this.datafileUrl, () => JSON.stringify(headers));\n        return this.requestHandler.makeRequest(this.datafileUrl, headers, 'GET');\n    }\n    syncDatafile() {\n        return __awaiter(this, void 0, void 0, function* () {\n            this.currentRequest = this.makeDatafileRequest();\n            return this.currentRequest.responsePromise\n                .then(this.onRequestResolved.bind(this), this.onRequestRejected.bind(this))\n                .finally(() => this.currentRequest = undefined);\n        });\n    }\n    handleDatafile(datafile) {\n        var _a;\n        if (this.isDone()) {\n            return;\n        }\n        this.currentDatafile = datafile;\n        (_a = this.cache) === null || _a === void 0 ? void 0 : _a.set(this.cacheKey, datafile);\n        if (this.isStarting()) {\n            this.startPromise.resolve();\n            this.state = ServiceState.Running;\n        }\n        this.emitter.emit('update', datafile);\n    }\n    getDatafileFromResponse(response) {\n        var _a;\n        (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(RESPONSE_STATUS_CODE, response.statusCode);\n        if (response.statusCode === 304) {\n            return undefined;\n        }\n        return response.body;\n    }\n    saveLastModified(headers) {\n        var _a;\n        const lastModifiedHeader = headers['last-modified'] || headers['Last-Modified'];\n        if (lastModifiedHeader !== undefined) {\n            this.lastResponseLastModified = lastModifiedHeader;\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(SAVED_LAST_MODIFIED_HEADER_VALUE_FROM_RESPONSE, this.lastResponseLastModified);\n        }\n    }\n    setDatafileFromCacheIfAvailable() {\n        return __awaiter(this, void 0, void 0, function* () {\n            if (!this.cache) {\n                return;\n            }\n            try {\n                const datafile = yield this.cache.get(this.cacheKey);\n                if (datafile && this.isStarting()) {\n                    this.handleDatafile(datafile);\n                }\n            }\n            catch (_a) {\n                // ignore error\n            }\n        });\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=polling_datafile_manager.js.map","/**\n * Copyright 2024-2026, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { scheduleMicrotask } from \"../microtask\";\nexport class ExponentialBackoff {\n    constructor(base, max, maxJitter) {\n        this.base = base;\n        this.max = max;\n        this.maxJitter = maxJitter;\n        if (this.maxJitter > this.base / 2) {\n            this.maxJitter = this.base / 2;\n        }\n        this.maxJitter = maxJitter;\n        this.current = base;\n    }\n    backoff() {\n        const ret = this.current + this.maxJitter * Math.random();\n        this.current = Math.min(this.current * 2, this.max);\n        return ret;\n    }\n    reset() {\n        this.current = this.base;\n    }\n}\nexport class ConstantBackoff {\n    constructor(value) {\n        this.value = value;\n    }\n    backoff() {\n        return this.value;\n    }\n    reset() {\n    }\n}\n// IntervalRepeater is a Repeater that invokes the task at a fixed interval \n// after the completion of the previous task invocation. If a backoff controller\n// is provided, the repeater will use the backoff controller to determine the\n// time between invocations after a failure instead. It will reset the backoffController\n// on success.\nexport class IntervalRepeater {\n    constructor(interval, backoffController) {\n        this.failureCount = 0;\n        this.running = false;\n        this.interval = interval;\n        this.backoffController = backoffController;\n    }\n    isRunning() {\n        return this.running;\n    }\n    handleSuccess() {\n        var _a;\n        this.failureCount = 0;\n        (_a = this.backoffController) === null || _a === void 0 ? void 0 : _a.reset();\n        this.setTimer(this.interval);\n    }\n    handleFailure() {\n        var _a, _b;\n        this.failureCount++;\n        const time = (_b = (_a = this.backoffController) === null || _a === void 0 ? void 0 : _a.backoff()) !== null && _b !== void 0 ? _b : this.interval;\n        this.setTimer(time);\n    }\n    setTimer(timeout) {\n        if (!this.running) {\n            return;\n        }\n        this.timeoutId = setTimeout(this.executeTask.bind(this), timeout);\n    }\n    executeTask() {\n        if (!this.task) {\n            return;\n        }\n        this.task(this.failureCount).then(this.handleSuccess.bind(this), this.handleFailure.bind(this));\n    }\n    start(immediateExecution) {\n        this.running = true;\n        if (immediateExecution) {\n            scheduleMicrotask(this.executeTask.bind(this));\n        }\n        else {\n            this.setTimer(this.interval);\n        }\n    }\n    stop() {\n        this.running = false;\n        clearInterval(this.timeoutId);\n    }\n    reset() {\n        var _a;\n        this.failureCount = 0;\n        (_a = this.backoffController) === null || _a === void 0 ? void 0 : _a.reset();\n        this.stop();\n    }\n    setTask(task) {\n        this.task = task;\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=repeater.js.map","/**\n * Copyright 2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport const scheduleMicrotask = (callback) => {\n    if (typeof queueMicrotask === 'function') {\n        queueMicrotask(callback);\n    }\n    else {\n        Promise.resolve().then(callback);\n    }\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","/**\n * Copyright 2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport const INVALID_STORE = 'Invalid store';\nexport const INVALID_STORE_METHOD = 'Invalid store method %s';\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport const validateStore = (store) => {\n    const errors = [];\n    if (!store || typeof store !== 'object') {\n        throw new Error(INVALID_STORE);\n    }\n    for (const method of ['set', 'get', 'remove', 'getKeys']) {\n        if (typeof store[method] !== 'function') {\n            errors.push(INVALID_STORE_METHOD.replace('%s', method));\n        }\n    }\n    if (errors.length > 0) {\n        throw new Error(errors.join(', '));\n    }\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=store_validator.js.map","/**\n * Copyright 2024-2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { ProjectConfigManagerImpl } from \"./project_config_manager\";\nimport { PollingDatafileManager } from \"./polling_datafile_manager\";\nimport { DEFAULT_UPDATE_INTERVAL } from './constant';\nimport { ExponentialBackoff, IntervalRepeater } from \"../utils/repeater/repeater\";\nimport { MIN_UPDATE_INTERVAL, UPDATE_INTERVAL_BELOW_MINIMUM_MESSAGE } from './constant';\nimport { LogLevel } from '../logging/logger';\nimport { validateStore } from \"../utils/cache/store_validator\";\nexport const INVALID_CONFIG_MANAGER = \"Invalid config manager\";\nconst configManagerSymbol = Symbol();\nexport const createStaticProjectConfigManager = (config) => {\n    return {\n        [configManagerSymbol]: new ProjectConfigManagerImpl(config),\n    };\n};\nexport const getPollingConfigManager = (opt) => {\n    var _a;\n    if (opt.cache) {\n        validateStore(opt.cache);\n    }\n    const updateInterval = (_a = opt.updateInterval) !== null && _a !== void 0 ? _a : DEFAULT_UPDATE_INTERVAL;\n    const backoff = new ExponentialBackoff(1000, updateInterval, 500);\n    const repeater = new IntervalRepeater(updateInterval, backoff);\n    const startupLogs = [];\n    if (updateInterval < MIN_UPDATE_INTERVAL) {\n        startupLogs.push({\n            level: LogLevel.Warn,\n            message: UPDATE_INTERVAL_BELOW_MINIMUM_MESSAGE,\n            params: [],\n        });\n    }\n    const datafileManagerConfig = {\n        sdkKey: opt.sdkKey,\n        autoUpdate: opt.autoUpdate,\n        urlTemplate: opt.urlTemplate,\n        datafileAccessToken: opt.datafileAccessToken,\n        customHeaders: opt.customHeaders,\n        requestHandler: opt.requestHandler,\n        cache: opt.cache,\n        repeater,\n        startupLogs,\n    };\n    const datafileManager = new PollingDatafileManager(datafileManagerConfig);\n    return new ProjectConfigManagerImpl({\n        datafile: opt.datafile,\n        datafileManager,\n        jsonSchemaValidator: opt.jsonSchemaValidator,\n    });\n};\nexport const getOpaquePollingConfigManager = (opt) => {\n    return {\n        [configManagerSymbol]: getPollingConfigManager(opt),\n    };\n};\nexport const wrapConfigManager = (configManager) => {\n    return {\n        [configManagerSymbol]: configManager,\n    };\n};\nexport const extractConfigManager = (opaqueConfigManager) => {\n    if (!opaqueConfigManager || typeof opaqueConfigManager !== 'object') {\n        throw new Error(INVALID_CONFIG_MANAGER);\n    }\n    const configManager = opaqueConfigManager[configManagerSymbol];\n    if (!configManager) {\n        throw new Error(INVALID_CONFIG_MANAGER);\n    }\n    return opaqueConfigManager[configManagerSymbol];\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=config_manager_factory.js.map","/**\n * Copyright 2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { __awaiter } from \"tslib\";\nexport class SyncStoreWithBatchedGet {\n    constructor() {\n        this.operation = 'sync';\n    }\n}\nexport class AsyncStoreWithBatchedGet {\n    constructor() {\n        this.operation = 'async';\n    }\n}\nexport const getBatchedSync = (store, keys) => {\n    if (store instanceof SyncStoreWithBatchedGet) {\n        return store.getBatched(keys);\n    }\n    return keys.map((key) => store.get(key));\n};\nexport const getBatchedAsync = (store, keys) => {\n    if (store instanceof AsyncStoreWithBatchedGet) {\n        return store.getBatched(keys);\n    }\n    return Promise.all(keys.map((key) => store.get(key)));\n};\nexport class SyncPrefixStore extends SyncStoreWithBatchedGet {\n    constructor(store, prefix, transformGet, transformSet) {\n        super();\n        this.operation = 'sync';\n        this.store = store;\n        this.prefix = prefix;\n        this.transformGet = transformGet;\n        this.transformSet = transformSet;\n    }\n    addPrefix(key) {\n        return `${this.prefix}${key}`;\n    }\n    removePrefix(key) {\n        return key.substring(this.prefix.length);\n    }\n    set(key, value) {\n        return this.store.set(this.addPrefix(key), this.transformSet(value));\n    }\n    get(key) {\n        const value = this.store.get(this.addPrefix(key));\n        return value ? this.transformGet(value) : undefined;\n    }\n    remove(key) {\n        return this.store.remove(this.addPrefix(key));\n    }\n    getInternalKeys() {\n        return this.store.getKeys().filter((key) => key.startsWith(this.prefix));\n    }\n    getKeys() {\n        return this.getInternalKeys().map((key) => this.removePrefix(key));\n    }\n    getBatched(keys) {\n        return getBatchedSync(this.store, keys.map((key) => this.addPrefix(key)))\n            .map((value) => value ? this.transformGet(value) : undefined);\n    }\n}\nexport class AsyncPrefixStore {\n    constructor(cache, prefix, transformGet, transformSet) {\n        this.operation = 'async';\n        this.cache = cache;\n        this.prefix = prefix;\n        this.transformGet = transformGet;\n        this.transformSet = transformSet;\n    }\n    addPrefix(key) {\n        return `${this.prefix}${key}`;\n    }\n    removePrefix(key) {\n        return key.substring(this.prefix.length);\n    }\n    set(key, value) {\n        return this.cache.set(this.addPrefix(key), this.transformSet(value));\n    }\n    get(key) {\n        return __awaiter(this, void 0, void 0, function* () {\n            const value = yield this.cache.get(this.addPrefix(key));\n            return value ? this.transformGet(value) : undefined;\n        });\n    }\n    remove(key) {\n        return this.cache.remove(this.addPrefix(key));\n    }\n    getInternalKeys() {\n        return __awaiter(this, void 0, void 0, function* () {\n            return this.cache.getKeys().then((keys) => keys.filter((key) => key.startsWith(this.prefix)));\n        });\n    }\n    getKeys() {\n        return __awaiter(this, void 0, void 0, function* () {\n            return this.getInternalKeys().then((keys) => keys.map((key) => this.removePrefix(key)));\n        });\n    }\n    getBatched(keys) {\n        return __awaiter(this, void 0, void 0, function* () {\n            const values = yield getBatchedAsync(this.cache, keys.map((key) => this.addPrefix(key)));\n            return values.map((value) => value ? this.transformGet(value) : undefined);\n        });\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=store.js.map","import { CONTROL_ATTRIBUTES } from '../../utils/enums';\nconst ACTIVATE_EVENT_KEY = 'campaign_activated';\nconst CUSTOM_ATTRIBUTE_FEATURE_TYPE = 'custom';\nexport const logxEndpoint = {\n    US: 'https://logx.optimizely.com/v1/events',\n    EU: 'https://eu.logx.optimizely.com/v1/events',\n};\n/**\n * Given an array of batchable Decision or ConversionEvent events it returns\n * a single EventV1 with proper batching\n *\n * @param {UserEvent[]} events\n * @returns {EventBatch}\n */\nexport function makeEventBatch(events) {\n    const visitors = [];\n    const data = events[0];\n    events.forEach(event => {\n        if (event.type === 'conversion' || event.type === 'impression') {\n            const visitor = makeVisitor(event);\n            if (event.type === 'impression') {\n                visitor.snapshots.push(makeDecisionSnapshot(event));\n            }\n            else if (event.type === 'conversion') {\n                visitor.snapshots.push(makeConversionSnapshot(event));\n            }\n            visitors.push(visitor);\n        }\n    });\n    return {\n        client_name: data.context.clientName,\n        client_version: data.context.clientVersion,\n        account_id: data.context.accountId,\n        project_id: data.context.projectId,\n        revision: data.context.revision,\n        anonymize_ip: data.context.anonymizeIP,\n        enrich_decisions: true,\n        visitors,\n    };\n}\nfunction makeConversionSnapshot(conversion) {\n    const tags = Object.assign({}, conversion.tags);\n    delete tags['revenue'];\n    delete tags['value'];\n    const event = {\n        entity_id: conversion.event.id,\n        key: conversion.event.key,\n        timestamp: conversion.timestamp,\n        uuid: conversion.uuid,\n    };\n    if (conversion.tags) {\n        event.tags = conversion.tags;\n    }\n    if (conversion.value != null) {\n        event.value = conversion.value;\n    }\n    if (conversion.revenue != null) {\n        event.revenue = conversion.revenue;\n    }\n    return {\n        events: [event],\n    };\n}\nfunction makeDecisionSnapshot(event) {\n    var _a, _b;\n    const { layer, experiment, variation, ruleKey, flagKey, ruleType, enabled, cmabUuid } = event;\n    const layerId = layer ? layer.id : null;\n    const experimentId = (_a = experiment === null || experiment === void 0 ? void 0 : experiment.id) !== null && _a !== void 0 ? _a : '';\n    const variationId = (_b = variation === null || variation === void 0 ? void 0 : variation.id) !== null && _b !== void 0 ? _b : '';\n    const variationKey = variation ? variation.key : '';\n    return {\n        decisions: [\n            {\n                campaign_id: layerId,\n                experiment_id: experimentId,\n                variation_id: variationId,\n                metadata: {\n                    flag_key: flagKey,\n                    rule_key: ruleKey,\n                    rule_type: ruleType,\n                    variation_key: variationKey,\n                    enabled: enabled,\n                    cmab_uuid: cmabUuid,\n                },\n            },\n        ],\n        events: [\n            {\n                entity_id: layerId,\n                timestamp: event.timestamp,\n                key: ACTIVATE_EVENT_KEY,\n                uuid: event.uuid,\n            },\n        ],\n    };\n}\nfunction makeVisitor(data) {\n    const visitor = {\n        snapshots: [],\n        visitor_id: data.user.id,\n        attributes: [],\n    };\n    data.user.attributes.forEach(attr => {\n        visitor.attributes.push({\n            entity_id: attr.entityId,\n            key: attr.key,\n            type: 'custom',\n            value: attr.value,\n        });\n    });\n    if (typeof data.context.botFiltering === 'boolean') {\n        visitor.attributes.push({\n            entity_id: CONTROL_ATTRIBUTES.BOT_FILTERING,\n            key: CONTROL_ATTRIBUTES.BOT_FILTERING,\n            type: CUSTOM_ATTRIBUTE_FEATURE_TYPE,\n            value: data.context.botFiltering,\n        });\n    }\n    return visitor;\n}\nexport function buildLogEvent(events) {\n    var _a;\n    const region = ((_a = events[0]) === null || _a === void 0 ? void 0 : _a.context.region) || 'US';\n    const url = logxEndpoint[region] || logxEndpoint['US'];\n    return {\n        url,\n        httpVerb: 'POST',\n        params: makeEventBatch(events),\n    };\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=log_event.js.map","import { OptimizelyError } from \"../../error/optimizly_error\";\nimport { RETRY_CANCELLED } from \"error_message\";\nimport { resolvablePromise } from \"../promise/resolvablePromise\";\nconst runTask = (task, returnPromise, cancelSignal, backoff, retryRemaining) => {\n    task().then((res) => {\n        returnPromise.resolve(res);\n    }).catch((e) => {\n        var _a;\n        if (retryRemaining === 0) {\n            returnPromise.reject(e);\n            return;\n        }\n        if (cancelSignal.cancelled) {\n            returnPromise.reject(new OptimizelyError(RETRY_CANCELLED));\n            return;\n        }\n        const delay = (_a = backoff === null || backoff === void 0 ? void 0 : backoff.backoff()) !== null && _a !== void 0 ? _a : 0;\n        setTimeout(() => {\n            retryRemaining = retryRemaining === undefined ? undefined : retryRemaining - 1;\n            runTask(task, returnPromise, cancelSignal, backoff, retryRemaining);\n        }, delay);\n    });\n};\nexport const runWithRetry = (task, backoff, maxRetries) => {\n    const returnPromise = resolvablePromise();\n    const cancelSignal = { cancelled: false };\n    const cancelRetry = () => {\n        cancelSignal.cancelled = true;\n    };\n    runTask(task, returnPromise, cancelSignal, backoff, maxRetries);\n    return { cancelRetry, result: returnPromise.promise };\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=backoff_retry_runner.js.map","/**\n * Copyright 2022-2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst idSuffixBase = 10000;\nexport class IdGenerator {\n    constructor() {\n        this.idSuffixOffset = 0;\n    }\n    // getId returns an Id that generally increases with each call.\n    // only exceptions are when idSuffix rotates back to 0 within the same millisecond\n    // or when the clock goes back\n    getId() {\n        const idSuffix = idSuffixBase + this.idSuffixOffset;\n        this.idSuffixOffset = (this.idSuffixOffset + 1) % idSuffixBase;\n        const timestamp = Date.now();\n        return `${timestamp}${idSuffix}`;\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","/**\n * Copyright 2020, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Get experiment key from the provided decision object\n * @param   {DecisionObj} decisionObj       Object representing decision\n * @returns {string}                        Experiment key or empty string if experiment is null\n */\nexport function getExperimentKey(decisionObj) {\n    var _a, _b;\n    return (_b = (_a = decisionObj.experiment) === null || _a === void 0 ? void 0 : _a.key) !== null && _b !== void 0 ? _b : '';\n}\n/**\n * Get variation key from the provided decision object\n * @param   {DecisionObj} decisionObj       Object representing decision\n * @returns {string}                        Variation key or empty string if variation is null\n */\nexport function getVariationKey(decisionObj) {\n    var _a, _b;\n    return (_b = (_a = decisionObj.variation) === null || _a === void 0 ? void 0 : _a.key) !== null && _b !== void 0 ? _b : '';\n}\n/**\n * Get featureEnabled from variation in the provided decision object\n * @param   {DecisionObj} decisionObj       Object representing decision\n * @returns {boolean}                       featureEnabled boolean or false if variation is null\n */\nexport function getFeatureEnabledFromVariation(decisionObj) {\n    var _a, _b;\n    return (_b = (_a = decisionObj.variation) === null || _a === void 0 ? void 0 : _a.featureEnabled) !== null && _b !== void 0 ? _b : false;\n}\n/**\n * Get experiment id from the provided decision object\n * @param   {DecisionObj} decisionObj       Object representing decision\n * @returns {string}                        Experiment id or null if experiment is null\n */\nexport function getExperimentId(decisionObj) {\n    var _a, _b;\n    return (_b = (_a = decisionObj.experiment) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : null;\n}\n/**\n * Get variation id from the provided decision object\n * @param   {DecisionObj} decisionObj       Object representing decision\n * @returns {string}                        Variation id or null if variation is null\n */\nexport function getVariationId(decisionObj) {\n    var _a, _b;\n    return (_b = (_a = decisionObj.variation) === null || _a === void 0 ? void 0 : _a.id) !== null && _b !== void 0 ? _b : null;\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","/**\n * Copyright 2024-2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport const DECISION_NOTIFICATION_TYPES = {\n    AB_TEST: 'ab-test',\n    FEATURE: 'feature',\n    FEATURE_TEST: 'feature-test',\n    FEATURE_VARIABLE: 'feature-variable',\n    ALL_FEATURE_VARIABLES: 'all-feature-variables',\n    FLAG: 'flag',\n};\nexport const NOTIFICATION_TYPES = {\n    ACTIVATE: 'ACTIVATE',\n    DECISION: 'DECISION',\n    LOG_EVENT: 'LOG_EVENT',\n    OPTIMIZELY_CONFIG_UPDATE: 'OPTIMIZELY_CONFIG_UPDATE',\n    TRACK: 'TRACK',\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=type.js.map","/**\n * Copyright 2020-2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function isHoldout(obj) {\n    // Holdout has 'status', 'includedFlags', and 'excludedFlags' properties\n    return (obj.status !== undefined &&\n        Array.isArray(obj.includedFlags) &&\n        Array.isArray(obj.excludedFlags));\n}\nexport var VariableType;\n(function (VariableType) {\n    VariableType[\"BOOLEAN\"] = \"boolean\";\n    VariableType[\"DOUBLE\"] = \"double\";\n    VariableType[\"INTEGER\"] = \"integer\";\n    VariableType[\"STRING\"] = \"string\";\n    VariableType[\"JSON\"] = \"json\";\n})(VariableType || (VariableType = {}));\n//TODO: Move OptimizelyDecideOption to @optimizely/optimizely-sdk/lib/utils/enums\nexport var OptimizelyDecideOption;\n(function (OptimizelyDecideOption) {\n    OptimizelyDecideOption[\"DISABLE_DECISION_EVENT\"] = \"DISABLE_DECISION_EVENT\";\n    OptimizelyDecideOption[\"ENABLED_FLAGS_ONLY\"] = \"ENABLED_FLAGS_ONLY\";\n    OptimizelyDecideOption[\"IGNORE_USER_PROFILE_SERVICE\"] = \"IGNORE_USER_PROFILE_SERVICE\";\n    OptimizelyDecideOption[\"INCLUDE_REASONS\"] = \"INCLUDE_REASONS\";\n    OptimizelyDecideOption[\"EXCLUDE_VARIABLES\"] = \"EXCLUDE_VARIABLES\";\n    OptimizelyDecideOption[\"IGNORE_CMAB_CACHE\"] = \"IGNORE_CMAB_CACHE\";\n    OptimizelyDecideOption[\"RESET_CMAB_CACHE\"] = \"RESET_CMAB_CACHE\";\n    OptimizelyDecideOption[\"INVALIDATE_USER_CMAB_CACHE\"] = \"INVALIDATE_USER_CMAB_CACHE\";\n})(OptimizelyDecideOption || (OptimizelyDecideOption = {}));\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=shared_types.js.map","import * as decision from '../../core/decision';\nimport { isAttributeValid } from '../../utils/attributes_validator';\nimport * as eventTagUtils from '../../utils/event_tag_utils';\nimport fns from '../../utils/fns';\nimport { getAttributeId, getEventId, getLayerId, } from '../../project_config/project_config';\nimport { DECISION_SOURCES } from '../../common_exports';\nexport const areEventContextsEqual = (eventA, eventB) => {\n    const contextA = eventA.context;\n    const contextB = eventB.context;\n    const regionA = contextA.region || 'US';\n    const regionB = contextB.region || 'US';\n    return (regionA === regionB &&\n        contextA.accountId === contextB.accountId &&\n        contextA.projectId === contextB.projectId &&\n        contextA.clientName === contextB.clientName &&\n        contextA.clientVersion === contextB.clientVersion &&\n        contextA.revision === contextB.revision &&\n        contextA.anonymizeIP === contextB.anonymizeIP &&\n        contextA.botFiltering === contextB.botFiltering);\n};\nconst buildBaseEvent = ({ configObj, userId, userAttributes, clientEngine, clientVersion, type, }) => {\n    return {\n        type,\n        timestamp: fns.currentTimestamp(),\n        uuid: fns.uuid(),\n        context: {\n            region: configObj.region,\n            accountId: configObj.accountId,\n            projectId: configObj.projectId,\n            revision: configObj.revision,\n            clientName: clientEngine,\n            clientVersion: clientVersion,\n            anonymizeIP: configObj.anonymizeIP || false,\n            botFiltering: configObj.botFiltering,\n        },\n        user: {\n            id: userId,\n            attributes: buildVisitorAttributes(configObj, userAttributes),\n        },\n    };\n};\n/**\n * Creates an ImpressionEvent object from decision data\n * @param  {ImpressionConfig}  config\n * @return {ImpressionEvent}   an ImpressionEvent object\n */\nexport const buildImpressionEvent = function ({ configObj, decisionObj, userId, flagKey, enabled, userAttributes, clientEngine, clientVersion, }) {\n    const ruleType = decisionObj.decisionSource;\n    const experimentKey = decision.getExperimentKey(decisionObj);\n    const experimentId = decision.getExperimentId(decisionObj);\n    const variationKey = decision.getVariationKey(decisionObj);\n    const variationId = decision.getVariationId(decisionObj);\n    const cmabUuid = decisionObj.cmabUuid;\n    const layerId = experimentId !== null ? (ruleType === DECISION_SOURCES.HOLDOUT ? '' : getLayerId(configObj, experimentId)) : null;\n    return Object.assign(Object.assign({}, buildBaseEvent({\n        configObj,\n        userId,\n        userAttributes,\n        clientEngine,\n        clientVersion,\n        type: 'impression',\n    })), { layer: {\n            id: layerId,\n        }, experiment: {\n            id: experimentId,\n            key: experimentKey,\n        }, variation: {\n            id: variationId,\n            key: variationKey,\n        }, ruleKey: experimentKey, flagKey: flagKey, ruleType: ruleType, enabled: enabled, cmabUuid });\n};\n/**\n * Creates a ConversionEvent object from track\n * @param  {ConversionConfig} config\n * @return {ConversionEvent}  a ConversionEvent object\n */\nexport const buildConversionEvent = function ({ configObj, userId, userAttributes, clientEngine, clientVersion, eventKey, eventTags, }, logger) {\n    const eventId = getEventId(configObj, eventKey);\n    const revenue = eventTags ? eventTagUtils.getRevenueValue(eventTags, logger) : null;\n    const eventValue = eventTags ? eventTagUtils.getEventValue(eventTags, logger) : null;\n    return Object.assign(Object.assign({}, buildBaseEvent({\n        configObj,\n        userId,\n        userAttributes,\n        clientEngine,\n        clientVersion,\n        type: 'conversion',\n    })), { event: {\n            id: eventId,\n            key: eventKey,\n        }, revenue: revenue, value: eventValue, tags: eventTags });\n};\nconst buildVisitorAttributes = (configObj, attributes, logger) => {\n    if (!attributes) {\n        return [];\n    }\n    // Omit attribute values that are not supported by the log endpoint.\n    const builtAttributes = [];\n    Object.keys(attributes).forEach(function (attributeKey) {\n        const attributeValue = attributes[attributeKey];\n        if (typeof attributeValue === 'object' || typeof attributeValue === 'undefined') {\n            return;\n        }\n        if (isAttributeValid(attributeKey, attributeValue)) {\n            const attributeId = getAttributeId(configObj, attributeKey, logger);\n            if (attributeId) {\n                builtAttributes.push({\n                    entityId: attributeId,\n                    key: attributeKey,\n                    value: attributeValue,\n                });\n            }\n        }\n    });\n    return builtAttributes;\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=user_event.js.map","/**\n * Copyright 2017, 2019-2020, 2022-2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { FAILED_TO_PARSE_REVENUE, FAILED_TO_PARSE_VALUE, PARSED_NUMERIC_VALUE, PARSED_REVENUE_VALUE, } from 'log_message';\n/**\n * Provides utility method for parsing event tag values\n */\nconst REVENUE_EVENT_METRIC_NAME = \"revenue\" /* RESERVED_EVENT_KEYWORDS.REVENUE */;\nconst VALUE_EVENT_METRIC_NAME = \"value\" /* RESERVED_EVENT_KEYWORDS.VALUE */;\n/**\n * Grab the revenue value from the event tags. \"revenue\" is a reserved keyword.\n * @param {EventTags} eventTags\n * @param {LoggerFacade} logger\n * @return {number|null}\n */\nexport function getRevenueValue(eventTags, logger) {\n    const rawValue = eventTags[REVENUE_EVENT_METRIC_NAME];\n    if (rawValue == null) {\n        // null or undefined event values\n        return null;\n    }\n    const parsedRevenueValue = typeof rawValue === 'string' ? parseInt(rawValue) : Math.trunc(rawValue);\n    if (isFinite(parsedRevenueValue)) {\n        logger === null || logger === void 0 ? void 0 : logger.info(PARSED_REVENUE_VALUE, parsedRevenueValue);\n        return parsedRevenueValue;\n    }\n    else {\n        // NaN, +/- infinity values\n        logger === null || logger === void 0 ? void 0 : logger.info(FAILED_TO_PARSE_REVENUE, rawValue);\n        return null;\n    }\n}\n/**\n * Grab the event value from the event tags. \"value\" is a reserved keyword.\n * @param {EventTags} eventTags\n * @param {LoggerFacade} logger\n * @return {number|null}\n */\nexport function getEventValue(eventTags, logger) {\n    const rawValue = eventTags[VALUE_EVENT_METRIC_NAME];\n    if (rawValue == null) {\n        // null or undefined event values\n        return null;\n    }\n    const parsedEventValue = typeof rawValue === 'string' ? parseFloat(rawValue) : rawValue;\n    if (isFinite(parsedEventValue)) {\n        logger === null || logger === void 0 ? void 0 : logger.info(PARSED_NUMERIC_VALUE, parsedEventValue);\n        return parsedEventValue;\n    }\n    else {\n        // NaN, +/- infinity values\n        logger === null || logger === void 0 ? void 0 : logger.info(FAILED_TO_PARSE_VALUE, rawValue);\n        return null;\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","import fns from '../../utils/fns';\nimport { INVALID_ATTRIBUTES, UNDEFINED_ATTRIBUTE } from 'error_message';\nimport { OptimizelyError } from '../../error/optimizly_error';\n/**\n * Validates user's provided attributes\n * @param  {unknown}  attributes\n * @return {boolean}  true if the attributes are valid\n * @throws If the attributes are not valid\n */\nexport function validate(attributes) {\n    if (typeof attributes === 'object' && !Array.isArray(attributes) && attributes !== null) {\n        Object.keys(attributes).forEach(function (key) {\n            if (typeof attributes[key] === 'undefined') {\n                throw new OptimizelyError(UNDEFINED_ATTRIBUTE, key);\n            }\n        });\n        return true;\n    }\n    else {\n        throw new OptimizelyError(INVALID_ATTRIBUTES);\n    }\n}\n/**\n * Validates user's provided attribute\n * @param  {unknown}  attributeKey\n * @param  {unknown}  attributeValue\n * @return {boolean}  true if the attribute is valid\n */\nexport function isAttributeValid(attributeKey, attributeValue) {\n    return (typeof attributeKey === 'string' &&\n        (typeof attributeValue === 'string' ||\n            typeof attributeValue === 'boolean' ||\n            (fns.isNumber(attributeValue) && fns.isSafeInteger(attributeValue))));\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","/**\n * Copyright 2024-2026, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { __awaiter } from \"tslib\";\nimport { getBatchedAsync, getBatchedSync } from \"../utils/cache/store\";\nimport { buildLogEvent } from \"./event_builder/log_event\";\nimport { ExponentialBackoff } from \"../utils/repeater/repeater\";\nimport { BaseService, ServiceState } from \"../service\";\nimport { runWithRetry } from \"../utils/executor/backoff_retry_runner\";\nimport { isSuccessStatusCode } from \"../utils/http_request_handler/http_util\";\nimport { EventEmitter } from \"../utils/event_emitter/event_emitter\";\nimport { IdGenerator } from \"../utils/id_generator\";\nimport { areEventContextsEqual } from \"./event_builder/user_event\";\nimport { FAILED_TO_DISPATCH_EVENTS, SERVICE_NOT_RUNNING } from \"error_message\";\nimport { OptimizelyError } from \"../error/optimizly_error\";\nimport { sprintf } from \"../utils/fns\";\nimport { SERVICE_STOPPED_BEFORE_RUNNING } from \"../service\";\nexport const DEFAULT_MIN_BACKOFF = 200;\nexport const DEFAULT_MAX_BACKOFF = 1000;\nexport const MAX_EVENTS_IN_STORE = 500;\nexport const LOGGER_NAME = 'BatchEventProcessor';\nexport class BatchEventProcessor extends BaseService {\n    constructor(config) {\n        var _a;\n        super(config.startupLogs);\n        this.eventQueue = [];\n        this.idGenerator = new IdGenerator();\n        this.runningTask = new Map();\n        this.dispatchingEvents = new Map();\n        this.eventEmitter = new EventEmitter();\n        this.eventDispatcher = config.eventDispatcher;\n        this.closingEventDispatcher = config.closingEventDispatcher;\n        this.batchSize = config.batchSize;\n        this.eventStore = config.eventStore;\n        this.retryConfig = config.retryConfig;\n        this.dispatchRepeater = config.dispatchRepeater;\n        this.dispatchRepeater.setTask(() => this.flush());\n        this.failedEventRepeater = config.failedEventRepeater;\n        (_a = this.failedEventRepeater) === null || _a === void 0 ? void 0 : _a.setTask(() => this.retryFailedEvents());\n        if (config.logger) {\n            this.setLogger(config.logger);\n        }\n    }\n    setLogger(logger) {\n        this.logger = logger;\n        this.logger.setName(LOGGER_NAME);\n    }\n    onDispatch(handler) {\n        return this.eventEmitter.on('dispatch', handler);\n    }\n    retryFailedEvents() {\n        return __awaiter(this, void 0, void 0, function* () {\n            if (!this.eventStore) {\n                return;\n            }\n            const keys = (yield this.eventStore.getKeys()).filter((k) => !this.dispatchingEvents.has(k) && !this.eventQueue.find((e) => e.id === k));\n            const events = yield (this.eventStore.operation === 'sync' ?\n                getBatchedSync(this.eventStore, keys) : getBatchedAsync(this.eventStore, keys));\n            const failedEvents = [];\n            events.forEach((e) => {\n                if (e) {\n                    failedEvents.push(e);\n                }\n            });\n            if (failedEvents.length == 0) {\n                return;\n            }\n            failedEvents.sort((a, b) => a.id < b.id ? -1 : 1);\n            const batches = [];\n            let currentBatch = [];\n            failedEvents.forEach((event) => {\n                if (currentBatch.length === this.batchSize ||\n                    (currentBatch.length > 0 && !areEventContextsEqual(currentBatch[0].event, event.event))) {\n                    batches.push({\n                        request: buildLogEvent(currentBatch.map((e) => e.event)),\n                        events: currentBatch,\n                    });\n                    currentBatch = [];\n                }\n                currentBatch.push(event);\n            });\n            if (currentBatch.length > 0) {\n                batches.push({\n                    request: buildLogEvent(currentBatch.map((e) => e.event)),\n                    events: currentBatch,\n                });\n            }\n            batches.forEach((batch) => {\n                this.dispatchBatch(batch, false);\n            });\n        });\n    }\n    createNewBatch() {\n        if (this.eventQueue.length == 0) {\n            return;\n        }\n        const events = [];\n        const eventWithIds = [];\n        this.eventQueue.forEach((event) => {\n            events.push(event.event);\n            eventWithIds.push(event);\n        });\n        this.eventQueue = [];\n        return { request: buildLogEvent(events), events: eventWithIds };\n    }\n    executeDispatch(request, closing = false) {\n        return __awaiter(this, void 0, void 0, function* () {\n            const dispatcher = closing && this.closingEventDispatcher ? this.closingEventDispatcher : this.eventDispatcher;\n            return dispatcher.dispatchEvent(request).then((res) => {\n                if (res.statusCode && !isSuccessStatusCode(res.statusCode)) {\n                    return Promise.reject(new OptimizelyError(FAILED_TO_DISPATCH_EVENTS, res.statusCode));\n                }\n                return Promise.resolve(res);\n            });\n        });\n    }\n    dispatchBatch(batch, closing) {\n        const { request, events } = batch;\n        events.forEach((event) => {\n            this.dispatchingEvents.set(event.id, event);\n        });\n        const runResult = this.retryConfig\n            ? runWithRetry(() => this.executeDispatch(request, closing), this.retryConfig.backoffProvider(), this.retryConfig.maxRetries) : {\n            result: this.executeDispatch(request, closing),\n            cancelRetry: () => { },\n        };\n        this.eventEmitter.emit('dispatch', request);\n        const taskId = this.idGenerator.getId();\n        this.runningTask.set(taskId, runResult);\n        runResult.result.then((res) => {\n            events.forEach((event) => {\n                var _a;\n                (_a = this.eventStore) === null || _a === void 0 ? void 0 : _a.remove(event.id);\n            });\n            return Promise.resolve();\n        }).catch((err) => {\n            var _a;\n            // if the dispatch fails, the events will still be\n            // in the store for future processing\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(err);\n        }).finally(() => {\n            this.runningTask.delete(taskId);\n            events.forEach((event) => this.dispatchingEvents.delete(event.id));\n        });\n    }\n    flush(useClosingDispatcher = false) {\n        return __awaiter(this, void 0, void 0, function* () {\n            const batch = this.createNewBatch();\n            if (!batch) {\n                return;\n            }\n            this.dispatchRepeater.reset();\n            this.dispatchBatch(batch, useClosingDispatcher);\n        });\n    }\n    process(event) {\n        var _a;\n        return __awaiter(this, void 0, void 0, function* () {\n            if (!this.isRunning()) {\n                return Promise.reject(new OptimizelyError(SERVICE_NOT_RUNNING, 'BatchEventProcessor'));\n            }\n            const eventWithId = {\n                id: this.idGenerator.getId(),\n                event: event,\n            };\n            // store in eventStore first to avoid data loss\n            yield Promise.resolve((_a = this.eventStore) === null || _a === void 0 ? void 0 : _a.set(eventWithId.id, eventWithId)).catch((e) => {\n                var _a;\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(e);\n            });\n            if (this.eventQueue.length > 0 && !areEventContextsEqual(this.eventQueue[0].event, event)) {\n                this.flush();\n            }\n            this.eventQueue.push(eventWithId);\n            if (this.eventQueue.length == this.batchSize) {\n                this.flush();\n            }\n            else if (!this.dispatchRepeater.isRunning()) {\n                this.dispatchRepeater.start();\n            }\n        });\n    }\n    start() {\n        var _a;\n        if (!this.isNew()) {\n            return;\n        }\n        super.start();\n        this.state = ServiceState.Running;\n        if (!this.disposable) {\n            (_a = this.failedEventRepeater) === null || _a === void 0 ? void 0 : _a.start();\n        }\n        this.retryFailedEvents();\n        this.startPromise.resolve();\n    }\n    makeDisposable() {\n        var _a, _b, _c;\n        super.makeDisposable();\n        this.batchSize = 1;\n        this.retryConfig = {\n            maxRetries: Math.min((_b = (_a = this.retryConfig) === null || _a === void 0 ? void 0 : _a.maxRetries) !== null && _b !== void 0 ? _b : 5, 5),\n            backoffProvider: ((_c = this.retryConfig) === null || _c === void 0 ? void 0 : _c.backoffProvider) ||\n                (() => new ExponentialBackoff(DEFAULT_MIN_BACKOFF, DEFAULT_MAX_BACKOFF, 500)),\n        };\n    }\n    flushImmediately() {\n        if (!this.isRunning()) {\n            return Promise.resolve();\n        }\n        return this.flush(true);\n    }\n    stop() {\n        var _a;\n        if (this.isDone()) {\n            return;\n        }\n        if (this.isNew()) {\n            this.startPromise.reject(new Error(sprintf(SERVICE_STOPPED_BEFORE_RUNNING, 'BatchEventProcessor')));\n        }\n        this.state = ServiceState.Stopping;\n        this.dispatchRepeater.stop();\n        (_a = this.failedEventRepeater) === null || _a === void 0 ? void 0 : _a.stop();\n        this.flush(true);\n        this.runningTask.forEach((task) => task.cancelRetry());\n        Promise.allSettled(Array.from(this.runningTask.values()).map((task) => task.result)).then(() => {\n            this.state = ServiceState.Terminated;\n            this.stopPromise.resolve();\n        });\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=batch_event_processor.js.map","/**\n * Copyright 2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass SerialRunner {\n    constructor() {\n        this.waitPromise = Promise.resolve();\n    }\n    // each call to serialize adds a new function to the end of the promise chain\n    // the function is called when the previous promise resolves\n    // if the function throws, the error is caught and ignored to allow the chain to continue\n    // the result of the function is returned as a promise\n    // if multiple calls to serialize are made, they will be executed in order\n    // even if some of them throw errors\n    run(fn) {\n        const resultPromise = this.waitPromise.then(fn);\n        this.waitPromise = resultPromise.catch(() => { });\n        return resultPromise;\n    }\n}\nexport { SerialRunner };\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=serial_runner.js.map","import { __awaiter } from \"tslib\";\nimport { OptimizelyError } from \"../error/optimizly_error\";\nimport { EVENT_STORE_FULL } from \"error_message\";\nimport { AsyncPrefixStore, AsyncStoreWithBatchedGet, SyncPrefixStore } from \"../utils/cache/store\";\nimport { SerialRunner } from \"../utils/executor/serial_runner\";\nconst identity = (v) => v;\nconst LOGGER_NAME = 'EventStore';\nexport const DEFAULT_MAX_EVENTS_IN_STORE = 500;\nexport const DEFAULT_STORE_TTL = 10 * 24 * 60 * 60 * 1000; // 10 days\nexport const EVENT_STORE_PREFIX = 'optly_event:';\nexport class EventStore extends AsyncStoreWithBatchedGet {\n    constructor(config) {\n        super();\n        this.operation = 'async';\n        this.serializer = new SerialRunner();\n        const { maxSize, ttl, store, logger } = config;\n        if (store.operation === 'sync') {\n            this.store = new SyncPrefixStore(store, EVENT_STORE_PREFIX, identity, identity);\n        }\n        else {\n            this.store = new AsyncPrefixStore(store, EVENT_STORE_PREFIX, identity, identity);\n        }\n        if (logger) {\n            logger.setName(LOGGER_NAME);\n            this.logger = logger;\n        }\n        this.maxSize = maxSize || DEFAULT_MAX_EVENTS_IN_STORE;\n        this.ttl = ttl || DEFAULT_STORE_TTL;\n    }\n    readKeys() {\n        return __awaiter(this, void 0, void 0, function* () {\n            return this.serializer.run(() => __awaiter(this, void 0, void 0, function* () {\n                var _a;\n                if (this.keys !== undefined) {\n                    return;\n                }\n                try {\n                    this.keys = new Set(yield this.getKeys());\n                }\n                catch (err) {\n                    (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(err);\n                }\n            }));\n        });\n    }\n    set(key, event) {\n        var _a;\n        return __awaiter(this, void 0, void 0, function* () {\n            yield this.readKeys();\n            // readKeys might have failed, in that case we cannot enforce max size\n            // that means, the store might grow beyond max size in failure scenarios\n            if (this.keys !== undefined && this.keys.size >= this.maxSize) {\n                return Promise.reject(new OptimizelyError(EVENT_STORE_FULL, event.event.uuid));\n            }\n            // this.store.set() might fail and cause the in memory set of keys to \n            // diverge from the actual stored key list. But the in memory set needs\n            // to be updated before the store set to limit the eventCount\n            // when concurrent set are present. Even if the store set fails, it will \n            // still keep the stored event count below maxSize (it will underfill the store).\n            // next getKeys() should fix the discrepency. \n            (_a = this.keys) === null || _a === void 0 ? void 0 : _a.add(key);\n            return this.store.set(key, Object.assign(Object.assign({}, event), { _time: { storedAt: Date.now(), ttl: this.ttl } }));\n        });\n    }\n    processStoredEvent(key, value) {\n        if (!value)\n            return undefined;\n        // if there is events in the stored saved by old version of the sdk, \n        // they will not have the storedAt time, update them with the current time\n        // before returning\n        if (value._time === undefined) {\n            value._time = { storedAt: Date.now(), ttl: this.ttl };\n            this.set(key, value).catch(() => { });\n            return value;\n        }\n        // use the ttl of the current store even if the stored event has a different ttl\n        // this ensures that if the store ttl is reduced, old events will also expire sooner\n        // and if the store ttl is increased, old events will stay longer\n        // the ttl at the time of save is still stored with the event for potential future use\n        if (value._time.storedAt + this.ttl <= Date.now()) {\n            this.remove(key).catch(() => { });\n            return undefined;\n        }\n        return value;\n    }\n    get(key) {\n        return __awaiter(this, void 0, void 0, function* () {\n            const value = yield this.store.get(key);\n            return this.processStoredEvent(key, value);\n        });\n    }\n    remove(key) {\n        var _a;\n        return __awaiter(this, void 0, void 0, function* () {\n            yield this.store.remove(key);\n            (_a = this.keys) === null || _a === void 0 ? void 0 : _a.delete(key);\n            return;\n        });\n    }\n    getKeys() {\n        return __awaiter(this, void 0, void 0, function* () {\n            const keys = yield this.store.getKeys();\n            this.keys = new Set(keys);\n            return keys;\n        });\n    }\n    getBatched(keys) {\n        return __awaiter(this, void 0, void 0, function* () {\n            const values = yield this.store.getBatched(keys);\n            return values.map((value, index) => this.processStoredEvent(keys[index], value));\n        });\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=event_store.js.map","/**\n * Copyright 2021-2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { buildLogEvent } from './event_builder/log_event';\nimport { BaseService, ServiceState } from '../service';\nimport { EventEmitter } from '../utils/event_emitter/event_emitter';\nimport { SERVICE_STOPPED_BEFORE_RUNNING } from '../service';\nimport { sprintf } from '../utils/fns';\nexport class ForwardingEventProcessor extends BaseService {\n    constructor(dispatcher) {\n        super();\n        this.dispatcher = dispatcher;\n        this.eventEmitter = new EventEmitter();\n    }\n    process(event) {\n        const formattedEvent = buildLogEvent([event]);\n        const res = this.dispatcher.dispatchEvent(formattedEvent);\n        this.eventEmitter.emit('dispatch', formattedEvent);\n        return res;\n    }\n    start() {\n        if (!this.isNew()) {\n            return;\n        }\n        this.state = ServiceState.Running;\n        this.startPromise.resolve();\n    }\n    stop() {\n        if (this.isDone()) {\n            return;\n        }\n        if (this.isNew()) {\n            this.startPromise.reject(new Error(sprintf(SERVICE_STOPPED_BEFORE_RUNNING, 'ForwardingEventProcessor')));\n        }\n        this.state = ServiceState.Terminated;\n        this.stopPromise.resolve();\n    }\n    onDispatch(handler) {\n        return this.eventEmitter.on('dispatch', handler);\n    }\n    flushImmediately() {\n        return Promise.resolve();\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=forwarding_event_processor.js.map","/**\n * Copyright 2024-2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { LogLevel } from \"../logging/logger\";\nimport { AsyncPrefixStore, SyncPrefixStore } from \"../utils/cache/store\";\nimport { validateStore } from \"../utils/cache/store_validator\";\nimport { ExponentialBackoff, IntervalRepeater } from \"../utils/repeater/repeater\";\nimport { BatchEventProcessor, DEFAULT_MAX_BACKOFF, DEFAULT_MIN_BACKOFF } from \"./batch_event_processor\";\nimport { EVENT_STORE_PREFIX } from \"./event_store\";\nimport { ForwardingEventProcessor } from \"./forwarding_event_processor\";\nexport const INVALID_EVENT_DISPATCHER = 'Invalid event dispatcher';\nexport const FAILED_EVENT_RETRY_INTERVAL = 20 * 1000;\nexport const getPrefixEventStore = (store) => {\n    if (store.operation === 'async') {\n        return new AsyncPrefixStore(store, EVENT_STORE_PREFIX, JSON.parse, JSON.stringify);\n    }\n    else {\n        return new SyncPrefixStore(store, EVENT_STORE_PREFIX, JSON.parse, JSON.stringify);\n    }\n};\nconst eventProcessorSymbol = Symbol();\nexport const validateEventDispatcher = (eventDispatcher) => {\n    if (!eventDispatcher || typeof eventDispatcher !== 'object' || typeof eventDispatcher.dispatchEvent !== 'function') {\n        throw new Error(INVALID_EVENT_DISPATCHER);\n    }\n};\nexport const getBatchEventProcessor = (options, EventProcessorConstructor = BatchEventProcessor) => {\n    const { eventDispatcher, closingEventDispatcher, retryOptions, eventStore } = options;\n    validateEventDispatcher(eventDispatcher);\n    if (closingEventDispatcher) {\n        validateEventDispatcher(closingEventDispatcher);\n    }\n    if (eventStore) {\n        validateStore(eventStore);\n    }\n    const retryConfig = retryOptions ? {\n        maxRetries: retryOptions.maxRetries,\n        backoffProvider: () => {\n            var _a, _b;\n            const minBackoff = (_a = retryOptions === null || retryOptions === void 0 ? void 0 : retryOptions.minBackoff) !== null && _a !== void 0 ? _a : DEFAULT_MIN_BACKOFF;\n            const maxBackoff = (_b = retryOptions === null || retryOptions === void 0 ? void 0 : retryOptions.maxBackoff) !== null && _b !== void 0 ? _b : DEFAULT_MAX_BACKOFF;\n            return new ExponentialBackoff(minBackoff, maxBackoff, 50);\n        }\n    } : undefined;\n    const startupLogs = [];\n    const { defaultFlushInterval, defaultBatchSize } = options;\n    let flushInterval = defaultFlushInterval;\n    if (options.flushInterval === undefined || options.flushInterval <= 0) {\n        startupLogs.push({\n            level: LogLevel.Warn,\n            message: 'Invalid flushInterval %s, defaulting to %s',\n            params: [options.flushInterval, defaultFlushInterval],\n        });\n    }\n    else {\n        flushInterval = options.flushInterval;\n    }\n    let batchSize = defaultBatchSize;\n    if (options.batchSize === undefined || options.batchSize <= 0) {\n        startupLogs.push({\n            level: LogLevel.Warn,\n            message: 'Invalid batchSize %s, defaulting to %s',\n            params: [options.batchSize, defaultBatchSize],\n        });\n    }\n    else {\n        batchSize = options.batchSize;\n    }\n    const dispatchRepeater = new IntervalRepeater(flushInterval);\n    const failedEventRepeater = options.failedEventRetryInterval ?\n        new IntervalRepeater(options.failedEventRetryInterval) : undefined;\n    return new EventProcessorConstructor({\n        eventDispatcher,\n        closingEventDispatcher,\n        dispatchRepeater,\n        failedEventRepeater,\n        retryConfig,\n        batchSize,\n        eventStore,\n        startupLogs,\n    });\n};\nexport const wrapEventProcessor = (eventProcessor) => {\n    return {\n        [eventProcessorSymbol]: eventProcessor,\n    };\n};\nexport const getOpaqueBatchEventProcessor = (options, EventProcessorConstructor = BatchEventProcessor) => {\n    return wrapEventProcessor(getBatchEventProcessor(options, EventProcessorConstructor));\n};\nexport const extractEventProcessor = (eventProcessor) => {\n    if (!eventProcessor || typeof eventProcessor !== 'object') {\n        return undefined;\n    }\n    return eventProcessor[eventProcessorSymbol];\n};\nexport function getForwardingEventProcessor(dispatcher) {\n    validateEventDispatcher(dispatcher);\n    return new ForwardingEventProcessor(dispatcher);\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=event_processor_factory.js.map","/**\n * Copyright 2022-2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport class InMemoryLruCache {\n    constructor(maxSize, ttl) {\n        this.operation = 'sync';\n        this.data = new Map();\n        this.maxSize = maxSize;\n        this.ttl = ttl;\n    }\n    lookup(key) {\n        const element = this.data.get(key);\n        if (!element)\n            return undefined;\n        this.data.delete(key);\n        if (element.expiresAt && element.expiresAt <= Date.now()) {\n            return undefined;\n        }\n        this.data.set(key, element);\n        return element.value;\n    }\n    save(key, value) {\n        this.data.delete(key);\n        if (this.data.size === this.maxSize) {\n            const firstMapEntryKey = this.data.keys().next().value;\n            this.data.delete(firstMapEntryKey);\n        }\n        this.data.set(key, {\n            value,\n            expiresAt: this.ttl ? Date.now() + this.ttl : undefined,\n        });\n    }\n    remove(key) {\n        this.data.delete(key);\n    }\n    reset() {\n        this.data.clear();\n    }\n    getKeys() {\n        return Array.from(this.data.keys());\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=in_memory_lru_cache.js.map","/**\n * Copyright 2022-2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { __awaiter } from \"tslib\";\nexport const LOGGER_NAME = 'OdpEventApiManager';\nexport class DefaultOdpEventApiManager {\n    constructor(requestHandler, requestDataGenerator, logger) {\n        this.requestHandler = requestHandler;\n        this.requestGenerator = requestDataGenerator;\n        if (logger) {\n            this.setLogger(logger);\n        }\n    }\n    setLogger(logger) {\n        this.logger = logger;\n        this.logger.setName(LOGGER_NAME);\n    }\n    sendEvents(odpConfig, events) {\n        return __awaiter(this, void 0, void 0, function* () {\n            if (events.length === 0) {\n                return {};\n            }\n            const { method, endpoint, headers, data } = this.requestGenerator(odpConfig, events);\n            const request = this.requestHandler.makeRequest(endpoint, headers, method, data);\n            return request.responsePromise;\n        });\n    }\n}\nexport const pixelApiRequestGenerator = (odpConfig, events) => {\n    const pixelApiPath = 'v2/zaius.gif';\n    const pixelApiEndpoint = new URL(pixelApiPath, odpConfig.pixelUrl);\n    const apiKey = odpConfig.apiKey;\n    const method = 'GET';\n    const event = events[0];\n    event.identifiers.forEach((v, k) => {\n        pixelApiEndpoint.searchParams.append(k, v);\n    });\n    event.data.forEach((v, k) => {\n        pixelApiEndpoint.searchParams.append(k, v);\n    });\n    pixelApiEndpoint.searchParams.append('tracker_id', apiKey);\n    pixelApiEndpoint.searchParams.append('event_type', event.type);\n    pixelApiEndpoint.searchParams.append('vdl_action', event.action);\n    const endpoint = pixelApiEndpoint.toString();\n    return {\n        method,\n        endpoint,\n        headers: {},\n        data: '',\n    };\n};\nexport const eventApiRequestGenerator = (odpConfig, events) => {\n    const { apiHost, apiKey } = odpConfig;\n    return {\n        method: 'POST',\n        endpoint: `${apiHost}/v3/events`,\n        headers: {\n            'Content-Type': 'application/json',\n            'x-api-key': apiKey,\n        },\n        data: JSON.stringify(events, (_, value) => {\n            return value instanceof Map ? Object.fromEntries(value) : value;\n        }),\n    };\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=odp_event_api_manager.js.map","/**\n * Copyright 2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport var ODP_USER_KEY;\n(function (ODP_USER_KEY) {\n    ODP_USER_KEY[\"VUID\"] = \"vuid\";\n    ODP_USER_KEY[\"FS_USER_ID\"] = \"fs_user_id\";\n    ODP_USER_KEY[\"FS_USER_ID_ALIAS\"] = \"fs-user-id\";\n})(ODP_USER_KEY || (ODP_USER_KEY = {}));\nexport var ODP_EVENT_ACTION;\n(function (ODP_EVENT_ACTION) {\n    ODP_EVENT_ACTION[\"IDENTIFIED\"] = \"identified\";\n    ODP_EVENT_ACTION[\"INITIALIZED\"] = \"client_initialized\";\n})(ODP_EVENT_ACTION || (ODP_EVENT_ACTION = {}));\nexport const ODP_DEFAULT_EVENT_TYPE = 'fullstack';\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=constant.js.map","/**\n * Copyright 2022-2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { __awaiter } from \"tslib\";\nimport { BaseService, ServiceState } from '../../service';\nimport { runWithRetry } from '../../utils/executor/backoff_retry_runner';\nimport { isSuccessStatusCode } from '../../utils/http_request_handler/http_util';\nimport { ODP_DEFAULT_EVENT_TYPE, ODP_USER_KEY } from '../constant';\nimport { EVENT_ACTION_INVALID, EVENT_DATA_INVALID, FAILED_TO_SEND_ODP_EVENTS, ODP_EVENTS_SHOULD_HAVE_ATLEAST_ONE_KEY_VALUE, ODP_NOT_INTEGRATED, FAILED_TO_DISPATCH_EVENTS, SERVICE_NOT_RUNNING } from 'error_message';\nimport { OptimizelyError } from '../../error/optimizly_error';\nimport { SERVICE_STOPPED_BEFORE_RUNNING } from '../../service';\nimport { sprintf } from '../../utils/fns';\nexport const LOGGER_NAME = 'OdpEventManager';\nexport class DefaultOdpEventManager extends BaseService {\n    constructor(config) {\n        super(config.startUpLogs);\n        this.queue = [];\n        this.apiManager = config.apiManager;\n        this.batchSize = config.batchSize;\n        this.retryConfig = config.retryConfig;\n        this.repeater = config.repeater;\n        this.repeater.setTask(() => this.flush());\n    }\n    setLogger(logger) {\n        this.logger = logger;\n        this.logger.setName(LOGGER_NAME);\n        this.apiManager.setLogger(logger.child());\n    }\n    executeDispatch(odpConfig, batch) {\n        return __awaiter(this, void 0, void 0, function* () {\n            const res = yield this.apiManager.sendEvents(odpConfig, batch);\n            if (res.statusCode && !isSuccessStatusCode(res.statusCode)) {\n                return Promise.reject(new OptimizelyError(FAILED_TO_DISPATCH_EVENTS, res.statusCode));\n            }\n            return yield Promise.resolve(res);\n        });\n    }\n    flush() {\n        return __awaiter(this, void 0, void 0, function* () {\n            if (!this.odpIntegrationConfig || !this.odpIntegrationConfig.integrated) {\n                return;\n            }\n            const odpConfig = this.odpIntegrationConfig.odpConfig;\n            const batch = this.queue;\n            this.queue = [];\n            // as the queue has been emptied, stop repeating flush\n            // until more events become available\n            this.repeater.reset();\n            return runWithRetry(() => this.executeDispatch(odpConfig, batch), this.retryConfig.backoffProvider(), this.retryConfig.maxRetries).result.catch((err) => {\n                var _a;\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(FAILED_TO_SEND_ODP_EVENTS, err);\n            });\n        });\n    }\n    start() {\n        if (!this.isNew()) {\n            return;\n        }\n        super.start();\n        if (this.odpIntegrationConfig) {\n            this.goToRunningState();\n        }\n        else {\n            this.state = ServiceState.Starting;\n        }\n    }\n    makeDisposable() {\n        super.makeDisposable();\n        this.retryConfig.maxRetries = Math.min(this.retryConfig.maxRetries, 5);\n        this.batchSize = 1;\n    }\n    updateConfig(odpIntegrationConfig) {\n        if (this.isDone()) {\n            return;\n        }\n        if (this.isNew()) {\n            this.odpIntegrationConfig = odpIntegrationConfig;\n            return;\n        }\n        if (this.isStarting()) {\n            this.odpIntegrationConfig = odpIntegrationConfig;\n            this.goToRunningState();\n            return;\n        }\n        // already running, flush the queue using the previous config first before updating the config\n        this.flush();\n        this.odpIntegrationConfig = odpIntegrationConfig;\n    }\n    goToRunningState() {\n        this.state = ServiceState.Running;\n        this.startPromise.resolve();\n    }\n    flushImmediately() {\n        if (!this.isRunning()) {\n            return Promise.resolve();\n        }\n        return this.flush();\n    }\n    stop() {\n        if (this.isDone()) {\n            return;\n        }\n        if (this.isNew()) {\n            this.startPromise.reject(new Error(sprintf(SERVICE_STOPPED_BEFORE_RUNNING, 'OdpEventManager')));\n        }\n        this.flush();\n        this.state = ServiceState.Terminated;\n        this.stopPromise.resolve();\n    }\n    sendEvent(event) {\n        var _a, _b, _c, _d, _e, _f;\n        if (!this.isRunning()) {\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(SERVICE_NOT_RUNNING, 'OdpEventManager');\n            return;\n        }\n        if (!((_b = this.odpIntegrationConfig) === null || _b === void 0 ? void 0 : _b.integrated)) {\n            (_c = this.logger) === null || _c === void 0 ? void 0 : _c.error(ODP_NOT_INTEGRATED);\n            return;\n        }\n        if (event.identifiers.size === 0) {\n            (_d = this.logger) === null || _d === void 0 ? void 0 : _d.error(ODP_EVENTS_SHOULD_HAVE_ATLEAST_ONE_KEY_VALUE);\n            return;\n        }\n        if (!this.isDataValid(event.data)) {\n            (_e = this.logger) === null || _e === void 0 ? void 0 : _e.error(EVENT_DATA_INVALID);\n            return;\n        }\n        if (!event.action) {\n            (_f = this.logger) === null || _f === void 0 ? void 0 : _f.error(EVENT_ACTION_INVALID);\n            return;\n        }\n        if (event.type === '') {\n            event.type = ODP_DEFAULT_EVENT_TYPE;\n        }\n        Array.from(event.identifiers.entries()).forEach(([key, value]) => {\n            // Catch for fs-user-id, FS-USER-ID, and FS_USER_ID and assign value to fs_user_id identifier.\n            if (ODP_USER_KEY.FS_USER_ID_ALIAS === key.toLowerCase() ||\n                ODP_USER_KEY.FS_USER_ID === key.toLowerCase()) {\n                event.identifiers.delete(key);\n                event.identifiers.set(ODP_USER_KEY.FS_USER_ID, value);\n            }\n        });\n        this.processEvent(event);\n    }\n    isDataValid(data) {\n        const validTypes = ['string', 'number', 'boolean'];\n        return Array.from(data.values()).reduce((valid, value) => valid && (value === null || validTypes.includes(typeof value)), true);\n    }\n    processEvent(event) {\n        this.queue.push(event);\n        if (this.queue.length === this.batchSize) {\n            this.flush();\n        }\n        else if (!this.repeater.isRunning()) {\n            this.repeater.start();\n        }\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=odp_event_manager.js.map","/**\n * Copyright 2022-2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport class OdpEvent {\n    /**\n     * Event to be sent and stored in the Optimizely Data Platform\n     * @param type Type of event (typically \"fullstack\")\n     * @param action Subcategory of the event type\n     * @param identifiers Key-value map of user identifiers\n     * @param data Event data in a key-value map.\n     */\n    constructor(type, action, identifiers, data) {\n        this.type = type;\n        this.action = action;\n        this.identifiers = identifiers !== null && identifiers !== void 0 ? identifiers : new Map();\n        this.data = data !== null && data !== void 0 ? data : new Map();\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=odp_event.js.map","/**\n * Copyright 2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { v4 as uuidV4 } from 'uuid';\nexport const VUID_PREFIX = `vuid_`;\nexport const VUID_MAX_LENGTH = 32;\nexport const isVuid = (vuid) => vuid.startsWith(VUID_PREFIX) && vuid.length > VUID_PREFIX.length;\nexport const makeVuid = () => {\n    // make sure UUIDv4 is used (not UUIDv1 or UUIDv6) since the trailing 5 chars will be truncated. See TDD for details.\n    const uuid = uuidV4();\n    const formatted = uuid.replace(/-/g, '');\n    const vuidFull = `${VUID_PREFIX}${formatted}`;\n    return vuidFull.length <= VUID_MAX_LENGTH ? vuidFull : vuidFull.substring(0, VUID_MAX_LENGTH);\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=vuid.js.map","/**\n * Copyright 2023-2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { __awaiter } from \"tslib\";\nimport { v4 as uuidV4 } from 'uuid';\nimport { odpIntegrationsAreEqual } from './odp_config';\nimport { OdpEvent } from './event_manager/odp_event';\nimport { resolvablePromise } from '../utils/promise/resolvablePromise';\nimport { BaseService, ServiceState } from '../service';\nimport { CLIENT_VERSION, JAVASCRIPT_CLIENT_ENGINE } from '../utils/enums';\nimport { ODP_DEFAULT_EVENT_TYPE, ODP_EVENT_ACTION, ODP_USER_KEY } from './constant';\nimport { isVuid } from '../vuid/vuid';\nimport { sprintf } from '../utils/fns';\nimport { SERVICE_STOPPED_BEFORE_RUNNING } from '../service';\nexport const LOGGER_NAME = 'OdpManager';\nexport class DefaultOdpManager extends BaseService {\n    constructor(config) {\n        super();\n        this.clientEngine = JAVASCRIPT_CLIENT_ENGINE;\n        this.clientVersion = CLIENT_VERSION;\n        this.segmentManager = config.segmentManager;\n        this.eventManager = config.eventManager;\n        this.configPromise = resolvablePromise();\n        if (config.userAgentParser) {\n            const { os, device } = config.userAgentParser.parseUserAgentInfo();\n            const userAgentInfo = {\n                'os': os.name,\n                'os_version': os.version,\n                'device_type': device.type,\n                'model': device.model,\n            };\n            this.userAgentData = new Map(Object.entries(userAgentInfo).filter(([_, value]) => value != null && value != undefined));\n        }\n        if (config.logger) {\n            this.setLogger(config.logger);\n        }\n    }\n    setLogger(logger) {\n        this.logger = logger;\n        this.logger.setName(LOGGER_NAME);\n        this.eventManager.setLogger(logger.child());\n        this.segmentManager.setLogger(logger.child());\n    }\n    setClientInfo(clientEngine, clientVersion) {\n        this.clientEngine = clientEngine;\n        this.clientVersion = clientVersion;\n    }\n    start() {\n        if (!this.isNew()) {\n            return;\n        }\n        this.state = ServiceState.Starting;\n        this.eventManager.start();\n        const startDependencies = [\n            this.configPromise,\n            this.eventManager.onRunning(),\n        ];\n        Promise.all(startDependencies)\n            .then(() => {\n            this.handleStartSuccess();\n        }).catch((err) => {\n            this.handleStartFailure(err);\n        });\n    }\n    makeDisposable() {\n        super.makeDisposable();\n        this.eventManager.makeDisposable();\n    }\n    handleStartSuccess() {\n        if (this.isDone()) {\n            return;\n        }\n        this.state = ServiceState.Running;\n        this.startPromise.resolve();\n    }\n    handleStartFailure(error) {\n        if (this.isDone()) {\n            return;\n        }\n        this.state = ServiceState.Failed;\n        this.startPromise.reject(error);\n        this.stopPromise.reject(error);\n    }\n    flushImmediately() {\n        if (!this.isRunning()) {\n            return Promise.resolve();\n        }\n        return this.eventManager.flushImmediately();\n    }\n    stop() {\n        if (this.isDone()) {\n            return;\n        }\n        if (!this.isRunning()) {\n            this.startPromise.reject(new Error(sprintf(SERVICE_STOPPED_BEFORE_RUNNING, 'OdpManager')));\n        }\n        this.state = ServiceState.Stopping;\n        this.eventManager.stop();\n        this.eventManager.onTerminated().then(() => {\n            this.state = ServiceState.Terminated;\n            this.stopPromise.resolve();\n        }).catch((err) => {\n            this.state = ServiceState.Failed;\n            this.stopPromise.reject(err);\n        });\n    }\n    updateConfig(odpIntegrationConfig) {\n        // do nothing if config did not change\n        if (this.odpIntegrationConfig && odpIntegrationsAreEqual(this.odpIntegrationConfig, odpIntegrationConfig)) {\n            return false;\n        }\n        if (this.isDone()) {\n            return false;\n        }\n        this.odpIntegrationConfig = odpIntegrationConfig;\n        this.configPromise.resolve();\n        this.segmentManager.updateConfig(odpIntegrationConfig);\n        this.eventManager.updateConfig(odpIntegrationConfig);\n        return true;\n    }\n    /**\n     * Attempts to fetch and return a list of a user's qualified segments from the local segments cache.\n     * If no cached data exists for the target user, this fetches and caches data from the ODP server instead.\n     * @param {string}                          userId  - Unique identifier of a target user.\n     * @param {Array<OptimizelySegmentOption>}  options - An array of OptimizelySegmentOption used to ignore and/or reset the cache.\n     * @returns {Promise<string[] | null>}      A promise holding either a list of qualified segments or null.\n     */\n    fetchQualifiedSegments(userId, options = []) {\n        return __awaiter(this, void 0, void 0, function* () {\n            if (isVuid(userId)) {\n                return this.segmentManager.fetchQualifiedSegments(ODP_USER_KEY.VUID, userId, options);\n            }\n            return this.segmentManager.fetchQualifiedSegments(ODP_USER_KEY.FS_USER_ID, userId, options);\n        });\n    }\n    identifyUser(userId, vuid) {\n        const identifiers = new Map();\n        let finalUserId = userId;\n        let finalVuid = vuid;\n        if (!vuid && isVuid(userId)) {\n            finalVuid = userId;\n            finalUserId = undefined;\n        }\n        if (finalVuid) {\n            identifiers.set(ODP_USER_KEY.VUID, finalVuid);\n        }\n        if (finalUserId) {\n            identifiers.set(ODP_USER_KEY.FS_USER_ID, finalUserId);\n        }\n        const event = new OdpEvent(ODP_DEFAULT_EVENT_TYPE, ODP_EVENT_ACTION.IDENTIFIED, identifiers);\n        this.sendEvent(event);\n    }\n    sendEvent(event) {\n        if (!event.identifiers.has(ODP_USER_KEY.VUID) && this.vuid) {\n            event.identifiers.set(ODP_USER_KEY.VUID, this.vuid);\n        }\n        event.data = this.augmentCommonData(event.data);\n        this.eventManager.sendEvent(event);\n    }\n    augmentCommonData(sourceData) {\n        const data = new Map(this.userAgentData);\n        data.set('idempotence_id', uuidV4());\n        data.set('data_source_type', 'sdk');\n        data.set('data_source', this.clientEngine);\n        data.set('data_source_version', this.clientVersion);\n        sourceData.forEach((value, key) => data.set(key, value));\n        return data;\n    }\n    setVuid(vuid) {\n        this.vuid = vuid;\n        this.onRunning().then(() => {\n            var _a;\n            if ((_a = this.odpIntegrationConfig) === null || _a === void 0 ? void 0 : _a.integrated) {\n                const event = new OdpEvent(ODP_DEFAULT_EVENT_TYPE, ODP_EVENT_ACTION.INITIALIZED);\n                this.sendEvent(event);\n            }\n        });\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=odp_manager.js.map","var schemaDefinition = {\n    $schema: 'http://json-schema.org/draft-04/schema#',\n    title: 'Project Config JSON Schema',\n    type: 'object',\n    properties: {\n        projectId: {\n            type: 'string',\n            required: true,\n        },\n        accountId: {\n            type: 'string',\n            required: true,\n        },\n        groups: {\n            type: 'array',\n            items: {\n                type: 'object',\n                properties: {\n                    id: {\n                        type: 'string',\n                        required: true,\n                    },\n                    policy: {\n                        type: 'string',\n                        required: true,\n                    },\n                    trafficAllocation: {\n                        type: 'array',\n                        items: {\n                            type: 'object',\n                            properties: {\n                                entityId: {\n                                    type: 'string',\n                                    required: true,\n                                },\n                                endOfRange: {\n                                    type: 'integer',\n                                    required: true,\n                                },\n                            },\n                        },\n                        required: true,\n                    },\n                    experiments: {\n                        type: 'array',\n                        items: {\n                            type: 'object',\n                            properties: {\n                                id: {\n                                    type: 'string',\n                                    required: true,\n                                },\n                                key: {\n                                    type: 'string',\n                                    required: true,\n                                },\n                                status: {\n                                    type: 'string',\n                                    required: true,\n                                },\n                                layerId: {\n                                    type: 'string',\n                                    required: true,\n                                },\n                                variations: {\n                                    type: 'array',\n                                    items: {\n                                        type: 'object',\n                                        properties: {\n                                            id: {\n                                                type: 'string',\n                                                required: true,\n                                            },\n                                            key: {\n                                                type: 'string',\n                                                required: true,\n                                            },\n                                        },\n                                    },\n                                    required: true,\n                                },\n                                trafficAllocation: {\n                                    type: 'array',\n                                    items: {\n                                        type: 'object',\n                                        properties: {\n                                            entityId: {\n                                                type: 'string',\n                                                required: true,\n                                            },\n                                            endOfRange: {\n                                                type: 'integer',\n                                                required: true,\n                                            },\n                                        },\n                                    },\n                                    required: true,\n                                },\n                                audienceIds: {\n                                    type: 'array',\n                                    items: {\n                                        type: 'string',\n                                    },\n                                    required: true,\n                                },\n                                forcedVariations: {\n                                    type: 'object',\n                                    required: true,\n                                },\n                            },\n                        },\n                        required: true,\n                    },\n                },\n            },\n            required: true,\n        },\n        experiments: {\n            type: 'array',\n            items: {\n                type: 'object',\n                properties: {\n                    id: {\n                        type: 'string',\n                        required: true,\n                    },\n                    key: {\n                        type: 'string',\n                        required: true,\n                    },\n                    status: {\n                        type: 'string',\n                        required: true,\n                    },\n                    layerId: {\n                        type: 'string',\n                        required: true,\n                    },\n                    variations: {\n                        type: 'array',\n                        items: {\n                            type: 'object',\n                            properties: {\n                                id: {\n                                    type: 'string',\n                                    required: true,\n                                },\n                                key: {\n                                    type: 'string',\n                                    required: true,\n                                },\n                            },\n                        },\n                        required: true,\n                    },\n                    trafficAllocation: {\n                        type: 'array',\n                        items: {\n                            type: 'object',\n                            properties: {\n                                entityId: {\n                                    type: 'string',\n                                    required: true,\n                                },\n                                endOfRange: {\n                                    type: 'integer',\n                                    required: true,\n                                },\n                            },\n                        },\n                        required: true,\n                    },\n                    audienceIds: {\n                        type: 'array',\n                        items: {\n                            type: 'string',\n                        },\n                        required: true,\n                    },\n                    forcedVariations: {\n                        type: 'object',\n                        required: true,\n                    },\n                    cmab: {\n                        type: 'object',\n                        required: false,\n                        properties: {\n                            attributes: {\n                                type: 'array',\n                                items: {\n                                    type: 'string',\n                                },\n                                required: true,\n                            }\n                        }\n                    }\n                },\n            },\n            required: true,\n        },\n        events: {\n            type: 'array',\n            items: {\n                type: 'object',\n                properties: {\n                    key: {\n                        type: 'string',\n                        required: true,\n                    },\n                    experimentIds: {\n                        type: 'array',\n                        items: {\n                            type: 'string',\n                            required: true,\n                        },\n                    },\n                    id: {\n                        type: 'string',\n                        required: true,\n                    },\n                },\n            },\n            required: true,\n        },\n        audiences: {\n            type: 'array',\n            items: {\n                type: 'object',\n                properties: {\n                    id: {\n                        type: 'string',\n                        required: true,\n                    },\n                    name: {\n                        type: 'string',\n                        required: true,\n                    },\n                    conditions: {\n                        type: 'string',\n                        required: true,\n                    },\n                },\n            },\n            required: true,\n        },\n        attributes: {\n            type: 'array',\n            items: {\n                type: 'object',\n                properties: {\n                    id: {\n                        type: 'string',\n                        required: true,\n                    },\n                    key: {\n                        type: 'string',\n                        required: true,\n                    },\n                },\n            },\n            required: true,\n        },\n        version: {\n            type: 'string',\n            required: true,\n        },\n        revision: {\n            type: 'string',\n            required: true,\n        },\n        integrations: {\n            type: 'array',\n            items: {\n                type: 'object',\n                properties: {\n                    key: {\n                        type: 'string',\n                        required: true\n                    },\n                    host: {\n                        type: 'string'\n                    },\n                    publicKey: {\n                        type: 'string'\n                    },\n                    pixelUrl: {\n                        type: 'string'\n                    },\n                },\n            },\n        },\n    },\n};\nconst schema = schemaDefinition;\nexport default schema;\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=project_config_schema.js.map","/**\n * Copyright 2022, 2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the 'License');\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an 'AS IS' BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * JSON Schema used to validate the ODP GraphQL response\n */\nexport const OdpResponseSchema = {\n    $schema: 'https://json-schema.org/draft/2019-09/schema',\n    $id: 'https://example.com/example.json',\n    title: 'ODP Response Schema',\n    type: 'object',\n    required: [\n        'data',\n    ],\n    properties: {\n        data: {\n            title: 'The data Schema',\n            type: 'object',\n            required: [\n                'customer',\n            ],\n            properties: {\n                customer: {\n                    title: 'The customer Schema',\n                    type: 'object',\n                    required: [],\n                    properties: {\n                        audiences: {\n                            title: 'The audiences Schema',\n                            type: 'object',\n                            required: [\n                                'edges',\n                            ],\n                            properties: {\n                                edges: {\n                                    title: 'The edges Schema',\n                                    type: 'array',\n                                    items: {\n                                        title: 'A Schema',\n                                        type: 'object',\n                                        required: [\n                                            'node',\n                                        ],\n                                        properties: {\n                                            node: {\n                                                title: 'The node Schema',\n                                                type: 'object',\n                                                required: [\n                                                    'name',\n                                                    'state',\n                                                ],\n                                                properties: {\n                                                    name: {\n                                                        title: 'The name Schema',\n                                                        type: 'string',\n                                                        examples: [\n                                                            'has_email',\n                                                            'has_email_opted_in',\n                                                        ],\n                                                    },\n                                                    state: {\n                                                        title: 'The state Schema',\n                                                        type: 'string',\n                                                        examples: [\n                                                            'qualified',\n                                                        ],\n                                                    },\n                                                },\n                                                examples: [],\n                                            },\n                                        },\n                                        examples: [],\n                                    },\n                                    examples: [],\n                                },\n                            },\n                            examples: [],\n                        },\n                    },\n                    examples: [],\n                },\n            },\n            examples: [],\n        },\n        errors: {\n            title: 'The errors Schema',\n            type: 'array',\n            default: [],\n            items: {\n                title: 'A Schema',\n                type: 'object',\n                required: [\n                    'message',\n                    'locations',\n                    'extensions',\n                ],\n                properties: {\n                    message: {\n                        title: 'The message Schema',\n                        type: 'string',\n                        examples: [\n                            'Exception while fetching data (/customer) : java.lang.RuntimeException: could not resolve _fs_user_id = asdsdaddddd',\n                        ],\n                    },\n                    locations: {\n                        title: 'The locations Schema',\n                        type: 'array',\n                        items: {\n                            title: 'A Schema',\n                            type: 'object',\n                            required: [\n                                'line',\n                                'column',\n                            ],\n                            properties: {\n                                line: {\n                                    title: 'The line Schema',\n                                    type: 'integer',\n                                    examples: [\n                                        2,\n                                    ],\n                                },\n                                column: {\n                                    title: 'The column Schema',\n                                    type: 'integer',\n                                    examples: [\n                                        3,\n                                    ],\n                                },\n                            },\n                            examples: [],\n                        },\n                        examples: [],\n                    },\n                    path: {\n                        title: 'The path Schema',\n                        type: 'array',\n                        items: {\n                            title: 'A Schema',\n                            type: 'string',\n                            examples: [\n                                'customer',\n                            ],\n                        },\n                        examples: [],\n                    },\n                    extensions: {\n                        title: 'The extensions Schema',\n                        type: 'object',\n                        required: [\n                            'classification',\n                        ],\n                        properties: {\n                            classification: {\n                                title: 'The classification Schema',\n                                type: 'string',\n                                examples: [\n                                    'InvalidIdentifierException',\n                                ],\n                            },\n                        },\n                        examples: [],\n                    },\n                },\n                examples: [],\n            },\n            examples: [],\n        },\n    },\n    examples: [],\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=odp_response_schema.js.map","/**\n * Copyright 2022-2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { __awaiter } from \"tslib\";\nimport { validate } from '../../utils/json_schema_validator';\nimport { OdpResponseSchema } from './odp_response_schema';\n/**\n * Expected value for a qualified/valid segment\n */\nconst QUALIFIED = 'qualified';\n/**\n * Return value when no valid segments found\n */\nconst EMPTY_SEGMENTS_COLLECTION = [];\n/**\n * Return value for scenarios with no valid JSON\n */\nconst EMPTY_JSON_RESPONSE = null;\n/**\n * Standard message for audience querying fetch errors\n */\nconst AUDIENCE_FETCH_FAILURE_MESSAGE = 'Audience segments fetch failed';\nexport const LOGGER_NAME = 'OdpSegmentApiManager';\nexport class DefaultOdpSegmentApiManager {\n    constructor(requestHandler, logger) {\n        /**\n         * Converts the query parameters to a GraphQL JSON payload\n         * @returns GraphQL JSON string\n         */\n        this.toGraphQLJson = (userKey, userValue, segmentsToCheck) => [\n            '{\"query\" : \"query {customer',\n            `(${userKey} : \\\\\"${userValue}\\\\\") `,\n            '{audiences',\n            '(subset: [',\n            ...((segmentsToCheck === null || segmentsToCheck === void 0 ? void 0 : segmentsToCheck.map((segment, index) => `\\\\\"${segment}\\\\\"${index < segmentsToCheck.length - 1 ? ',' : ''}`)) || ''),\n            ']) {edges {node {name state}}}}}\"}',\n        ].join('');\n        this.requestHandler = requestHandler;\n        if (logger) {\n            this.setLogger(logger);\n        }\n    }\n    setLogger(logger) {\n        this.logger = logger;\n        this.logger.setName(LOGGER_NAME);\n    }\n    /**\n     * Retrieves the audience segments from ODP\n     * @param apiKey ODP public key\n     * @param apiHost Host of ODP endpoint\n     * @param userKey 'vuid' or 'fs_user_id key'\n     * @param userValue Associated value to query for the user key\n     * @param segmentsToCheck Audience segments to check for experiment inclusion\n     */\n    fetchSegments(apiKey, apiHost, userKey, userValue, segmentsToCheck) {\n        var _a, _b, _c, _d, _e, _f, _g, _h, _j;\n        return __awaiter(this, void 0, void 0, function* () {\n            if ((segmentsToCheck === null || segmentsToCheck === void 0 ? void 0 : segmentsToCheck.length) === 0) {\n                return EMPTY_SEGMENTS_COLLECTION;\n            }\n            const endpoint = `${apiHost}/v3/graphql`;\n            const query = this.toGraphQLJson(userKey, userValue, segmentsToCheck);\n            const segmentsResponse = yield this.querySegments(apiKey, endpoint, query);\n            if (!segmentsResponse) {\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(`${AUDIENCE_FETCH_FAILURE_MESSAGE} (network error)`);\n                return null;\n            }\n            const parsedSegments = this.parseSegmentsResponseJson(segmentsResponse);\n            if (!parsedSegments) {\n                (_b = this.logger) === null || _b === void 0 ? void 0 : _b.error(`${AUDIENCE_FETCH_FAILURE_MESSAGE} (decode error)`);\n                return null;\n            }\n            if (((_c = parsedSegments.errors) === null || _c === void 0 ? void 0 : _c.length) > 0) {\n                const { code, classification } = parsedSegments.errors[0].extensions;\n                if (code == 'INVALID_IDENTIFIER_EXCEPTION') {\n                    (_d = this.logger) === null || _d === void 0 ? void 0 : _d.error(`${AUDIENCE_FETCH_FAILURE_MESSAGE} (invalid identifier)`);\n                }\n                else {\n                    (_e = this.logger) === null || _e === void 0 ? void 0 : _e.error(`${AUDIENCE_FETCH_FAILURE_MESSAGE} (${classification})`);\n                }\n                return null;\n            }\n            const edges = (_h = (_g = (_f = parsedSegments === null || parsedSegments === void 0 ? void 0 : parsedSegments.data) === null || _f === void 0 ? void 0 : _f.customer) === null || _g === void 0 ? void 0 : _g.audiences) === null || _h === void 0 ? void 0 : _h.edges;\n            if (!edges) {\n                (_j = this.logger) === null || _j === void 0 ? void 0 : _j.error(`${AUDIENCE_FETCH_FAILURE_MESSAGE} (decode error)`);\n                return null;\n            }\n            return edges.filter(edge => edge.node.state == QUALIFIED).map(edge => edge.node.name);\n        });\n    }\n    /**\n     * Handler for querying the ODP GraphQL endpoint\n     * @param apiKey ODP API key\n     * @param endpoint Fully-qualified GraphQL endpoint URL\n     * @param userKey 'vuid' or 'fs_user_id'\n     * @param userValue userKey's value\n     * @param query GraphQL formatted query string\n     * @returns JSON response string from ODP or null\n     */\n    querySegments(apiKey, endpoint, query) {\n        return __awaiter(this, void 0, void 0, function* () {\n            const method = 'POST';\n            const url = endpoint;\n            const headers = {\n                'Content-Type': 'application/json',\n                'x-api-key': apiKey,\n            };\n            try {\n                const request = this.requestHandler.makeRequest(url, headers, method, query);\n                const { statusCode, body } = yield request.responsePromise;\n                if (!(statusCode >= 200 && statusCode < 300)) {\n                    return null;\n                }\n                return body;\n            }\n            catch (_a) {\n                return null;\n            }\n        });\n    }\n    /**\n     * Parses JSON response\n     * @param jsonResponse JSON response from ODP\n     * @private\n     * @returns Response Strongly-typed ODP Response object\n     */\n    parseSegmentsResponseJson(jsonResponse) {\n        let jsonObject = {};\n        try {\n            jsonObject = JSON.parse(jsonResponse);\n        }\n        catch (_a) {\n            return EMPTY_JSON_RESPONSE;\n        }\n        if (validate(jsonObject, OdpResponseSchema, false)) {\n            return jsonObject;\n        }\n        return EMPTY_JSON_RESPONSE;\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=odp_segment_api_manager.js.map","/**\n * Copyright 2016-2017, 2020, 2022, 2024 Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { validate as jsonSchemaValidator } from 'json-schema';\nimport schema from '../../project_config/project_config_schema';\nimport { INVALID_DATAFILE, INVALID_JSON, NO_JSON_PROVIDED } from 'error_message';\nimport { OptimizelyError } from '../../error/optimizly_error';\n/**\n * Validate the given json object against the specified schema\n * @param {unknown} jsonObject The object to validate against the schema\n * @param {JSONSchema4} validationSchema Provided schema to use for validation\n * @param {boolean} shouldThrowOnError Should validation throw if invalid JSON object\n * @return {boolean} true if the given object is valid; throws or false if invalid\n */\nexport function validate(jsonObject, validationSchema = schema, shouldThrowOnError = true) {\n    if (typeof jsonObject !== 'object' || jsonObject === null) {\n        throw new OptimizelyError(NO_JSON_PROVIDED);\n    }\n    const result = jsonSchemaValidator(jsonObject, validationSchema);\n    if (result.valid) {\n        return true;\n    }\n    if (!shouldThrowOnError) {\n        return false;\n    }\n    if (Array.isArray(result.errors)) {\n        throw new OptimizelyError(INVALID_DATAFILE, result.errors[0].property, result.errors[0].message);\n    }\n    throw new OptimizelyError(INVALID_JSON);\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","/**\n * Copyright 2022, 2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport var OptimizelySegmentOption;\n(function (OptimizelySegmentOption) {\n    OptimizelySegmentOption[\"IGNORE_CACHE\"] = \"IGNORE_CACHE\";\n    OptimizelySegmentOption[\"RESET_CACHE\"] = \"RESET_CACHE\";\n})(OptimizelySegmentOption || (OptimizelySegmentOption = {}));\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=optimizely_segment_option.js.map","/**\n * Copyright 2022-2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { __awaiter } from \"tslib\";\nimport { OptimizelySegmentOption } from './optimizely_segment_option';\nimport { ODP_CONFIG_NOT_AVAILABLE, ODP_NOT_INTEGRATED } from 'error_message';\nexport const LOGGER_NAME = 'OdpSegmentManager';\nexport class DefaultOdpSegmentManager {\n    constructor(segmentsCache, odpSegmentApiManager, logger) {\n        this.segmentsCache = segmentsCache;\n        this.odpSegmentApiManager = odpSegmentApiManager;\n        if (logger) {\n            this.setLogger(logger);\n        }\n    }\n    setLogger(logger) {\n        this.logger = logger;\n        this.logger.setName(LOGGER_NAME);\n        this.odpSegmentApiManager.setLogger(logger.child());\n    }\n    /**\n     * Attempts to fetch and return a list of a user's qualified segments from the local segments cache.\n     * If no cached data exists for the target user, this fetches and caches data from the ODP server instead.\n     * @param userKey Key used for identifying the id type.\n     * @param userValue The id value itself.\n     * @param options An array of OptimizelySegmentOption used to ignore and/or reset the cache.\n     * @returns Qualified segments for the user from the cache or the ODP server if the cache is empty.\n     */\n    fetchQualifiedSegments(userKey, userValue, options) {\n        var _a, _b;\n        return __awaiter(this, void 0, void 0, function* () {\n            if (!this.odpIntegrationConfig) {\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.warn(ODP_CONFIG_NOT_AVAILABLE);\n                return null;\n            }\n            if (!this.odpIntegrationConfig.integrated) {\n                (_b = this.logger) === null || _b === void 0 ? void 0 : _b.warn(ODP_NOT_INTEGRATED);\n                return null;\n            }\n            const odpConfig = this.odpIntegrationConfig.odpConfig;\n            const segmentsToCheck = odpConfig.segmentsToCheck;\n            if (!segmentsToCheck || segmentsToCheck.length <= 0) {\n                return [];\n            }\n            const cacheKey = this.makeCacheKey(userKey, userValue);\n            const ignoreCache = options === null || options === void 0 ? void 0 : options.includes(OptimizelySegmentOption.IGNORE_CACHE);\n            const resetCache = options === null || options === void 0 ? void 0 : options.includes(OptimizelySegmentOption.RESET_CACHE);\n            if (resetCache) {\n                this.segmentsCache.reset();\n            }\n            if (!ignoreCache) {\n                const cachedSegments = yield this.segmentsCache.lookup(cacheKey);\n                if (cachedSegments) {\n                    return cachedSegments;\n                }\n            }\n            const segments = yield this.odpSegmentApiManager.fetchSegments(odpConfig.apiKey, odpConfig.apiHost, userKey, userValue, segmentsToCheck);\n            if (segments && !ignoreCache) {\n                this.segmentsCache.save(cacheKey, segments);\n            }\n            return segments;\n        });\n    }\n    makeCacheKey(userKey, userValue) {\n        return `${userKey}-$-${userValue}`;\n    }\n    updateConfig(config) {\n        this.odpIntegrationConfig = config;\n        this.segmentsCache.reset();\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=odp_segment_manager.js.map","/**\n * Copyright 2024-2026, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { InMemoryLruCache } from \"../utils/cache/in_memory_lru_cache\";\nimport { ExponentialBackoff, IntervalRepeater } from \"../utils/repeater/repeater\";\nimport { DefaultOdpEventApiManager } from \"./event_manager/odp_event_api_manager\";\nimport { DefaultOdpEventManager } from \"./event_manager/odp_event_manager\";\nimport { DefaultOdpManager } from \"./odp_manager\";\nimport { DefaultOdpSegmentApiManager } from \"./segment_manager/odp_segment_api_manager\";\nimport { DefaultOdpSegmentManager } from \"./segment_manager/odp_segment_manager\";\nexport const DEFAULT_CACHE_SIZE = 10000;\nexport const DEFAULT_CACHE_TIMEOUT = 600000;\nexport const DEFAULT_EVENT_BATCH_SIZE = 100;\nexport const DEFAULT_EVENT_FLUSH_INTERVAL = 10000;\nexport const DEFAULT_EVENT_MAX_RETRIES = 2;\nexport const DEFAULT_EVENT_MIN_BACKOFF = 200;\nexport const DEFAULT_EVENT_MAX_BACKOFF = 1000;\nexport const INVALID_CACHE = 'Invalid cache';\nexport const INVALID_CACHE_METHOD = 'Invalid cache method %s';\nconst odpManagerSymbol = Symbol();\nconst validateCache = (cache) => {\n    const errors = [];\n    if (!cache || typeof cache !== 'object') {\n        throw new Error(INVALID_CACHE);\n    }\n    for (const method of ['save', 'lookup', 'reset']) {\n        if (typeof cache[method] !== 'function') {\n            errors.push(INVALID_CACHE_METHOD.replace('%s', method));\n        }\n    }\n    if (errors.length > 0) {\n        throw new Error(errors.join(', '));\n    }\n};\nconst getDefaultSegmentsCache = (cacheSize, cacheTimeout) => {\n    return new InMemoryLruCache(cacheSize || DEFAULT_CACHE_SIZE, cacheTimeout || DEFAULT_CACHE_TIMEOUT);\n};\nconst getDefaultSegmentManager = (options) => {\n    if (options.segmentsCache) {\n        validateCache(options.segmentsCache);\n    }\n    return new DefaultOdpSegmentManager(options.segmentsCache || getDefaultSegmentsCache(options.segmentsCacheSize, options.segmentsCacheTimeout), new DefaultOdpSegmentApiManager(options.segmentRequestHandler));\n};\nconst getDefaultEventManager = (options) => {\n    return new DefaultOdpEventManager({\n        apiManager: new DefaultOdpEventApiManager(options.eventRequestHandler, options.eventRequestGenerator),\n        batchSize: options.eventBatchSize || DEFAULT_EVENT_BATCH_SIZE,\n        repeater: new IntervalRepeater(options.eventFlushInterval || DEFAULT_EVENT_FLUSH_INTERVAL),\n        retryConfig: {\n            maxRetries: options.eventMaxRetries || DEFAULT_EVENT_MAX_RETRIES,\n            backoffProvider: () => new ExponentialBackoff(options.eventMinBackoff || DEFAULT_EVENT_MIN_BACKOFF, options.eventMaxBackoff || DEFAULT_EVENT_MAX_BACKOFF, 50),\n        },\n    });\n};\nexport const getOdpManager = (options) => {\n    const segmentManager = getDefaultSegmentManager(options);\n    const eventManager = getDefaultEventManager(options);\n    return new DefaultOdpManager({\n        segmentManager,\n        eventManager,\n        userAgentParser: options.userAgentParser,\n    });\n};\nexport const getOpaqueOdpManager = (options) => {\n    return {\n        [odpManagerSymbol]: getOdpManager(options),\n    };\n};\nexport const extractOdpManager = (manager) => {\n    if (!manager || typeof manager !== 'object') {\n        return undefined;\n    }\n    return manager[odpManagerSymbol];\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=odp_manager_factory.js.map","/**\n * Copyright 2024-2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst vuidManagerSymbol = Symbol();\nexport const extractVuidManager = (opaqueVuidManager) => {\n    if (!opaqueVuidManager || typeof opaqueVuidManager !== 'object') {\n        return undefined;\n    }\n    return opaqueVuidManager[vuidManagerSymbol];\n};\nexport const wrapVuidManager = (vuidManager) => {\n    return {\n        [vuidManagerSymbol]: vuidManager\n    };\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=vuid_manager_factory.js.map","import { OptimizelyError } from \"./optimizly_error\";\nexport class ErrorReporter {\n    constructor(logger, errorNotifier) {\n        this.logger = logger;\n        this.errorNotifier = errorNotifier;\n    }\n    report(error, ...params) {\n        if (typeof error === 'string') {\n            error = new OptimizelyError(error, ...params);\n            this.report(error);\n            return;\n        }\n        if (this.errorNotifier) {\n            this.errorNotifier.notify(error);\n        }\n        if (this.logger) {\n            this.logger.error(error);\n        }\n    }\n    setLogger(logger) {\n        this.logger = logger;\n    }\n    setErrorNotifier(errorNotifier) {\n        this.errorNotifier = errorNotifier;\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=error_reporter.js.map","import { objectValues } from '../utils/fns';\nimport { NOTIFICATION_TYPES } from './type';\nimport { EventEmitter } from '../utils/event_emitter/event_emitter';\nimport { NOTIFICATION_LISTENER_EXCEPTION } from 'error_message';\nimport { ErrorReporter } from '../error/error_reporter';\n/**\n * NotificationCenter allows registration and triggering of callback functions using\n * notification event types defined in NOTIFICATION_TYPES of utils/enums/index.js:\n * - ACTIVATE: An impression event will be sent to Optimizely.\n * - TRACK a conversion event will be sent to Optimizely\n */\nexport class DefaultNotificationCenter {\n    /**\n     * @constructor\n     * @param   {NotificationCenterOptions}  options\n     * @param   {LogHandler}                 options.logger       An instance of a logger to log messages with\n     * @param   {ErrorHandler}               options.errorHandler An instance of errorHandler to handle any unexpected error\n     */\n    constructor(options) {\n        this.removerId = 1;\n        this.eventEmitter = new EventEmitter();\n        this.removers = new Map();\n        this.errorReporter = new ErrorReporter(options.logger, options.errorNotifier);\n    }\n    /**\n     * Add a notification callback to the notification center\n     * @param   {string}                   notificationType     One of the values from NOTIFICATION_TYPES in utils/enums/index.js\n     * @param   {NotificationListener<T>}  callback             Function that will be called when the event is triggered\n     * @returns {number}                   If the callback was successfully added, returns a listener ID which can be used\n     * to remove the callback by calling removeNotificationListener. The ID is a number greater than 0.\n     * If there was an error and the listener was not added, addNotificationListener returns -1. This\n     * can happen if the first argument is not a valid notification type, or if the same callback\n     * function was already added as a listener by a prior call to this function.\n     */\n    addNotificationListener(notificationType, callback) {\n        const notificationTypeValues = objectValues(NOTIFICATION_TYPES);\n        const isNotificationTypeValid = notificationTypeValues.indexOf(notificationType) > -1;\n        if (!isNotificationTypeValid) {\n            return -1;\n        }\n        const returnId = this.removerId++;\n        const remover = this.eventEmitter.on(notificationType, this.wrapWithErrorReporting(notificationType, callback));\n        this.removers.set(returnId, remover);\n        return returnId;\n    }\n    wrapWithErrorReporting(notificationType, callback) {\n        return (notificationData) => {\n            try {\n                callback(notificationData);\n            }\n            catch (ex) {\n                const message = ex instanceof Error ? ex.message : String(ex);\n                this.errorReporter.report(NOTIFICATION_LISTENER_EXCEPTION, notificationType, message);\n            }\n        };\n    }\n    /**\n     * Remove a previously added notification callback\n     * @param   {number}                 listenerId ID of listener to be removed\n     * @returns {boolean}                Returns true if the listener was found and removed, and false\n     * otherwise.\n     */\n    removeNotificationListener(listenerId) {\n        const remover = this.removers.get(listenerId);\n        if (remover) {\n            remover();\n            return true;\n        }\n        return false;\n    }\n    /**\n     * Removes all previously added notification listeners, for all notification types\n     */\n    clearAllNotificationListeners() {\n        this.eventEmitter.removeAllListeners();\n    }\n    /**\n     * Remove all previously added notification listeners for the argument type\n     * @param   {NotificationType}    notificationType One of NotificationType\n     */\n    clearNotificationListeners(notificationType) {\n        this.eventEmitter.removeListeners(notificationType);\n    }\n    /**\n     * Fires notifications for the argument type. All registered callbacks for this type will be\n     * called. The notificationData object will be passed on to callbacks called.\n     * @param {NotificationType} notificationType One of NotificationType\n     * @param {Object} notificationData Will be passed to callbacks called\n     */\n    sendNotifications(notificationType, notificationData) {\n        this.eventEmitter.emit(notificationType, notificationData);\n    }\n}\n/**\n * Create an instance of NotificationCenter\n * @param   {NotificationCenterOptions}   options\n * @returns {NotificationCenter}          An instance of NotificationCenter\n */\nexport function createNotificationCenter(options) {\n    return new DefaultNotificationCenter(options);\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","export function newErrorDecision(key, user, reasons) {\n    return {\n        variationKey: null,\n        enabled: false,\n        variables: {},\n        ruleKey: null,\n        flagKey: key,\n        userContext: user,\n        reasons: reasons,\n    };\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","import { __awaiter } from \"tslib\";\nexport const FORCED_DECISION_NULL_RULE_KEY = '$opt_null_rule_key';\nexport default class OptimizelyUserContext {\n    constructor({ optimizely, userId, attributes }) {\n        this._qualifiedSegments = null;\n        this.optimizely = optimizely;\n        this.userId = userId;\n        this.attributes = Object.assign({}, attributes);\n        this.forcedDecisionsMap = {};\n    }\n    /**\n     * Sets an attribute for a given key.\n     * @param     {string}                     key         An attribute key\n     * @param     {any}                        value       An attribute value\n     */\n    setAttribute(key, value) {\n        this.attributes[key] = value;\n    }\n    getUserId() {\n        return this.userId;\n    }\n    getAttributes() {\n        return Object.assign({}, this.attributes);\n    }\n    getOptimizely() {\n        return this.optimizely;\n    }\n    get qualifiedSegments() {\n        return this._qualifiedSegments;\n    }\n    set qualifiedSegments(qualifiedSegments) {\n        this._qualifiedSegments = qualifiedSegments;\n    }\n    /**\n     * Returns a decision result for a given flag key and a user context, which contains all data required to deliver the flag.\n     * If the SDK finds an error, it will return a decision with null for variationKey. The decision will include an error message in reasons.\n     * @param     {string}                     key         A flag key for which a decision will be made.\n     * @param     {OptimizelyDecideOption}     options     An array of options for decision-making.\n     * @return    {OptimizelyDecision}                     A decision result.\n     */\n    decide(key, options = []) {\n        return this.optimizely.decide(this.cloneUserContext(), key, options);\n    }\n    /**\n     * Returns a promise that resolves in decision result for a given flag key and a user context, which contains all data required to deliver the flag.\n     * If the SDK finds an error, it will return a decision with null for variationKey. The decision will include an error message in reasons.\n     * @param     {string}                     key         A flag key for which a decision will be made.\n     * @param     {OptimizelyDecideOption}     options     An array of options for decision-making.\n     * @return    {Promise<OptimizelyDecision>}                     A Promise that resolves decision result.\n     */\n    decideAsync(key, options) {\n        return this.optimizely.decideAsync(this.cloneUserContext(), key, options);\n    }\n    /**\n     * Returns an object of decision results for multiple flag keys and a user context.\n     * If the SDK finds an error for a key, the response will include a decision for the key showing reasons for the error.\n     * The SDK will always return key-mapped decisions. When it cannot process requests, it will return an empty map after logging the errors.\n     * @param     {string[]}                   keys        An array of flag keys for which decisions will be made.\n     * @param     {OptimizelyDecideOption[]}   options     An array of options for decision-making.\n     * @return    {[key: string]: OptimizelyDecision}      An object of decision results mapped by flag keys.\n     */\n    decideForKeys(keys, options = []) {\n        return this.optimizely.decideForKeys(this.cloneUserContext(), keys, options);\n    }\n    /**\n     * Returns a promise that resolves in an object of decision results for multiple flag keys and a user context.\n     * If the SDK finds an error for a key, the response will include a decision for the key showing reasons for the error.\n     * The SDK will always return key-mapped decisions. When it cannot process requests, it will return an empty map after logging the errors.\n     * @param     {string[]}                   keys        An array of flag keys for which decisions will be made.\n     * @param     {OptimizelyDecideOption[]}   options     An array of options for decision-making.\n     * @return    {Promise<Record<string, OptimizelyDecision>>}      A promise that resolves in an object of decision results mapped by flag keys.\n     */\n    decideForKeysAsync(keys, options) {\n        return this.optimizely.decideForKeysAsync(this.cloneUserContext(), keys, options);\n    }\n    /**\n     * Returns an object of decision results for all active flag keys.\n     * @param     {OptimizelyDecideOption[]}   options     An array of options for decision-making.\n     * @return    {[key: string]: OptimizelyDecision}      An object of all decision results mapped by flag keys.\n     */\n    decideAll(options = []) {\n        return this.optimizely.decideAll(this.cloneUserContext(), options);\n    }\n    /**\n     * Returns a promise that resolves in an object of decision results for all active flag keys.\n     * @param     {OptimizelyDecideOption[]}   options     An array of options for decision-making.\n     * @return    {Promise<Record<string ,OptimizelyDecision>>}      A promise that resolves in an object of all decision results mapped by flag keys.\n     */\n    decideAllAsync(options = []) {\n        return this.optimizely.decideAllAsync(this.cloneUserContext(), options);\n    }\n    /**\n     * Tracks an event.\n     * @param     {string}                     eventName The event name.\n     * @param     {EventTags}                  eventTags An optional map of event tag names to event tag values.\n     */\n    trackEvent(eventName, eventTags) {\n        this.optimizely.track(eventName, this.userId, this.attributes, eventTags);\n    }\n    /**\n     * Sets the forced decision for specified optimizely decision context.\n     * @param     {OptimizelyDecisionContext}   context      OptimizelyDecisionContext containing flagKey and optional ruleKey.\n     * @param     {OptimizelyForcedDecision}    decision     OptimizelyForcedDecision containing forced variation key.\n     * @return    {boolean}                     true if the forced decision has been set successfully.\n     */\n    setForcedDecision(context, decision) {\n        var _a;\n        const flagKey = context.flagKey;\n        const ruleKey = (_a = context.ruleKey) !== null && _a !== void 0 ? _a : FORCED_DECISION_NULL_RULE_KEY;\n        const variationKey = decision.variationKey;\n        const forcedDecision = { variationKey };\n        if (!this.forcedDecisionsMap[flagKey]) {\n            this.forcedDecisionsMap[flagKey] = {};\n        }\n        this.forcedDecisionsMap[flagKey][ruleKey] = forcedDecision;\n        return true;\n    }\n    /**\n     * Returns the forced decision for specified optimizely decision context.\n     * @param     {OptimizelyDecisionContext}  context  OptimizelyDecisionContext containing flagKey and optional ruleKey.\n     * @return    {OptimizelyForcedDecision|null}       OptimizelyForcedDecision for specified context if exists or null.\n     */\n    getForcedDecision(context) {\n        return this.findForcedDecision(context);\n    }\n    /**\n     * Removes the forced decision for specified optimizely decision context.\n     * @param     {OptimizelyDecisionContext}  context  OptimizelyDecisionContext containing flagKey and optional ruleKey.\n     * @return    {boolean}                    true if the forced decision has been removed successfully\n     */\n    removeForcedDecision(context) {\n        var _a;\n        const ruleKey = (_a = context.ruleKey) !== null && _a !== void 0 ? _a : FORCED_DECISION_NULL_RULE_KEY;\n        const flagKey = context.flagKey;\n        let isForcedDecisionRemoved = false;\n        if (this.forcedDecisionsMap.hasOwnProperty(flagKey)) {\n            const forcedDecisionByRuleKey = this.forcedDecisionsMap[flagKey];\n            if (forcedDecisionByRuleKey.hasOwnProperty(ruleKey)) {\n                delete this.forcedDecisionsMap[flagKey][ruleKey];\n                isForcedDecisionRemoved = true;\n            }\n            if (Object.keys(this.forcedDecisionsMap[flagKey]).length === 0) {\n                delete this.forcedDecisionsMap[flagKey];\n            }\n        }\n        return isForcedDecisionRemoved;\n    }\n    /**\n     * Removes all forced decisions bound to this user context.\n     * @return    {boolean}                    true if the forced decision has been removed successfully\n     */\n    removeAllForcedDecisions() {\n        this.forcedDecisionsMap = {};\n        return true;\n    }\n    /**\n     * Finds a forced decision in forcedDecisionsMap for provided optimizely decision context.\n     * @param     {OptimizelyDecisionContext}     context  OptimizelyDecisionContext containing flagKey and optional ruleKey.\n     * @return    {OptimizelyForcedDecision|null}          OptimizelyForcedDecision for specified context if exists or null.\n     */\n    findForcedDecision(context) {\n        var _a;\n        let variationKey;\n        const validRuleKey = (_a = context.ruleKey) !== null && _a !== void 0 ? _a : FORCED_DECISION_NULL_RULE_KEY;\n        const flagKey = context.flagKey;\n        if (this.forcedDecisionsMap.hasOwnProperty(context.flagKey)) {\n            const forcedDecisionByRuleKey = this.forcedDecisionsMap[flagKey];\n            if (forcedDecisionByRuleKey.hasOwnProperty(validRuleKey)) {\n                variationKey = forcedDecisionByRuleKey[validRuleKey].variationKey;\n                return { variationKey };\n            }\n        }\n        return null;\n    }\n    cloneUserContext() {\n        const userContext = new OptimizelyUserContext({\n            optimizely: this.getOptimizely(),\n            userId: this.getUserId(),\n            attributes: this.getAttributes(),\n        });\n        if (Object.keys(this.forcedDecisionsMap).length > 0) {\n            userContext.forcedDecisionsMap = Object.assign({}, this.forcedDecisionsMap);\n        }\n        userContext._qualifiedSegments = this._qualifiedSegments;\n        return userContext;\n    }\n    /**\n     * Fetches a target user's list of qualified segments filtered by any given segment options and stores in qualifiedSegments.\n     * @param {OptimizelySegmentOption[]} options   (Optional) List of segment options used to filter qualified segment results.\n     * @returns Boolean representing if segments were populated.\n     */\n    fetchQualifiedSegments(options) {\n        return __awaiter(this, void 0, void 0, function* () {\n            const segments = yield this.optimizely.fetchQualifiedSegments(this.userId, options);\n            this.qualifiedSegments = segments;\n            return segments !== null;\n        });\n    }\n    /**\n     * Returns a boolean representing if a user is qualified for a particular segment.\n     * @param   {string}  segment   Target segment to be evaluated for user qualification.\n     * @returns {boolean}           Boolean representing if a user qualified for the passed in segment.\n     */\n    isQualifiedFor(segment) {\n        if (!this._qualifiedSegments) {\n            return false;\n        }\n        return this._qualifiedSegments.indexOf(segment) > -1;\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","/**\n * Copyright 2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport murmurhash from 'murmurhash';\nimport { INVALID_BUCKETING_ID } from 'error_message';\nimport { OptimizelyError } from '../../error/optimizly_error';\nconst HASH_SEED = 1;\nconst MAX_HASH_VALUE = Math.pow(2, 32);\nconst MAX_TRAFFIC_VALUE = 10000;\n/**\n * Helper function to generate bucket value in half-closed interval [0, MAX_TRAFFIC_VALUE)\n * @param  {string}               bucketingKey          String value for bucketing\n * @return {number}               The generated bucket value\n * @throws                        If bucketing value is not a valid string\n */\nexport const generateBucketValue = function (bucketingKey) {\n    try {\n        // NOTE: the mmh library already does cast the hash value as an unsigned 32bit int\n        // https://github.com/perezd/node-murmurhash/blob/master/murmurhash.js#L115\n        const hashValue = murmurhash.v3(bucketingKey, HASH_SEED);\n        const ratio = hashValue / MAX_HASH_VALUE;\n        return Math.floor(ratio * MAX_TRAFFIC_VALUE);\n    }\n    catch (ex) {\n        throw new OptimizelyError(INVALID_BUCKETING_ID, bucketingKey, ex.message);\n    }\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=bucket_value_generator.js.map","/**\n * Copyright 2016, 2019-2022, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { INVALID_GROUP_ID } from 'error_message';\nimport { OptimizelyError } from '../../error/optimizly_error';\nimport { generateBucketValue } from './bucket_value_generator';\nexport const USER_NOT_IN_ANY_EXPERIMENT = 'User %s is not in any experiment of group %s.';\nexport const USER_NOT_BUCKETED_INTO_EXPERIMENT_IN_GROUP = 'User %s is not in experiment %s of group %s.';\nexport const USER_BUCKETED_INTO_EXPERIMENT_IN_GROUP = 'User %s is in experiment %s of group %s.';\nexport const USER_ASSIGNED_TO_EXPERIMENT_BUCKET = 'Assigned bucket %s to user with bucketing ID %s.';\nexport const INVALID_VARIATION_ID = 'Bucketed into an invalid variation ID. Returning null.';\nconst RANDOM_POLICY = 'random';\n/**\n * Determines ID of variation to be shown for the given input params\n * @param  {Object}             bucketerParams\n * @param  {string}             bucketerParams.experimentId\n * @param  {string}             bucketerParams.experimentKey\n * @param  {string}             bucketerParams.userId\n * @param  {Object[]}           bucketerParams.trafficAllocationConfig\n * @param  {Array}              bucketerParams.experimentKeyMap\n * @param  {Object}             bucketerParams.groupIdMap\n * @param  {Object}             bucketerParams.variationIdMap\n * @param  {string}             bucketerParams.varationIdMap[].key\n * @param  {Object}             bucketerParams.logger\n * @param  {string}             bucketerParams.bucketingId\n * @return {Object}             DecisionResponse                         DecisionResponse containing variation ID that user has been bucketed into,\n *                                                                       null if user is not bucketed into any experiment and the decide reasons.\n */\nexport const bucket = function (bucketerParams) {\n    var _a, _b, _c, _d, _e;\n    const decideReasons = [];\n    // Check if user is in a random group; if so, check if user is bucketed into a specific experiment\n    const experiment = bucketerParams.experimentIdMap[bucketerParams.experimentId];\n    // Optional chaining skips groupId check for holdout experiments; Holdout experimentId is not in experimentIdMap\n    const groupId = experiment === null || experiment === void 0 ? void 0 : experiment['groupId'];\n    if (groupId) {\n        const group = bucketerParams.groupIdMap[groupId];\n        if (!group) {\n            throw new OptimizelyError(INVALID_GROUP_ID, groupId);\n        }\n        if (group.policy === RANDOM_POLICY) {\n            const bucketedExperimentId = bucketUserIntoExperiment(group, bucketerParams.bucketingId, bucketerParams.userId, bucketerParams.logger);\n            // Return if user is not bucketed into any experiment\n            if (bucketedExperimentId === null) {\n                (_a = bucketerParams.logger) === null || _a === void 0 ? void 0 : _a.info(USER_NOT_IN_ANY_EXPERIMENT, bucketerParams.userId, groupId);\n                decideReasons.push([\n                    USER_NOT_IN_ANY_EXPERIMENT,\n                    bucketerParams.userId,\n                    groupId,\n                ]);\n                return {\n                    result: null,\n                    reasons: decideReasons,\n                };\n            }\n            // Return if user is bucketed into a different experiment than the one specified\n            if (bucketedExperimentId !== bucketerParams.experimentId) {\n                (_b = bucketerParams.logger) === null || _b === void 0 ? void 0 : _b.info(USER_NOT_BUCKETED_INTO_EXPERIMENT_IN_GROUP, bucketerParams.userId, bucketerParams.experimentKey, groupId);\n                decideReasons.push([\n                    USER_NOT_BUCKETED_INTO_EXPERIMENT_IN_GROUP,\n                    bucketerParams.userId,\n                    bucketerParams.experimentKey,\n                    groupId,\n                ]);\n                return {\n                    result: null,\n                    reasons: decideReasons,\n                };\n            }\n            // Continue bucketing if user is bucketed into specified experiment      \n            (_c = bucketerParams.logger) === null || _c === void 0 ? void 0 : _c.info(USER_BUCKETED_INTO_EXPERIMENT_IN_GROUP, bucketerParams.userId, bucketerParams.experimentKey, groupId);\n            decideReasons.push([\n                USER_BUCKETED_INTO_EXPERIMENT_IN_GROUP,\n                bucketerParams.userId,\n                bucketerParams.experimentKey,\n                groupId,\n            ]);\n        }\n    }\n    const bucketingId = `${bucketerParams.bucketingId}${bucketerParams.experimentId}`;\n    const bucketValue = generateBucketValue(bucketingId);\n    (_d = bucketerParams.logger) === null || _d === void 0 ? void 0 : _d.debug(USER_ASSIGNED_TO_EXPERIMENT_BUCKET, bucketValue, bucketerParams.userId);\n    decideReasons.push([\n        USER_ASSIGNED_TO_EXPERIMENT_BUCKET,\n        bucketValue,\n        bucketerParams.userId,\n    ]);\n    const entityId = _findBucket(bucketValue, bucketerParams.trafficAllocationConfig);\n    if (bucketerParams.validateEntity && entityId !== null && !bucketerParams.variationIdMap[entityId]) {\n        if (entityId) {\n            (_e = bucketerParams.logger) === null || _e === void 0 ? void 0 : _e.warn(INVALID_VARIATION_ID);\n            decideReasons.push([INVALID_VARIATION_ID]);\n        }\n        return {\n            result: null,\n            reasons: decideReasons,\n        };\n    }\n    return {\n        result: entityId,\n        reasons: decideReasons,\n    };\n};\n/**\n * Returns bucketed experiment ID to compare against experiment user is being called into\n * @param  {Group}       group        Group that experiment is in\n * @param  {string}      bucketingId  Bucketing ID\n * @param  {string}      userId       ID of user to be bucketed into experiment\n * @param  {LoggerFacade}  logger       Logger implementation\n * @return {string|null}              ID of experiment if user is bucketed into experiment within the group, null otherwise\n */\nexport const bucketUserIntoExperiment = function (group, bucketingId, userId, logger) {\n    const bucketingKey = `${bucketingId}${group.id}`;\n    const bucketValue = generateBucketValue(bucketingKey);\n    logger === null || logger === void 0 ? void 0 : logger.debug(USER_ASSIGNED_TO_EXPERIMENT_BUCKET, bucketValue, userId);\n    const trafficAllocationConfig = group.trafficAllocation;\n    const bucketedExperimentId = _findBucket(bucketValue, trafficAllocationConfig);\n    return bucketedExperimentId;\n};\n/**\n * Returns entity ID associated with bucket value\n * @param  {number}                bucketValue\n * @param  {TrafficAllocation[]}   trafficAllocationConfig\n * @param  {number}                trafficAllocationConfig[].endOfRange\n * @param  {string}                trafficAllocationConfig[].entityId\n * @return {string|null}           Entity ID for bucketing if bucket value is within traffic allocation boundaries, null otherwise\n */\nexport const _findBucket = function (bucketValue, trafficAllocationConfig) {\n    for (let i = 0; i < trafficAllocationConfig.length; i++) {\n        if (bucketValue < trafficAllocationConfig[i].endOfRange) {\n            return trafficAllocationConfig[i].entityId;\n        }\n    }\n    return null;\n};\nexport default {\n    bucket: bucket,\n    bucketUserIntoExperiment: bucketUserIntoExperiment,\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","/**\n * Copyright 2020, 2022, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { UNKNOWN_MATCH_TYPE } from 'error_message';\n/**\n * Evaluate if provided string is number only\n * @param  {unknown}  content\n * @return {boolean}  true if the string is number only\n *\n */\nfunction isNumber(content) {\n    return /^\\d+$/.test(content);\n}\n/**\n * Evaluate if provided version contains pre-release \"-\"\n * @param  {unknown}  version\n * @return {boolean}  true if the version contains \"-\" and meets condition\n *\n */\nfunction isPreReleaseVersion(version) {\n    const preReleaseIndex = version.indexOf(\"-\" /* VERSION_TYPE.PRE_RELEASE_VERSION_DELIMITER */);\n    const buildIndex = version.indexOf(\"+\" /* VERSION_TYPE.BUILD_VERSION_DELIMITER */);\n    if (preReleaseIndex < 0) {\n        return false;\n    }\n    if (buildIndex < 0) {\n        return true;\n    }\n    return preReleaseIndex < buildIndex;\n}\n/**\n * Evaluate if provided version contains build \"+\"\n * @param  {unknown}  version\n * @return {boolean}  true if the version contains \"+\" and meets condition\n *\n */\nfunction isBuildVersion(version) {\n    const preReleaseIndex = version.indexOf(\"-\" /* VERSION_TYPE.PRE_RELEASE_VERSION_DELIMITER */);\n    const buildIndex = version.indexOf(\"+\" /* VERSION_TYPE.BUILD_VERSION_DELIMITER */);\n    if (buildIndex < 0) {\n        return false;\n    }\n    if (preReleaseIndex < 0) {\n        return true;\n    }\n    return buildIndex < preReleaseIndex;\n}\n/**\n * check if there is any white spaces \" \" in version\n * @param  {unknown}  version\n * @return {boolean}  true if the version contains \" \"\n *\n */\nfunction hasWhiteSpaces(version) {\n    return /\\s/.test(version);\n}\n/**\n * split version in parts\n * @param  {unknown}  version\n * @return {boolean}  The array of version split into smaller parts i.e major, minor, patch etc\n *                    null if given version is in invalid format\n */\nfunction splitVersion(version, logger) {\n    let targetPrefix = version;\n    let targetSuffix = '';\n    // check that version shouldn't have white space\n    if (hasWhiteSpaces(version)) {\n        logger === null || logger === void 0 ? void 0 : logger.warn(UNKNOWN_MATCH_TYPE, version);\n        return null;\n    }\n    //check for pre release e.g. 1.0.0-alpha where 'alpha' is a pre release\n    //otherwise check for build e.g. 1.0.0+001 where 001 is a build metadata\n    if (isPreReleaseVersion(version)) {\n        targetPrefix = version.substring(0, version.indexOf(\"-\" /* VERSION_TYPE.PRE_RELEASE_VERSION_DELIMITER */));\n        targetSuffix = version.substring(version.indexOf(\"-\" /* VERSION_TYPE.PRE_RELEASE_VERSION_DELIMITER */) + 1);\n    }\n    else if (isBuildVersion(version)) {\n        targetPrefix = version.substring(0, version.indexOf(\"+\" /* VERSION_TYPE.BUILD_VERSION_DELIMITER */));\n        targetSuffix = version.substring(version.indexOf(\"+\" /* VERSION_TYPE.BUILD_VERSION_DELIMITER */) + 1);\n    }\n    // check dot counts in target_prefix\n    if (typeof targetPrefix !== 'string' || typeof targetSuffix !== 'string') {\n        return null;\n    }\n    const dotCount = targetPrefix.split('.').length - 1;\n    if (dotCount > 2) {\n        logger === null || logger === void 0 ? void 0 : logger.warn(UNKNOWN_MATCH_TYPE, version);\n        return null;\n    }\n    const targetVersionParts = targetPrefix.split('.');\n    if (targetVersionParts.length != dotCount + 1) {\n        logger === null || logger === void 0 ? void 0 : logger.warn(UNKNOWN_MATCH_TYPE, version);\n        return null;\n    }\n    for (const part of targetVersionParts) {\n        if (!isNumber(part)) {\n            logger === null || logger === void 0 ? void 0 : logger.warn(UNKNOWN_MATCH_TYPE, version);\n            return null;\n        }\n    }\n    if (targetSuffix) {\n        targetVersionParts.push(targetSuffix);\n    }\n    return targetVersionParts;\n}\n/**\n * Compare user version with condition version\n * @param  {string}  conditionsVersion\n * @param  {string}  userProvidedVersion\n * @return {number | null}  0 if user version is equal to condition version\n *                          1 if user version is greater than condition version\n *                         -1 if user version is less than condition version\n *                          null if invalid user or condition version is provided\n */\nexport function compareVersion(conditionsVersion, userProvidedVersion, logger) {\n    const userVersionParts = splitVersion(userProvidedVersion, logger);\n    const conditionsVersionParts = splitVersion(conditionsVersion, logger);\n    if (!userVersionParts || !conditionsVersionParts) {\n        return null;\n    }\n    const userVersionPartsLen = userVersionParts.length;\n    for (let idx = 0; idx < conditionsVersionParts.length; idx++) {\n        if (userVersionPartsLen <= idx) {\n            return isPreReleaseVersion(conditionsVersion) || isBuildVersion(conditionsVersion) ? 1 : -1;\n        }\n        else if (!isNumber(userVersionParts[idx])) {\n            if (userVersionParts[idx] < conditionsVersionParts[idx]) {\n                return isPreReleaseVersion(conditionsVersion) && !isPreReleaseVersion(userProvidedVersion) ? 1 : -1;\n            }\n            else if (userVersionParts[idx] > conditionsVersionParts[idx]) {\n                return !isPreReleaseVersion(conditionsVersion) && isPreReleaseVersion(userProvidedVersion) ? -1 : 1;\n            }\n        }\n        else {\n            const userVersionPart = parseInt(userVersionParts[idx]);\n            const conditionsVersionPart = parseInt(conditionsVersionParts[idx]);\n            if (userVersionPart > conditionsVersionPart) {\n                return 1;\n            }\n            else if (userVersionPart < conditionsVersionPart) {\n                return -1;\n            }\n        }\n    }\n    // check if user version contains release and target version does not\n    if (isPreReleaseVersion(userProvidedVersion) && !isPreReleaseVersion(conditionsVersion)) {\n        return -1;\n    }\n    return 0;\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","/****************************************************************************\n * Copyright 2018-2019, 2020, 2022, Optimizely, Inc. and contributors              *\n *                                                                          *\n * Licensed under the Apache License, Version 2.0 (the \"License\");          *\n * you may not use this file except in compliance with the License.         *\n * You may obtain a copy of the License at                                  *\n *                                                                          *\n *    http://www.apache.org/licenses/LICENSE-2.0                            *\n *                                                                          *\n * Unless required by applicable law or agreed to in writing, software      *\n * distributed under the License is distributed on an \"AS IS\" BASIS,        *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and      *\n * limitations under the License.                                           *\n ***************************************************************************/\nimport fns from '../../utils/fns';\nimport { compareVersion } from '../../utils/semantic_version';\nimport { MISSING_ATTRIBUTE_VALUE, UNEXPECTED_TYPE_NULL, } from 'log_message';\nimport { OUT_OF_BOUNDS, UNEXPECTED_TYPE, UNEXPECTED_CONDITION_VALUE, UNKNOWN_MATCH_TYPE } from 'error_message';\nconst EXACT_MATCH_TYPE = 'exact';\nconst EXISTS_MATCH_TYPE = 'exists';\nconst GREATER_OR_EQUAL_THAN_MATCH_TYPE = 'ge';\nconst GREATER_THAN_MATCH_TYPE = 'gt';\nconst LESS_OR_EQUAL_THAN_MATCH_TYPE = 'le';\nconst LESS_THAN_MATCH_TYPE = 'lt';\nconst SEMVER_EXACT_MATCH_TYPE = 'semver_eq';\nconst SEMVER_GREATER_OR_EQUAL_THAN_MATCH_TYPE = 'semver_ge';\nconst SEMVER_GREATER_THAN_MATCH_TYPE = 'semver_gt';\nconst SEMVER_LESS_OR_EQUAL_THAN_MATCH_TYPE = 'semver_le';\nconst SEMVER_LESS_THAN_MATCH_TYPE = 'semver_lt';\nconst SUBSTRING_MATCH_TYPE = 'substring';\nconst MATCH_TYPES = [\n    EXACT_MATCH_TYPE,\n    EXISTS_MATCH_TYPE,\n    GREATER_THAN_MATCH_TYPE,\n    GREATER_OR_EQUAL_THAN_MATCH_TYPE,\n    LESS_THAN_MATCH_TYPE,\n    LESS_OR_EQUAL_THAN_MATCH_TYPE,\n    SUBSTRING_MATCH_TYPE,\n    SEMVER_EXACT_MATCH_TYPE,\n    SEMVER_LESS_THAN_MATCH_TYPE,\n    SEMVER_LESS_OR_EQUAL_THAN_MATCH_TYPE,\n    SEMVER_GREATER_THAN_MATCH_TYPE,\n    SEMVER_GREATER_OR_EQUAL_THAN_MATCH_TYPE\n];\nconst EVALUATORS_BY_MATCH_TYPE = {};\nEVALUATORS_BY_MATCH_TYPE[EXACT_MATCH_TYPE] = exactEvaluator;\nEVALUATORS_BY_MATCH_TYPE[EXISTS_MATCH_TYPE] = existsEvaluator;\nEVALUATORS_BY_MATCH_TYPE[GREATER_THAN_MATCH_TYPE] = greaterThanEvaluator;\nEVALUATORS_BY_MATCH_TYPE[GREATER_OR_EQUAL_THAN_MATCH_TYPE] = greaterThanOrEqualEvaluator;\nEVALUATORS_BY_MATCH_TYPE[LESS_THAN_MATCH_TYPE] = lessThanEvaluator;\nEVALUATORS_BY_MATCH_TYPE[LESS_OR_EQUAL_THAN_MATCH_TYPE] = lessThanOrEqualEvaluator;\nEVALUATORS_BY_MATCH_TYPE[SUBSTRING_MATCH_TYPE] = substringEvaluator;\nEVALUATORS_BY_MATCH_TYPE[SEMVER_EXACT_MATCH_TYPE] = semverEqualEvaluator;\nEVALUATORS_BY_MATCH_TYPE[SEMVER_GREATER_THAN_MATCH_TYPE] = semverGreaterThanEvaluator;\nEVALUATORS_BY_MATCH_TYPE[SEMVER_GREATER_OR_EQUAL_THAN_MATCH_TYPE] = semverGreaterThanOrEqualEvaluator;\nEVALUATORS_BY_MATCH_TYPE[SEMVER_LESS_THAN_MATCH_TYPE] = semverLessThanEvaluator;\nEVALUATORS_BY_MATCH_TYPE[SEMVER_LESS_OR_EQUAL_THAN_MATCH_TYPE] = semverLessThanOrEqualEvaluator;\nexport const getEvaluator = (logger) => {\n    return {\n        evaluate(condition, user) {\n            return evaluate(condition, user, logger);\n        }\n    };\n};\n/**\n * Given a custom attribute audience condition and user attributes, evaluate the\n * condition against the attributes.\n * @param  {Condition}              condition\n * @param  {OptimizelyUserContext}  user\n * @return {?boolean}               true/false if the given user attributes match/don't match the given condition,\n *                                  null if the given user attributes and condition can't be evaluated\n * TODO: Change to accept and object with named properties\n */\nfunction evaluate(condition, user, logger) {\n    const userAttributes = user.getAttributes();\n    const conditionMatch = condition.match;\n    if (typeof conditionMatch !== 'undefined' && MATCH_TYPES.indexOf(conditionMatch) === -1) {\n        logger === null || logger === void 0 ? void 0 : logger.warn(UNKNOWN_MATCH_TYPE, JSON.stringify(condition));\n        return null;\n    }\n    const attributeKey = condition.name;\n    if (!userAttributes.hasOwnProperty(attributeKey) && conditionMatch != EXISTS_MATCH_TYPE) {\n        logger === null || logger === void 0 ? void 0 : logger.debug(MISSING_ATTRIBUTE_VALUE, JSON.stringify(condition), attributeKey);\n        return null;\n    }\n    let evaluatorForMatch;\n    if (!conditionMatch) {\n        evaluatorForMatch = exactEvaluator;\n    }\n    else {\n        evaluatorForMatch = EVALUATORS_BY_MATCH_TYPE[conditionMatch] || exactEvaluator;\n    }\n    return evaluatorForMatch(condition, user, logger);\n}\n/**\n * Returns true if the value is valid for exact conditions. Valid values include\n * strings, booleans, and numbers that aren't NaN, -Infinity, or Infinity.\n * @param value\n * @returns {boolean}\n */\nfunction isValueTypeValidForExactConditions(value) {\n    return typeof value === 'string' || typeof value === 'boolean' || fns.isNumber(value);\n}\n/**\n * Evaluate the given exact match condition for the given user attributes\n * @param  {Condition}              condition\n * @param  {OptimizelyUserContext}  user\n * @return  {?boolean}              true if the user attribute value is equal (===) to the condition value,\n *                                  false if the user attribute value is not equal (!==) to the condition value,\n *                                  null if the condition value or user attribute value has an invalid type, or\n *                                  if there is a mismatch between the user attribute type and the condition value\n *                                  type\n */\nfunction exactEvaluator(condition, user, logger) {\n    const userAttributes = user.getAttributes();\n    const conditionValue = condition.value;\n    const conditionValueType = typeof conditionValue;\n    const conditionName = condition.name;\n    const userValue = userAttributes[conditionName];\n    const userValueType = typeof userValue;\n    if (!isValueTypeValidForExactConditions(conditionValue) ||\n        (fns.isNumber(conditionValue) && !fns.isSafeInteger(conditionValue))) {\n        logger === null || logger === void 0 ? void 0 : logger.warn(UNEXPECTED_CONDITION_VALUE, JSON.stringify(condition));\n        return null;\n    }\n    if (userValue === null) {\n        logger === null || logger === void 0 ? void 0 : logger.debug(UNEXPECTED_TYPE_NULL, JSON.stringify(condition), conditionName);\n        return null;\n    }\n    if (!isValueTypeValidForExactConditions(userValue) || conditionValueType !== userValueType) {\n        logger === null || logger === void 0 ? void 0 : logger.warn(UNEXPECTED_TYPE, JSON.stringify(condition), userValueType, conditionName);\n        return null;\n    }\n    if (fns.isNumber(userValue) && !fns.isSafeInteger(userValue)) {\n        logger === null || logger === void 0 ? void 0 : logger.warn(OUT_OF_BOUNDS, JSON.stringify(condition), conditionName);\n        return null;\n    }\n    return conditionValue === userValue;\n}\n/**\n * Evaluate the given exists match condition for the given user attributes\n * @param  {Condition}              condition\n * @param  {OptimizelyUserContext}  user\n * @returns {boolean}               true if both:\n *                                    1) the user attributes have a value for the given condition, and\n *                                    2) the user attribute value is neither null nor undefined\n *                                  Returns false otherwise\n */\nfunction existsEvaluator(condition, user, logger) {\n    const userAttributes = user.getAttributes();\n    const userValue = userAttributes[condition.name];\n    return typeof userValue !== 'undefined' && userValue !== null;\n}\n/**\n * Validate user and condition values\n * @param  {Condition}              condition\n * @param  {OptimizelyUserContext}  user\n * @returns {?boolean}              true if values are valid,\n *                                  false if values are not valid\n */\nfunction validateValuesForNumericCondition(condition, user, logger) {\n    const userAttributes = user.getAttributes();\n    const conditionName = condition.name;\n    const userValue = userAttributes[conditionName];\n    const userValueType = typeof userValue;\n    const conditionValue = condition.value;\n    if (conditionValue === null || !fns.isSafeInteger(conditionValue)) {\n        logger === null || logger === void 0 ? void 0 : logger.warn(UNEXPECTED_CONDITION_VALUE, JSON.stringify(condition));\n        return false;\n    }\n    if (userValue === null) {\n        logger === null || logger === void 0 ? void 0 : logger.debug(UNEXPECTED_TYPE_NULL, JSON.stringify(condition), conditionName);\n        return false;\n    }\n    if (!fns.isNumber(userValue)) {\n        logger === null || logger === void 0 ? void 0 : logger.warn(UNEXPECTED_TYPE, JSON.stringify(condition), userValueType, conditionName);\n        return false;\n    }\n    if (!fns.isSafeInteger(userValue)) {\n        logger === null || logger === void 0 ? void 0 : logger.warn(OUT_OF_BOUNDS, JSON.stringify(condition), conditionName);\n        return false;\n    }\n    return true;\n}\n/**\n * Evaluate the given greater than match condition for the given user attributes\n * @param  {Condition}              condition\n * @param  {OptimizelyUserContext}  user\n * @returns {?boolean}              true if the user attribute value is greater than the condition value,\n *                                  false if the user attribute value is less than or equal to the condition value,\n *                                  null if the condition value isn't a number or the user attribute value\n *                                  isn't a number\n */\nfunction greaterThanEvaluator(condition, user, logger) {\n    const userAttributes = user.getAttributes();\n    const userValue = userAttributes[condition.name];\n    const conditionValue = condition.value;\n    if (!validateValuesForNumericCondition(condition, user, logger) || conditionValue === null) {\n        return null;\n    }\n    return userValue > conditionValue;\n}\n/**\n * Evaluate the given greater or equal than match condition for the given user attributes\n * @param  {Condition}              condition\n * @param  {OptimizelyUserContext}  user\n * @returns {?Boolean}              true if the user attribute value is greater or equal than the condition value,\n *                                  false if the user attribute value is less than to the condition value,\n *                                  null if the condition value isn't a number or the user attribute value isn't a\n *                                  number\n */\nfunction greaterThanOrEqualEvaluator(condition, user, logger) {\n    const userAttributes = user.getAttributes();\n    const userValue = userAttributes[condition.name];\n    const conditionValue = condition.value;\n    if (!validateValuesForNumericCondition(condition, user, logger) || conditionValue === null) {\n        return null;\n    }\n    return userValue >= conditionValue;\n}\n/**\n * Evaluate the given less than match condition for the given user attributes\n * @param  {Condition}              condition\n * @param  {OptimizelyUserContext}  user\n * @returns {?boolean}              true if the user attribute value is less than the condition value,\n *                                  false if the user attribute value is greater than or equal to the condition value,\n *                                  null if the condition value isn't a number or the user attribute value isn't a\n *                                  number\n */\nfunction lessThanEvaluator(condition, user, logger) {\n    const userAttributes = user.getAttributes();\n    const userValue = userAttributes[condition.name];\n    const conditionValue = condition.value;\n    if (!validateValuesForNumericCondition(condition, user, logger) || conditionValue === null) {\n        return null;\n    }\n    return userValue < conditionValue;\n}\n/**\n * Evaluate the given less or equal than match condition for the given user attributes\n * @param  {Condition}              condition\n * @param  {OptimizelyUserContext}  user\n * @returns {?Boolean}              true if the user attribute value is less or equal than the condition value,\n *                                  false if the user attribute value is greater than to the condition value,\n *                                  null if the condition value isn't a number or the user attribute value isn't a\n *                                  number\n */\nfunction lessThanOrEqualEvaluator(condition, user, logger) {\n    const userAttributes = user.getAttributes();\n    const userValue = userAttributes[condition.name];\n    const conditionValue = condition.value;\n    if (!validateValuesForNumericCondition(condition, user, logger) || conditionValue === null) {\n        return null;\n    }\n    return userValue <= conditionValue;\n}\n/**\n * Evaluate the given substring match condition for the given user attributes\n * @param  {Condition}              condition\n * @param  {OptimizelyUserContext}  user\n * @returns {?Boolean}              true if the condition value is a substring of the user attribute value,\n *                                  false if the condition value is not a substring of the user attribute value,\n *                                  null if the condition value isn't a string or the user attribute value\n *                                  isn't a string\n */\nfunction substringEvaluator(condition, user, logger) {\n    const userAttributes = user.getAttributes();\n    const conditionName = condition.name;\n    const userValue = userAttributes[condition.name];\n    const userValueType = typeof userValue;\n    const conditionValue = condition.value;\n    if (typeof conditionValue !== 'string') {\n        logger === null || logger === void 0 ? void 0 : logger.warn(UNEXPECTED_CONDITION_VALUE, JSON.stringify(condition));\n        return null;\n    }\n    if (userValue === null) {\n        logger === null || logger === void 0 ? void 0 : logger.debug(UNEXPECTED_TYPE_NULL, JSON.stringify(condition), conditionName);\n        return null;\n    }\n    if (typeof userValue !== 'string') {\n        logger === null || logger === void 0 ? void 0 : logger.warn(UNEXPECTED_TYPE, JSON.stringify(condition), userValueType, conditionName);\n        return null;\n    }\n    return userValue.indexOf(conditionValue) !== -1;\n}\n/**\n * Evaluate the given semantic version match condition for the given user attributes\n * @param  {Condition}              condition\n * @param  {OptimizelyUserContext}  user\n * @returns {?number}               returns compareVersion result\n *                                  null if the user attribute version has an invalid type\n */\nfunction evaluateSemanticVersion(condition, user, logger) {\n    const userAttributes = user.getAttributes();\n    const conditionName = condition.name;\n    const userValue = userAttributes[conditionName];\n    const userValueType = typeof userValue;\n    const conditionValue = condition.value;\n    if (typeof conditionValue !== 'string') {\n        logger === null || logger === void 0 ? void 0 : logger.warn(UNEXPECTED_CONDITION_VALUE, JSON.stringify(condition));\n        return null;\n    }\n    if (userValue === null) {\n        logger === null || logger === void 0 ? void 0 : logger.debug(UNEXPECTED_TYPE_NULL, JSON.stringify(condition), conditionName);\n        return null;\n    }\n    if (typeof userValue !== 'string') {\n        logger === null || logger === void 0 ? void 0 : logger.warn(UNEXPECTED_TYPE, JSON.stringify(condition), userValueType, conditionName);\n        return null;\n    }\n    return compareVersion(conditionValue, userValue, logger);\n}\n/**\n * Evaluate the given version match condition for the given user attributes\n * @param  {Condition}              condition\n * @param  {OptimizelyUserContext}  user\n * @returns {?Boolean}              true if the user attribute version is equal (===) to the condition version,\n *                                  false if the user attribute version is not equal (!==) to the condition version,\n *                                  null if the user attribute version has an invalid type\n */\nfunction semverEqualEvaluator(condition, user, logger) {\n    const result = evaluateSemanticVersion(condition, user, logger);\n    if (result === null) {\n        return null;\n    }\n    return result === 0;\n}\n/**\n * Evaluate the given version match condition for the given user attributes\n * @param  {Condition}              condition\n * @param  {OptimizelyUserContext}  user\n * @returns {?Boolean}              true if the user attribute version is greater (>) than the condition version,\n *                                  false if the user attribute version is not greater than the condition version,\n *                                  null if the user attribute version has an invalid type\n */\nfunction semverGreaterThanEvaluator(condition, user, logger) {\n    const result = evaluateSemanticVersion(condition, user, logger);\n    if (result === null) {\n        return null;\n    }\n    return result > 0;\n}\n/**\n * Evaluate the given version match condition for the given user attributes\n * @param  {Condition}              condition\n * @param  {OptimizelyUserContext}  user\n * @returns {?Boolean}              true if the user attribute version is less (<) than the condition version,\n *                                  false if the user attribute version is not less than the condition version,\n *                                  null if the user attribute version has an invalid type\n */\nfunction semverLessThanEvaluator(condition, user, logger) {\n    const result = evaluateSemanticVersion(condition, user, logger);\n    if (result === null) {\n        return null;\n    }\n    return result < 0;\n}\n/**\n * Evaluate the given version match condition for the given user attributes\n * @param  {Condition}              condition\n * @param  {OptimizelyUserContext}  user\n * @returns {?Boolean}              true if the user attribute version is greater than or equal (>=) to the condition version,\n *                                  false if the user attribute version is not greater than or equal to the condition version,\n *                                  null if the user attribute version has an invalid type\n */\nfunction semverGreaterThanOrEqualEvaluator(condition, user, logger) {\n    const result = evaluateSemanticVersion(condition, user, logger);\n    if (result === null) {\n        return null;\n    }\n    return result >= 0;\n}\n/**\n * Evaluate the given version match condition for the given user attributes\n * @param  {Condition}              condition\n * @param  {OptimizelyUserContext}  user\n * @returns {?Boolean}              true if the user attribute version is less than or equal (<=) to the condition version,\n *                                  false if the user attribute version is not less than or equal to the condition version,\n *                                  null if the user attribute version has an invalid type\n */\nfunction semverLessThanOrEqualEvaluator(condition, user, logger) {\n    const result = evaluateSemanticVersion(condition, user, logger);\n    if (result === null) {\n        return null;\n    }\n    return result <= 0;\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","/****************************************************************************\n * Copyright 2022 Optimizely, Inc. and contributors              *\n *                                                                          *\n * Licensed under the Apache License, Version 2.0 (the \"License\");          *\n * you may not use this file except in compliance with the License.         *\n * You may obtain a copy of the License at                                  *\n *                                                                          *\n *    http://www.apache.org/licenses/LICENSE-2.0                            *\n *                                                                          *\n * Unless required by applicable law or agreed to in writing, software      *\n * distributed under the License is distributed on an \"AS IS\" BASIS,        *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and      *\n * limitations under the License.                                           *\n ***************************************************************************/\nimport { UNKNOWN_MATCH_TYPE } from 'error_message';\nconst QUALIFIED_MATCH_TYPE = 'qualified';\nconst MATCH_TYPES = [\n    QUALIFIED_MATCH_TYPE,\n];\nconst EVALUATORS_BY_MATCH_TYPE = {};\nEVALUATORS_BY_MATCH_TYPE[QUALIFIED_MATCH_TYPE] = qualifiedEvaluator;\nexport const getEvaluator = (logger) => {\n    return {\n        evaluate(condition, user) {\n            return evaluate(condition, user, logger);\n        }\n    };\n};\n/**\n * Given a custom attribute audience condition and user attributes, evaluate the\n * condition against the attributes.\n * @param  {Condition}        condition\n * @param  {OptimizelyUserContext} user\n * @return {?boolean}         true/false if the given user attributes match/don't match the given condition,\n *                            null if the given user attributes and condition can't be evaluated\n * TODO: Change to accept and object with named properties\n */\nfunction evaluate(condition, user, logger) {\n    const conditionMatch = condition.match;\n    if (typeof conditionMatch !== 'undefined' && MATCH_TYPES.indexOf(conditionMatch) === -1) {\n        logger === null || logger === void 0 ? void 0 : logger.warn(UNKNOWN_MATCH_TYPE, JSON.stringify(condition));\n        return null;\n    }\n    let evaluator;\n    if (!conditionMatch) {\n        evaluator = qualifiedEvaluator;\n    }\n    else {\n        evaluator = EVALUATORS_BY_MATCH_TYPE[conditionMatch] || qualifiedEvaluator;\n    }\n    return evaluator(condition, user);\n}\nfunction qualifiedEvaluator(condition, user) {\n    return user.isQualifiedFor(condition.value);\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","/**\n * Copyright 2016, 2018-2022, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport * as conditionTreeEvaluator from '../condition_tree_evaluator';\nimport * as customAttributeConditionEvaluator from '../custom_attribute_condition_evaluator';\nimport * as odpSegmentsConditionEvaluator from './odp_segment_condition_evaluator';\nimport { CONDITION_EVALUATOR_ERROR, UNKNOWN_CONDITION_TYPE } from 'error_message';\nimport { AUDIENCE_EVALUATION_RESULT, EVALUATING_AUDIENCE } from 'log_message';\nexport class AudienceEvaluator {\n    /**\n     * Construct an instance of AudienceEvaluator with given options\n     * @param {Object=} UNSTABLE_conditionEvaluators     A map of condition evaluators provided by the consumer. This enables matching\n     *                                                   condition types which are not supported natively by the SDK. Note that built in\n     *                                                   Optimizely evaluators cannot be overridden.\n     * @constructor\n     */\n    constructor(UNSTABLE_conditionEvaluators, logger) {\n        this.logger = logger;\n        this.typeToEvaluatorMap = Object.assign(Object.assign({}, UNSTABLE_conditionEvaluators), { custom_attribute: customAttributeConditionEvaluator.getEvaluator(this.logger), third_party_dimension: odpSegmentsConditionEvaluator.getEvaluator(this.logger) });\n    }\n    /**\n     * Determine if the given user attributes satisfy the given audience conditions\n     * @param  {Array<string|string[]}        audienceConditions    Audience conditions to match the user attributes against - can be an array\n     *                                                              of audience IDs, a nested array of conditions, or a single leaf condition.\n     *                                                              Examples: [\"5\", \"6\"], [\"and\", [\"or\", \"1\", \"2\"], \"3\"], \"1\"\n     * @param  {[id: string]: Audience}       audiencesById         Object providing access to full audience objects for audience IDs\n     *                                                              contained in audienceConditions. Keys should be audience IDs, values\n     *                                                              should be full audience objects with conditions properties\n     * @param  {OptimizelyUserContext}        userAttributes        User context which contains the attributes and segments which will be used in\n     *                                                              determining if audience conditions are met.\n     * @return {boolean}                                            true if the user attributes match the given audience conditions, false\n     *                                                              otherwise\n     */\n    evaluate(audienceConditions, audiencesById, user) {\n        // if there are no audiences, return true because that means ALL users are included in the experiment\n        if (!audienceConditions || audienceConditions.length === 0) {\n            return true;\n        }\n        const evaluateAudience = (audienceId) => {\n            var _a, _b;\n            const audience = audiencesById[audienceId];\n            if (audience) {\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(EVALUATING_AUDIENCE, audienceId, JSON.stringify(audience.conditions));\n                const result = conditionTreeEvaluator.evaluate(audience.conditions, this.evaluateConditionWithUserAttributes.bind(this, user));\n                const resultText = result === null ? 'UNKNOWN' : result.toString().toUpperCase();\n                (_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug(AUDIENCE_EVALUATION_RESULT, audienceId, resultText);\n                return result;\n            }\n            return null;\n        };\n        return !!conditionTreeEvaluator.evaluate(audienceConditions, evaluateAudience);\n    }\n    /**\n     * Wrapper around evaluator.evaluate that is passed to the conditionTreeEvaluator.\n     * Evaluates the condition provided given the user attributes if an evaluator has been defined for the condition type.\n     * @param  {OptimizelyUserContext}  user             Optimizely user context containing attributes and segments\n     * @param  {Condition}              condition        A single condition object to evaluate.\n     * @return {boolean|null}                            true if the condition is satisfied, null if a matcher is not found.\n     */\n    evaluateConditionWithUserAttributes(user, condition) {\n        var _a, _b;\n        const evaluator = this.typeToEvaluatorMap[condition.type];\n        if (!evaluator) {\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.warn(UNKNOWN_CONDITION_TYPE, JSON.stringify(condition));\n            return null;\n        }\n        try {\n            return evaluator.evaluate(condition, user);\n        }\n        catch (err) {\n            (_b = this.logger) === null || _b === void 0 ? void 0 : _b.error(CONDITION_EVALUATOR_ERROR, condition.type, err.message);\n        }\n        return null;\n    }\n}\nexport default AudienceEvaluator;\nexport const createAudienceEvaluator = function (UNSTABLE_conditionEvaluators, logger) {\n    return new AudienceEvaluator(UNSTABLE_conditionEvaluators, logger);\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","/**\n * Copyright 2018, 2020, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function validate(input) {\n    return typeof input === 'string' && input !== '';\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","import { PROMISE_NOT_ALLOWED } from '../../message/error_message';\nimport { OptimizelyError } from '../../error/optimizly_error';\nconst isPromise = (val) => {\n    return val && typeof val.then === 'function';\n};\n/**\n * A class that wraps a value that can be either a synchronous value or a promise and provides\n * a promise like interface. This class is used to handle both synchronous and asynchronous values\n * in a uniform way.\n */\nexport class Value {\n    constructor(op, val) {\n        this.op = op;\n        this.val = val;\n    }\n    get() {\n        return this.val;\n    }\n    then(fn) {\n        if (this.op === 'sync') {\n            const newVal = fn(this.val);\n            return Value.of(this.op, newVal.get());\n        }\n        return Value.of(this.op, this.val.then(fn));\n    }\n    static of(op, val) {\n        if (op === 'sync') {\n            if (isPromise(val)) {\n                throw new OptimizelyError(PROMISE_NOT_ALLOWED);\n            }\n            return new Value(op, val);\n        }\n        return new Value(op, Promise.resolve(val));\n    }\n}\nValue.all = (op, vals) => {\n    if (op === 'sync') {\n        const values = vals.map(v => v.get());\n        return Value.of(op, values);\n    }\n    const promises = vals.map(v => v.get());\n    return Value.of(op, Promise.all(promises));\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=operation_value.js.map","/**\n * Copyright 2024-2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport const NOTIFICATION_LISTENER_EXCEPTION = 'Notification listener for (%s) threw exception: %s';\nexport const CONDITION_EVALUATOR_ERROR = 'Error evaluating audience condition of type %s: %s';\nexport const EXPERIMENT_KEY_NOT_IN_DATAFILE = 'Experiment key %s is not in datafile.';\nexport const FEATURE_NOT_IN_DATAFILE = 'Feature key %s is not in datafile.';\nexport const INVALID_ATTRIBUTES = 'Provided attributes are in an invalid format.';\nexport const INVALID_BUCKETING_ID = 'Unable to generate hash for bucketing ID %s: %s';\nexport const INVALID_DATAFILE = 'Datafile is invalid - property %s: %s';\nexport const INVALID_DATAFILE_MALFORMED = 'Datafile is invalid because it is malformed.';\nexport const INVALID_CONFIG = 'Provided Optimizely config is in an invalid format.';\nexport const INVALID_JSON = 'JSON object is not valid.';\nexport const INVALID_EVENT_TAGS = 'Provided event tags are in an invalid format.';\nexport const INVALID_EXPERIMENT_KEY = 'Experiment key %s is not in datafile. It is either invalid, paused, or archived.';\nexport const INVALID_EXPERIMENT_ID = 'Experiment ID %s is not in datafile.';\nexport const INVALID_GROUP_ID = 'Group ID %s is not in datafile.';\nexport const INVALID_USER_ID = 'Provided user ID is in an invalid format.';\nexport const INVALID_USER_PROFILE_SERVICE = 'Provided user profile service instance is in an invalid format: %s.';\nexport const MISSING_INTEGRATION_KEY = 'Integration key missing from datafile. All integrations should include a key.';\nexport const NO_DATAFILE_SPECIFIED = 'No datafile specified. Cannot start optimizely.';\nexport const NO_JSON_PROVIDED = 'No JSON object to validate against schema.';\nexport const NO_EVENT_PROCESSOR = 'No event processor is provided';\nexport const NO_VARIATION_FOR_EXPERIMENT_KEY = 'No variation key %s defined in datafile for experiment %s.';\nexport const ODP_CONFIG_NOT_AVAILABLE = 'ODP config is not available.';\nexport const ODP_EVENT_FAILED = 'ODP event send failed.';\nexport const ODP_EVENTS_SHOULD_HAVE_ATLEAST_ONE_KEY_VALUE = 'ODP events should have at least one key-value pair in identifiers.';\nexport const ODP_MANAGER_MISSING = 'ODP Manager is missing. %s failed.';\nexport const ODP_NOT_INTEGRATED = 'ODP is not integrated';\nexport const UNDEFINED_ATTRIBUTE = 'Provided attribute: %s has an undefined value.';\nexport const UNRECOGNIZED_ATTRIBUTE = 'Unrecognized attribute %s provided. Pruning before sending event to Optimizely.';\nexport const UNABLE_TO_CAST_VALUE = 'Unable to cast value %s to type %s, returning null.';\nexport const USER_NOT_IN_FORCED_VARIATION = 'User %s is not in the forced variation map. Cannot remove their forced variation.';\nexport const USER_PROFILE_LOOKUP_ERROR = 'Error while looking up user profile for user ID \"%s\": %s.';\nexport const USER_PROFILE_SAVE_ERROR = 'Error while saving user profile for user ID \"%s\": %s.';\nexport const VARIABLE_KEY_NOT_IN_DATAFILE = 'Variable with key \"%s\" associated with feature with key \"%s\" is not in datafile.';\nexport const VARIATION_ID_NOT_IN_DATAFILE = 'Variation ID %s is not in the datafile.';\nexport const INVALID_INPUT_FORMAT = 'Provided %s is in an invalid format.';\nexport const INVALID_DATAFILE_VERSION = 'This version of the JavaScript SDK does not support the given datafile version: %s';\nexport const INVALID_VARIATION_KEY = 'Provided variation key is in an invalid format.';\nexport const ERROR_FETCHING_DATAFILE = 'Error fetching datafile: %s';\nexport const DATAFILE_FETCH_REQUEST_FAILED = 'Datafile fetch request failed with status: %s';\nexport const EVENT_DATA_INVALID = 'Event data invalid.';\nexport const EVENT_ACTION_INVALID = 'Event action invalid.';\nexport const FAILED_TO_SEND_ODP_EVENTS = 'failed to send odp events';\nexport const UNABLE_TO_GET_VUID_VUID_MANAGER_NOT_AVAILABLE = 'Unable to get VUID - VuidManager is not available';\nexport const UNKNOWN_CONDITION_TYPE = 'Audience condition %s has an unknown condition type. You may need to upgrade to a newer release of the Optimizely SDK.';\nexport const UNKNOWN_MATCH_TYPE = 'Audience condition %s uses an unknown match type. You may need to upgrade to a newer release of the Optimizely SDK.';\nexport const UNRECOGNIZED_DECIDE_OPTION = 'Unrecognized decide option %s provided.';\nexport const NO_PROJECT_CONFIG_FAILURE = 'No project config available. Failing %s.';\nexport const EVENT_KEY_NOT_FOUND = 'Event key %s is not in datafile.';\nexport const NOT_TRACKING_USER = 'Not tracking user %s.';\nexport const VARIABLE_REQUESTED_WITH_WRONG_TYPE = 'Requested variable type \"%s\", but variable is of type \"%s\". Use correct API to retrieve value. Returning None.';\nexport const UNEXPECTED_RESERVED_ATTRIBUTE_PREFIX = 'Attribute %s unexpectedly has reserved prefix %s; using attribute ID instead of reserved attribute name.';\nexport const BUCKETING_ID_NOT_STRING = 'BucketingID attribute is not a string. Defaulted to userId';\nexport const UNEXPECTED_CONDITION_VALUE = 'Audience condition %s evaluated to UNKNOWN because the condition value is not supported.';\nexport const UNEXPECTED_TYPE = 'Audience condition %s evaluated to UNKNOWN because a value of type \"%s\" was passed for user attribute \"%s\".';\nexport const OUT_OF_BOUNDS = 'Audience condition %s evaluated to UNKNOWN because the number value for user attribute \"%s\" is not in the range [-2^53, +2^53].';\nexport const REQUEST_TIMEOUT = 'Request timeout';\nexport const REQUEST_ERROR = 'Request error';\nexport const NO_STATUS_CODE_IN_RESPONSE = 'No status code in response';\nexport const UNSUPPORTED_PROTOCOL = 'Unsupported protocol: %s';\nexport const RETRY_CANCELLED = 'Retry cancelled';\nexport const ONLY_POST_REQUESTS_ARE_SUPPORTED = 'Only POST requests are supported';\nexport const SEND_BEACON_FAILED = 'sendBeacon failed';\nexport const FAILED_TO_DISPATCH_EVENTS = 'Failed to dispatch events, status: %s';\nexport const ODP_EVENT_MANAGER_STOPPED = \"ODP event manager stopped before it could start\";\nexport const UNABLE_TO_ATTACH_UNLOAD = 'unable to bind optimizely.close() to page unload event: \"%s\"';\nexport const UNABLE_TO_PARSE_AND_SKIPPED_HEADER = 'Unable to parse & skipped header item';\nexport const CMAB_FETCH_FAILED = 'CMAB decision fetch failed with status: %s';\nexport const INVALID_CMAB_FETCH_RESPONSE = 'Invalid CMAB fetch response';\nexport const PROMISE_NOT_ALLOWED = \"Promise value is not allowed in sync operation\";\nexport const SERVICE_NOT_RUNNING = \"%s not running\";\nexport const EVENT_STORE_FULL = 'Event store is full. Not saving event with id %d.';\nexport const messages = [];\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=error_message.js.map","import { bucket } from '../bucketer/index';\nimport { AUDIENCE_EVALUATION_TYPES, CONTROL_ATTRIBUTES, DECISION_SOURCES, } from '../../utils/enums';\nimport { getAudiencesById, getExperimentFromId, getExperimentFromKey, getFlagVariationByKey, getVariationIdFromExperimentAndVariationKey, getVariationFromId, getVariationKeyFromId, isActive, getHoldoutsForFlag, } from '../../project_config/project_config';\nimport { createAudienceEvaluator } from '../audience_evaluator';\nimport * as stringValidator from '../../utils/string_value_validator';\nimport { OptimizelyDecideOption, } from '../../shared_types';\nimport { INVALID_USER_ID, INVALID_VARIATION_KEY, NO_VARIATION_FOR_EXPERIMENT_KEY, USER_NOT_IN_FORCED_VARIATION, USER_PROFILE_LOOKUP_ERROR, USER_PROFILE_SAVE_ERROR, BUCKETING_ID_NOT_STRING, } from 'error_message';\nimport { SAVED_USER_VARIATION, SAVED_VARIATION_NOT_FOUND, USER_HAS_NO_FORCED_VARIATION, USER_MAPPED_TO_FORCED_VARIATION, USER_HAS_NO_FORCED_VARIATION_FOR_EXPERIMENT, VALID_BUCKETING_ID, VARIATION_REMOVED_FOR_USER, } from 'log_message';\nimport { OptimizelyError } from '../../error/optimizly_error';\nimport { Value } from '../../utils/promise/operation_value';\nexport const EXPERIMENT_NOT_RUNNING = 'Experiment %s is not running.';\nexport const RETURNING_STORED_VARIATION = 'Returning previously activated variation \"%s\" of experiment \"%s\" for user \"%s\" from user profile.';\nexport const USER_NOT_IN_EXPERIMENT = 'User %s does not meet conditions to be in experiment %s.';\nexport const USER_HAS_NO_VARIATION = 'User %s is in no variation of experiment %s.';\nexport const USER_HAS_VARIATION = 'User %s is in variation %s of experiment %s.';\nexport const USER_FORCED_IN_VARIATION = 'User %s is forced in variation %s.';\nexport const FORCED_BUCKETING_FAILED = 'Variation key %s is not in datafile. Not activating user %s.';\nexport const EVALUATING_AUDIENCES_COMBINED = 'Evaluating audiences for %s \"%s\": %s.';\nexport const AUDIENCE_EVALUATION_RESULT_COMBINED = 'Audiences for %s %s collectively evaluated to %s.';\nexport const USER_IN_ROLLOUT = 'User %s is in rollout of feature %s.';\nexport const USER_NOT_IN_ROLLOUT = 'User %s is not in rollout of feature %s.';\nexport const FEATURE_HAS_NO_EXPERIMENTS = 'Feature %s is not attached to any experiments.';\nexport const USER_DOESNT_MEET_CONDITIONS_FOR_TARGETING_RULE = 'User %s does not meet conditions for targeting rule %s.';\nexport const USER_NOT_BUCKETED_INTO_TARGETING_RULE = 'User %s not bucketed into targeting rule %s due to traffic allocation. Trying everyone rule.';\nexport const USER_BUCKETED_INTO_TARGETING_RULE = 'User %s bucketed into targeting rule %s.';\nexport const NO_ROLLOUT_EXISTS = 'There is no rollout of feature %s.';\nexport const INVALID_ROLLOUT_ID = 'Invalid rollout ID %s attached to feature %s';\nexport const ROLLOUT_HAS_NO_EXPERIMENTS = 'Rollout of feature %s has no experiments';\nexport const IMPROPERLY_FORMATTED_EXPERIMENT = 'Experiment key %s is improperly formatted.';\nexport const USER_HAS_FORCED_VARIATION = 'Variation %s is mapped to experiment %s and user %s in the forced variation map.';\nexport const USER_MEETS_CONDITIONS_FOR_TARGETING_RULE = 'User %s meets conditions for targeting rule %s.';\nexport const USER_HAS_FORCED_DECISION_WITH_RULE_SPECIFIED = 'Variation (%s) is mapped to flag (%s), rule (%s) and user (%s) in the forced decision map.';\nexport const USER_HAS_FORCED_DECISION_WITH_NO_RULE_SPECIFIED = 'Variation (%s) is mapped to flag (%s) and user (%s) in the forced decision map.';\nexport const USER_HAS_FORCED_DECISION_WITH_RULE_SPECIFIED_BUT_INVALID = 'Invalid variation is mapped to flag (%s), rule (%s) and user (%s) in the forced decision map.';\nexport const USER_HAS_FORCED_DECISION_WITH_NO_RULE_SPECIFIED_BUT_INVALID = 'Invalid variation is mapped to flag (%s) and user (%s) in the forced decision map.';\nexport const CMAB_NOT_SUPPORTED_IN_SYNC = 'CMAB is not supported in sync mode.';\nexport const CMAB_FETCH_FAILED = 'Failed to fetch CMAB data for experiment %s.';\nexport const CMAB_FETCHED_VARIATION_INVALID = 'Fetched variation %s for cmab experiment %s is invalid.';\nexport const HOLDOUT_NOT_RUNNING = 'Holdout %s is not running.';\nexport const USER_MEETS_CONDITIONS_FOR_HOLDOUT = 'User %s meets conditions for holdout %s.';\nexport const USER_DOESNT_MEET_CONDITIONS_FOR_HOLDOUT = 'User %s does not meet conditions for holdout %s.';\nexport const USER_BUCKETED_INTO_HOLDOUT_VARIATION = 'User %s is in variation %s of holdout %s.';\nexport const USER_NOT_BUCKETED_INTO_HOLDOUT_VARIATION = 'User %s is in no holdout variation.';\nexport const CMAB_DUMMY_ENTITY_ID = '$';\nexport const LOGGER_NAME = 'DecisionService';\n/**\n * Optimizely's decision service that determines which variation of an experiment the user will be allocated to.\n *\n * The decision service contains all logic around how a user decision is made. This includes all of the following (in order):\n *   1. Checking experiment status\n *   2. Checking forced bucketing\n *   3. Checking whitelisting\n *   4. Checking user profile service for past bucketing decisions (sticky bucketing)\n *   5. Checking audience targeting\n *   6. Using Murmurhash3 to bucket the user.\n *\n * @constructor\n * @param   {DecisionServiceOptions}      options\n * @returns {DecisionService}\n */\nexport class DecisionService {\n    constructor(options) {\n        var _a;\n        this.logger = options.logger;\n        (_a = this.logger) === null || _a === void 0 ? void 0 : _a.setName(LOGGER_NAME);\n        this.audienceEvaluator = createAudienceEvaluator(options.UNSTABLE_conditionEvaluators, this.logger);\n        this.forcedVariationMap = {};\n        this.userProfileService = options.userProfileService;\n        this.userProfileServiceAsync = options.userProfileServiceAsync;\n        this.cmabService = options.cmabService;\n    }\n    isCmab(experiment) {\n        return !!experiment.cmab;\n    }\n    /**\n     * Resolves the variation into which the visitor will be bucketed.\n     *\n     * @param {ProjectConfig} configObj - The parsed project configuration object.\n     * @param {Experiment} experiment - The experiment for which the variation is being resolved.\n     * @param {OptimizelyUserContext} user - The user context associated with this decision.\n     * @returns {DecisionResponse<string|null>} - A DecisionResponse containing the variation the user is bucketed into,\n     *                                            along with the decision reasons.\n     */\n    resolveVariation(op, configObj, experiment, user, decideOptions, userProfileTracker) {\n        var _a, _b, _c;\n        const userId = user.getUserId();\n        const experimentKey = experiment.key;\n        if (!isActive(configObj, experimentKey)) {\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(EXPERIMENT_NOT_RUNNING, experimentKey);\n            return Value.of(op, {\n                result: {},\n                reasons: [[EXPERIMENT_NOT_RUNNING, experimentKey]],\n            });\n        }\n        const decideReasons = [];\n        const decisionForcedVariation = this.getForcedVariation(configObj, experimentKey, userId);\n        decideReasons.push(...decisionForcedVariation.reasons);\n        const forcedVariationKey = decisionForcedVariation.result;\n        if (forcedVariationKey) {\n            return Value.of(op, {\n                result: { variationKey: forcedVariationKey },\n                reasons: decideReasons,\n            });\n        }\n        const decisionWhitelistedVariation = this.getWhitelistedVariation(experiment, userId);\n        decideReasons.push(...decisionWhitelistedVariation.reasons);\n        let variation = decisionWhitelistedVariation.result;\n        if (variation) {\n            return Value.of(op, {\n                result: { variationKey: variation.key },\n                reasons: decideReasons,\n            });\n        }\n        // check for sticky bucketing\n        if (userProfileTracker) {\n            variation = this.getStoredVariation(configObj, experiment, userId, userProfileTracker.userProfile);\n            if (variation) {\n                (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(RETURNING_STORED_VARIATION, variation.key, experimentKey, userId);\n                decideReasons.push([\n                    RETURNING_STORED_VARIATION,\n                    variation.key,\n                    experimentKey,\n                    userId,\n                ]);\n                return Value.of(op, {\n                    result: { variationKey: variation.key },\n                    reasons: decideReasons,\n                });\n            }\n        }\n        const decisionifUserIsInAudience = this.checkIfUserIsInAudience(configObj, experiment, AUDIENCE_EVALUATION_TYPES.EXPERIMENT, user, '');\n        decideReasons.push(...decisionifUserIsInAudience.reasons);\n        if (!decisionifUserIsInAudience.result) {\n            (_c = this.logger) === null || _c === void 0 ? void 0 : _c.info(USER_NOT_IN_EXPERIMENT, userId, experimentKey);\n            decideReasons.push([\n                USER_NOT_IN_EXPERIMENT,\n                userId,\n                experimentKey,\n            ]);\n            return Value.of(op, {\n                result: {},\n                reasons: decideReasons,\n            });\n        }\n        const decisionVariationValue = this.isCmab(experiment) ?\n            this.getDecisionForCmabExperiment(op, configObj, experiment, user, decideOptions) :\n            this.getDecisionFromBucketer(op, configObj, experiment, user);\n        return decisionVariationValue.then((variationResult) => {\n            var _a, _b;\n            decideReasons.push(...variationResult.reasons);\n            if (variationResult.error) {\n                return Value.of(op, {\n                    error: true,\n                    result: {},\n                    reasons: decideReasons,\n                });\n            }\n            const variationId = variationResult.result.variationId;\n            variation = variationId ? configObj.variationIdMap[variationId] : null;\n            if (!variation) {\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(USER_HAS_NO_VARIATION, userId, experimentKey);\n                decideReasons.push([\n                    USER_HAS_NO_VARIATION,\n                    userId,\n                    experimentKey,\n                ]);\n                return Value.of(op, {\n                    result: {},\n                    reasons: decideReasons,\n                });\n            }\n            (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(USER_HAS_VARIATION, userId, variation.key, experimentKey);\n            decideReasons.push([\n                USER_HAS_VARIATION,\n                userId,\n                variation.key,\n                experimentKey,\n            ]);\n            // store the bucketing decision in user profile\n            // cmab experiments will be excluded\n            if (userProfileTracker && !this.isCmab(experiment)) {\n                this.updateUserProfile(experiment, variation, userProfileTracker);\n            }\n            return Value.of(op, {\n                result: { variationKey: variation.key, cmabUuid: variationResult.result.cmabUuid },\n                reasons: decideReasons,\n            });\n        });\n    }\n    getDecisionForCmabExperiment(op, configObj, experiment, user, decideOptions) {\n        if (op === 'sync') {\n            return Value.of(op, {\n                error: false,\n                result: {},\n                reasons: [[CMAB_NOT_SUPPORTED_IN_SYNC]],\n            });\n        }\n        const userId = user.getUserId();\n        const attributes = user.getAttributes();\n        const bucketingId = this.getBucketingId(userId, attributes);\n        const bucketerParams = this.buildBucketerParams(configObj, experiment, bucketingId, userId);\n        const bucketerResult = bucket(bucketerParams);\n        // this means the user is not in the cmab experiment\n        if (bucketerResult.result !== CMAB_DUMMY_ENTITY_ID) {\n            return Value.of(op, {\n                error: false,\n                result: {},\n                reasons: bucketerResult.reasons,\n            });\n        }\n        const cmabPromise = this.cmabService.getDecision(configObj, user, experiment.id, decideOptions).then((cmabDecision) => {\n            return {\n                error: false,\n                result: cmabDecision,\n                reasons: [],\n            };\n        }).catch((ex) => {\n            var _a;\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(CMAB_FETCH_FAILED, experiment.key);\n            return {\n                error: true,\n                result: {},\n                reasons: [[CMAB_FETCH_FAILED, experiment.key]],\n            };\n        });\n        return Value.of(op, cmabPromise);\n    }\n    getDecisionFromBucketer(op, configObj, experiment, user) {\n        const userId = user.getUserId();\n        const attributes = user.getAttributes();\n        // by default, the bucketing ID should be the user ID\n        const bucketingId = this.getBucketingId(userId, attributes);\n        const bucketerParams = this.buildBucketerParams(configObj, experiment, bucketingId, userId);\n        const decisionVariation = bucket(bucketerParams);\n        return Value.of(op, {\n            result: {\n                variationId: decisionVariation.result || undefined,\n            },\n            reasons: decisionVariation.reasons,\n        });\n    }\n    /**\n     * Gets variation where visitor will be bucketed.\n     * @param  {ProjectConfig}                          configObj         The parsed project configuration object\n     * @param  {Experiment}                             experiment\n     * @param  {OptimizelyUserContext}                  user              A user context\n     * @param  {[key: string]: boolean}                 options           Optional map of decide options\n     * @return {DecisionResponse<string|null>}          DecisionResponse containing the variation the user is bucketed into\n     *                                                                    and the decide reasons.\n     */\n    getVariation(configObj, experiment, user, options = {}) {\n        const shouldIgnoreUPS = options[OptimizelyDecideOption.IGNORE_USER_PROFILE_SERVICE];\n        const userProfileTracker = shouldIgnoreUPS ? undefined\n            : {\n                isProfileUpdated: false,\n                userProfile: this.resolveExperimentBucketMap('sync', user.getUserId(), user.getAttributes()).get(),\n            };\n        const result = this.resolveVariation('sync', configObj, experiment, user, options, userProfileTracker).get();\n        if (userProfileTracker) {\n            this.saveUserProfile('sync', user.getUserId(), userProfileTracker);\n        }\n        return {\n            result: result.result.variationKey || null,\n            reasons: result.reasons,\n        };\n    }\n    /**\n     * Merges attributes from attributes[STICKY_BUCKETING_KEY] and userProfileService\n     * @param  {string}               userId\n     * @param  {UserAttributes}       attributes\n     * @return {ExperimentBucketMap}  finalized copy of experiment_bucket_map\n     */\n    resolveExperimentBucketMap(op, userId, attributes = {}) {\n        const fromAttributes = (attributes[CONTROL_ATTRIBUTES.STICKY_BUCKETING_KEY] || {});\n        return this.getUserProfile(op, userId).then((userProfile) => {\n            const fromUserProfileService = (userProfile === null || userProfile === void 0 ? void 0 : userProfile.experiment_bucket_map) || {};\n            return Value.of(op, Object.assign(Object.assign({}, fromUserProfileService), fromAttributes));\n        });\n    }\n    /**\n     * Checks if user is whitelisted into any variation and return that variation if so\n     * @param  {Experiment}                                 experiment\n     * @param  {string}                                     userId\n     * @return {DecisionResponse<Variation|null>}           DecisionResponse containing the forced variation if it exists\n     *                                                      or user ID and the decide reasons.\n     */\n    getWhitelistedVariation(experiment, userId) {\n        var _a, _b;\n        const decideReasons = [];\n        if (experiment.forcedVariations && experiment.forcedVariations.hasOwnProperty(userId)) {\n            const forcedVariationKey = experiment.forcedVariations[userId];\n            if (experiment.variationKeyMap.hasOwnProperty(forcedVariationKey)) {\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(USER_FORCED_IN_VARIATION, userId, forcedVariationKey);\n                decideReasons.push([\n                    USER_FORCED_IN_VARIATION,\n                    userId,\n                    forcedVariationKey,\n                ]);\n                return {\n                    result: experiment.variationKeyMap[forcedVariationKey],\n                    reasons: decideReasons,\n                };\n            }\n            else {\n                (_b = this.logger) === null || _b === void 0 ? void 0 : _b.error(FORCED_BUCKETING_FAILED, forcedVariationKey, userId);\n                decideReasons.push([\n                    FORCED_BUCKETING_FAILED,\n                    forcedVariationKey,\n                    userId,\n                ]);\n                return {\n                    result: null,\n                    reasons: decideReasons,\n                };\n            }\n        }\n        return {\n            result: null,\n            reasons: decideReasons,\n        };\n    }\n    /**\n     * Checks whether the user is included in experiment audience\n     * @param  {ProjectConfig}                configObj            The parsed project configuration object\n     * @param  {string}                       experimentKey        Key of experiment being validated\n     * @param  {string}                       evaluationAttribute  String representing experiment key or rule\n     * @param  {string}                       userId               ID of user\n     * @param  {UserAttributes}               attributes           Optional parameter for user's attributes\n     * @param  {string}                       loggingKey           String representing experiment key or rollout rule. To be used in log messages only.\n     * @return {DecisionResponse<boolean>}    DecisionResponse     DecisionResponse containing result true if user meets audience conditions and\n     *                                                             the decide reasons.\n     */\n    checkIfUserIsInAudience(configObj, experiment, evaluationAttribute, user, loggingKey) {\n        var _a, _b;\n        const decideReasons = [];\n        const experimentAudienceConditions = experiment.audienceConditions || experiment.audienceIds;\n        const audiencesById = getAudiencesById(configObj);\n        (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(EVALUATING_AUDIENCES_COMBINED, evaluationAttribute, loggingKey || experiment.key, JSON.stringify(experimentAudienceConditions));\n        decideReasons.push([\n            EVALUATING_AUDIENCES_COMBINED,\n            evaluationAttribute,\n            loggingKey || experiment.key,\n            JSON.stringify(experimentAudienceConditions),\n        ]);\n        const result = this.audienceEvaluator.evaluate(experimentAudienceConditions, audiencesById, user);\n        (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(AUDIENCE_EVALUATION_RESULT_COMBINED, evaluationAttribute, loggingKey || experiment.key, result.toString().toUpperCase());\n        decideReasons.push([\n            AUDIENCE_EVALUATION_RESULT_COMBINED,\n            evaluationAttribute,\n            loggingKey || experiment.key,\n            result.toString().toUpperCase(),\n        ]);\n        return {\n            result: result,\n            reasons: decideReasons,\n        };\n    }\n    /**\n     * Given an experiment key and user ID, returns params used in bucketer call\n     * @param  {ProjectConfig}         configObj     The parsed project configuration object\n     * @param  {string}                experimentKey Experiment key used for bucketer\n     * @param  {string}                bucketingId   ID to bucket user into\n     * @param  {string}                userId        ID of user to be bucketed\n     * @return {BucketerParams}\n     */\n    buildBucketerParams(configObj, experiment, bucketingId, userId) {\n        let validateEntity = true;\n        let trafficAllocationConfig = experiment.trafficAllocation;\n        if ('cmab' in experiment && experiment.cmab) {\n            trafficAllocationConfig = [{\n                    entityId: CMAB_DUMMY_ENTITY_ID,\n                    endOfRange: experiment.cmab.trafficAllocation\n                }];\n            validateEntity = false;\n        }\n        return {\n            bucketingId,\n            experimentId: experiment.id,\n            experimentKey: experiment.key,\n            experimentIdMap: configObj.experimentIdMap,\n            experimentKeyMap: configObj.experimentKeyMap,\n            groupIdMap: configObj.groupIdMap,\n            logger: this.logger,\n            trafficAllocationConfig,\n            userId,\n            variationIdMap: configObj.variationIdMap,\n            validateEntity,\n        };\n    }\n    /**\n     * Determines if a user should be bucketed into a holdout variation.\n     * @param {ProjectConfig} configObj - The parsed project configuration object.\n     * @param {Holdout} holdout - The holdout to evaluate.\n     * @param {OptimizelyUserContext} user - The user context.\n     * @returns {DecisionResponse<DecisionObj>} - DecisionResponse containing holdout decision and reasons.\n     */\n    getVariationForHoldout(configObj, holdout, user) {\n        var _a, _b, _c, _d, _e;\n        const userId = user.getUserId();\n        const decideReasons = [];\n        if (holdout.status !== 'Running') {\n            const reason = [HOLDOUT_NOT_RUNNING, holdout.key];\n            decideReasons.push(reason);\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(HOLDOUT_NOT_RUNNING, holdout.key);\n            return {\n                result: {\n                    experiment: null,\n                    variation: null,\n                    decisionSource: DECISION_SOURCES.HOLDOUT\n                },\n                reasons: decideReasons\n            };\n        }\n        const audienceResult = this.checkIfUserIsInAudience(configObj, holdout, AUDIENCE_EVALUATION_TYPES.EXPERIMENT, user);\n        decideReasons.push(...audienceResult.reasons);\n        if (!audienceResult.result) {\n            const reason = [USER_DOESNT_MEET_CONDITIONS_FOR_HOLDOUT, userId, holdout.key];\n            decideReasons.push(reason);\n            (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(USER_DOESNT_MEET_CONDITIONS_FOR_HOLDOUT, userId, holdout.key);\n            return {\n                result: {\n                    experiment: null,\n                    variation: null,\n                    decisionSource: DECISION_SOURCES.HOLDOUT\n                },\n                reasons: decideReasons\n            };\n        }\n        const reason = [USER_MEETS_CONDITIONS_FOR_HOLDOUT, userId, holdout.key];\n        decideReasons.push(reason);\n        (_c = this.logger) === null || _c === void 0 ? void 0 : _c.info(USER_MEETS_CONDITIONS_FOR_HOLDOUT, userId, holdout.key);\n        const attributes = user.getAttributes();\n        const bucketingId = this.getBucketingId(userId, attributes);\n        const bucketerParams = this.buildBucketerParams(configObj, holdout, bucketingId, userId);\n        const bucketResult = bucket(bucketerParams);\n        decideReasons.push(...bucketResult.reasons);\n        if (bucketResult.result) {\n            const variation = configObj.variationIdMap[bucketResult.result];\n            if (variation) {\n                const bucketReason = [USER_BUCKETED_INTO_HOLDOUT_VARIATION, userId, holdout.key, variation.key];\n                decideReasons.push(bucketReason);\n                (_d = this.logger) === null || _d === void 0 ? void 0 : _d.info(USER_BUCKETED_INTO_HOLDOUT_VARIATION, userId, holdout.key, variation.key);\n                return {\n                    result: {\n                        experiment: holdout,\n                        variation: variation,\n                        decisionSource: DECISION_SOURCES.HOLDOUT\n                    },\n                    reasons: decideReasons\n                };\n            }\n        }\n        const noBucketReason = [USER_NOT_BUCKETED_INTO_HOLDOUT_VARIATION, userId];\n        decideReasons.push(noBucketReason);\n        (_e = this.logger) === null || _e === void 0 ? void 0 : _e.info(USER_NOT_BUCKETED_INTO_HOLDOUT_VARIATION, userId);\n        return {\n            result: {\n                experiment: null,\n                variation: null,\n                decisionSource: DECISION_SOURCES.HOLDOUT\n            },\n            reasons: decideReasons\n        };\n    }\n    /**\n     * Pull the stored variation out of the experimentBucketMap for an experiment/userId\n     * @param  {ProjectConfig}        configObj            The parsed project configuration object\n     * @param  {Experiment}           experiment\n     * @param  {string}               userId\n     * @param  {ExperimentBucketMap}  experimentBucketMap  mapping experiment => { variation_id: <variationId> }\n     * @return {Variation|null}       the stored variation or null if the user profile does not have one for the given experiment\n     */\n    getStoredVariation(configObj, experiment, userId, experimentBucketMap) {\n        var _a;\n        if (experimentBucketMap === null || experimentBucketMap === void 0 ? void 0 : experimentBucketMap.hasOwnProperty(experiment.id)) {\n            const decision = experimentBucketMap[experiment.id];\n            const variationId = decision.variation_id;\n            if (configObj.variationIdMap.hasOwnProperty(variationId)) {\n                return configObj.variationIdMap[decision.variation_id];\n            }\n            else {\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(SAVED_VARIATION_NOT_FOUND, userId, variationId, experiment.key);\n            }\n        }\n        return null;\n    }\n    /**\n     * Get the user profile with the given user ID\n     * @param  {string} userId\n     * @return {UserProfile} the stored user profile or an empty profile if one isn't found or error\n     */\n    getUserProfile(op, userId) {\n        var _a;\n        const emptyProfile = {\n            user_id: userId,\n            experiment_bucket_map: {},\n        };\n        if (this.userProfileService) {\n            try {\n                return Value.of(op, this.userProfileService.lookup(userId));\n            }\n            catch (ex) {\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(USER_PROFILE_LOOKUP_ERROR, userId, ex.message);\n            }\n            return Value.of(op, emptyProfile);\n        }\n        if (this.userProfileServiceAsync && op === 'async') {\n            return Value.of(op, this.userProfileServiceAsync.lookup(userId).catch((ex) => {\n                var _a;\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(USER_PROFILE_LOOKUP_ERROR, userId, ex.message);\n                return emptyProfile;\n            }));\n        }\n        return Value.of(op, emptyProfile);\n    }\n    updateUserProfile(experiment, variation, userProfileTracker) {\n        if (!userProfileTracker.userProfile) {\n            return;\n        }\n        userProfileTracker.userProfile[experiment.id] = {\n            variation_id: variation.id\n        };\n        userProfileTracker.isProfileUpdated = true;\n    }\n    /**\n     * Saves the bucketing decision to the user profile\n     * @param {Experiment}          experiment\n     * @param {Variation}           variation\n     * @param {string}              userId\n     * @param {ExperimentBucketMap} experimentBucketMap\n     */\n    saveUserProfile(op, userId, userProfileTracker) {\n        var _a, _b;\n        const { userProfile, isProfileUpdated } = userProfileTracker;\n        if (!userProfile || !isProfileUpdated) {\n            return Value.of(op, undefined);\n        }\n        if (op === 'sync' && !this.userProfileService) {\n            return Value.of(op, undefined);\n        }\n        if (this.userProfileService) {\n            try {\n                this.userProfileService.save({\n                    user_id: userId,\n                    experiment_bucket_map: userProfile,\n                });\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(SAVED_USER_VARIATION, userId);\n            }\n            catch (ex) {\n                (_b = this.logger) === null || _b === void 0 ? void 0 : _b.error(USER_PROFILE_SAVE_ERROR, userId, ex.message);\n            }\n            return Value.of(op, undefined);\n        }\n        if (this.userProfileServiceAsync) {\n            return Value.of(op, this.userProfileServiceAsync.save({\n                user_id: userId,\n                experiment_bucket_map: userProfile,\n            }).catch((ex) => {\n                var _a;\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(USER_PROFILE_SAVE_ERROR, userId, ex.message);\n            }));\n        }\n        return Value.of(op, undefined);\n    }\n    /**\n     * Determines variations for the specified feature flags.\n     *\n     * @param {ProjectConfig} configObj - The parsed project configuration object.\n     * @param {FeatureFlag[]} featureFlags - The feature flags for which variations are to be determined.\n     * @param {OptimizelyUserContext} user - The user context associated with this decision.\n     * @param {Record<string, boolean>} options - An optional map of decision options.\n     * @returns {DecisionResponse<DecisionObj>[]} - An array of DecisionResponse containing objects with\n     *                                               experiment, variation, decisionSource properties, and decision reasons.\n     */\n    getVariationsForFeatureList(configObj, featureFlags, user, options = {}) {\n        return this.resolveVariationsForFeatureList('sync', configObj, featureFlags, user, options).get();\n    }\n    resolveVariationsForFeatureList(op, configObj, featureFlags, user, options) {\n        const userId = user.getUserId();\n        const attributes = user.getAttributes();\n        const decisions = [];\n        // const userProfileTracker : UserProfileTracker = {\n        //   isProfileUpdated: false,\n        //   userProfile: null,\n        // }\n        const shouldIgnoreUPS = !!options[OptimizelyDecideOption.IGNORE_USER_PROFILE_SERVICE];\n        const userProfileTrackerValue = shouldIgnoreUPS ? Value.of(op, undefined)\n            : this.resolveExperimentBucketMap(op, userId, attributes).then((userProfile) => {\n                return Value.of(op, {\n                    isProfileUpdated: false,\n                    userProfile: userProfile,\n                });\n            });\n        return userProfileTrackerValue.then((userProfileTracker) => {\n            const flagResults = featureFlags.map((feature) => this.resolveVariationForFlag(op, configObj, feature, user, options, userProfileTracker));\n            const opFlagResults = Value.all(op, flagResults);\n            return opFlagResults.then(() => {\n                if (userProfileTracker) {\n                    this.saveUserProfile(op, userId, userProfileTracker);\n                }\n                return opFlagResults;\n            });\n        });\n    }\n    resolveVariationForFlag(op, configObj, feature, user, decideOptions, userProfileTracker) {\n        const decideReasons = [];\n        const forcedDecisionResponse = this.findValidatedForcedDecision(configObj, user, feature.key);\n        decideReasons.push(...forcedDecisionResponse.reasons);\n        if (forcedDecisionResponse.result) {\n            return Value.of(op, {\n                result: {\n                    variation: forcedDecisionResponse.result,\n                    experiment: null,\n                    decisionSource: DECISION_SOURCES.FEATURE_TEST,\n                },\n                reasons: decideReasons,\n            });\n        }\n        const holdouts = getHoldoutsForFlag(configObj, feature.key);\n        for (const holdout of holdouts) {\n            const holdoutDecision = this.getVariationForHoldout(configObj, holdout, user);\n            decideReasons.push(...holdoutDecision.reasons);\n            if (holdoutDecision.result.variation) {\n                return Value.of(op, {\n                    result: holdoutDecision.result,\n                    reasons: decideReasons,\n                });\n            }\n        }\n        return this.getVariationForFeatureExperiment(op, configObj, feature, user, decideOptions, userProfileTracker).then((experimentDecision) => {\n            var _a, _b;\n            if (experimentDecision.error || experimentDecision.result.variation !== null) {\n                return Value.of(op, Object.assign(Object.assign({}, experimentDecision), { reasons: [...decideReasons, ...experimentDecision.reasons] }));\n            }\n            decideReasons.push(...experimentDecision.reasons);\n            const rolloutDecision = this.getVariationForRollout(configObj, feature, user);\n            decideReasons.push(...rolloutDecision.reasons);\n            const rolloutDecisionResult = rolloutDecision.result;\n            const userId = user.getUserId();\n            if (rolloutDecisionResult.variation) {\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(USER_IN_ROLLOUT, userId, feature.key);\n                decideReasons.push([USER_IN_ROLLOUT, userId, feature.key]);\n            }\n            else {\n                (_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug(USER_NOT_IN_ROLLOUT, userId, feature.key);\n                decideReasons.push([USER_NOT_IN_ROLLOUT, userId, feature.key]);\n            }\n            return Value.of(op, {\n                result: rolloutDecisionResult,\n                reasons: decideReasons,\n            });\n        });\n    }\n    /**\n     * Given a feature, user ID, and attributes, returns a decision response containing\n     * an object representing a decision and decide reasons. If the user was bucketed into\n     * a variation for the given feature and attributes, the decision object will have variation and\n     * experiment properties (both objects), as well as a decisionSource property.\n     * decisionSource indicates whether the decision was due to a rollout or an\n     * experiment.\n     * @param   {ProjectConfig}               configObj         The parsed project configuration object\n     * @param   {FeatureFlag}                 feature           A feature flag object from project configuration\n     * @param   {OptimizelyUserContext}       user              A user context\n     * @param   {[key: string]: boolean}      options           Map of decide options\n     * @return  {DecisionResponse}            DecisionResponse  DecisionResponse containing an object with experiment, variation, and decisionSource\n     *                                                          properties and decide reasons. If the user was not bucketed into a variation, the variation\n     *                                                          property in decision object is null.\n     */\n    getVariationForFeature(configObj, feature, user, options = {}) {\n        return this.resolveVariationsForFeatureList('sync', configObj, [feature], user, options).get()[0];\n    }\n    getVariationForFeatureExperiment(op, configObj, feature, user, decideOptions, userProfileTracker) {\n        // const decideReasons: DecisionReason[] = [];\n        // let variationKey = null;\n        // let decisionVariation;\n        // let index;\n        // let variationForFeatureExperiment;\n        var _a;\n        if (feature.experimentIds.length === 0) {\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(FEATURE_HAS_NO_EXPERIMENTS, feature.key);\n            return Value.of(op, {\n                result: {\n                    experiment: null,\n                    variation: null,\n                    decisionSource: DECISION_SOURCES.FEATURE_TEST,\n                },\n                reasons: [\n                    [FEATURE_HAS_NO_EXPERIMENTS, feature.key],\n                ],\n            });\n        }\n        return this.traverseFeatureExperimentList(op, configObj, feature, 0, user, [], decideOptions, userProfileTracker);\n    }\n    traverseFeatureExperimentList(op, configObj, feature, fromIndex, user, decideReasons, decideOptions, userProfileTracker) {\n        const experimentIds = feature.experimentIds;\n        if (fromIndex >= experimentIds.length) {\n            return Value.of(op, {\n                result: {\n                    experiment: null,\n                    variation: null,\n                    decisionSource: DECISION_SOURCES.FEATURE_TEST,\n                },\n                reasons: decideReasons,\n            });\n        }\n        const experiment = getExperimentFromId(configObj, experimentIds[fromIndex], this.logger);\n        if (!experiment) {\n            return this.traverseFeatureExperimentList(op, configObj, feature, fromIndex + 1, user, decideReasons, decideOptions, userProfileTracker);\n        }\n        const decisionVariationValue = this.getVariationFromExperimentRule(op, configObj, feature.key, experiment, user, decideOptions, userProfileTracker);\n        return decisionVariationValue.then((decisionVariation) => {\n            decideReasons.push(...decisionVariation.reasons);\n            if (decisionVariation.error) {\n                return Value.of(op, {\n                    error: true,\n                    result: {\n                        experiment,\n                        variation: null,\n                        decisionSource: DECISION_SOURCES.FEATURE_TEST,\n                    },\n                    reasons: decideReasons,\n                });\n            }\n            if (!decisionVariation.result.variationKey) {\n                return this.traverseFeatureExperimentList(op, configObj, feature, fromIndex + 1, user, decideReasons, decideOptions, userProfileTracker);\n            }\n            const variationKey = decisionVariation.result.variationKey;\n            let variation = experiment.variationKeyMap[variationKey];\n            if (!variation) {\n                variation = getFlagVariationByKey(configObj, feature.key, variationKey);\n            }\n            return Value.of(op, {\n                result: {\n                    cmabUuid: decisionVariation.result.cmabUuid,\n                    experiment,\n                    variation,\n                    decisionSource: DECISION_SOURCES.FEATURE_TEST,\n                },\n                reasons: decideReasons,\n            });\n        });\n    }\n    getVariationForRollout(configObj, feature, user) {\n        var _a, _b, _c;\n        const decideReasons = [];\n        let decisionObj;\n        if (!feature.rolloutId) {\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(NO_ROLLOUT_EXISTS, feature.key);\n            decideReasons.push([NO_ROLLOUT_EXISTS, feature.key]);\n            decisionObj = {\n                experiment: null,\n                variation: null,\n                decisionSource: DECISION_SOURCES.ROLLOUT,\n            };\n            return {\n                result: decisionObj,\n                reasons: decideReasons,\n            };\n        }\n        const rollout = configObj.rolloutIdMap[feature.rolloutId];\n        if (!rollout) {\n            (_b = this.logger) === null || _b === void 0 ? void 0 : _b.error(INVALID_ROLLOUT_ID, feature.rolloutId, feature.key);\n            decideReasons.push([INVALID_ROLLOUT_ID, feature.rolloutId, feature.key]);\n            decisionObj = {\n                experiment: null,\n                variation: null,\n                decisionSource: DECISION_SOURCES.ROLLOUT,\n            };\n            return {\n                result: decisionObj,\n                reasons: decideReasons,\n            };\n        }\n        const rolloutRules = rollout.experiments;\n        if (rolloutRules.length === 0) {\n            (_c = this.logger) === null || _c === void 0 ? void 0 : _c.error(ROLLOUT_HAS_NO_EXPERIMENTS, feature.rolloutId);\n            decideReasons.push([ROLLOUT_HAS_NO_EXPERIMENTS, feature.rolloutId]);\n            decisionObj = {\n                experiment: null,\n                variation: null,\n                decisionSource: DECISION_SOURCES.ROLLOUT,\n            };\n            return {\n                result: decisionObj,\n                reasons: decideReasons,\n            };\n        }\n        let decisionVariation;\n        let skipToEveryoneElse;\n        let variation;\n        let rolloutRule;\n        let index = 0;\n        while (index < rolloutRules.length) {\n            decisionVariation = this.getVariationFromDeliveryRule(configObj, feature.key, rolloutRules, index, user);\n            decideReasons.push(...decisionVariation.reasons);\n            variation = decisionVariation.result;\n            skipToEveryoneElse = decisionVariation.skipToEveryoneElse;\n            if (variation) {\n                rolloutRule = configObj.experimentIdMap[rolloutRules[index].id];\n                decisionObj = {\n                    experiment: rolloutRule,\n                    variation: variation,\n                    decisionSource: DECISION_SOURCES.ROLLOUT\n                };\n                return {\n                    result: decisionObj,\n                    reasons: decideReasons,\n                };\n            }\n            // the last rule is special for \"Everyone Else\"\n            index = skipToEveryoneElse ? (rolloutRules.length - 1) : (index + 1);\n        }\n        decisionObj = {\n            experiment: null,\n            variation: null,\n            decisionSource: DECISION_SOURCES.ROLLOUT,\n        };\n        return {\n            result: decisionObj,\n            reasons: decideReasons,\n        };\n    }\n    /**\n     * Get bucketing Id from user attributes.\n     * @param   {string}          userId\n     * @param   {UserAttributes}  attributes\n     * @returns {string}          Bucketing Id if it is a string type in attributes, user Id otherwise.\n     */\n    getBucketingId(userId, attributes) {\n        var _a, _b;\n        let bucketingId = userId;\n        // If the bucketing ID key is defined in attributes, than use that in place of the userID for the murmur hash key\n        if (attributes != null &&\n            typeof attributes === 'object' &&\n            attributes.hasOwnProperty(CONTROL_ATTRIBUTES.BUCKETING_ID)) {\n            if (typeof attributes[CONTROL_ATTRIBUTES.BUCKETING_ID] === 'string') {\n                bucketingId = String(attributes[CONTROL_ATTRIBUTES.BUCKETING_ID]);\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(VALID_BUCKETING_ID, bucketingId);\n            }\n            else {\n                (_b = this.logger) === null || _b === void 0 ? void 0 : _b.warn(BUCKETING_ID_NOT_STRING);\n            }\n        }\n        return bucketingId;\n    }\n    /**\n     * Finds a validated forced decision for specific flagKey and optional ruleKey.\n     * @param     {ProjectConfig}         config               A projectConfig.\n     * @param     {OptimizelyUserContext} user                 A Optimizely User Context.\n     * @param     {string}                flagKey              A flagKey.\n     * @param     {ruleKey}               ruleKey              A ruleKey (optional).\n     * @return    {DecisionResponse<Variation|null>}  DecisionResponse object containing valid variation object and decide reasons.\n     */\n    findValidatedForcedDecision(config, user, flagKey, ruleKey) {\n        var _a, _b, _c, _d;\n        const decideReasons = [];\n        const forcedDecision = user.getForcedDecision({ flagKey, ruleKey });\n        let variation = null;\n        let variationKey;\n        const userId = user.getUserId();\n        if (config && forcedDecision) {\n            variationKey = forcedDecision.variationKey;\n            variation = getFlagVariationByKey(config, flagKey, variationKey);\n            if (variation) {\n                if (ruleKey) {\n                    (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(USER_HAS_FORCED_DECISION_WITH_RULE_SPECIFIED, variationKey, flagKey, ruleKey, userId);\n                    decideReasons.push([\n                        USER_HAS_FORCED_DECISION_WITH_RULE_SPECIFIED,\n                        variationKey,\n                        flagKey,\n                        ruleKey,\n                        userId\n                    ]);\n                }\n                else {\n                    (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(USER_HAS_FORCED_DECISION_WITH_NO_RULE_SPECIFIED, variationKey, flagKey, userId);\n                    decideReasons.push([\n                        USER_HAS_FORCED_DECISION_WITH_NO_RULE_SPECIFIED,\n                        variationKey,\n                        flagKey,\n                        userId\n                    ]);\n                }\n            }\n            else {\n                if (ruleKey) {\n                    (_c = this.logger) === null || _c === void 0 ? void 0 : _c.info(USER_HAS_FORCED_DECISION_WITH_RULE_SPECIFIED_BUT_INVALID, flagKey, ruleKey, userId);\n                    decideReasons.push([\n                        USER_HAS_FORCED_DECISION_WITH_RULE_SPECIFIED_BUT_INVALID,\n                        flagKey,\n                        ruleKey,\n                        userId\n                    ]);\n                }\n                else {\n                    (_d = this.logger) === null || _d === void 0 ? void 0 : _d.info(USER_HAS_FORCED_DECISION_WITH_NO_RULE_SPECIFIED_BUT_INVALID, flagKey, userId);\n                    decideReasons.push([\n                        USER_HAS_FORCED_DECISION_WITH_NO_RULE_SPECIFIED_BUT_INVALID,\n                        flagKey,\n                        userId\n                    ]);\n                }\n            }\n        }\n        return {\n            result: variation,\n            reasons: decideReasons,\n        };\n    }\n    /**\n     * Removes forced variation for given userId and experimentKey\n     * @param  {string} userId         String representing the user id\n     * @param  {string} experimentId   Number representing the experiment id\n     * @param  {string} experimentKey  Key representing the experiment id\n     * @throws If the user id is not valid or not in the forced variation map\n     */\n    removeForcedVariation(userId, experimentId, experimentKey) {\n        var _a;\n        if (!userId) {\n            throw new OptimizelyError(INVALID_USER_ID);\n        }\n        if (this.forcedVariationMap.hasOwnProperty(userId)) {\n            delete this.forcedVariationMap[userId][experimentId];\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(VARIATION_REMOVED_FOR_USER, experimentKey, userId);\n        }\n        else {\n            throw new OptimizelyError(USER_NOT_IN_FORCED_VARIATION, userId);\n        }\n    }\n    /**\n     * Sets forced variation for given userId and experimentKey\n     * @param  {string} userId        String representing the user id\n     * @param  {string} experimentId  Number representing the experiment id\n     * @param  {number} variationId   Number representing the variation id\n     * @throws If the user id is not valid\n     */\n    setInForcedVariationMap(userId, experimentId, variationId) {\n        var _a;\n        if (this.forcedVariationMap.hasOwnProperty(userId)) {\n            this.forcedVariationMap[userId][experimentId] = variationId;\n        }\n        else {\n            this.forcedVariationMap[userId] = {};\n            this.forcedVariationMap[userId][experimentId] = variationId;\n        }\n        (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(USER_MAPPED_TO_FORCED_VARIATION, variationId, experimentId, userId);\n    }\n    /**\n     * Gets the forced variation key for the given user and experiment.\n     * @param  {ProjectConfig}                  configObj         Object representing project configuration\n     * @param  {string}                         experimentKey     Key for experiment.\n     * @param  {string}                         userId            The user Id.\n     * @return {DecisionResponse<string|null>}                    DecisionResponse containing variation which the given user and experiment\n     *                                                            should be forced into and the decide reasons.\n     */\n    getForcedVariation(configObj, experimentKey, userId) {\n        var _a, _b, _c, _d, _e, _f;\n        const decideReasons = [];\n        const experimentToVariationMap = this.forcedVariationMap[userId];\n        if (!experimentToVariationMap) {\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(USER_HAS_NO_FORCED_VARIATION, userId);\n            return {\n                result: null,\n                reasons: decideReasons,\n            };\n        }\n        let experimentId;\n        try {\n            const experiment = getExperimentFromKey(configObj, experimentKey);\n            if (experiment.hasOwnProperty('id')) {\n                experimentId = experiment['id'];\n            }\n            else {\n                // catching improperly formatted experiments\n                (_b = this.logger) === null || _b === void 0 ? void 0 : _b.error(IMPROPERLY_FORMATTED_EXPERIMENT, experimentKey);\n                decideReasons.push([\n                    IMPROPERLY_FORMATTED_EXPERIMENT,\n                    experimentKey,\n                ]);\n                return {\n                    result: null,\n                    reasons: decideReasons,\n                };\n            }\n        }\n        catch (ex) {\n            // catching experiment not in datafile\n            (_c = this.logger) === null || _c === void 0 ? void 0 : _c.error(ex);\n            decideReasons.push(ex.message);\n            return {\n                result: null,\n                reasons: decideReasons,\n            };\n        }\n        const variationId = experimentToVariationMap[experimentId];\n        if (!variationId) {\n            (_d = this.logger) === null || _d === void 0 ? void 0 : _d.debug(USER_HAS_NO_FORCED_VARIATION_FOR_EXPERIMENT, experimentKey, userId);\n            return {\n                result: null,\n                reasons: decideReasons,\n            };\n        }\n        const variationKey = getVariationKeyFromId(configObj, variationId);\n        if (variationKey) {\n            (_e = this.logger) === null || _e === void 0 ? void 0 : _e.debug(USER_HAS_FORCED_VARIATION, variationKey, experimentKey, userId);\n            decideReasons.push([\n                USER_HAS_FORCED_VARIATION,\n                variationKey,\n                experimentKey,\n                userId,\n            ]);\n        }\n        else {\n            (_f = this.logger) === null || _f === void 0 ? void 0 : _f.debug(USER_HAS_NO_FORCED_VARIATION_FOR_EXPERIMENT, experimentKey, userId);\n        }\n        return {\n            result: variationKey,\n            reasons: decideReasons,\n        };\n    }\n    /**\n     * Sets the forced variation for a user in a given experiment\n     * @param  {ProjectConfig}  configObj      Object representing project configuration\n     * @param  {string}         experimentKey  Key for experiment.\n     * @param  {string}         userId         The user Id.\n     * @param  {string|null}    variationKey   Key for variation. If null, then clear the existing experiment-to-variation mapping\n     * @return {boolean}     A boolean value that indicates if the set completed successfully.\n     */\n    setForcedVariation(configObj, experimentKey, userId, variationKey) {\n        var _a, _b, _c, _d, _e, _f;\n        if (variationKey != null && !stringValidator.validate(variationKey)) {\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(INVALID_VARIATION_KEY);\n            return false;\n        }\n        let experimentId;\n        try {\n            const experiment = getExperimentFromKey(configObj, experimentKey);\n            if (experiment.hasOwnProperty('id')) {\n                experimentId = experiment['id'];\n            }\n            else {\n                // catching improperly formatted experiments\n                (_b = this.logger) === null || _b === void 0 ? void 0 : _b.error(IMPROPERLY_FORMATTED_EXPERIMENT, experimentKey);\n                return false;\n            }\n        }\n        catch (ex) {\n            // catching experiment not in datafile\n            (_c = this.logger) === null || _c === void 0 ? void 0 : _c.error(ex);\n            return false;\n        }\n        if (variationKey == null) {\n            try {\n                this.removeForcedVariation(userId, experimentId, experimentKey);\n                return true;\n            }\n            catch (ex) {\n                (_d = this.logger) === null || _d === void 0 ? void 0 : _d.error(ex);\n                return false;\n            }\n        }\n        const variationId = getVariationIdFromExperimentAndVariationKey(configObj, experimentKey, variationKey);\n        if (!variationId) {\n            (_e = this.logger) === null || _e === void 0 ? void 0 : _e.error(NO_VARIATION_FOR_EXPERIMENT_KEY, variationKey, experimentKey);\n            return false;\n        }\n        try {\n            this.setInForcedVariationMap(userId, experimentId, variationId);\n            return true;\n        }\n        catch (ex) {\n            (_f = this.logger) === null || _f === void 0 ? void 0 : _f.error(ex);\n            return false;\n        }\n    }\n    getVariationFromExperimentRule(op, configObj, flagKey, rule, user, decideOptions, userProfileTracker) {\n        const decideReasons = [];\n        // check forced decision first\n        const forcedDecisionResponse = this.findValidatedForcedDecision(configObj, user, flagKey, rule.key);\n        decideReasons.push(...forcedDecisionResponse.reasons);\n        const forcedVariation = forcedDecisionResponse.result;\n        if (forcedVariation) {\n            return Value.of(op, {\n                result: { variationKey: forcedVariation.key },\n                reasons: decideReasons,\n            });\n        }\n        const decisionVariationValue = this.resolveVariation(op, configObj, rule, user, decideOptions, userProfileTracker);\n        return decisionVariationValue.then((variationResult) => {\n            decideReasons.push(...variationResult.reasons);\n            return Value.of(op, {\n                error: variationResult.error,\n                result: variationResult.result,\n                reasons: decideReasons,\n            });\n        });\n        // return response;\n        // decideReasons.push(...decisionVariation.reasons);\n        // const variationKey = decisionVariation.result;\n        // return {\n        //   result: variationKey,\n        //   reasons: decideReasons,\n        // };\n    }\n    getVariationFromDeliveryRule(configObj, flagKey, rules, ruleIndex, user) {\n        var _a, _b, _c, _d;\n        const decideReasons = [];\n        let skipToEveryoneElse = false;\n        // check forced decision first\n        const rule = rules[ruleIndex];\n        const forcedDecisionResponse = this.findValidatedForcedDecision(configObj, user, flagKey, rule.key);\n        decideReasons.push(...forcedDecisionResponse.reasons);\n        const forcedVariation = forcedDecisionResponse.result;\n        if (forcedVariation) {\n            return {\n                result: forcedVariation,\n                reasons: decideReasons,\n                skipToEveryoneElse,\n            };\n        }\n        const userId = user.getUserId();\n        const attributes = user.getAttributes();\n        const bucketingId = this.getBucketingId(userId, attributes);\n        const everyoneElse = ruleIndex === rules.length - 1;\n        const loggingKey = everyoneElse ? \"Everyone Else\" : ruleIndex + 1;\n        let bucketedVariation = null;\n        let bucketerVariationId;\n        let bucketerParams;\n        let decisionVariation;\n        const decisionifUserIsInAudience = this.checkIfUserIsInAudience(configObj, rule, AUDIENCE_EVALUATION_TYPES.RULE, user, loggingKey);\n        decideReasons.push(...decisionifUserIsInAudience.reasons);\n        if (decisionifUserIsInAudience.result) {\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(USER_MEETS_CONDITIONS_FOR_TARGETING_RULE, userId, loggingKey);\n            decideReasons.push([\n                USER_MEETS_CONDITIONS_FOR_TARGETING_RULE,\n                userId,\n                loggingKey\n            ]);\n            bucketerParams = this.buildBucketerParams(configObj, rule, bucketingId, userId);\n            decisionVariation = bucket(bucketerParams);\n            decideReasons.push(...decisionVariation.reasons);\n            bucketerVariationId = decisionVariation.result;\n            if (bucketerVariationId) {\n                bucketedVariation = getVariationFromId(configObj, bucketerVariationId);\n            }\n            if (bucketedVariation) {\n                (_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug(USER_BUCKETED_INTO_TARGETING_RULE, userId, loggingKey);\n                decideReasons.push([\n                    USER_BUCKETED_INTO_TARGETING_RULE,\n                    userId,\n                    loggingKey\n                ]);\n            }\n            else if (!everyoneElse) {\n                // skip this logging for EveryoneElse since this has a message not for EveryoneElse\n                (_c = this.logger) === null || _c === void 0 ? void 0 : _c.debug(USER_NOT_BUCKETED_INTO_TARGETING_RULE, userId, loggingKey);\n                decideReasons.push([\n                    USER_NOT_BUCKETED_INTO_TARGETING_RULE,\n                    userId,\n                    loggingKey\n                ]);\n                // skip the rest of rollout rules to the everyone-else rule if audience matches but not bucketed\n                skipToEveryoneElse = true;\n            }\n        }\n        else {\n            (_d = this.logger) === null || _d === void 0 ? void 0 : _d.debug(USER_DOESNT_MEET_CONDITIONS_FOR_TARGETING_RULE, userId, loggingKey);\n            decideReasons.push([\n                USER_DOESNT_MEET_CONDITIONS_FOR_TARGETING_RULE,\n                userId,\n                loggingKey\n            ]);\n        }\n        return {\n            result: bucketedVariation,\n            reasons: decideReasons,\n            skipToEveryoneElse,\n        };\n    }\n}\n/**\n * Creates an instance of the DecisionService.\n * @param  {DecisionServiceOptions}     options       Configuration options\n * @return {Object}                     An instance of the DecisionService\n */\nexport function createDecisionService(options) {\n    return new DecisionService(options);\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","import { __awaiter } from \"tslib\";\nimport { sprintf, objectValues } from '../utils/fns';\nimport { createNotificationCenter } from '../notification_center';\nimport { OdpEvent } from '../odp/event_manager/odp_event';\nimport { BaseService, ServiceState } from '../service';\nimport { OptimizelyDecideOption, isHoldout, } from '../shared_types';\nimport { newErrorDecision } from '../optimizely_decision';\nimport OptimizelyUserContext from '../optimizely_user_context';\nimport { createDecisionService } from '../core/decision_service';\nimport { buildLogEvent } from '../event_processor/event_builder/log_event';\nimport { buildImpressionEvent, buildConversionEvent } from '../event_processor/event_builder/user_event';\nimport { isSafeInteger } from '../utils/fns';\nimport { validate } from '../utils/attributes_validator';\nimport * as eventTagsValidator from '../utils/event_tags_validator';\nimport * as projectConfig from '../project_config/project_config';\nimport * as userProfileServiceValidator from '../utils/user_profile_service_validator';\nimport * as stringValidator from '../utils/string_value_validator';\nimport * as decision from '../core/decision';\nimport { DECISION_SOURCES, DECISION_MESSAGES, FEATURE_VARIABLE_TYPES, NODE_CLIENT_ENGINE, CLIENT_VERSION, } from '../utils/enums';\nimport { resolvablePromise } from '../utils/promise/resolvablePromise';\nimport { NOTIFICATION_TYPES, DECISION_NOTIFICATION_TYPES } from '../notification_center/type';\nimport { FEATURE_NOT_IN_DATAFILE, INVALID_INPUT_FORMAT, NO_EVENT_PROCESSOR, ODP_EVENT_FAILED, ODP_MANAGER_MISSING, UNABLE_TO_GET_VUID_VUID_MANAGER_NOT_AVAILABLE, UNRECOGNIZED_DECIDE_OPTION, NO_PROJECT_CONFIG_FAILURE, EVENT_KEY_NOT_FOUND, NOT_TRACKING_USER, VARIABLE_REQUESTED_WITH_WRONG_TYPE, } from 'error_message';\nimport { FEATURE_ENABLED_FOR_USER, FEATURE_NOT_ENABLED_FOR_USER, FEATURE_NOT_ENABLED_RETURN_DEFAULT_VARIABLE_VALUE, INVALID_CLIENT_ENGINE, INVALID_DECIDE_OPTIONS, INVALID_DEFAULT_DECIDE_OPTIONS, INVALID_EXPERIMENT_KEY_INFO, NOT_ACTIVATING_USER, SHOULD_NOT_DISPATCH_ACTIVATE, TRACK_EVENT, UPDATED_OPTIMIZELY_CONFIG, USER_RECEIVED_DEFAULT_VARIABLE_VALUE, USER_RECEIVED_VARIABLE_VALUE, VALID_USER_PROFILE_SERVICE, VARIABLE_NOT_USED_RETURN_DEFAULT_VARIABLE_VALUE, } from 'log_message';\nimport { SERVICE_STOPPED_BEFORE_RUNNING } from '../service';\nimport { ErrorReporter } from '../error/error_reporter';\nimport { OptimizelyError } from '../error/optimizly_error';\nimport { Value } from '../utils/promise/operation_value';\nconst DEFAULT_ONREADY_TIMEOUT = 30000;\nexport const INSTANCE_CLOSED = 'Instance closed';\nexport const ONREADY_TIMEOUT = 'onReady timeout expired after %s ms';\nexport const INVALID_IDENTIFIER = 'Invalid identifier';\nexport const INVALID_ATTRIBUTES = 'Invalid attributes';\nexport default class Optimizely extends BaseService {\n    constructor(config) {\n        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;\n        super();\n        this.cleanupTasks = new Map();\n        this.nextCleanupTaskId = 0;\n        let clientEngine = config.clientEngine;\n        if (!clientEngine) {\n            (_a = config.logger) === null || _a === void 0 ? void 0 : _a.info(INVALID_CLIENT_ENGINE, clientEngine);\n            clientEngine = NODE_CLIENT_ENGINE;\n        }\n        this.clientEngine = clientEngine;\n        this.clientVersion = config.clientVersion || CLIENT_VERSION;\n        this.errorNotifier = config.errorNotifier;\n        this.logger = config.logger;\n        this.projectConfigManager = config.projectConfigManager;\n        this.errorReporter = new ErrorReporter(this.logger, this.errorNotifier);\n        this.odpManager = config.odpManager;\n        this.vuidManager = config.vuidManager;\n        this.eventProcessor = config.eventProcessor;\n        if (config.disposable) {\n            this.projectConfigManager.makeDisposable();\n            (_b = this.eventProcessor) === null || _b === void 0 ? void 0 : _b.makeDisposable();\n            (_c = this.odpManager) === null || _c === void 0 ? void 0 : _c.makeDisposable();\n        }\n        // pass a child logger to sub-components\n        if (this.logger) {\n            this.projectConfigManager.setLogger(this.logger.child());\n            (_d = this.eventProcessor) === null || _d === void 0 ? void 0 : _d.setLogger(this.logger.child());\n            (_e = this.odpManager) === null || _e === void 0 ? void 0 : _e.setLogger(this.logger.child());\n        }\n        let decideOptionsArray = (_f = config.defaultDecideOptions) !== null && _f !== void 0 ? _f : [];\n        if (!Array.isArray(decideOptionsArray)) {\n            (_g = this.logger) === null || _g === void 0 ? void 0 : _g.debug(INVALID_DEFAULT_DECIDE_OPTIONS);\n            decideOptionsArray = [];\n        }\n        const defaultDecideOptions = {};\n        decideOptionsArray.forEach(option => {\n            var _a;\n            // Filter out all provided default decide options that are not in OptimizelyDecideOption[]\n            if (OptimizelyDecideOption[option]) {\n                defaultDecideOptions[option] = true;\n            }\n            else {\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.warn(UNRECOGNIZED_DECIDE_OPTION, option);\n            }\n        });\n        this.defaultDecideOptions = defaultDecideOptions;\n        this.projectConfigManager = config.projectConfigManager;\n        this.projectConfigManager.onUpdate((configObj) => {\n            var _a;\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(UPDATED_OPTIMIZELY_CONFIG, configObj.revision, configObj.projectId);\n            this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.OPTIMIZELY_CONFIG_UPDATE, undefined);\n            this.updateOdpSettings();\n        });\n        this.eventProcessor = config.eventProcessor;\n        (_h = this.eventProcessor) === null || _h === void 0 ? void 0 : _h.onDispatch((event) => {\n            this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.LOG_EVENT, event);\n        });\n        this.odpManager = config.odpManager;\n        let userProfileService = undefined;\n        if (config.userProfileService) {\n            try {\n                if (userProfileServiceValidator.validate(config.userProfileService)) {\n                    userProfileService = config.userProfileService;\n                    (_j = this.logger) === null || _j === void 0 ? void 0 : _j.info(VALID_USER_PROFILE_SERVICE);\n                }\n            }\n            catch (ex) {\n                (_k = this.logger) === null || _k === void 0 ? void 0 : _k.warn(ex);\n            }\n        }\n        this.decisionService = createDecisionService({\n            userProfileService: userProfileService,\n            userProfileServiceAsync: config.userProfileServiceAsync || undefined,\n            cmabService: config.cmabService,\n            logger: (_l = this.logger) === null || _l === void 0 ? void 0 : _l.child(),\n            UNSTABLE_conditionEvaluators: config.UNSTABLE_conditionEvaluators,\n        });\n        this.notificationCenter = createNotificationCenter({ logger: this.logger, errorNotifier: this.errorNotifier });\n        this.start();\n    }\n    start() {\n        var _a, _b;\n        if (!this.isNew()) {\n            return;\n        }\n        super.start();\n        this.state = ServiceState.Starting;\n        this.projectConfigManager.start();\n        (_a = this.eventProcessor) === null || _a === void 0 ? void 0 : _a.start();\n        (_b = this.odpManager) === null || _b === void 0 ? void 0 : _b.start();\n        Promise.all([\n            this.projectConfigManager.onRunning(),\n            this.eventProcessor ? this.eventProcessor.onRunning() : Promise.resolve(),\n            this.odpManager ? this.odpManager.onRunning() : Promise.resolve(),\n            this.vuidManager ? this.vuidManager.initialize() : Promise.resolve(),\n        ]).then(() => {\n            var _a, _b;\n            this.state = ServiceState.Running;\n            this.startPromise.resolve();\n            const vuid = (_a = this.vuidManager) === null || _a === void 0 ? void 0 : _a.getVuid();\n            if (vuid) {\n                (_b = this.odpManager) === null || _b === void 0 ? void 0 : _b.setVuid(vuid);\n            }\n        }).catch((err) => {\n            this.state = ServiceState.Failed;\n            this.errorReporter.report(err);\n            this.startPromise.reject(err);\n        });\n    }\n    /**\n     * Returns the project configuration retrieved from projectConfigManager\n     * @return {projectConfig.ProjectConfig}\n     */\n    getProjectConfig() {\n        return this.projectConfigManager.getConfig() || null;\n    }\n    /**\n     * Buckets visitor and sends impression event to Optimizely.\n     * @param  {string}             experimentKey\n     * @param  {string}             userId\n     * @param  {UserAttributes}     attributes\n     * @return {string|null}        variation key\n     */\n    activate(experimentKey, userId, attributes) {\n        var _a, _b;\n        try {\n            const configObj = this.getProjectConfig();\n            if (!configObj) {\n                this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'activate');\n                return null;\n            }\n            if (!this.validateInputs({ experiment_key: experimentKey, user_id: userId }, attributes)) {\n                return this.notActivatingExperiment(experimentKey, userId);\n            }\n            try {\n                const variationKey = this.getVariation(experimentKey, userId, attributes);\n                if (variationKey === null) {\n                    return this.notActivatingExperiment(experimentKey, userId);\n                }\n                // If experiment is not set to 'Running' status, log accordingly and return variation key\n                if (!projectConfig.isRunning(configObj, experimentKey)) {\n                    (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(SHOULD_NOT_DISPATCH_ACTIVATE, experimentKey);\n                    return variationKey;\n                }\n                const experiment = projectConfig.getExperimentFromKey(configObj, experimentKey);\n                const variation = experiment.variationKeyMap[variationKey];\n                const decisionObj = {\n                    experiment: experiment,\n                    variation: variation,\n                    decisionSource: DECISION_SOURCES.EXPERIMENT,\n                };\n                this.sendImpressionEvent(decisionObj, '', userId, true, attributes);\n                return variationKey;\n            }\n            catch (ex) {\n                (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(NOT_ACTIVATING_USER, userId, experimentKey);\n                this.errorReporter.report(ex);\n                return null;\n            }\n        }\n        catch (e) {\n            this.errorReporter.report(e);\n            return null;\n        }\n    }\n    /**\n     * Create an impression event and call the event dispatcher's dispatch method to\n     * send this event to Optimizely. Then use the notification center to trigger\n     * any notification listeners for the ACTIVATE notification type.\n     * @param {DecisionObj}    decisionObj    Decision Object\n     * @param {string}         flagKey        Key for a feature flag\n     * @param {string}         userId         ID of user to whom the variation was shown\n     * @param {UserAttributes} attributes     Optional user attributes\n     * @param {boolean}        enabled        Boolean representing if feature is enabled\n     */\n    sendImpressionEvent(decisionObj, flagKey, userId, enabled, attributes) {\n        var _a;\n        if (!this.eventProcessor) {\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(NO_EVENT_PROCESSOR);\n            return;\n        }\n        const configObj = this.getProjectConfig();\n        if (!configObj) {\n            return;\n        }\n        const impressionEvent = buildImpressionEvent({\n            decisionObj: decisionObj,\n            flagKey: flagKey,\n            enabled: enabled,\n            userId: userId,\n            userAttributes: attributes,\n            clientEngine: this.clientEngine,\n            clientVersion: this.clientVersion,\n            configObj: configObj,\n        });\n        this.eventProcessor.process(impressionEvent);\n        const logEvent = buildLogEvent([impressionEvent]);\n        const activateNotificationPayload = {\n            experiment: null,\n            holdout: null,\n            userId: userId,\n            attributes: attributes,\n            variation: decisionObj.variation,\n            logEvent,\n        };\n        if (decisionObj.experiment) {\n            if (isHoldout(decisionObj.experiment)) {\n                activateNotificationPayload.holdout = decisionObj.experiment;\n            }\n            else {\n                activateNotificationPayload.experiment = decisionObj.experiment;\n            }\n        }\n        this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.ACTIVATE, activateNotificationPayload);\n    }\n    /**\n     * Sends conversion event to Optimizely.\n     * @param  {string}         eventKey\n     * @param  {string}         userId\n     * @param  {UserAttributes} attributes\n     * @param  {EventTags}      eventTags Values associated with the event.\n     */\n    track(eventKey, userId, attributes, eventTags) {\n        var _a, _b, _c, _d, _e;\n        try {\n            if (!this.eventProcessor) {\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(NO_EVENT_PROCESSOR);\n                return;\n            }\n            const configObj = this.getProjectConfig();\n            if (!configObj) {\n                this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'track');\n                return;\n            }\n            if (!this.validateInputs({ user_id: userId, event_key: eventKey }, attributes, eventTags)) {\n                return;\n            }\n            if (!projectConfig.eventWithKeyExists(configObj, eventKey)) {\n                (_b = this.logger) === null || _b === void 0 ? void 0 : _b.warn(EVENT_KEY_NOT_FOUND, eventKey);\n                (_c = this.logger) === null || _c === void 0 ? void 0 : _c.warn(NOT_TRACKING_USER, userId);\n                return;\n            }\n            // remove null values from eventTags\n            eventTags = this.filterEmptyValues(eventTags);\n            const conversionEvent = buildConversionEvent({\n                eventKey: eventKey,\n                eventTags: eventTags,\n                userId: userId,\n                userAttributes: attributes,\n                clientEngine: this.clientEngine,\n                clientVersion: this.clientVersion,\n                configObj: configObj,\n            }, this.logger);\n            (_d = this.logger) === null || _d === void 0 ? void 0 : _d.info(TRACK_EVENT, eventKey, userId);\n            // TODO is it okay to not pass a projectConfig as second argument\n            this.eventProcessor.process(conversionEvent);\n            const logEvent = buildLogEvent([conversionEvent]);\n            this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.TRACK, {\n                eventKey,\n                userId,\n                attributes,\n                eventTags,\n                logEvent,\n            });\n        }\n        catch (e) {\n            this.errorReporter.report(e);\n            (_e = this.logger) === null || _e === void 0 ? void 0 : _e.error(NOT_TRACKING_USER, userId);\n        }\n    }\n    /**\n     * Gets variation where visitor will be bucketed.\n     * @param  {string}              experimentKey\n     * @param  {string}              userId\n     * @param  {UserAttributes}      attributes\n     * @return {string|null}         variation key\n     */\n    getVariation(experimentKey, userId, attributes) {\n        var _a;\n        try {\n            const configObj = this.getProjectConfig();\n            if (!configObj) {\n                this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'getVariation');\n                return null;\n            }\n            try {\n                if (!this.validateInputs({ experiment_key: experimentKey, user_id: userId }, attributes)) {\n                    return null;\n                }\n                const experiment = configObj.experimentKeyMap[experimentKey];\n                if (!experiment || experiment.isRollout) {\n                    (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(INVALID_EXPERIMENT_KEY_INFO, experimentKey);\n                    return null;\n                }\n                const variationKey = this.decisionService.getVariation(configObj, experiment, this.createInternalUserContext(userId, attributes)).result;\n                const decisionNotificationType = projectConfig.isFeatureExperiment(configObj, experiment.id)\n                    ? DECISION_NOTIFICATION_TYPES.FEATURE_TEST\n                    : DECISION_NOTIFICATION_TYPES.AB_TEST;\n                this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.DECISION, {\n                    type: decisionNotificationType,\n                    userId: userId,\n                    attributes: attributes || {},\n                    decisionInfo: {\n                        experimentKey: experimentKey,\n                        variationKey: variationKey,\n                    },\n                });\n                return variationKey;\n            }\n            catch (ex) {\n                this.errorReporter.report(ex);\n                return null;\n            }\n        }\n        catch (e) {\n            this.errorReporter.report(e);\n            return null;\n        }\n    }\n    /**\n     * Force a user into a variation for a given experiment.\n     * @param  {string}      experimentKey\n     * @param  {string}      userId\n     * @param  {string|null} variationKey   user will be forced into. If null,\n     *                                      then clear the existing experiment-to-variation mapping.\n     * @return {boolean}                    A boolean value that indicates if the set completed successfully.\n     */\n    setForcedVariation(experimentKey, userId, variationKey) {\n        if (!this.validateInputs({ experiment_key: experimentKey, user_id: userId })) {\n            return false;\n        }\n        const configObj = this.getProjectConfig();\n        if (!configObj) {\n            return false;\n        }\n        try {\n            return this.decisionService.setForcedVariation(configObj, experimentKey, userId, variationKey);\n        }\n        catch (ex) {\n            this.errorReporter.report(ex);\n            return false;\n        }\n    }\n    /**\n     * Gets the forced variation for a given user and experiment.\n     * @param  {string}      experimentKey\n     * @param  {string}      userId\n     * @return {string|null} The forced variation key.\n     */\n    getForcedVariation(experimentKey, userId) {\n        if (!this.validateInputs({ experiment_key: experimentKey, user_id: userId })) {\n            return null;\n        }\n        const configObj = this.getProjectConfig();\n        if (!configObj) {\n            return null;\n        }\n        try {\n            return this.decisionService.getForcedVariation(configObj, experimentKey, userId).result;\n        }\n        catch (ex) {\n            this.errorReporter.report(ex);\n            return null;\n        }\n    }\n    /**\n     * Validate string inputs, user attributes and event tags.\n     * @param  {StringInputs}  stringInputs   Map of string keys and associated values\n     * @param  {unknown}       userAttributes Optional parameter for user's attributes\n     * @param  {unknown}       eventTags      Optional parameter for event tags\n     * @return {boolean}                      True if inputs are valid\n     *\n     */\n    validateInputs(stringInputs, userAttributes, eventTags) {\n        try {\n            if (stringInputs.hasOwnProperty('user_id')) {\n                const userId = stringInputs['user_id'];\n                if (typeof userId !== 'string' || userId === null || userId === 'undefined') {\n                    throw new OptimizelyError(INVALID_INPUT_FORMAT, 'user_id');\n                }\n                delete stringInputs['user_id'];\n            }\n            Object.keys(stringInputs).forEach(key => {\n                if (!stringValidator.validate(stringInputs[key])) {\n                    throw new OptimizelyError(INVALID_INPUT_FORMAT, key);\n                }\n            });\n            if (userAttributes) {\n                validate(userAttributes);\n            }\n            if (eventTags) {\n                eventTagsValidator.validate(eventTags);\n            }\n            return true;\n        }\n        catch (ex) {\n            this.errorReporter.report(ex);\n            return false;\n        }\n    }\n    /**\n     * Shows failed activation log message and returns null when user is not activated in experiment\n     * @param  {string} experimentKey\n     * @param  {string} userId\n     * @return {null}\n     */\n    notActivatingExperiment(experimentKey, userId) {\n        var _a;\n        (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(NOT_ACTIVATING_USER, userId, experimentKey);\n        return null;\n    }\n    /**\n     * Filters out attributes/eventTags with null or undefined values\n     * @param   {EventTags | undefined} map\n     * @returns {EventTags | undefined}\n     */\n    filterEmptyValues(map) {\n        for (const key in map) {\n            const typedKey = key;\n            if (map.hasOwnProperty(typedKey) && (map[typedKey] === null || map[typedKey] === undefined)) {\n                delete map[typedKey];\n            }\n        }\n        return map;\n    }\n    /**\n     * Returns true if the feature is enabled for the given user.\n     * @param  {string}         featureKey   Key of feature which will be checked\n     * @param  {string}         userId       ID of user which will be checked\n     * @param  {UserAttributes} attributes   Optional user attributes\n     * @return {boolean}                     true if the feature is enabled for the user, false otherwise\n     */\n    isFeatureEnabled(featureKey, userId, attributes) {\n        var _a, _b;\n        try {\n            const configObj = this.getProjectConfig();\n            if (!configObj) {\n                this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'isFeatureEnabled');\n                return false;\n            }\n            if (!this.validateInputs({ feature_key: featureKey, user_id: userId }, attributes)) {\n                return false;\n            }\n            const feature = projectConfig.getFeatureFromKey(configObj, featureKey, this.logger);\n            if (!feature) {\n                return false;\n            }\n            let sourceInfo = {};\n            const user = this.createInternalUserContext(userId, attributes);\n            const decisionObj = this.decisionService.getVariationForFeature(configObj, feature, user).result;\n            const decisionSource = decisionObj.decisionSource;\n            const experimentKey = decision.getExperimentKey(decisionObj);\n            const variationKey = decision.getVariationKey(decisionObj);\n            let featureEnabled = decision.getFeatureEnabledFromVariation(decisionObj);\n            if (decisionSource === DECISION_SOURCES.FEATURE_TEST || decisionSource === DECISION_SOURCES.HOLDOUT) {\n                sourceInfo = {\n                    experimentKey: experimentKey,\n                    variationKey: variationKey,\n                };\n            }\n            if (decisionSource === DECISION_SOURCES.FEATURE_TEST ||\n                decisionSource === DECISION_SOURCES.HOLDOUT ||\n                (decisionSource === DECISION_SOURCES.ROLLOUT && projectConfig.getSendFlagDecisionsValue(configObj))) {\n                this.sendImpressionEvent(decisionObj, feature.key, userId, featureEnabled, attributes);\n            }\n            if (featureEnabled === true) {\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(FEATURE_ENABLED_FOR_USER, featureKey, userId);\n            }\n            else {\n                (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(FEATURE_NOT_ENABLED_FOR_USER, featureKey, userId);\n                featureEnabled = false;\n            }\n            const featureInfo = {\n                featureKey: featureKey,\n                featureEnabled: featureEnabled,\n                source: decisionObj.decisionSource,\n                sourceInfo: sourceInfo,\n            };\n            this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.DECISION, {\n                type: DECISION_NOTIFICATION_TYPES.FEATURE,\n                userId: userId,\n                attributes: attributes || {},\n                decisionInfo: featureInfo,\n            });\n            return featureEnabled;\n        }\n        catch (e) {\n            this.errorReporter.report(e);\n            return false;\n        }\n    }\n    /**\n     * Returns an Array containing the keys of all features in the project that are\n     * enabled for the given user.\n     * @param  {string}         userId\n     * @param  {UserAttributes} attributes\n     * @return {string[]}       Array of feature keys (strings)\n     */\n    getEnabledFeatures(userId, attributes) {\n        try {\n            const enabledFeatures = [];\n            const configObj = this.getProjectConfig();\n            if (!configObj) {\n                this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'getEnabledFeatures');\n                return enabledFeatures;\n            }\n            if (!this.validateInputs({ user_id: userId })) {\n                return enabledFeatures;\n            }\n            objectValues(configObj.featureKeyMap).forEach((feature) => {\n                if (this.isFeatureEnabled(feature.key, userId, attributes)) {\n                    enabledFeatures.push(feature.key);\n                }\n            });\n            return enabledFeatures;\n        }\n        catch (e) {\n            this.errorReporter.report(e);\n            return [];\n        }\n    }\n    /**\n     * Returns dynamically-typed value of the variable attached to the given\n     * feature flag. Returns null if the feature key or variable key is invalid.\n     *\n     * @param  {string}          featureKey           Key of the feature whose variable's\n     *                                                value is being accessed\n     * @param  {string}          variableKey          Key of the variable whose value is\n     *                                                being accessed\n     * @param  {string}          userId               ID for the user\n     * @param  {UserAttributes}  attributes           Optional user attributes\n     * @return {unknown}                              Value of the variable cast to the appropriate\n     *                                                type, or null if the feature key is invalid or\n     *                                                the variable key is invalid\n     */\n    getFeatureVariable(featureKey, variableKey, userId, attributes) {\n        try {\n            if (!this.getProjectConfig()) {\n                this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'getFeatureVariable');\n                return null;\n            }\n            return this.getFeatureVariableForType(featureKey, variableKey, null, userId, attributes);\n        }\n        catch (e) {\n            this.errorReporter.report(e);\n            return null;\n        }\n    }\n    /**\n     * Helper method to get the value for a variable of a certain type attached to a\n     * feature flag. Returns null if the feature key is invalid, the variable key is\n     * invalid, the given variable type does not match the variable's actual type,\n     * or the variable value cannot be cast to the required type. If the given variable\n     * type is null, the value of the variable cast to the appropriate type is returned.\n     *\n     * @param   {string}         featureKey           Key of the feature whose variable's value is\n     *                                                being accessed\n     * @param   {string}         variableKey          Key of the variable whose value is being\n     *                                                accessed\n     * @param   {string|null}    variableType         Type of the variable whose value is being\n     *                                                accessed (must be one of FEATURE_VARIABLE_TYPES\n     *                                                in lib/utils/enums/index.js), or null to return the\n     *                                                value of the variable cast to the appropriate type\n     * @param   {string}         userId               ID for the user\n     * @param   {UserAttributes} attributes           Optional user attributes\n     * @return  {unknown}                             Value of the variable cast to the appropriate\n     *                                                type, or null if the feature key is invalid, thevariable\n     *                                                key is invalid, or there is a mismatch with the type of\n     *                                                the variable\n     */\n    getFeatureVariableForType(featureKey, variableKey, variableType, userId, attributes) {\n        var _a;\n        if (!this.validateInputs({ feature_key: featureKey, variable_key: variableKey, user_id: userId }, attributes)) {\n            return null;\n        }\n        const configObj = this.getProjectConfig();\n        if (!configObj) {\n            return null;\n        }\n        const featureFlag = projectConfig.getFeatureFromKey(configObj, featureKey, this.logger);\n        if (!featureFlag) {\n            return null;\n        }\n        const variable = projectConfig.getVariableForFeature(configObj, featureKey, variableKey, this.logger);\n        if (!variable) {\n            return null;\n        }\n        if (variableType && variable.type !== variableType) {\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.warn(VARIABLE_REQUESTED_WITH_WRONG_TYPE, variableType, variable.type);\n            return null;\n        }\n        const user = this.createInternalUserContext(userId, attributes);\n        const decisionObj = this.decisionService.getVariationForFeature(configObj, featureFlag, user).result;\n        const featureEnabled = decision.getFeatureEnabledFromVariation(decisionObj);\n        const variableValue = this.getFeatureVariableValueFromVariation(featureKey, featureEnabled, decisionObj.variation, variable, userId);\n        let sourceInfo = {};\n        if (decisionObj.decisionSource === DECISION_SOURCES.FEATURE_TEST &&\n            decisionObj.experiment !== null &&\n            decisionObj.variation !== null) {\n            sourceInfo = {\n                experimentKey: decisionObj.experiment.key,\n                variationKey: decisionObj.variation.key,\n            };\n        }\n        this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.DECISION, {\n            type: DECISION_NOTIFICATION_TYPES.FEATURE_VARIABLE,\n            userId: userId,\n            attributes: attributes || {},\n            decisionInfo: {\n                featureKey: featureKey,\n                featureEnabled: featureEnabled,\n                source: decisionObj.decisionSource,\n                variableKey: variableKey,\n                variableValue: variableValue,\n                variableType: variable.type,\n                sourceInfo: sourceInfo,\n            },\n        });\n        return variableValue;\n    }\n    /**\n     * Helper method to get the non type-casted value for a variable attached to a\n     * feature flag. Returns appropriate variable value depending on whether there\n     * was a matching variation, feature was enabled or not or varible was part of the\n     * available variation or not. Also logs the appropriate message explaining how it\n     * evaluated the value of the variable.\n     *\n     * @param  {string}          featureKey           Key of the feature whose variable's value is\n     *                                                being accessed\n     * @param  {boolean}         featureEnabled       Boolean indicating if feature is enabled or not\n     * @param  {Variation}       variation            variation returned by decision service\n     * @param  {FeatureVariable} variable             varible whose value is being evaluated\n     * @param  {string}          userId               ID for the user\n     * @return {unknown}                              Value of the variable or null if the\n     *                                                config Obj is null\n     */\n    getFeatureVariableValueFromVariation(featureKey, featureEnabled, variation, variable, userId) {\n        var _a, _b, _c, _d;\n        const configObj = this.getProjectConfig();\n        if (!configObj) {\n            return null;\n        }\n        let variableValue = variable.defaultValue;\n        if (variation !== null) {\n            const value = projectConfig.getVariableValueForVariation(configObj, variable, variation, this.logger);\n            if (value !== null) {\n                if (featureEnabled) {\n                    variableValue = value;\n                    (_a = this.logger) === null || _a === void 0 ? void 0 : _a.info(USER_RECEIVED_VARIABLE_VALUE, variableValue, variable.key, featureKey);\n                }\n                else {\n                    (_b = this.logger) === null || _b === void 0 ? void 0 : _b.info(FEATURE_NOT_ENABLED_RETURN_DEFAULT_VARIABLE_VALUE, featureKey, userId, variableValue);\n                }\n            }\n            else {\n                (_c = this.logger) === null || _c === void 0 ? void 0 : _c.info(VARIABLE_NOT_USED_RETURN_DEFAULT_VARIABLE_VALUE, variable.key, variation.key);\n            }\n        }\n        else {\n            (_d = this.logger) === null || _d === void 0 ? void 0 : _d.info(USER_RECEIVED_DEFAULT_VARIABLE_VALUE, userId, variable.key, featureKey);\n        }\n        return projectConfig.getTypeCastValue(variableValue, variable.type, this.logger);\n    }\n    /**\n     * Returns value for the given boolean variable attached to the given feature\n     * flag.\n     * @param  {string}         featureKey   Key of the feature whose variable's value is\n     *                                       being accessed\n     * @param  {string}         variableKey  Key of the variable whose value is being\n     *                                       accessed\n     * @param  {string}         userId       ID for the user\n     * @param  {UserAttributes} attributes   Optional user attributes\n     * @return {boolean|null}                Boolean value of the variable, or null if the\n     *                                       feature key is invalid, the variable key is invalid,\n     *                                       or there is a mismatch with the type of the variable.\n     */\n    getFeatureVariableBoolean(featureKey, variableKey, userId, attributes) {\n        try {\n            if (!this.getProjectConfig()) {\n                this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'getFeatureVariableBoolean');\n                return null;\n            }\n            return this.getFeatureVariableForType(featureKey, variableKey, FEATURE_VARIABLE_TYPES.BOOLEAN, userId, attributes);\n        }\n        catch (e) {\n            this.errorReporter.report(e);\n            return null;\n        }\n    }\n    /**\n     * Returns value for the given double variable attached to the given feature\n     * flag.\n     * @param  {string} featureKey           Key of the feature whose variable's value is\n     *                                       being accessed\n     * @param  {string} variableKey          Key of the variable whose value is being\n     *                                       accessed\n     * @param  {string} userId               ID for the user\n     * @param  {UserAttributes} attributes   Optional user attributes\n     * @return {number|null}                 Number value of the variable, or null if the\n     *                                       feature key is invalid, the variable key is\n     *                                       invalid, or there is a mismatch with the type\n     *                                       of the variable\n     */\n    getFeatureVariableDouble(featureKey, variableKey, userId, attributes) {\n        try {\n            if (!this.getProjectConfig()) {\n                this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'getFeatureVariableDouble');\n                return null;\n            }\n            return this.getFeatureVariableForType(featureKey, variableKey, FEATURE_VARIABLE_TYPES.DOUBLE, userId, attributes);\n        }\n        catch (e) {\n            this.errorReporter.report(e);\n            return null;\n        }\n    }\n    /**\n     * Returns value for the given integer variable attached to the given feature\n     * flag.\n     * @param  {string}         featureKey   Key of the feature whose variable's value is\n     *                                       being accessed\n     * @param  {string}         variableKey  Key of the variable whose value is being\n     *                                       accessed\n     * @param  {string}         userId       ID for the user\n     * @param  {UserAttributes} attributes   Optional user attributes\n     * @return {number|null}                 Number value of the variable, or null if the\n     *                                       feature key is invalid, the variable key is\n     *                                       invalid, or there is a mismatch with the type\n     *                                       of the variable\n     */\n    getFeatureVariableInteger(featureKey, variableKey, userId, attributes) {\n        try {\n            if (!this.getProjectConfig()) {\n                this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'getFeatureVariableInteger');\n                return null;\n            }\n            return this.getFeatureVariableForType(featureKey, variableKey, FEATURE_VARIABLE_TYPES.INTEGER, userId, attributes);\n        }\n        catch (e) {\n            this.errorReporter.report(e);\n            return null;\n        }\n    }\n    /**\n     * Returns value for the given string variable attached to the given feature\n     * flag.\n     * @param  {string}         featureKey   Key of the feature whose variable's value is\n     *                                       being accessed\n     * @param  {string}         variableKey  Key of the variable whose value is being\n     *                                       accessed\n     * @param  {string}         userId       ID for the user\n     * @param  {UserAttributes} attributes   Optional user attributes\n     * @return {string|null}                 String value of the variable, or null if the\n     *                                       feature key is invalid, the variable key is\n     *                                       invalid, or there is a mismatch with the type\n     *                                       of the variable\n     */\n    getFeatureVariableString(featureKey, variableKey, userId, attributes) {\n        try {\n            if (!this.getProjectConfig()) {\n                this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'getFeatureVariableString');\n                return null;\n            }\n            return this.getFeatureVariableForType(featureKey, variableKey, FEATURE_VARIABLE_TYPES.STRING, userId, attributes);\n        }\n        catch (e) {\n            this.errorReporter.report(e);\n            return null;\n        }\n    }\n    /**\n     * Returns value for the given json variable attached to the given feature\n     * flag.\n     * @param  {string}         featureKey   Key of the feature whose variable's value is\n     *                                       being accessed\n     * @param  {string}         variableKey  Key of the variable whose value is being\n     *                                       accessed\n     * @param  {string}         userId       ID for the user\n     * @param  {UserAttributes} attributes   Optional user attributes\n     * @return {unknown}                     Object value of the variable, or null if the\n     *                                       feature key is invalid, the variable key is\n     *                                       invalid, or there is a mismatch with the type\n     *                                       of the variable\n     */\n    getFeatureVariableJSON(featureKey, variableKey, userId, attributes) {\n        try {\n            if (!this.getProjectConfig()) {\n                this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'getFeatureVariableJSON');\n                return null;\n            }\n            return this.getFeatureVariableForType(featureKey, variableKey, FEATURE_VARIABLE_TYPES.JSON, userId, attributes);\n        }\n        catch (e) {\n            this.errorReporter.report(e);\n            return null;\n        }\n    }\n    /**\n     * Returns values for all the variables attached to the given feature\n     * flag.\n     * @param  {string}         featureKey   Key of the feature whose variables are being\n     *                                       accessed\n     * @param  {string}         userId       ID for the user\n     * @param  {UserAttributes} attributes   Optional user attributes\n     * @return {object|null}                 Object containing all the variables, or null if the\n     *                                       feature key is invalid\n     */\n    getAllFeatureVariables(featureKey, userId, attributes) {\n        try {\n            const configObj = this.getProjectConfig();\n            if (!configObj) {\n                this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'getAllFeatureVariables');\n                return null;\n            }\n            if (!this.validateInputs({ feature_key: featureKey, user_id: userId }, attributes)) {\n                return null;\n            }\n            const featureFlag = projectConfig.getFeatureFromKey(configObj, featureKey, this.logger);\n            if (!featureFlag) {\n                return null;\n            }\n            const user = this.createInternalUserContext(userId, attributes);\n            const decisionObj = this.decisionService.getVariationForFeature(configObj, featureFlag, user).result;\n            const featureEnabled = decision.getFeatureEnabledFromVariation(decisionObj);\n            const allVariables = {};\n            featureFlag.variables.forEach((variable) => {\n                allVariables[variable.key] = this.getFeatureVariableValueFromVariation(featureKey, featureEnabled, decisionObj.variation, variable, userId);\n            });\n            let sourceInfo = {};\n            if (decisionObj.decisionSource === DECISION_SOURCES.FEATURE_TEST &&\n                decisionObj.experiment !== null &&\n                decisionObj.variation !== null) {\n                sourceInfo = {\n                    experimentKey: decisionObj.experiment.key,\n                    variationKey: decisionObj.variation.key,\n                };\n            }\n            this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.DECISION, {\n                type: DECISION_NOTIFICATION_TYPES.ALL_FEATURE_VARIABLES,\n                userId: userId,\n                attributes: attributes || {},\n                decisionInfo: {\n                    featureKey: featureKey,\n                    featureEnabled: featureEnabled,\n                    source: decisionObj.decisionSource,\n                    variableValues: allVariables,\n                    sourceInfo: sourceInfo,\n                },\n            });\n            return allVariables;\n        }\n        catch (e) {\n            this.errorReporter.report(e);\n            return null;\n        }\n    }\n    /**\n     * Returns OptimizelyConfig object containing experiments and features data\n     * @return {OptimizelyConfig|null}\n     *\n     * OptimizelyConfig Object Schema\n     * {\n     *   'experimentsMap': {\n     *     'my-fist-experiment': {\n     *       'id': '111111',\n     *       'key': 'my-fist-experiment'\n     *       'variationsMap': {\n     *         'variation_1': {\n     *           'id': '121212',\n     *           'key': 'variation_1',\n     *           'variablesMap': {\n     *             'age': {\n     *               'id': '222222',\n     *               'key': 'age',\n     *               'type': 'integer',\n     *               'value': '0',\n     *             }\n     *           }\n     *         }\n     *       }\n     *     }\n     *   },\n     *   'featuresMap': {\n     *     'awesome-feature': {\n     *       'id': '333333',\n     *       'key': 'awesome-feature',\n     *       'experimentsMap': Object,\n     *       'variationsMap': Object,\n     *     }\n     *   }\n     * }\n     */\n    getOptimizelyConfig() {\n        try {\n            const configObj = this.getProjectConfig();\n            if (!configObj) {\n                return null;\n            }\n            return this.projectConfigManager.getOptimizelyConfig() || null;\n        }\n        catch (e) {\n            this.errorReporter.report(e);\n            return null;\n        }\n    }\n    flushImmediately() {\n        const flushPromises = [];\n        if (!this.isRunning()) {\n            return Promise.resolve();\n        }\n        if (this.eventProcessor) {\n            flushPromises.push(this.eventProcessor.flushImmediately());\n        }\n        if (this.odpManager) {\n            flushPromises.push(this.odpManager.flushImmediately());\n        }\n        return Promise.all(flushPromises);\n    }\n    /**\n     * Stop background processes belonging to this instance, including:\n     *\n     * - Active datafile requests\n     * - Pending datafile requests\n     * - Pending event queue flushes\n     *\n     * In-flight datafile requests will be aborted. Any events waiting to be sent\n     * as part of a batched event request will be immediately flushed to the event\n     * dispatcher.\n     *\n     * Returns a Promise that fulfills after all in-flight event dispatcher requests\n     * (including any final request resulting from flushing the queue as described\n     * above) are complete. If there are no in-flight event dispatcher requests and\n     * no queued events waiting to be sent, returns an immediately-fulfilled Promise.\n     *\n     *\n     * NOTE: After close is called, this instance is no longer usable - any events\n     * generated will no longer be sent to the event dispatcher.\n     *\n     * @return {Promise}\n     */\n    close() {\n        this.stop();\n        return this.onTerminated();\n    }\n    stop() {\n        var _a, _b;\n        if (this.isDone()) {\n            return;\n        }\n        if (!this.isRunning()) {\n            this.startPromise.reject(new Error(sprintf(SERVICE_STOPPED_BEFORE_RUNNING, 'Client')));\n        }\n        this.state = ServiceState.Stopping;\n        this.projectConfigManager.stop();\n        (_a = this.eventProcessor) === null || _a === void 0 ? void 0 : _a.stop();\n        (_b = this.odpManager) === null || _b === void 0 ? void 0 : _b.stop();\n        this.notificationCenter.clearAllNotificationListeners();\n        this.cleanupTasks.forEach((onClose) => onClose());\n        Promise.all([\n            this.projectConfigManager.onTerminated(),\n            this.eventProcessor ? this.eventProcessor.onTerminated() : Promise.resolve(),\n            this.odpManager ? this.odpManager.onTerminated() : Promise.resolve(),\n        ]).then(() => {\n            this.state = ServiceState.Terminated;\n            this.stopPromise.resolve();\n        }).catch((err) => {\n            this.errorReporter.report(err);\n            this.state = ServiceState.Failed;\n            this.stopPromise.reject(err);\n        });\n    }\n    /**\n     * Returns a Promise that fulfills when this instance is ready to use (meaning\n     * it has a valid datafile), or rejects when it has failed to become ready within a period of\n     * time (configurable by the timeout property of the options argument), or when\n     * this instance is closed via the close method before it became ready.\n     *\n     * If a static project config manager with a valid datafile was provided in the constructor,\n     * the returned Promise is immediately fulfilled. If a polling config manager was provided,\n     * it will be used to fetch  a datafile, and the returned promise will fulfill if that fetch\n     * succeeds, or it will reject if the datafile fetch does not complete before the timeout.\n     * The default timeout is 30 seconds.\n     *\n     * The returned Promise is fulfilled with an unknown result which is not needed to\n     * be inspected to know that the instance is ready. If the promise is fulfilled, it\n     * is guaranteed that the instance is ready to use. If the promise is rejected, it\n     * means the instance is not ready to use, and the reason for the promise rejection\n     * will contain an error denoting the cause of failure.\n  \n     * @param  {Object=}          options\n     * @param  {number|undefined} options.timeout\n     * @return {Promise}\n     */\n    onReady(options) {\n        let timeoutValue;\n        if (typeof options === 'object' && options !== null) {\n            if (options.timeout !== undefined) {\n                timeoutValue = options.timeout;\n            }\n        }\n        if (!isSafeInteger(timeoutValue)) {\n            timeoutValue = DEFAULT_ONREADY_TIMEOUT;\n        }\n        const timeoutPromise = resolvablePromise();\n        const cleanupTaskId = this.nextCleanupTaskId++;\n        const onReadyTimeout = () => {\n            this.cleanupTasks.delete(cleanupTaskId);\n            timeoutPromise.reject(new Error(sprintf(ONREADY_TIMEOUT, timeoutValue)));\n        };\n        const readyTimeout = setTimeout(onReadyTimeout, timeoutValue);\n        this.cleanupTasks.set(cleanupTaskId, () => {\n            clearTimeout(readyTimeout);\n            timeoutPromise.reject(new Error(INSTANCE_CLOSED));\n        });\n        return Promise.race([this.onRunning().then(() => {\n                clearTimeout(readyTimeout);\n                this.cleanupTasks.delete(cleanupTaskId);\n            }), timeoutPromise]);\n    }\n    //============ decide ============//\n    /**\n     * Creates a context of the user for which decision APIs will be called.\n     *\n     * A user context will be created successfully even when the SDK is not fully configured yet, so no\n     * this.isValidInstance() check is performed here.\n     *\n     * @param  {string}          userId      (Optional) The user ID to be used for bucketing.\n     * @param  {UserAttributes}  attributes  (Optional) user attributes.\n     * @return {OptimizelyUserContext|null}  An OptimizelyUserContext associated with this OptimizelyClient or\n     *                                       throws if provided inputs are invalid\n     */\n    createUserContext(userId, attributes) {\n        var _a;\n        const userIdentifier = userId !== null && userId !== void 0 ? userId : (_a = this.vuidManager) === null || _a === void 0 ? void 0 : _a.getVuid();\n        if (userIdentifier === undefined || !this.validateInputs({ user_id: userIdentifier })) {\n            throw new Error(INVALID_IDENTIFIER);\n        }\n        if (!this.validateInputs({}, attributes)) {\n            throw new Error(INVALID_ATTRIBUTES);\n        }\n        const userContext = new OptimizelyUserContext({\n            optimizely: this,\n            userId: userIdentifier,\n            attributes,\n        });\n        this.onRunning().then(() => {\n            if (this.odpManager && this.isOdpIntegrated()) {\n                this.odpManager.identifyUser(userIdentifier);\n            }\n        }).catch(() => { });\n        return userContext;\n    }\n    /**\n     * Creates an internal context of the user for which decision APIs will be called.\n     *\n     * A user context will be created successfully even when the SDK is not fully configured yet, so no\n     * this.isValidInstance() check is performed here.\n     *\n     * @param  {string}          userId      The user ID to be used for bucketing.\n     * @param  {UserAttributes}  attributes  Optional user attributes.\n     * @return {OptimizelyUserContext|null}  An OptimizelyUserContext associated with this OptimizelyClient or\n     *                                       null if provided inputs are invalid\n     */\n    createInternalUserContext(userId, attributes) {\n        return new OptimizelyUserContext({\n            optimizely: this,\n            userId,\n            attributes,\n        });\n    }\n    decide(user, key, options = []) {\n        const configObj = this.getProjectConfig();\n        if (!configObj) {\n            this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'decide');\n            return newErrorDecision(key, user, [DECISION_MESSAGES.SDK_NOT_READY]);\n        }\n        return this.decideForKeys(user, [key], options, true)[key];\n    }\n    decideAsync(user, key, options = []) {\n        return __awaiter(this, void 0, void 0, function* () {\n            const configObj = this.getProjectConfig();\n            if (!configObj) {\n                this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'decide');\n                return newErrorDecision(key, user, [DECISION_MESSAGES.SDK_NOT_READY]);\n            }\n            const result = yield this.decideForKeysAsync(user, [key], options, true);\n            return result[key];\n        });\n    }\n    /**\n     * Get all decide options.\n     * @param  {OptimizelyDecideOption[]}          options   decide options\n     * @return {[key: string]: boolean}             Map of all provided decide options including default decide options\n     */\n    getAllDecideOptions(options) {\n        var _a;\n        const allDecideOptions = Object.assign({}, this.defaultDecideOptions);\n        if (!Array.isArray(options)) {\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(INVALID_DECIDE_OPTIONS);\n        }\n        else {\n            options.forEach(option => {\n                var _a;\n                // Filter out all provided decide options that are not in OptimizelyDecideOption[]\n                if (OptimizelyDecideOption[option]) {\n                    allDecideOptions[option] = true;\n                }\n                else {\n                    (_a = this.logger) === null || _a === void 0 ? void 0 : _a.warn(UNRECOGNIZED_DECIDE_OPTION, option);\n                }\n            });\n        }\n        return allDecideOptions;\n    }\n    /**\n     * Makes a decision for a given feature key.\n     *\n     * @param {OptimizelyUserContext} user - The user context associated with this Optimizely client.\n     * @param {string} key - The feature key for which a decision will be made.\n     * @param {DecisionObj} decisionObj - The decision object containing decision details.\n     * @param {DecisionReasons[]} reasons - An array of reasons for the decision.\n     * @param {Record<string, boolean>} options - A map of options for decision-making.\n     * @param {projectConfig.ProjectConfig} configObj - The project configuration object.\n     * @returns {OptimizelyDecision} - The decision object for the feature flag.\n     */\n    generateDecision(user, key, decisionObj, reasons, options, configObj) {\n        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;\n        const userId = user.getUserId();\n        const attributes = user.getAttributes();\n        const feature = configObj.featureKeyMap[key];\n        const decisionSource = decisionObj.decisionSource;\n        const experimentKey = (_b = (_a = decisionObj.experiment) === null || _a === void 0 ? void 0 : _a.key) !== null && _b !== void 0 ? _b : null;\n        const experimentId = (_d = (_c = decisionObj.experiment) === null || _c === void 0 ? void 0 : _c.id) !== null && _d !== void 0 ? _d : null;\n        const variationKey = (_f = (_e = decisionObj.variation) === null || _e === void 0 ? void 0 : _e.key) !== null && _f !== void 0 ? _f : null;\n        const variationId = (_h = (_g = decisionObj.variation) === null || _g === void 0 ? void 0 : _g.id) !== null && _h !== void 0 ? _h : null;\n        const flagEnabled = decision.getFeatureEnabledFromVariation(decisionObj);\n        const variablesMap = {};\n        let decisionEventDispatched = false;\n        if (flagEnabled) {\n            (_j = this.logger) === null || _j === void 0 ? void 0 : _j.info(FEATURE_ENABLED_FOR_USER, key, userId);\n        }\n        else {\n            (_k = this.logger) === null || _k === void 0 ? void 0 : _k.info(FEATURE_NOT_ENABLED_FOR_USER, key, userId);\n        }\n        if (!options[OptimizelyDecideOption.EXCLUDE_VARIABLES]) {\n            feature.variables.forEach(variable => {\n                variablesMap[variable.key] = this.getFeatureVariableValueFromVariation(key, flagEnabled, decisionObj.variation, variable, userId);\n            });\n        }\n        if (!options[OptimizelyDecideOption.DISABLE_DECISION_EVENT] &&\n            (decisionSource === DECISION_SOURCES.FEATURE_TEST ||\n                decisionSource === DECISION_SOURCES.HOLDOUT ||\n                (decisionSource === DECISION_SOURCES.ROLLOUT && projectConfig.getSendFlagDecisionsValue(configObj)))) {\n            this.sendImpressionEvent(decisionObj, key, userId, flagEnabled, attributes);\n            decisionEventDispatched = true;\n        }\n        const shouldIncludeReasons = options[OptimizelyDecideOption.INCLUDE_REASONS];\n        let reportedReasons = [];\n        if (shouldIncludeReasons) {\n            reportedReasons = reasons.map(reason => sprintf(reason[0], ...reason.slice(1)));\n        }\n        const featureInfo = {\n            flagKey: key,\n            enabled: flagEnabled,\n            variationKey: variationKey,\n            ruleKey: experimentKey,\n            variables: variablesMap,\n            reasons: reportedReasons,\n            decisionEventDispatched: decisionEventDispatched,\n            experimentId: experimentId,\n            variationId: variationId,\n        };\n        this.notificationCenter.sendNotifications(NOTIFICATION_TYPES.DECISION, {\n            type: DECISION_NOTIFICATION_TYPES.FLAG,\n            userId: userId,\n            attributes: attributes,\n            decisionInfo: featureInfo,\n        });\n        return {\n            variationKey: variationKey,\n            enabled: flagEnabled,\n            variables: variablesMap,\n            ruleKey: experimentKey,\n            flagKey: key,\n            userContext: user,\n            reasons: reportedReasons,\n        };\n    }\n    /**\n     * Returns an object of decision results for multiple flag keys and a user context.\n     * If the SDK finds an error for a key, the response will include a decision for the key showing reasons for the error.\n     * The SDK will always return an object of decisions. When it cannot process requests, it will return an empty object after logging the errors.\n     * @param     {OptimizelyUserContext}      user        A user context associated with this OptimizelyClient\n     * @param     {string[]}                   keys        An array of flag keys for which decisions will be made.\n     * @param     {OptimizelyDecideOption[]}  options     An array of options for decision-making.\n     * @return    {[key: string]: OptimizelyDecision}      An object of decision results mapped by flag keys.\n     */\n    decideForKeys(user, keys, options = [], ignoreEnabledFlagOption) {\n        return this.getDecisionForKeys('sync', user, keys, options, ignoreEnabledFlagOption).get();\n    }\n    decideForKeysAsync(user, keys, options = [], ignoreEnabledFlagOption) {\n        return this.getDecisionForKeys('async', user, keys, options, ignoreEnabledFlagOption).get();\n    }\n    getDecisionForKeys(op, user, keys, options = [], ignoreEnabledFlagOption) {\n        var _a;\n        const decisionMap = {};\n        const flagDecisions = {};\n        const decisionReasonsMap = {};\n        const configObj = this.getProjectConfig();\n        if (!configObj) {\n            this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'decideForKeys');\n            return Value.of(op, decisionMap);\n        }\n        if (keys.length === 0) {\n            return Value.of(op, decisionMap);\n        }\n        const allDecideOptions = this.getAllDecideOptions(options);\n        if (ignoreEnabledFlagOption) {\n            delete allDecideOptions[OptimizelyDecideOption.ENABLED_FLAGS_ONLY];\n        }\n        const validFlags = [];\n        for (const key of keys) {\n            const feature = configObj.featureKeyMap[key];\n            if (!feature) {\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(FEATURE_NOT_IN_DATAFILE, key);\n                decisionMap[key] = newErrorDecision(key, user, [sprintf(DECISION_MESSAGES.FLAG_KEY_INVALID, key)]);\n                continue;\n            }\n            validFlags.push(feature);\n        }\n        return this.decisionService.resolveVariationsForFeatureList(op, configObj, validFlags, user, allDecideOptions)\n            .then((decisionList) => {\n            for (let i = 0; i < validFlags.length; i++) {\n                const key = validFlags[i].key;\n                const decision = decisionList[i];\n                if (decision.error) {\n                    decisionMap[key] = newErrorDecision(key, user, decision.reasons.map(r => sprintf(r[0], ...r.slice(1))));\n                }\n                else {\n                    flagDecisions[key] = decision.result;\n                    decisionReasonsMap[key] = decision.reasons;\n                }\n            }\n            for (const validFlag of validFlags) {\n                const validKey = validFlag.key;\n                // if there is already a value for this flag, that must have come from \n                // the newErrorDecision above, so we skip it\n                if (decisionMap[validKey]) {\n                    continue;\n                }\n                const decision = this.generateDecision(user, validKey, flagDecisions[validKey], decisionReasonsMap[validKey], allDecideOptions, configObj);\n                if (!allDecideOptions[OptimizelyDecideOption.ENABLED_FLAGS_ONLY] || decision.enabled) {\n                    decisionMap[validKey] = decision;\n                }\n            }\n            return Value.of(op, decisionMap);\n        });\n    }\n    /**\n     * Returns an object of decision results for all active flag keys.\n     * @param     {OptimizelyUserContext}      user        A user context associated with this OptimizelyClient\n     * @param     {OptimizelyDecideOption[]}  options     An array of options for decision-making.\n     * @return    {[key: string]: OptimizelyDecision}      An object of all decision results mapped by flag keys.\n     */\n    decideAll(user, options = []) {\n        const decisionMap = {};\n        const configObj = this.getProjectConfig();\n        if (!configObj) {\n            this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'decideAll');\n            return decisionMap;\n        }\n        const allFlagKeys = Object.keys(configObj.featureKeyMap);\n        return this.decideForKeys(user, allFlagKeys, options);\n    }\n    decideAllAsync(user, options = []) {\n        return __awaiter(this, void 0, void 0, function* () {\n            const decisionMap = {};\n            const configObj = this.getProjectConfig();\n            if (!configObj) {\n                this.errorReporter.report(NO_PROJECT_CONFIG_FAILURE, 'decideAll');\n                return decisionMap;\n            }\n            const allFlagKeys = Object.keys(configObj.featureKeyMap);\n            return this.decideForKeysAsync(user, allFlagKeys, options);\n        });\n    }\n    /**\n     * Updates ODP Config with most recent ODP key, host, pixelUrl, and segments from the project config\n     */\n    updateOdpSettings() {\n        const projectConfig = this.getProjectConfig();\n        if (!projectConfig) {\n            return;\n        }\n        if (this.odpManager) {\n            this.odpManager.updateConfig(projectConfig.odpIntegrationConfig);\n        }\n    }\n    /**\n     * Sends an action as an ODP Event with optional custom parameters including type, identifiers, and data\n     * Note: Since this depends on this.odpManager, it must await Optimizely client's onReady() promise resolution.\n     * @param {string}              action         Subcategory of the event type (i.e. \"client_initialized\", \"identified\", or a custom action)\n     * @param {string}              type           (Optional) Type of event (Defaults to \"fullstack\")\n     * @param {Map<string, string>} identifiers    (Optional) Key-value map of user identifiers\n     * @param {Map<string, string>} data           (Optional) Event data in a key-value map.\n     */\n    sendOdpEvent(action, type, identifiers, data) {\n        var _a, _b;\n        if (!this.odpManager) {\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(ODP_MANAGER_MISSING, 'sendOdpEvent');\n            return;\n        }\n        try {\n            const odpEvent = new OdpEvent(type || '', action, identifiers, data);\n            this.odpManager.sendEvent(odpEvent);\n        }\n        catch (e) {\n            (_b = this.logger) === null || _b === void 0 ? void 0 : _b.error(ODP_EVENT_FAILED, e);\n        }\n    }\n    /**\n     * Checks if ODP (Optimizely Data Platform) is integrated into the project.\n     * @returns { boolean } `true` if ODP settings were found in the datafile otherwise `false`\n     */\n    isOdpIntegrated() {\n        var _a, _b, _c;\n        return (_c = (_b = (_a = this.getProjectConfig()) === null || _a === void 0 ? void 0 : _a.odpIntegrationConfig) === null || _b === void 0 ? void 0 : _b.integrated) !== null && _c !== void 0 ? _c : false;\n    }\n    /**\n     * Fetches list of qualified segments from ODP for a particular userId.\n     * @param {string}                          userId\n     * @param {Array<OptimizelySegmentOption>}  options\n     * @returns {Promise<string[] | null>}\n     */\n    fetchQualifiedSegments(userId, options) {\n        var _a;\n        return __awaiter(this, void 0, void 0, function* () {\n            if (!this.odpManager) {\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(ODP_MANAGER_MISSING, 'fetchQualifiedSegments');\n                return null;\n            }\n            return yield this.odpManager.fetchQualifiedSegments(userId, options);\n        });\n    }\n    /**\n     * @returns {string|undefined}    Currently provisioned VUID from local ODP Manager or undefined if\n     *                                ODP Manager has not been instantiated yet for any reason.\n     */\n    getVuid() {\n        var _a;\n        if (!this.vuidManager) {\n            (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(UNABLE_TO_GET_VUID_VUID_MANAGER_NOT_AVAILABLE);\n            return undefined;\n        }\n        return this.vuidManager.getVuid();\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","/****************************************************************************\n * Copyright 2017, 2020, 2022, Optimizely, Inc. and contributors                  *\n *                                                                          *\n * Licensed under the Apache License, Version 2.0 (the \"License\");          *\n * you may not use this file except in compliance with the License.         *\n * You may obtain a copy of the License at                                  *\n *                                                                          *\n *    http://www.apache.org/licenses/LICENSE-2.0                            *\n *                                                                          *\n * Unless required by applicable law or agreed to in writing, software      *\n * distributed under the License is distributed on an \"AS IS\" BASIS,        *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and      *\n * limitations under the License.                                           *\n ***************************************************************************/\nimport { INVALID_USER_PROFILE_SERVICE } from 'error_message';\nimport { OptimizelyError } from '../../error/optimizly_error';\n/**\n * Validates user's provided user profile service instance\n * @param  {unknown}  userProfileServiceInstance\n * @return {boolean} true if the instance is valid\n * @throws If the instance is not valid\n */\nexport function validate(userProfileServiceInstance) {\n    if (typeof userProfileServiceInstance === 'object' && userProfileServiceInstance !== null) {\n        if (typeof userProfileServiceInstance['lookup'] !== 'function') {\n            throw new OptimizelyError(INVALID_USER_PROFILE_SERVICE, \"Missing function 'lookup'\");\n        }\n        else if (typeof userProfileServiceInstance['save'] !== 'function') {\n            throw new OptimizelyError(INVALID_USER_PROFILE_SERVICE, \"Missing function 'save'\");\n        }\n        return true;\n    }\n    throw new OptimizelyError(INVALID_USER_PROFILE_SERVICE, 'Not an object');\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","/**\n * Copyright 2017, 2020, 2022 Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides utility method for validating that event tags user has provided are valid\n */\nimport { OptimizelyError } from '../../error/optimizly_error';\nimport { INVALID_EVENT_TAGS } from 'error_message';\n/**\n * Validates user's provided event tags\n * @param  {unknown}  eventTags\n * @return {boolean} true if event tags are valid\n * @throws If event tags are not valid\n */\nexport function validate(eventTags) {\n    if (typeof eventTags === 'object' && !Array.isArray(eventTags) && eventTags !== null) {\n        return true;\n    }\n    else {\n        throw new OptimizelyError(INVALID_EVENT_TAGS);\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=index.js.map","/**\n * Copyright 2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { __awaiter } from \"tslib\";\nimport { OptimizelyError } from \"../../../error/optimizly_error\";\nimport { CMAB_FETCH_FAILED, INVALID_CMAB_FETCH_RESPONSE } from \"../../../message/error_message\";\nimport { runWithRetry } from \"../../../utils/executor/backoff_retry_runner\";\nimport { sprintf } from \"../../../utils/fns\";\nimport { isSuccessStatusCode } from \"../../../utils/http_request_handler/http_util\";\nconst DEFAULT_CMAB_PREDICTION_ENDPOINT = 'https://prediction.cmab.optimizely.com/predict/%s';\nexport class DefaultCmabClient {\n    constructor(config) {\n        this.predictionEndpointTemplate = DEFAULT_CMAB_PREDICTION_ENDPOINT;\n        this.requestHandler = config.requestHandler;\n        this.retryConfig = config.retryConfig;\n        if (config.predictionEndpointTemplate) {\n            this.predictionEndpointTemplate = config.predictionEndpointTemplate;\n        }\n    }\n    fetchDecision(ruleId, userId, attributes, cmabUuid) {\n        var _a, _b;\n        return __awaiter(this, void 0, void 0, function* () {\n            const url = sprintf(this.predictionEndpointTemplate, ruleId);\n            const cmabAttributes = Object.keys(attributes).map((key) => ({\n                id: key,\n                value: attributes[key],\n                type: 'custom_attribute',\n            }));\n            const body = {\n                instances: [\n                    {\n                        visitorId: userId,\n                        experimentId: ruleId,\n                        attributes: cmabAttributes,\n                        cmabUUID: cmabUuid,\n                    }\n                ]\n            };\n            const variation = yield (this.retryConfig ?\n                runWithRetry(() => this.doFetch(url, JSON.stringify(body)), (_b = (_a = this.retryConfig).backoffProvider) === null || _b === void 0 ? void 0 : _b.call(_a), this.retryConfig.maxRetries).result : this.doFetch(url, JSON.stringify(body)));\n            return variation;\n        });\n    }\n    doFetch(url, data) {\n        return __awaiter(this, void 0, void 0, function* () {\n            const response = yield this.requestHandler.makeRequest(url, { 'Content-Type': 'application/json' }, 'POST', data).responsePromise;\n            if (!isSuccessStatusCode(response.statusCode)) {\n                return Promise.reject(new OptimizelyError(CMAB_FETCH_FAILED, response.statusCode));\n            }\n            const body = JSON.parse(response.body);\n            if (!this.validateResponse(body)) {\n                return Promise.reject(new OptimizelyError(INVALID_CMAB_FETCH_RESPONSE));\n            }\n            return String(body.predictions[0].variation_id);\n        });\n    }\n    validateResponse(body) {\n        return body.predictions && body.predictions.length > 0 && body.predictions[0].variation_id;\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=cmab_client.js.map","/**\n * Copyright 2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { __awaiter } from \"tslib\";\nimport { OptimizelyDecideOption } from \"../../../shared_types\";\nimport { v4 as uuidV4 } from 'uuid';\nimport murmurhash from \"murmurhash\";\nimport { SerialRunner } from \"../../../utils/executor/serial_runner\";\nimport { CMAB_CACHE_ATTRIBUTES_MISMATCH, CMAB_CACHE_HIT, CMAB_CACHE_MISS, IGNORE_CMAB_CACHE, INVALIDATE_CMAB_CACHE, RESET_CMAB_CACHE, } from 'log_message';\nconst SERIALIZER_BUCKETS = 1000;\nconst LOGGER_NAME = 'CmabService';\nexport class DefaultCmabService {\n    constructor(options) {\n        var _a;\n        this.serializers = Array.from({ length: SERIALIZER_BUCKETS }, () => new SerialRunner());\n        this.cmabCache = options.cmabCache;\n        this.cmabClient = options.cmabClient;\n        this.logger = options.logger;\n        (_a = this.logger) === null || _a === void 0 ? void 0 : _a.setName(LOGGER_NAME);\n    }\n    getSerializerIndex(userId, experimentId) {\n        const key = this.getCacheKey(userId, experimentId);\n        const hash = murmurhash.v3(key);\n        return Math.abs(hash) % SERIALIZER_BUCKETS;\n    }\n    getDecision(projectConfig, userContext, ruleId, options) {\n        return __awaiter(this, void 0, void 0, function* () {\n            const serializerIndex = this.getSerializerIndex(userContext.getUserId(), ruleId);\n            return this.serializers[serializerIndex].run(() => this.getDecisionInternal(projectConfig, userContext, ruleId, options));\n        });\n    }\n    getDecisionInternal(projectConfig, userContext, ruleId, options) {\n        var _a, _b, _c, _d, _e, _f;\n        return __awaiter(this, void 0, void 0, function* () {\n            const userId = userContext.getUserId();\n            const filteredAttributes = this.filterAttributes(projectConfig, userContext, ruleId);\n            if (options[OptimizelyDecideOption.IGNORE_CMAB_CACHE]) {\n                (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(IGNORE_CMAB_CACHE, userId, ruleId);\n                return this.fetchDecision(ruleId, userId, filteredAttributes);\n            }\n            if (options[OptimizelyDecideOption.RESET_CMAB_CACHE]) {\n                (_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug(RESET_CMAB_CACHE, userId, ruleId);\n                this.cmabCache.reset();\n            }\n            const cacheKey = this.getCacheKey(userId, ruleId);\n            if (options[OptimizelyDecideOption.INVALIDATE_USER_CMAB_CACHE]) {\n                (_c = this.logger) === null || _c === void 0 ? void 0 : _c.debug(INVALIDATE_CMAB_CACHE, userId, ruleId);\n                this.cmabCache.remove(cacheKey);\n            }\n            const cachedValue = yield this.cmabCache.lookup(cacheKey);\n            const attributesJson = JSON.stringify(filteredAttributes, Object.keys(filteredAttributes).sort());\n            const attributesHash = String(murmurhash.v3(attributesJson));\n            if (cachedValue) {\n                if (cachedValue.attributesHash === attributesHash) {\n                    (_d = this.logger) === null || _d === void 0 ? void 0 : _d.debug(CMAB_CACHE_HIT, userId, ruleId);\n                    return { variationId: cachedValue.variationId, cmabUuid: cachedValue.cmabUuid };\n                }\n                else {\n                    (_e = this.logger) === null || _e === void 0 ? void 0 : _e.debug(CMAB_CACHE_ATTRIBUTES_MISMATCH, userId, ruleId);\n                    this.cmabCache.remove(cacheKey);\n                }\n            }\n            else {\n                (_f = this.logger) === null || _f === void 0 ? void 0 : _f.debug(CMAB_CACHE_MISS, userId, ruleId);\n            }\n            const variation = yield this.fetchDecision(ruleId, userId, filteredAttributes);\n            this.cmabCache.save(cacheKey, {\n                attributesHash,\n                variationId: variation.variationId,\n                cmabUuid: variation.cmabUuid,\n            });\n            return variation;\n        });\n    }\n    fetchDecision(ruleId, userId, attributes) {\n        return __awaiter(this, void 0, void 0, function* () {\n            const cmabUuid = uuidV4();\n            const variationId = yield this.cmabClient.fetchDecision(ruleId, userId, attributes, cmabUuid);\n            return { variationId, cmabUuid };\n        });\n    }\n    filterAttributes(projectConfig, userContext, ruleId) {\n        const filteredAttributes = {};\n        const userAttributes = userContext.getAttributes();\n        const experiment = projectConfig.experimentIdMap[ruleId];\n        if (!experiment || !experiment.cmab) {\n            return filteredAttributes;\n        }\n        const cmabAttributeIds = experiment.cmab.attributeIds;\n        cmabAttributeIds.forEach((aid) => {\n            const attribute = projectConfig.attributeIdMap[aid];\n            if (userAttributes.hasOwnProperty(attribute.key)) {\n                filteredAttributes[attribute.key] = userAttributes[attribute.key];\n            }\n        });\n        return filteredAttributes;\n    }\n    getCacheKey(userId, ruleId) {\n        const len = userId.length;\n        return `${len}-${userId}-${ruleId}`;\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=cmab_service.js.map","export const transformCache = (cache, transformGet, transformSet) => {\n    const transform = (value, transformer) => {\n        if (value === undefined) {\n            return undefined;\n        }\n        return transformer(value);\n    };\n    const lookup = (key) => {\n        if (cache.operation === 'sync') {\n            return transform(cache.lookup(key), transformGet);\n        }\n        return cache.lookup(key).then((v) => transform(v, transformGet));\n    };\n    const save = (key, value) => {\n        return cache.save(key, transformSet(value));\n    };\n    const transformedCache = {\n        lookup,\n        save,\n    };\n    Object.setPrototypeOf(transformedCache, cache);\n    return transformedCache;\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=cache.js.map","import { extractLogger } from \"./logging/logger_factory\";\nimport { extractErrorNotifier } from \"./error/error_notifier_factory\";\nimport { extractConfigManager } from \"./project_config/config_manager_factory\";\nimport { extractEventProcessor } from \"./event_processor/event_processor_factory\";\nimport { extractOdpManager } from \"./odp/odp_manager_factory\";\nimport { extractVuidManager } from \"./vuid/vuid_manager_factory\";\nimport { CLIENT_VERSION, DEFAULT_CMAB_BACKOFF_MS, DEFAULT_CMAB_CACHE_SIZE, DEFAULT_CMAB_CACHE_TIMEOUT_MS, DEFAULT_CMAB_RETRIES, JAVASCRIPT_CLIENT_ENGINE } from \"./utils/enums\";\nimport Optimizely from \"./optimizely\";\nimport { DefaultCmabClient } from \"./core/decision_service/cmab/cmab_client\";\nimport { DefaultCmabService } from \"./core/decision_service/cmab/cmab_service\";\nimport { InMemoryLruCache } from \"./utils/cache/in_memory_lru_cache\";\nimport { transformCache } from \"./utils/cache/cache\";\nimport { ConstantBackoff } from \"./utils/repeater/repeater\";\nexport const getOptimizelyInstance = (config) => {\n    var _a, _b;\n    const { clientEngine, clientVersion, jsonSchemaValidator, userProfileService, userProfileServiceAsync, defaultDecideOptions, disposable, requestHandler, } = config;\n    const projectConfigManager = extractConfigManager(config.projectConfigManager);\n    const eventProcessor = extractEventProcessor(config.eventProcessor);\n    const odpManager = extractOdpManager(config.odpManager);\n    const vuidManager = extractVuidManager(config.vuidManager);\n    const errorNotifier = extractErrorNotifier(config.errorNotifier);\n    const logger = extractLogger(config.logger);\n    const cmabClient = new DefaultCmabClient({\n        requestHandler,\n        retryConfig: {\n            maxRetries: DEFAULT_CMAB_RETRIES,\n            backoffProvider: () => new ConstantBackoff(DEFAULT_CMAB_BACKOFF_MS),\n        },\n        predictionEndpointTemplate: (_a = config.cmab) === null || _a === void 0 ? void 0 : _a.predictionEndpointTemplate,\n    });\n    const cmabCache = ((_b = config.cmab) === null || _b === void 0 ? void 0 : _b.cache) ?\n        transformCache(config.cmab.cache, (value) => JSON.parse(value), (value) => JSON.stringify(value)) :\n        (() => {\n            var _a, _b;\n            const cacheSize = ((_a = config.cmab) === null || _a === void 0 ? void 0 : _a.cacheSize) || DEFAULT_CMAB_CACHE_SIZE;\n            const cacheTtl = ((_b = config.cmab) === null || _b === void 0 ? void 0 : _b.cacheTtl) || DEFAULT_CMAB_CACHE_TIMEOUT_MS;\n            return new InMemoryLruCache(cacheSize, cacheTtl);\n        })();\n    const cmabService = new DefaultCmabService({\n        cmabClient,\n        cmabCache,\n        logger: logger === null || logger === void 0 ? void 0 : logger.child()\n    });\n    const optimizelyOptions = {\n        cmabService,\n        clientEngine: clientEngine || JAVASCRIPT_CLIENT_ENGINE,\n        clientVersion: clientVersion || CLIENT_VERSION,\n        jsonSchemaValidator,\n        userProfileService,\n        userProfileServiceAsync,\n        defaultDecideOptions,\n        disposable,\n        logger,\n        errorNotifier,\n        projectConfigManager,\n        eventProcessor,\n        odpManager,\n        vuidManager,\n        // UNSTABLE_conditionEvaluators is not exposed in the public types, but we want to pass it through\n        // for internal use cases.\n        UNSTABLE_conditionEvaluators: config.UNSTABLE_conditionEvaluators,\n    };\n    return new Optimizely(optimizelyOptions);\n};\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=client_factory.js.map","/**\n * Copyright 2022-2023, 2025 Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport http from 'http';\nimport https from 'https';\nimport url from 'url';\nimport decompressResponse from 'decompress-response';\nimport { REQUEST_TIMEOUT_MS } from '../enums';\nimport { NO_STATUS_CODE_IN_RESPONSE, REQUEST_ERROR, REQUEST_TIMEOUT, UNSUPPORTED_PROTOCOL } from 'error_message';\nimport { OptimizelyError } from '../../error/optimizly_error';\n/**\n * Handles sending requests and receiving responses over HTTP via NodeJS http module\n */\nexport class NodeRequestHandler {\n    constructor(opt = {}) {\n        var _a;\n        this.logger = opt.logger;\n        this.timeout = (_a = opt.timeout) !== null && _a !== void 0 ? _a : REQUEST_TIMEOUT_MS;\n    }\n    /**\n     * Builds an XMLHttpRequest\n     * @param requestUrl Fully-qualified URL to which to send the request\n     * @param headers List of headers to include in the request\n     * @param method HTTP method to use\n     * @param data? stringified version of data to POST, PUT, etc\n     * @returns AbortableRequest contains both the response Promise and capability to abort()\n     */\n    makeRequest(requestUrl, headers, method, data) {\n        const parsedUrl = url.parse(requestUrl);\n        if (parsedUrl.protocol !== 'https:' && parsedUrl.protocol !== 'http:') {\n            return {\n                responsePromise: Promise.reject(new OptimizelyError(UNSUPPORTED_PROTOCOL, parsedUrl.protocol)),\n                abort: () => { },\n            };\n        }\n        const requestModule = parsedUrl.protocol === 'https:' ? https : http;\n        const request = requestModule.request(Object.assign(Object.assign({}, this.getRequestOptionsFromUrl(parsedUrl)), { method, headers: Object.assign(Object.assign({}, headers), { 'accept-encoding': 'gzip,deflate', 'content-length': String((data === null || data === void 0 ? void 0 : data.length) || 0) }), timeout: this.timeout }));\n        const abortableRequest = this.getAbortableRequestFromRequest(request);\n        if (data) {\n            request.write(data);\n        }\n        request.end();\n        return abortableRequest;\n    }\n    /**\n     * Parses a URL into its constituent parts\n     * @param url URL object to parse\n     * @private\n     * @returns http.RequestOptions Standard request options dictionary compatible with both http and https\n     */\n    getRequestOptionsFromUrl(url) {\n        return {\n            hostname: url.hostname,\n            path: url.path,\n            port: url.port,\n            protocol: url.protocol,\n        };\n    }\n    /**\n     * Parses headers from an http response\n     * @param incomingMessage Incoming response message to parse\n     * @private\n     * @returns Headers Dictionary of headers without duplicates\n     */\n    createHeadersFromNodeIncomingMessage(incomingMessage) {\n        const headers = {};\n        Object.keys(incomingMessage.headers).forEach(headerName => {\n            const headerValue = incomingMessage.headers[headerName];\n            if (typeof headerValue === 'string') {\n                headers[headerName] = headerValue;\n            }\n            else if (typeof headerValue === 'undefined') {\n                // no value provided for this header\n            }\n            else {\n                // array\n                if (headerValue.length > 0) {\n                    // We don't care about multiple values - just take the first one\n                    headers[headerName] = headerValue[0];\n                }\n            }\n        });\n        return headers;\n    }\n    /**\n     * Sends a built request handling response, errors, and events around the transmission\n     * @param request Request to send\n     * @private\n     * @returns AbortableRequest with simplified response promise\n     */\n    getAbortableRequestFromRequest(request) {\n        let aborted = false;\n        const abort = () => {\n            aborted = true;\n            request.destroy();\n        };\n        const responsePromise = new Promise((resolve, reject) => {\n            request.on('timeout', () => {\n                aborted = true;\n                request.destroy();\n                reject(new OptimizelyError(REQUEST_TIMEOUT));\n            });\n            // eslint-disable-next-line @typescript-eslint/no-explicit-any\n            request.on('error', (err) => {\n                if (err instanceof Error) {\n                    reject(err);\n                }\n                else if (typeof err === 'string') {\n                    reject(new Error(err));\n                }\n                else {\n                    reject(new OptimizelyError(REQUEST_ERROR));\n                }\n            });\n            request.once('response', (incomingMessage) => {\n                if (aborted) {\n                    return;\n                }\n                const response = decompressResponse(incomingMessage);\n                response.setEncoding('utf8');\n                let responseData = '';\n                response.on('data', (chunk) => {\n                    if (!aborted) {\n                        responseData += chunk;\n                    }\n                });\n                response.on('end', () => {\n                    if (aborted) {\n                        return;\n                    }\n                    if (!incomingMessage.statusCode) {\n                        reject(new OptimizelyError(NO_STATUS_CODE_IN_RESPONSE));\n                        return;\n                    }\n                    resolve({\n                        statusCode: incomingMessage.statusCode,\n                        body: responseData,\n                        headers: this.createHeadersFromNodeIncomingMessage(incomingMessage),\n                    });\n                });\n            });\n        });\n        return { abort, responsePromise };\n    }\n}\nexport const __platforms = ['node'];\n//# sourceMappingURL=request_handler.node.js.map","import { NodeRequestHandler } from '../../utils/http_request_handler/request_handler.node';\nimport { DefaultEventDispatcher } from './default_dispatcher';\nconst eventDispatcher = new DefaultEventDispatcher(new NodeRequestHandler());\nexport default eventDispatcher;\nexport const __platforms = ['node'];\n//# sourceMappingURL=default_dispatcher.node.js.map","import { __awaiter } from \"tslib\";\n/**\n * Copyright 2024, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { OptimizelyError } from '../../error/optimizly_error';\nimport { ONLY_POST_REQUESTS_ARE_SUPPORTED } from 'error_message';\nexport class DefaultEventDispatcher {\n    constructor(requestHandler) {\n        this.requestHandler = requestHandler;\n    }\n    dispatchEvent(eventObj) {\n        return __awaiter(this, void 0, void 0, function* () {\n            // Non-POST requests not supported\n            if (eventObj.httpVerb !== 'POST') {\n                return Promise.reject(new OptimizelyError(ONLY_POST_REQUESTS_ARE_SUPPORTED));\n            }\n            const dataString = JSON.stringify(eventObj.params);\n            const headers = {\n                'content-type': 'application/json',\n            };\n            const abortableRequest = this.requestHandler.makeRequest(eventObj.url, headers, 'POST', dataString);\n            return abortableRequest.responsePromise;\n        });\n    }\n}\nexport const __platforms = ['__universal__'];\n//# sourceMappingURL=default_dispatcher.js.map","/**\n * Copyright 2024-2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { NodeRequestHandler } from \"../utils/http_request_handler/request_handler.node\";\nimport { getOpaquePollingConfigManager } from \"./config_manager_factory\";\nexport const createPollingProjectConfigManager = (config) => {\n    const defaultConfig = {\n        autoUpdate: true,\n        requestHandler: new NodeRequestHandler(),\n    };\n    return getOpaquePollingConfigManager(Object.assign(Object.assign({}, defaultConfig), config));\n};\nexport const __platforms = ['node'];\n//# sourceMappingURL=config_manager_factory.node.js.map","import defaultEventDispatcher from './event_dispatcher/default_dispatcher.node';\nimport { FAILED_EVENT_RETRY_INTERVAL, getOpaqueBatchEventProcessor, getPrefixEventStore, wrapEventProcessor, getForwardingEventProcessor, } from './event_processor_factory';\nexport const DEFAULT_EVENT_BATCH_SIZE = 10;\nexport const DEFAULT_EVENT_FLUSH_INTERVAL = 30000;\nexport const EVENT_MAX_RETRIES_NODE = 2;\nexport const createForwardingEventProcessor = (eventDispatcher = defaultEventDispatcher) => {\n    return wrapEventProcessor(getForwardingEventProcessor(eventDispatcher));\n};\nexport const createBatchEventProcessor = (options = {}) => {\n    var _a;\n    const eventStore = options.eventStore ? getPrefixEventStore(options.eventStore) : undefined;\n    return getOpaqueBatchEventProcessor({\n        eventDispatcher: options.eventDispatcher || defaultEventDispatcher,\n        closingEventDispatcher: options.closingEventDispatcher,\n        flushInterval: options.flushInterval,\n        batchSize: options.batchSize,\n        defaultFlushInterval: DEFAULT_EVENT_FLUSH_INTERVAL,\n        defaultBatchSize: DEFAULT_EVENT_BATCH_SIZE,\n        retryOptions: {\n            maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : EVENT_MAX_RETRIES_NODE,\n        },\n        failedEventRetryInterval: eventStore ? FAILED_EVENT_RETRY_INTERVAL : undefined,\n        eventStore,\n    });\n};\nexport const __platforms = ['node'];\n//# sourceMappingURL=event_processor_factory.node.js.map","/**\n * Copyright 2024-2025, Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { NodeRequestHandler } from '../utils/http_request_handler/request_handler.node';\nimport { eventApiRequestGenerator } from './event_manager/odp_event_api_manager';\nimport { getOpaqueOdpManager } from './odp_manager_factory';\nexport const NODE_DEFAULT_API_TIMEOUT = 10000;\nexport const NODE_DEFAULT_BATCH_SIZE = 10;\nexport const NODE_DEFAULT_FLUSH_INTERVAL = 1000;\nexport const createOdpManager = (options = {}) => {\n    const segmentRequestHandler = new NodeRequestHandler({\n        timeout: options.segmentsApiTimeout || NODE_DEFAULT_API_TIMEOUT,\n    });\n    const eventRequestHandler = new NodeRequestHandler({\n        timeout: options.eventApiTimeout || NODE_DEFAULT_API_TIMEOUT,\n    });\n    return getOpaqueOdpManager(Object.assign(Object.assign({}, options), { segmentRequestHandler,\n        eventRequestHandler, eventBatchSize: options.eventBatchSize || NODE_DEFAULT_BATCH_SIZE, eventFlushInterval: options.eventFlushInterval || NODE_DEFAULT_FLUSH_INTERVAL, eventRequestGenerator: eventApiRequestGenerator }));\n};\nexport const __platforms = ['node'];\n//# sourceMappingURL=odp_manager_factory.node.js.map","/**\n* Copyright 2024-2025, Optimizely\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* https://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\nimport { wrapVuidManager } from './vuid_manager_factory';\nexport const createVuidManager = (options = {}) => {\n    return wrapVuidManager(undefined);\n};\nexport const __platforms = ['node'];\n//# sourceMappingURL=vuid_manager_factory.node.js.map","/**\n * Copyright 2016-2017, 2019-2025 Optimizely\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { NODE_CLIENT_ENGINE } from './utils/enums';\nimport { getOptimizelyInstance } from './client_factory';\nimport { NodeRequestHandler } from './utils/http_request_handler/request_handler.node';\n/**\n * Creates an instance of the Optimizely class\n * @param  {Config} config\n * @return {Client|null} the Optimizely client object\n *                           null on error\n */\nexport const createInstance = function (config) {\n    const nodeConfig = Object.assign(Object.assign({}, config), { clientEngine: config.clientEngine || NODE_CLIENT_ENGINE, requestHandler: new NodeRequestHandler() });\n    return getOptimizelyInstance(nodeConfig);\n};\nexport const getSendBeaconEventDispatcher = function () {\n    return undefined;\n};\nexport { default as eventDispatcher } from './event_processor/event_dispatcher/default_dispatcher.node';\nexport { createPollingProjectConfigManager } from './project_config/config_manager_factory.node';\nexport { createForwardingEventProcessor, createBatchEventProcessor } from './event_processor/event_processor_factory.node';\nexport { createOdpManager } from './odp/odp_manager_factory.node';\nexport { createVuidManager } from './vuid/vuid_manager_factory.node';\nexport * from './common_exports';\nexport * from './export_types';\nexport const clientEngine = NODE_CLIENT_ENGINE;\nexport const __platforms = ['node'];\n//# sourceMappingURL=index.node.js.map"],"names":["CONTROL_ATTRIBUTES","JAVASCRIPT_CLIENT_ENGINE","NODE_CLIENT_ENGINE","CLIENT_VERSION","DECISION_SOURCES","FEATURE_TEST","ROLLOUT","EXPERIMENT","HOLDOUT","AUDIENCE_EVALUATION_TYPES","FEATURE_VARIABLE_TYPES","DATAFILE_VERSIONS","DECISION_MESSAGES","MAX_SAFE_INTEGER_LIMIT","Math","pow","isSafeInteger","number","abs","keyBy","arr","key","base","assignBy","forEach","e","objectValues","obj","Object","keys","map","objectEntries","find","cond","found","item","sprintf","format","args","i","replace","arg","type","String","checkArrayEquality","arrayA","arrayB","length","every","index","LogLevel","fns","currentTimestamp","round","Date","getTime","uuid","v4","isNumber","value","getTimestamp","groupBy","grouperFn","grouper","push","OptimizelyError","Error","constructor","baseMessage","params","super","this","resolved","name","setPrototypeOf","prototype","setMessage","resolver","message","resolve","LogLevelToUpper","Debug","Info","Warn","LogLevelToLower","ConsoleLogHandler","prefix","log","level","consoleLog","toISOString","logLevel","console","call","OptimizelyLogger","config","logHandler","infoResolver","infoMsgResolver","errorResolver","errorMsgResolver","setName","child","info","debug","warn","error","handleLog","resolvedMessage","UNEXPECTED_TYPE_NULL","messages","FEATURE_NOT_IN_DATAFILE","INVALID_USER_PROFILE_SERVICE","NO_PROJECT_CONFIG_FAILURE","UNABLE_TO_CAST_VALUE","UNEXPECTED_CONDITION_VALUE","UNEXPECTED_TYPE","UNKNOWN_MATCH_TYPE","messageNum","parseInt","infoMessages","errorMessages","debugPreset","infoPreset","warnPreset","errorPreset","levelPresetSymbol","Symbol","DEBUG","INFO","WARN","ERROR","loggerSymbol","createLogger","preset","extractLevelPreset","validateLogHandler","DefaultErrorNotifier","errorHandler","messageResolver","notify","handleError","errorNotifierSymbol","createErrorNotifier","validateErrorHandler","DEFAULT_OPERATOR_TYPES","evaluate","conditions","leafEvaluator","Array","isArray","firstOperator","restOfConditions","slice","indexOf","sawNullResult","conditionResult","andEvaluator","result","notEvaluator","orEvaluator","OptimizelyConfig","configObj","datafile","logger","_a","_b","sdkKey","environmentKey","attributes","audiences","getAudiences","events","revision","featureIdVariablesMap","featureFlags","reduce","resultMap","feature","id","variables","variableIdMap","getVariableIdMap","experimentsMapById","experimentsMapByKey","getExperimentsMap","experimentsMap","featuresMap","getFeaturesMap","getDatafile","typedAudienceIds","typedAudiences","typedAudience","JSON","stringify","audience","getSerializedAudiences","audiencesById","serializedAudience","subAudience","toUpperCase","audienceName","concat","getExperimentAudiences","experiment","audienceConditions","mergeFeatureVariables","featureIdVariableMap","featureId","featureVariableUsages","isFeatureEnabled","variablesMap","optlyVariablesMap","featureVariable","defaultValue","featureVariableUsage","defaultVariable","optimizelyVariable","getVariationsMap","variations","variationsMap","optlyVariationsMap","variation","featureEnabled","variablesIdMap","variable","getDeliveryRules","featureVariableIdMap","experiments","getRolloutExperimentIds","rollouts","experimentIds","rollout","rolloutExperimentIds","featureIds","experimentFeatureMap","toString","optimizelyExperiment","getExperimentsKeyMap","experimentKeysMap","featureFlag","featureExperimentMap","experimentRules","experimentId","featureVariableMap","deliveryRules","rolloutIdMap","rolloutId","SUPPORTED_VERSIONS","configValidator","parse","ex","OdpConfig","apiKey","apiHost","pixelUrl","segmentsToCheck","equals","configToCompare","EXPERIMENT_RUNNING_STATUS","RESERVED_ATTRIBUTE_PREFIX","createProjectConfig","datafileObj","datafileStr","projectConfig","datafileCopy","assign","groups","group","groupCopy","rolloutCopy","createMutationSafeDatafileCopy","region","__datafileStr","attributeKeyMap","attributeIdMap","attribute","eventKeyMap","groupIdMap","Id","groupId","isRollout","variationKeyMap","allSegmentsSet","Set","getAudienceSegments","audienceSegments","segment","add","allSegments","from","odpIntegrated","odpApiHost","odpApiKey","odpPixelUrl","integrations","integrationKeyMap","integration","publicKey","host","odpIntegrationConfig","integrated","odpConfig","experimentKeyMap","experimentIdMap","variationIdMap","variationVariableUsageMap","featureKeyMap","subType","variableKeyMap","flagRulesMap","flagRuleExperiments","flagVariationsMap","flagKey","rules","rule","parseHoldoutsConfig","holdouts","holdoutIdMap","globalHoldouts","includedHoldouts","excludedHoldouts","flagHoldoutsMap","featureFlagIdMap","holdout","includedFlags","excludedFlags","flagId","flag","getSegmentsFromConditions","condition","segments","includes","isLogicalOperator","nextCondition","getExperimentStatus","experimentKey","status","getExperimentFromKey","hasOwnProperty","getFlagVariationByKey","variationKey","getFeatureFromKey","featureKey","getSendFlagDecisionsValue","sendFlagDecisions","noop","resolvablePromise","reject","promise","Promise","res","rej","then","bind","SERVICE_FAILED_TO_START","SERVICE_STOPPED_BEFORE_RUNNING","ServiceState","BaseService","startupLogs","disposable","state","New","startPromise","stopPromise","catch","makeDisposable","setLogger","printStartupLogs","methodName","onRunning","onTerminated","getState","isStarting","Starting","isRunning","Running","isNew","isDone","Stopping","Terminated","Failed","start","EventEmitter","listeners","on","eventName","listener","Map","curId","set","delete","emit","data","removeListeners","clear","removeAllListeners","ProjectConfigManagerImpl","eventEmitter","jsonSchemaValidator","datafileManager","_c","handleNewDatafile","onUpdate","err","handleDatafileManagerError","handleInitError","stop","newDatafile","fromConfig","newDatafileObj","createProjectConfigArgs","tryCreatingProjectConfig","optimizelyConfig","undefined","getConfig","getOptimizelyConfig","__awaiter","thisArg","_arguments","P","generator","fulfilled","step","next","rejected","done","apply","SuppressedError","isSuccessStatusCode","statusCode","PollingDatafileManager","autoUpdate","datafileAccessToken","customHeaders","urlTemplate","cache","initRetry","repeater","requestHandler","cacheKey","emitter","initRetryRemaining","urlTemplateToUse","datafileUrl","get","currentDatafile","setDatafileFromCacheIfAvailable","setTask","syncDatafile","min","currentRequest","abort","handleInitFailure","errorOrStatus","onRequestRejected","onRequestResolved","response","saveLastModified","headers","getDatafileFromResponse","handleDatafile","makeDatafileRequest","lastResponseLastModified","makeRequest","responsePromise","finally","body","lastModifiedHeader","ExponentialBackoff","max","maxJitter","current","backoff","ret","random","reset","ConstantBackoff","IntervalRepeater","interval","backoffController","failureCount","running","handleSuccess","setTimer","handleFailure","time","timeout","timeoutId","setTimeout","executeTask","task","immediateExecution","callback","queueMicrotask","clearInterval","validateStore","store","errors","method","join","INVALID_CONFIG_MANAGER","configManagerSymbol","createStaticProjectConfigManager","getPollingConfigManager","opt","updateInterval","DEFAULT_UPDATE_INTERVAL_MINUTES","MIN_UPDATE_INTERVAL_SECONDS","datafileManagerConfig","SyncStoreWithBatchedGet","operation","AsyncStoreWithBatchedGet","getBatchedSync","getBatched","getBatchedAsync","all","SyncPrefixStore","transformGet","transformSet","addPrefix","removePrefix","substring","remove","getInternalKeys","getKeys","filter","startsWith","AsyncPrefixStore","ACTIVATE_EVENT_KEY","CUSTOM_ATTRIBUTE_FEATURE_TYPE","logxEndpoint","US","EU","makeEventBatch","visitors","event","visitor","snapshots","visitor_id","user","attr","entity_id","entityId","context","botFiltering","makeVisitor","layer","ruleKey","ruleType","enabled","cmabUuid","layerId","variationId","decisions","campaign_id","experiment_id","variation_id","metadata","flag_key","rule_key","rule_type","variation_key","cmab_uuid","timestamp","makeDecisionSnapshot","conversion","tags","revenue","makeConversionSnapshot","client_name","clientName","client_version","clientVersion","account_id","accountId","project_id","projectId","anonymize_ip","anonymizeIP","enrich_decisions","buildLogEvent","url","httpVerb","runTask","returnPromise","cancelSignal","retryRemaining","cancelled","delay","runWithRetry","maxRetries","cancelRetry","IdGenerator","idSuffixOffset","getId","idSuffix","now","getExperimentKey","decisionObj","getVariationKey","getFeatureEnabledFromVariation","DECISION_NOTIFICATION_TYPES","AB_TEST","FEATURE","FEATURE_VARIABLE","ALL_FEATURE_VARIABLES","FLAG","NOTIFICATION_TYPES","ACTIVATE","DECISION","LOG_EVENT","OPTIMIZELY_CONFIG_UPDATE","TRACK","VariableType","OptimizelyDecideOption","areEventContextsEqual","eventA","eventB","contextA","contextB","buildBaseEvent","userId","userAttributes","clientEngine","buildVisitorAttributes","buildImpressionEvent","decisionSource","decision.getExperimentKey","decision.getExperimentId","decision.getVariationKey","decision.getVariationId","getLayerId","buildConversionEvent","eventKey","eventTags","eventId","getEventId","rawValue","parsedRevenueValue","trunc","isFinite","eventTagUtils.getRevenueValue","eventValue","parsedEventValue","parseFloat","eventTagUtils.getEventValue","builtAttributes","attributeKey","attributeValue","isAttributeValid","attributeId","hasReservedPrefix","getAttributeId","BatchEventProcessor","eventQueue","idGenerator","runningTask","dispatchingEvents","eventDispatcher","closingEventDispatcher","batchSize","eventStore","retryConfig","dispatchRepeater","flush","failedEventRepeater","retryFailedEvents","onDispatch","handler","k","has","failedEvents","sort","a","b","batches","currentBatch","request","batch","dispatchBatch","createNewBatch","eventWithIds","executeDispatch","closing","dispatchEvent","runResult","backoffProvider","taskId","useClosingDispatcher","process","eventWithId","flushImmediately","allSettled","values","SerialRunner","waitPromise","run","fn","resultPromise","EVENT_STORE_PREFIX","ForwardingEventProcessor","dispatcher","formattedEvent","eventProcessorSymbol","validateEventDispatcher","wrapEventProcessor","eventProcessor","getOpaqueBatchEventProcessor","options","EventProcessorConstructor","retryOptions","minBackoff","maxBackoff","defaultFlushInterval","defaultBatchSize","flushInterval","failedEventRetryInterval","getBatchEventProcessor","InMemoryLruCache","maxSize","ttl","lookup","element","expiresAt","save","size","firstMapEntryKey","DefaultOdpEventApiManager","requestDataGenerator","requestGenerator","sendEvents","endpoint","eventApiRequestGenerator","_","fromEntries","ODP_USER_KEY","ODP_EVENT_ACTION","ODP_DEFAULT_EVENT_TYPE","DefaultOdpEventManager","startUpLogs","queue","apiManager","goToRunningState","updateConfig","sendEvent","_d","_e","_f","identifiers","isDataValid","action","entries","FS_USER_ID_ALIAS","toLowerCase","FS_USER_ID","processEvent","validTypes","valid","OdpEvent","VUID_PREFIX","isVuid","vuid","DefaultOdpManager","segmentManager","eventManager","configPromise","userAgentParser","os","device","parseUserAgentInfo","userAgentInfo","os_version","version","device_type","model","userAgentData","setClientInfo","startDependencies","handleStartSuccess","handleStartFailure","config1","config2","fetchQualifiedSegments","VUID","identifyUser","finalUserId","finalVuid","IDENTIFIED","augmentCommonData","sourceData","uuidV4","setVuid","INITIALIZED","schema","$schema","title","properties","required","items","policy","trafficAllocation","endOfRange","audienceIds","forcedVariations","cmab","OdpResponseSchema","$id","customer","edges","node","examples","default","locations","line","column","path","extensions","classification","EMPTY_SEGMENTS_COLLECTION","AUDIENCE_FETCH_FAILURE_MESSAGE","DefaultOdpSegmentApiManager","toGraphQLJson","userKey","userValue","fetchSegments","_g","_h","_j","query","segmentsResponse","querySegments","parsedSegments","parseSegmentsResponseJson","code","edge","jsonResponse","jsonObject","validationSchema","shouldThrowOnError","property","validate","OptimizelySegmentOption","DefaultOdpSegmentManager","segmentsCache","odpSegmentApiManager","makeCacheKey","ignoreCache","IGNORE_CACHE","RESET_CACHE","cachedSegments","odpManagerSymbol","getDefaultSegmentManager","validateCache","cacheSize","segmentsCacheSize","cacheTimeout","segmentsCacheTimeout","segmentRequestHandler","getOdpManager","eventRequestHandler","eventRequestGenerator","eventBatchSize","eventFlushInterval","eventMaxRetries","eventMinBackoff","eventMaxBackoff","getDefaultEventManager","vuidManagerSymbol","ErrorReporter","errorNotifier","report","setErrorNotifier","DefaultNotificationCenter","removerId","removers","errorReporter","addNotificationListener","notificationType","returnId","remover","wrapWithErrorReporting","notificationData","removeNotificationListener","listenerId","clearAllNotificationListeners","clearNotificationListeners","sendNotifications","newErrorDecision","reasons","userContext","FORCED_DECISION_NULL_RULE_KEY","OptimizelyUserContext","optimizely","_qualifiedSegments","forcedDecisionsMap","setAttribute","getUserId","getAttributes","getOptimizely","qualifiedSegments","decide","cloneUserContext","decideAsync","decideForKeys","decideForKeysAsync","decideAll","decideAllAsync","trackEvent","track","setForcedDecision","decision","forcedDecision","getForcedDecision","findForcedDecision","removeForcedDecision","isForcedDecisionRemoved","removeAllForcedDecisions","validRuleKey","forcedDecisionByRuleKey","isQualifiedFor","MAX_HASH_VALUE","generateBucketValue","bucketingKey","ratio","murmurhash","v3","floor","USER_NOT_IN_ANY_EXPERIMENT","USER_NOT_BUCKETED_INTO_EXPERIMENT_IN_GROUP","USER_BUCKETED_INTO_EXPERIMENT_IN_GROUP","USER_ASSIGNED_TO_EXPERIMENT_BUCKET","INVALID_VARIATION_ID","bucket","bucketerParams","decideReasons","bucketedExperimentId","bucketUserIntoExperiment","bucketingId","bucketValue","_findBucket","trafficAllocationConfig","validateEntity","content","test","isPreReleaseVersion","preReleaseIndex","buildIndex","isBuildVersion","splitVersion","targetPrefix","targetSuffix","hasWhiteSpaces","dotCount","split","targetVersionParts","part","EXACT_MATCH_TYPE","EXISTS_MATCH_TYPE","SEMVER_EXACT_MATCH_TYPE","SEMVER_GREATER_OR_EQUAL_THAN_MATCH_TYPE","SEMVER_GREATER_THAN_MATCH_TYPE","SEMVER_LESS_OR_EQUAL_THAN_MATCH_TYPE","SEMVER_LESS_THAN_MATCH_TYPE","SUBSTRING_MATCH_TYPE","MATCH_TYPES","EVALUATORS_BY_MATCH_TYPE","exactEvaluator","conditionValue","validateValuesForNumericCondition","conditionName","userValueType","evaluateSemanticVersion","getEvaluator","conditionMatch","match","evaluatorForMatch","isValueTypeValidForExactConditions","conditionValueType","conditionsVersion","userProvidedVersion","userVersionParts","conditionsVersionParts","userVersionPartsLen","idx","userVersionPart","conditionsVersionPart","compareVersion","QUALIFIED_MATCH_TYPE","qualifiedEvaluator","evaluator","AudienceEvaluator","UNSTABLE_conditionEvaluators","typeToEvaluatorMap","custom_attribute","customAttributeConditionEvaluator.getEvaluator","third_party_dimension","odpSegmentsConditionEvaluator.getEvaluator","conditionTreeEvaluator.evaluate","audienceId","evaluateConditionWithUserAttributes","resultText","input","Value","op","val","newVal","of","isPromise","vals","v","promises","EXPERIMENT_NOT_RUNNING","RETURNING_STORED_VARIATION","USER_NOT_IN_EXPERIMENT","USER_HAS_NO_VARIATION","USER_HAS_VARIATION","USER_FORCED_IN_VARIATION","FORCED_BUCKETING_FAILED","EVALUATING_AUDIENCES_COMBINED","AUDIENCE_EVALUATION_RESULT_COMBINED","USER_IN_ROLLOUT","USER_NOT_IN_ROLLOUT","FEATURE_HAS_NO_EXPERIMENTS","USER_DOESNT_MEET_CONDITIONS_FOR_TARGETING_RULE","USER_NOT_BUCKETED_INTO_TARGETING_RULE","USER_BUCKETED_INTO_TARGETING_RULE","NO_ROLLOUT_EXISTS","INVALID_ROLLOUT_ID","ROLLOUT_HAS_NO_EXPERIMENTS","IMPROPERLY_FORMATTED_EXPERIMENT","USER_HAS_FORCED_VARIATION","USER_MEETS_CONDITIONS_FOR_TARGETING_RULE","USER_HAS_FORCED_DECISION_WITH_RULE_SPECIFIED","USER_HAS_FORCED_DECISION_WITH_NO_RULE_SPECIFIED","USER_HAS_FORCED_DECISION_WITH_RULE_SPECIFIED_BUT_INVALID","USER_HAS_FORCED_DECISION_WITH_NO_RULE_SPECIFIED_BUT_INVALID","CMAB_FETCH_FAILED","HOLDOUT_NOT_RUNNING","USER_MEETS_CONDITIONS_FOR_HOLDOUT","USER_DOESNT_MEET_CONDITIONS_FOR_HOLDOUT","USER_BUCKETED_INTO_HOLDOUT_VARIATION","USER_NOT_BUCKETED_INTO_HOLDOUT_VARIATION","DecisionService","audienceEvaluator","forcedVariationMap","userProfileService","userProfileServiceAsync","cmabService","isCmab","resolveVariation","decideOptions","userProfileTracker","isActive","decisionForcedVariation","getForcedVariation","forcedVariationKey","decisionWhitelistedVariation","getWhitelistedVariation","getStoredVariation","userProfile","decisionifUserIsInAudience","checkIfUserIsInAudience","getDecisionForCmabExperiment","getDecisionFromBucketer","variationResult","updateUserProfile","getBucketingId","buildBucketerParams","bucketerResult","cmabPromise","getDecision","cmabDecision","decisionVariation","getVariation","IGNORE_USER_PROFILE_SERVICE","isProfileUpdated","resolveExperimentBucketMap","saveUserProfile","fromAttributes","getUserProfile","fromUserProfileService","experiment_bucket_map","evaluationAttribute","loggingKey","experimentAudienceConditions","getVariationForHoldout","reason","audienceResult","bucketResult","bucketReason","noBucketReason","experimentBucketMap","emptyProfile","user_id","getVariationsForFeatureList","resolveVariationsForFeatureList","flagResults","resolveVariationForFlag","opFlagResults","forcedDecisionResponse","findValidatedForcedDecision","flagHoldouts","getHoldoutsForFlag","holdoutDecision","getVariationForFeatureExperiment","experimentDecision","rolloutDecision","getVariationForRollout","rolloutDecisionResult","getVariationForFeature","traverseFeatureExperimentList","fromIndex","getExperimentFromId","getVariationFromExperimentRule","rolloutRules","skipToEveryoneElse","rolloutRule","getVariationFromDeliveryRule","removeForcedVariation","setInForcedVariationMap","experimentToVariationMap","getVariationKeyFromId","setForcedVariation","stringValidator.validate","getVariationIdFromExperimentAndVariationKey","forcedVariation","ruleIndex","everyoneElse","bucketerVariationId","bucketedVariation","Optimizely","_k","_l","cleanupTasks","nextCleanupTaskId","projectConfigManager","odpManager","vuidManager","decideOptionsArray","defaultDecideOptions","option","notificationCenter","updateOdpSettings","userProfileServiceInstance","userProfileServiceValidator.validate","decisionService","createNotificationCenter","initialize","getVuid","getProjectConfig","activate","validateInputs","experiment_key","notActivatingExperiment","projectConfig.isRunning","projectConfig.getExperimentFromKey","sendImpressionEvent","impressionEvent","logEvent","activateNotificationPayload","event_key","projectConfig.eventWithKeyExists","filterEmptyValues","conversionEvent","createInternalUserContext","decisionNotificationType","decisionInfo","stringInputs","eventTagsValidator.validate","typedKey","feature_key","projectConfig.getFeatureFromKey","sourceInfo","decision.getFeatureEnabledFromVariation","projectConfig.getSendFlagDecisionsValue","featureInfo","source","getEnabledFeatures","enabledFeatures","getFeatureVariable","variableKey","getFeatureVariableForType","variableType","variable_key","projectConfig.getVariableForFeature","variableValue","getFeatureVariableValueFromVariation","variableUsage","projectConfig.getVariableValueForVariation","castValue","isNaN","projectConfig.getTypeCastValue","getFeatureVariableBoolean","getFeatureVariableDouble","getFeatureVariableInteger","getFeatureVariableString","getFeatureVariableJSON","getAllFeatureVariables","allVariables","variableValues","flushPromises","close","onClose","onReady","timeoutValue","timeoutPromise","cleanupTaskId","readyTimeout","clearTimeout","race","createUserContext","userIdentifier","isOdpIntegrated","getAllDecideOptions","allDecideOptions","generateDecision","flagEnabled","decisionEventDispatched","EXCLUDE_VARIABLES","DISABLE_DECISION_EVENT","reportedReasons","INCLUDE_REASONS","ignoreEnabledFlagOption","getDecisionForKeys","decisionMap","flagDecisions","decisionReasonsMap","ENABLED_FLAGS_ONLY","validFlags","decisionList","r","validFlag","validKey","allFlagKeys","sendOdpEvent","odpEvent","DefaultCmabClient","predictionEndpointTemplate","fetchDecision","ruleId","cmabAttributes","instances","visitorId","cmabUUID","doFetch","validateResponse","predictions","DefaultCmabService","serializers","cmabCache","cmabClient","getSerializerIndex","getCacheKey","hash","serializerIndex","getDecisionInternal","filteredAttributes","filterAttributes","IGNORE_CMAB_CACHE","RESET_CMAB_CACHE","INVALIDATE_USER_CMAB_CACHE","cachedValue","attributesJson","attributesHash","attributeIds","aid","getOptimizelyInstance","opaqueConfigManager","extractConfigManager","extractEventProcessor","manager","extractOdpManager","opaqueVuidManager","extractVuidManager","extractErrorNotifier","extractLogger","transform","transformer","transformedCache","transformCache","cacheTtl","optimizelyOptions","NodeRequestHandler","requestUrl","parsedUrl","protocol","https","http","getRequestOptionsFromUrl","abortableRequest","getAbortableRequestFromRequest","write","end","hostname","port","createHeadersFromNodeIncomingMessage","incomingMessage","headerName","headerValue","aborted","destroy","once","decompressResponse","setEncoding","responseData","chunk","eventObj","dataString","createPollingProjectConfigManager","defaultConfig","createForwardingEventProcessor","defaultEventDispatcher","createBatchEventProcessor","createOdpManager","segmentsApiTimeout","eventApiTimeout","getOpaqueOdpManager","createVuidManager","createInstance","nodeConfig","getSendBeaconEventDispatcher","__platforms"],"mappings":"0LAsBO,MAAMA,EACM,qBADNA,EAEK,oBAFLA,EAGa,6BAGbC,EAA2B,iBAC3BC,EAAqB,WAErBC,EAAiB,QAOjBC,EAAmB,CAC5BC,aAAc,eACdC,QAAS,UACTC,WAAY,aACZC,QAAS,WAEAC,EACH,OADGA,EAEG,aAKHC,EACA,UADAA,EAED,SAFCA,EAGA,UAHAA,EAID,SAJCA,EAKH,OAKGC,EACL,IADKA,EAEL,IAFKA,EAGL,IAEKC,EACM,8CADNA,EAES,kCCpDhBC,EAAyBC,KAAKC,IAAI,EAAG,IAIpC,SAASC,EAAcC,GAC1B,MAAwB,iBAAVA,GAAsBH,KAAKI,IAAID,IAAWJ,CAC5D,CACO,SAASM,EAAMC,EAAKC,GACvB,IAAKD,EACD,MAAO,CAAA,EACX,MAAME,EAAO,CAAA,EAEb,OADAC,EAASH,EAAKC,EAAKC,GACZA,CACX,CACO,SAASC,EAASH,EAAKC,EAAKC,GAC1BF,GAELA,EAAII,QAASC,IACTH,EAAKG,EAAEJ,IAAQI,GAEvB,CAmBO,SAASC,EAAaC,GACzB,OAAOC,OAAOC,KAAKF,GAAKG,IAAIT,GAAOM,EAAIN,GAC3C,CACO,SAASU,EAAcJ,GAC1B,OAAOC,OAAOC,KAAKF,GAAKG,IAAIT,GAAO,CAACA,EAAKM,EAAIN,IACjD,CACO,SAASW,EAAKZ,EAAKa,GACtB,IAAIC,EACJ,IAAK,MAAMC,KAAQf,EACf,GAAIa,EAAKE,GAAO,CACZD,EAAQC,EACR,KACJ,CAEJ,OAAOD,CACX,CAGO,SAASE,EAAQC,KAAWC,GAC/B,IAAIC,EAAI,EACR,OAAOF,EAAOG,QAAQ,MAAO,WACzB,MAAMC,EAAMH,EAAKC,KACXG,SAAcD,EACpB,MAAa,aAATC,EACOD,IAEO,WAATC,EACED,EAGAE,OAAOF,EAEtB,EACJ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