Created
June 14, 2021 15:41
-
-
Save thegreekjester/1d08111f4fcb59a346df9fc5cd976588 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { logger as logger$1 } from 'log'; | |
| import { httpRequest } from 'http-request'; | |
| import 'create-response'; | |
| import { Cookies } from 'cookies'; | |
| var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; | |
| function unwrapExports (x) { | |
| return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; | |
| } | |
| function createCommonjsModule(fn, module) { | |
| return module = { exports: {} }, fn(module, module.exports), module.exports; | |
| } | |
| var errorHandler = createCommonjsModule(function (module, exports) { | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| /** | |
| * @export | |
| * @class NoopErrorHandler | |
| * @implements {ErrorHandler} | |
| */ | |
| var NoopErrorHandler = /** @class */ (function () { | |
| function NoopErrorHandler() { | |
| } | |
| /** | |
| * @param {Error} exception | |
| * @memberof NoopErrorHandler | |
| */ | |
| NoopErrorHandler.prototype.handleError = function (exception) { | |
| // no-op | |
| return; | |
| }; | |
| return NoopErrorHandler; | |
| }()); | |
| exports.NoopErrorHandler = NoopErrorHandler; | |
| var globalErrorHandler = new NoopErrorHandler(); | |
| /** | |
| * @export | |
| * @param {ErrorHandler} handler | |
| */ | |
| function setErrorHandler(handler) { | |
| globalErrorHandler = handler; | |
| } | |
| exports.setErrorHandler = setErrorHandler; | |
| /** | |
| * @export | |
| * @returns {ErrorHandler} | |
| */ | |
| function getErrorHandler() { | |
| return globalErrorHandler; | |
| } | |
| exports.getErrorHandler = getErrorHandler; | |
| /** | |
| * @export | |
| */ | |
| function resetErrorHandler() { | |
| globalErrorHandler = new NoopErrorHandler(); | |
| } | |
| exports.resetErrorHandler = resetErrorHandler; | |
| }); | |
| unwrapExports(errorHandler); | |
| errorHandler.NoopErrorHandler; | |
| errorHandler.setErrorHandler; | |
| errorHandler.getErrorHandler; | |
| errorHandler.resetErrorHandler; | |
| var models = createCommonjsModule(function (module, exports) { | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| (function (LogLevel) { | |
| LogLevel[LogLevel["NOTSET"] = 0] = "NOTSET"; | |
| LogLevel[LogLevel["DEBUG"] = 1] = "DEBUG"; | |
| LogLevel[LogLevel["INFO"] = 2] = "INFO"; | |
| LogLevel[LogLevel["WARNING"] = 3] = "WARNING"; | |
| LogLevel[LogLevel["ERROR"] = 4] = "ERROR"; | |
| })(exports.LogLevel || (exports.LogLevel = {})); | |
| }); | |
| unwrapExports(models); | |
| models.LogLevel; | |
| var rngBrowser = createCommonjsModule(function (module) { | |
| // Unique ID creation requires a high quality random # generator. In the | |
| // browser this is a little complicated due to unknown quality of Math.random() | |
| // and inconsistent support for the `crypto` API. We do the best we can via | |
| // feature-detection | |
| // getRandomValues needs to be invoked in a context where "this" is a Crypto | |
| // implementation. Also, find the complete implementation of crypto on IE11. | |
| var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) || | |
| (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto)); | |
| if (getRandomValues) { | |
| // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto | |
| var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef | |
| module.exports = function whatwgRNG() { | |
| getRandomValues(rnds8); | |
| return rnds8; | |
| }; | |
| } else { | |
| // Math.random()-based (RNG) | |
| // | |
| // If all else fails, use Math.random(). It's fast, but is of unspecified | |
| // quality. | |
| var rnds = new Array(16); | |
| module.exports = function mathRNG() { | |
| for (var i = 0, r; i < 16; i++) { | |
| if ((i & 0x03) === 0) r = Math.random() * 0x100000000; | |
| rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; | |
| } | |
| return rnds; | |
| }; | |
| } | |
| }); | |
| /** | |
| * Convert array of 16 byte values to UUID string format of the form: | |
| * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX | |
| */ | |
| var byteToHex = []; | |
| for (var i = 0; i < 256; ++i) { | |
| byteToHex[i] = (i + 0x100).toString(16).substr(1); | |
| } | |
| function bytesToUuid(buf, offset) { | |
| var i = offset || 0; | |
| var bth = byteToHex; | |
| // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 | |
| return ([ | |
| bth[buf[i++]], bth[buf[i++]], | |
| bth[buf[i++]], bth[buf[i++]], '-', | |
| bth[buf[i++]], bth[buf[i++]], '-', | |
| bth[buf[i++]], bth[buf[i++]], '-', | |
| bth[buf[i++]], bth[buf[i++]], '-', | |
| bth[buf[i++]], bth[buf[i++]], | |
| bth[buf[i++]], bth[buf[i++]], | |
| bth[buf[i++]], bth[buf[i++]] | |
| ]).join(''); | |
| } | |
| var bytesToUuid_1 = bytesToUuid; | |
| // **`v1()` - Generate time-based UUID** | |
| // | |
| // Inspired by https://github.com/LiosK/UUID.js | |
| // and http://docs.python.org/library/uuid.html | |
| var _nodeId; | |
| var _clockseq; | |
| // Previous uuid creation time | |
| var _lastMSecs = 0; | |
| var _lastNSecs = 0; | |
| // See https://github.com/uuidjs/uuid for API details | |
| function v1(options, buf, offset) { | |
| var i = buf && offset || 0; | |
| var b = buf || []; | |
| options = options || {}; | |
| var node = options.node || _nodeId; | |
| var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; | |
| // node and clockseq need to be initialized to random values if they're not | |
| // specified. We do this lazily to minimize issues related to insufficient | |
| // system entropy. See #189 | |
| if (node == null || clockseq == null) { | |
| var seedBytes = rngBrowser(); | |
| if (node == null) { | |
| // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) | |
| node = _nodeId = [ | |
| seedBytes[0] | 0x01, | |
| seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5] | |
| ]; | |
| } | |
| if (clockseq == null) { | |
| // Per 4.2.2, randomize (14 bit) clockseq | |
| clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; | |
| } | |
| } | |
| // UUID timestamps are 100 nano-second units since the Gregorian epoch, | |
| // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so | |
| // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' | |
| // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. | |
| var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); | |
| // Per 4.2.1.2, use count of uuid's generated during the current clock | |
| // cycle to simulate higher resolution clock | |
| var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; | |
| // Time since last uuid creation (in msecs) | |
| var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; | |
| // Per 4.2.1.2, Bump clockseq on clock regression | |
| if (dt < 0 && options.clockseq === undefined) { | |
| clockseq = clockseq + 1 & 0x3fff; | |
| } | |
| // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new | |
| // time interval | |
| if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { | |
| nsecs = 0; | |
| } | |
| // Per 4.2.1.2 Throw error if too many uuids are requested | |
| if (nsecs >= 10000) { | |
| throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); | |
| } | |
| _lastMSecs = msecs; | |
| _lastNSecs = nsecs; | |
| _clockseq = clockseq; | |
| // Per 4.1.4 - Convert from unix epoch to Gregorian epoch | |
| msecs += 12219292800000; | |
| // `time_low` | |
| var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; | |
| b[i++] = tl >>> 24 & 0xff; | |
| b[i++] = tl >>> 16 & 0xff; | |
| b[i++] = tl >>> 8 & 0xff; | |
| b[i++] = tl & 0xff; | |
| // `time_mid` | |
| var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; | |
| b[i++] = tmh >>> 8 & 0xff; | |
| b[i++] = tmh & 0xff; | |
| // `time_high_and_version` | |
| b[i++] = tmh >>> 24 & 0xf | 0x10; // include version | |
| b[i++] = tmh >>> 16 & 0xff; | |
| // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) | |
| b[i++] = clockseq >>> 8 | 0x80; | |
| // `clock_seq_low` | |
| b[i++] = clockseq & 0xff; | |
| // `node` | |
| for (var n = 0; n < 6; ++n) { | |
| b[i + n] = node[n]; | |
| } | |
| return buf ? buf : bytesToUuid_1(b); | |
| } | |
| var v1_1 = v1; | |
| function v4(options, buf, offset) { | |
| var i = buf && offset || 0; | |
| if (typeof(options) == 'string') { | |
| buf = options === 'binary' ? new Array(16) : null; | |
| options = null; | |
| } | |
| options = options || {}; | |
| var rnds = options.random || (options.rng || rngBrowser)(); | |
| // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` | |
| rnds[6] = (rnds[6] & 0x0f) | 0x40; | |
| rnds[8] = (rnds[8] & 0x3f) | 0x80; | |
| // Copy bytes to buffer, if provided | |
| if (buf) { | |
| for (var ii = 0; ii < 16; ++ii) { | |
| buf[i + ii] = rnds[ii]; | |
| } | |
| } | |
| return buf || bytesToUuid_1(rnds); | |
| } | |
| var v4_1 = v4; | |
| var uuid = v4_1; | |
| uuid.v1 = v1_1; | |
| uuid.v4 = v4_1; | |
| var uuid_1 = uuid; | |
| var lib$3 = createCommonjsModule(function (module, exports) { | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| /** | |
| * Copyright 2019, Optimizely | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| function getTimestamp() { | |
| return new Date().getTime(); | |
| } | |
| exports.getTimestamp = getTimestamp; | |
| function generateUUID() { | |
| return uuid_1.v4(); | |
| } | |
| exports.generateUUID = generateUUID; | |
| /** | |
| * Validates a value is a valid TypeScript enum | |
| * | |
| * @export | |
| * @param {object} enumToCheck | |
| * @param {*} value | |
| * @returns {boolean} | |
| */ | |
| function isValidEnum(enumToCheck, value) { | |
| var found = false; | |
| var keys = Object.keys(enumToCheck); | |
| for (var index = 0; index < keys.length; index++) { | |
| if (value === enumToCheck[keys[index]]) { | |
| found = true; | |
| break; | |
| } | |
| } | |
| return found; | |
| } | |
| exports.isValidEnum = isValidEnum; | |
| function groupBy(arr, grouperFn) { | |
| var grouper = {}; | |
| arr.forEach(function (item) { | |
| var key = grouperFn(item); | |
| grouper[key] = grouper[key] || []; | |
| grouper[key].push(item); | |
| }); | |
| return objectValues(grouper); | |
| } | |
| exports.groupBy = groupBy; | |
| function objectValues(obj) { | |
| return Object.keys(obj).map(function (key) { return obj[key]; }); | |
| } | |
| exports.objectValues = objectValues; | |
| function find(arr, cond) { | |
| var found; | |
| for (var _i = 0, arr_1 = arr; _i < arr_1.length; _i++) { | |
| var item = arr_1[_i]; | |
| if (cond(item)) { | |
| found = item; | |
| break; | |
| } | |
| } | |
| return found; | |
| } | |
| exports.find = find; | |
| function keyBy(arr, keyByFn) { | |
| var map = {}; | |
| arr.forEach(function (item) { | |
| var key = keyByFn(item); | |
| map[key] = item; | |
| }); | |
| return map; | |
| } | |
| exports.keyBy = keyBy; | |
| function sprintf(format) { | |
| var args = []; | |
| for (var _i = 1; _i < arguments.length; _i++) { | |
| args[_i - 1] = arguments[_i]; | |
| } | |
| var i = 0; | |
| return format.replace(/%s/g, function () { | |
| var arg = args[i++]; | |
| var type = typeof arg; | |
| if (type === 'function') { | |
| return arg(); | |
| } | |
| else if (type === 'string') { | |
| return arg; | |
| } | |
| else { | |
| return String(arg); | |
| } | |
| }); | |
| } | |
| exports.sprintf = sprintf; | |
| }); | |
| unwrapExports(lib$3); | |
| lib$3.getTimestamp; | |
| lib$3.generateUUID; | |
| lib$3.isValidEnum; | |
| lib$3.groupBy; | |
| lib$3.objectValues; | |
| lib$3.find; | |
| lib$3.keyBy; | |
| lib$3.sprintf; | |
| var logger = createCommonjsModule(function (module, exports) { | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| /** | |
| * Copyright 2019, Optimizely | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| var stringToLogLevel = { | |
| NOTSET: 0, | |
| DEBUG: 1, | |
| INFO: 2, | |
| WARNING: 3, | |
| ERROR: 4, | |
| }; | |
| function coerceLogLevel(level) { | |
| if (typeof level !== 'string') { | |
| return level; | |
| } | |
| level = level.toUpperCase(); | |
| if (level === 'WARN') { | |
| level = 'WARNING'; | |
| } | |
| if (!stringToLogLevel[level]) { | |
| return level; | |
| } | |
| return stringToLogLevel[level]; | |
| } | |
| var DefaultLogManager = /** @class */ (function () { | |
| function DefaultLogManager() { | |
| this.defaultLoggerFacade = new OptimizelyLogger(); | |
| this.loggers = {}; | |
| } | |
| DefaultLogManager.prototype.getLogger = function (name) { | |
| if (!name) { | |
| return this.defaultLoggerFacade; | |
| } | |
| if (!this.loggers[name]) { | |
| this.loggers[name] = new OptimizelyLogger({ messagePrefix: name }); | |
| } | |
| return this.loggers[name]; | |
| }; | |
| return DefaultLogManager; | |
| }()); | |
| var ConsoleLogHandler = /** @class */ (function () { | |
| /** | |
| * Creates an instance of ConsoleLogger. | |
| * @param {ConsoleLogHandlerConfig} config | |
| * @memberof ConsoleLogger | |
| */ | |
| function ConsoleLogHandler(config) { | |
| if (config === void 0) { config = {}; } | |
| this.logLevel = models.LogLevel.NOTSET; | |
| if (config.logLevel !== undefined && lib$3.isValidEnum(models.LogLevel, config.logLevel)) { | |
| this.setLogLevel(config.logLevel); | |
| } | |
| this.logToConsole = config.logToConsole !== undefined ? !!config.logToConsole : true; | |
| this.prefix = config.prefix !== undefined ? config.prefix : '[OPTIMIZELY]'; | |
| } | |
| /** | |
| * @param {LogLevel} level | |
| * @param {string} message | |
| * @memberof ConsoleLogger | |
| */ | |
| ConsoleLogHandler.prototype.log = function (level, message) { | |
| if (!this.shouldLog(level) || !this.logToConsole) { | |
| return; | |
| } | |
| var logMessage = this.prefix + " - " + this.getLogLevelName(level) + " " + this.getTime() + " " + message; | |
| this.consoleLog(level, [logMessage]); | |
| }; | |
| /** | |
| * @param {LogLevel} level | |
| * @memberof ConsoleLogger | |
| */ | |
| ConsoleLogHandler.prototype.setLogLevel = function (level) { | |
| level = coerceLogLevel(level); | |
| if (!lib$3.isValidEnum(models.LogLevel, level) || level === undefined) { | |
| this.logLevel = models.LogLevel.ERROR; | |
| } | |
| else { | |
| this.logLevel = level; | |
| } | |
| }; | |
| /** | |
| * @returns {string} | |
| * @memberof ConsoleLogger | |
| */ | |
| ConsoleLogHandler.prototype.getTime = function () { | |
| return new Date().toISOString(); | |
| }; | |
| /** | |
| * @private | |
| * @param {LogLevel} targetLogLevel | |
| * @returns {boolean} | |
| * @memberof ConsoleLogger | |
| */ | |
| ConsoleLogHandler.prototype.shouldLog = function (targetLogLevel) { | |
| return targetLogLevel >= this.logLevel; | |
| }; | |
| /** | |
| * @private | |
| * @param {LogLevel} logLevel | |
| * @returns {string} | |
| * @memberof ConsoleLogger | |
| */ | |
| ConsoleLogHandler.prototype.getLogLevelName = function (logLevel) { | |
| switch (logLevel) { | |
| case models.LogLevel.DEBUG: | |
| return 'DEBUG'; | |
| case models.LogLevel.INFO: | |
| return 'INFO '; | |
| case models.LogLevel.WARNING: | |
| return 'WARN '; | |
| case models.LogLevel.ERROR: | |
| return 'ERROR'; | |
| default: | |
| return 'NOTSET'; | |
| } | |
| }; | |
| /** | |
| * @private | |
| * @param {LogLevel} logLevel | |
| * @param {string[]} logArguments | |
| * @memberof ConsoleLogger | |
| */ | |
| ConsoleLogHandler.prototype.consoleLog = function (logLevel, logArguments) { | |
| switch (logLevel) { | |
| case models.LogLevel.DEBUG: | |
| console.log.apply(console, logArguments); | |
| break; | |
| case models.LogLevel.INFO: | |
| console.info.apply(console, logArguments); | |
| break; | |
| case models.LogLevel.WARNING: | |
| console.warn.apply(console, logArguments); | |
| break; | |
| case models.LogLevel.ERROR: | |
| console.error.apply(console, logArguments); | |
| break; | |
| default: | |
| console.log.apply(console, logArguments); | |
| } | |
| }; | |
| return ConsoleLogHandler; | |
| }()); | |
| exports.ConsoleLogHandler = ConsoleLogHandler; | |
| var globalLogLevel = models.LogLevel.NOTSET; | |
| var globalLogHandler = null; | |
| var OptimizelyLogger = /** @class */ (function () { | |
| function OptimizelyLogger(opts) { | |
| if (opts === void 0) { opts = {}; } | |
| this.messagePrefix = ''; | |
| if (opts.messagePrefix) { | |
| this.messagePrefix = opts.messagePrefix; | |
| } | |
| } | |
| /** | |
| * @param {(LogLevel | LogInputObject)} levelOrObj | |
| * @param {string} [message] | |
| * @memberof OptimizelyLogger | |
| */ | |
| OptimizelyLogger.prototype.log = function (level, message) { | |
| this.internalLog(coerceLogLevel(level), { | |
| message: message, | |
| splat: [], | |
| }); | |
| }; | |
| OptimizelyLogger.prototype.info = function (message) { | |
| var splat = []; | |
| for (var _i = 1; _i < arguments.length; _i++) { | |
| splat[_i - 1] = arguments[_i]; | |
| } | |
| this.namedLog(models.LogLevel.INFO, message, splat); | |
| }; | |
| OptimizelyLogger.prototype.debug = function (message) { | |
| var splat = []; | |
| for (var _i = 1; _i < arguments.length; _i++) { | |
| splat[_i - 1] = arguments[_i]; | |
| } | |
| this.namedLog(models.LogLevel.DEBUG, message, splat); | |
| }; | |
| OptimizelyLogger.prototype.warn = function (message) { | |
| var splat = []; | |
| for (var _i = 1; _i < arguments.length; _i++) { | |
| splat[_i - 1] = arguments[_i]; | |
| } | |
| this.namedLog(models.LogLevel.WARNING, message, splat); | |
| }; | |
| OptimizelyLogger.prototype.error = function (message) { | |
| var splat = []; | |
| for (var _i = 1; _i < arguments.length; _i++) { | |
| splat[_i - 1] = arguments[_i]; | |
| } | |
| this.namedLog(models.LogLevel.ERROR, message, splat); | |
| }; | |
| OptimizelyLogger.prototype.format = function (data) { | |
| return "" + (this.messagePrefix ? this.messagePrefix + ': ' : '') + lib$3.sprintf.apply(void 0, [data.message].concat(data.splat)); | |
| }; | |
| OptimizelyLogger.prototype.internalLog = function (level, data) { | |
| if (!globalLogHandler) { | |
| return; | |
| } | |
| if (level < globalLogLevel) { | |
| return; | |
| } | |
| globalLogHandler.log(level, this.format(data)); | |
| if (data.error && data.error instanceof Error) { | |
| errorHandler.getErrorHandler().handleError(data.error); | |
| } | |
| }; | |
| OptimizelyLogger.prototype.namedLog = function (level, message, splat) { | |
| var error; | |
| if (message instanceof Error) { | |
| error = message; | |
| message = error.message; | |
| this.internalLog(level, { | |
| error: error, | |
| message: message, | |
| splat: splat, | |
| }); | |
| return; | |
| } | |
| if (splat.length === 0) { | |
| this.internalLog(level, { | |
| message: message, | |
| splat: splat, | |
| }); | |
| return; | |
| } | |
| var last = splat[splat.length - 1]; | |
| if (last instanceof Error) { | |
| error = last; | |
| splat.splice(-1); | |
| } | |
| this.internalLog(level, { message: message, error: error, splat: splat }); | |
| }; | |
| return OptimizelyLogger; | |
| }()); | |
| var globalLogManager = new DefaultLogManager(); | |
| function getLogger(name) { | |
| return globalLogManager.getLogger(name); | |
| } | |
| exports.getLogger = getLogger; | |
| function setLogHandler(logger) { | |
| globalLogHandler = logger; | |
| } | |
| exports.setLogHandler = setLogHandler; | |
| function setLogLevel(level) { | |
| level = coerceLogLevel(level); | |
| if (!lib$3.isValidEnum(models.LogLevel, level) || level === undefined) { | |
| globalLogLevel = models.LogLevel.ERROR; | |
| } | |
| else { | |
| globalLogLevel = level; | |
| } | |
| } | |
| exports.setLogLevel = setLogLevel; | |
| function getLogLevel() { | |
| return globalLogLevel; | |
| } | |
| exports.getLogLevel = getLogLevel; | |
| /** | |
| * Resets all global logger state to it's original | |
| */ | |
| function resetLogger() { | |
| globalLogManager = new DefaultLogManager(); | |
| globalLogLevel = models.LogLevel.NOTSET; | |
| } | |
| exports.resetLogger = resetLogger; | |
| }); | |
| unwrapExports(logger); | |
| logger.ConsoleLogHandler; | |
| logger.getLogger; | |
| logger.setLogHandler; | |
| logger.setLogLevel; | |
| logger.getLogLevel; | |
| logger.resetLogger; | |
| var lib$2 = createCommonjsModule(function (module, exports) { | |
| function __export(m) { | |
| for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; | |
| } | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| /** | |
| * Copyright 2019, Optimizely | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| __export(errorHandler); | |
| __export(models); | |
| __export(logger); | |
| }); | |
| unwrapExports(lib$2); | |
| lib$2.ConsoleLogHandler; | |
| lib$2.getLogger; | |
| lib$2.setLogLevel; | |
| lib$2.LogLevel; | |
| lib$2.setLogHandler; | |
| lib$2.setErrorHandler; | |
| lib$2.getErrorHandler; | |
| var events = createCommonjsModule(function (module, exports) { | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| exports.areEventContextsEqual = void 0; | |
| function areEventContextsEqual(eventA, eventB) { | |
| var contextA = eventA.context; | |
| var contextB = eventB.context; | |
| return (contextA.accountId === contextB.accountId && | |
| contextA.projectId === contextB.projectId && | |
| contextA.clientName === contextB.clientName && | |
| contextA.clientVersion === contextB.clientVersion && | |
| contextA.revision === contextB.revision && | |
| contextA.anonymizeIP === contextB.anonymizeIP && | |
| contextA.botFiltering === contextB.botFiltering); | |
| } | |
| exports.areEventContextsEqual = areEventContextsEqual; | |
| }); | |
| unwrapExports(events); | |
| events.areEventContextsEqual; | |
| var eventQueue = createCommonjsModule(function (module, exports) { | |
| /** | |
| * Copyright 2019, Optimizely | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| exports.DefaultEventQueue = exports.SingleEventQueue = void 0; | |
| var logger = lib$2.getLogger('EventProcessor'); | |
| var Timer = /** @class */ (function () { | |
| function Timer(_a) { | |
| var timeout = _a.timeout, callback = _a.callback; | |
| this.timeout = Math.max(timeout, 0); | |
| this.callback = callback; | |
| } | |
| Timer.prototype.start = function () { | |
| this.timeoutId = setTimeout(this.callback, this.timeout); | |
| }; | |
| Timer.prototype.refresh = function () { | |
| this.stop(); | |
| this.start(); | |
| }; | |
| Timer.prototype.stop = function () { | |
| if (this.timeoutId) { | |
| clearTimeout(this.timeoutId); | |
| } | |
| }; | |
| return Timer; | |
| }()); | |
| var SingleEventQueue = /** @class */ (function () { | |
| function SingleEventQueue(_a) { | |
| var sink = _a.sink; | |
| this.sink = sink; | |
| } | |
| SingleEventQueue.prototype.start = function () { | |
| // no-op | |
| }; | |
| SingleEventQueue.prototype.stop = function () { | |
| // no-op | |
| return Promise.resolve(); | |
| }; | |
| SingleEventQueue.prototype.enqueue = function (event) { | |
| this.sink([event]); | |
| }; | |
| return SingleEventQueue; | |
| }()); | |
| exports.SingleEventQueue = SingleEventQueue; | |
| var DefaultEventQueue = /** @class */ (function () { | |
| function DefaultEventQueue(_a) { | |
| var flushInterval = _a.flushInterval, maxQueueSize = _a.maxQueueSize, sink = _a.sink, batchComparator = _a.batchComparator; | |
| this.buffer = []; | |
| this.maxQueueSize = Math.max(maxQueueSize, 1); | |
| this.sink = sink; | |
| this.batchComparator = batchComparator; | |
| this.timer = new Timer({ | |
| callback: this.flush.bind(this), | |
| timeout: flushInterval, | |
| }); | |
| this.started = false; | |
| } | |
| DefaultEventQueue.prototype.start = function () { | |
| this.started = true; | |
| // dont start the timer until the first event is enqueued | |
| }; | |
| DefaultEventQueue.prototype.stop = function () { | |
| this.started = false; | |
| var result = this.sink(this.buffer); | |
| this.buffer = []; | |
| this.timer.stop(); | |
| return result; | |
| }; | |
| DefaultEventQueue.prototype.enqueue = function (event) { | |
| if (!this.started) { | |
| logger.warn('Queue is stopped, not accepting event'); | |
| return; | |
| } | |
| // If new event cannot be included into the current batch, flush so it can | |
| // be in its own new batch. | |
| var bufferedEvent = this.buffer[0]; | |
| if (bufferedEvent && !this.batchComparator(bufferedEvent, event)) { | |
| this.flush(); | |
| } | |
| // start the timer when the first event is put in | |
| if (this.buffer.length === 0) { | |
| this.timer.refresh(); | |
| } | |
| this.buffer.push(event); | |
| if (this.buffer.length >= this.maxQueueSize) { | |
| this.flush(); | |
| } | |
| }; | |
| DefaultEventQueue.prototype.flush = function () { | |
| this.sink(this.buffer); | |
| this.buffer = []; | |
| this.timer.stop(); | |
| }; | |
| return DefaultEventQueue; | |
| }()); | |
| exports.DefaultEventQueue = DefaultEventQueue; | |
| }); | |
| unwrapExports(eventQueue); | |
| eventQueue.DefaultEventQueue; | |
| eventQueue.SingleEventQueue; | |
| var lib$1 = createCommonjsModule(function (module, exports) { | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| /** | |
| * Copyright 2019, Optimizely | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| function generateUUID() { | |
| return uuid_1.v4(); | |
| } | |
| exports.generateUUID = generateUUID; | |
| function getTimestamp() { | |
| return new Date().getTime(); | |
| } | |
| exports.getTimestamp = getTimestamp; | |
| /** | |
| * Validates a value is a valid TypeScript enum | |
| * | |
| * @export | |
| * @param {object} enumToCheck | |
| * @param {*} value | |
| * @returns {boolean} | |
| */ | |
| function isValidEnum(enumToCheck, value) { | |
| var found = false; | |
| var keys = Object.keys(enumToCheck); | |
| for (var index = 0; index < keys.length; index++) { | |
| if (value === enumToCheck[keys[index]]) { | |
| found = true; | |
| break; | |
| } | |
| } | |
| return found; | |
| } | |
| exports.isValidEnum = isValidEnum; | |
| function groupBy(arr, grouperFn) { | |
| var grouper = {}; | |
| arr.forEach(function (item) { | |
| var key = grouperFn(item); | |
| grouper[key] = grouper[key] || []; | |
| grouper[key].push(item); | |
| }); | |
| return objectValues(grouper); | |
| } | |
| exports.groupBy = groupBy; | |
| function objectValues(obj) { | |
| return Object.keys(obj).map(function (key) { return obj[key]; }); | |
| } | |
| exports.objectValues = objectValues; | |
| function objectEntries(obj) { | |
| return Object.keys(obj).map(function (key) { return [key, obj[key]]; }); | |
| } | |
| exports.objectEntries = objectEntries; | |
| function find(arr, cond) { | |
| var found; | |
| for (var _i = 0, arr_1 = arr; _i < arr_1.length; _i++) { | |
| var item = arr_1[_i]; | |
| if (cond(item)) { | |
| found = item; | |
| break; | |
| } | |
| } | |
| return found; | |
| } | |
| exports.find = find; | |
| function keyBy(arr, keyByFn) { | |
| var map = {}; | |
| arr.forEach(function (item) { | |
| var key = keyByFn(item); | |
| map[key] = item; | |
| }); | |
| return map; | |
| } | |
| exports.keyBy = keyBy; | |
| function sprintf(format) { | |
| var args = []; | |
| for (var _i = 1; _i < arguments.length; _i++) { | |
| args[_i - 1] = arguments[_i]; | |
| } | |
| var i = 0; | |
| return format.replace(/%s/g, function () { | |
| var arg = args[i++]; | |
| var type = typeof arg; | |
| if (type === 'function') { | |
| return arg(); | |
| } | |
| else if (type === 'string') { | |
| return arg; | |
| } | |
| else { | |
| return String(arg); | |
| } | |
| }); | |
| } | |
| exports.sprintf = sprintf; | |
| (function (NOTIFICATION_TYPES) { | |
| NOTIFICATION_TYPES["ACTIVATE"] = "ACTIVATE:experiment, user_id,attributes, variation, event"; | |
| NOTIFICATION_TYPES["DECISION"] = "DECISION:type, userId, attributes, decisionInfo"; | |
| NOTIFICATION_TYPES["LOG_EVENT"] = "LOG_EVENT:logEvent"; | |
| NOTIFICATION_TYPES["OPTIMIZELY_CONFIG_UPDATE"] = "OPTIMIZELY_CONFIG_UPDATE"; | |
| NOTIFICATION_TYPES["TRACK"] = "TRACK:event_key, user_id, attributes, event_tags, event"; | |
| })(exports.NOTIFICATION_TYPES || (exports.NOTIFICATION_TYPES = {})); | |
| }); | |
| unwrapExports(lib$1); | |
| var lib_1 = lib$1.generateUUID; | |
| lib$1.getTimestamp; | |
| lib$1.isValidEnum; | |
| lib$1.groupBy; | |
| lib$1.objectValues; | |
| lib$1.objectEntries; | |
| lib$1.find; | |
| lib$1.keyBy; | |
| lib$1.sprintf; | |
| lib$1.NOTIFICATION_TYPES; | |
| var eventProcessor = createCommonjsModule(function (module, exports) { | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| exports.sendEventNotification = exports.getQueue = exports.validateAndGetBatchSize = exports.validateAndGetFlushInterval = exports.DEFAULT_BATCH_SIZE = exports.DEFAULT_FLUSH_INTERVAL = void 0; | |
| exports.DEFAULT_FLUSH_INTERVAL = 30000; // Unit is ms - default flush interval is 30s | |
| exports.DEFAULT_BATCH_SIZE = 10; | |
| var logger = lib$2.getLogger('EventProcessor'); | |
| function validateAndGetFlushInterval(flushInterval) { | |
| if (flushInterval <= 0) { | |
| logger.warn("Invalid flushInterval " + flushInterval + ", defaulting to " + exports.DEFAULT_FLUSH_INTERVAL); | |
| flushInterval = exports.DEFAULT_FLUSH_INTERVAL; | |
| } | |
| return flushInterval; | |
| } | |
| exports.validateAndGetFlushInterval = validateAndGetFlushInterval; | |
| function validateAndGetBatchSize(batchSize) { | |
| batchSize = Math.floor(batchSize); | |
| if (batchSize < 1) { | |
| logger.warn("Invalid batchSize " + batchSize + ", defaulting to " + exports.DEFAULT_BATCH_SIZE); | |
| batchSize = exports.DEFAULT_BATCH_SIZE; | |
| } | |
| batchSize = Math.max(1, batchSize); | |
| return batchSize; | |
| } | |
| exports.validateAndGetBatchSize = validateAndGetBatchSize; | |
| function getQueue(batchSize, flushInterval, sink, batchComparator) { | |
| var queue; | |
| if (batchSize > 1) { | |
| queue = new eventQueue.DefaultEventQueue({ | |
| flushInterval: flushInterval, | |
| maxQueueSize: batchSize, | |
| sink: sink, | |
| batchComparator: batchComparator, | |
| }); | |
| } | |
| else { | |
| queue = new eventQueue.SingleEventQueue({ sink: sink }); | |
| } | |
| return queue; | |
| } | |
| exports.getQueue = getQueue; | |
| function sendEventNotification(notificationCenter, event) { | |
| if (notificationCenter) { | |
| notificationCenter.sendNotifications(lib$1.NOTIFICATION_TYPES.LOG_EVENT, event); | |
| } | |
| } | |
| exports.sendEventNotification = sendEventNotification; | |
| }); | |
| unwrapExports(eventProcessor); | |
| eventProcessor.sendEventNotification; | |
| eventProcessor.getQueue; | |
| eventProcessor.validateAndGetBatchSize; | |
| eventProcessor.validateAndGetFlushInterval; | |
| eventProcessor.DEFAULT_BATCH_SIZE; | |
| eventProcessor.DEFAULT_FLUSH_INTERVAL; | |
| var eventDispatcher = createCommonjsModule(function (module, exports) { | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| }); | |
| unwrapExports(eventDispatcher); | |
| var managed = createCommonjsModule(function (module, exports) { | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| }); | |
| unwrapExports(managed); | |
| var pendingEventsStore = createCommonjsModule(function (module, exports) { | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| exports.LocalStorageStore = void 0; | |
| /** | |
| * Copyright 2019, Optimizely | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| var logger = lib$2.getLogger('EventProcessor'); | |
| var LocalStorageStore = /** @class */ (function () { | |
| function LocalStorageStore(_a) { | |
| var key = _a.key, _b = _a.maxValues, maxValues = _b === void 0 ? 1000 : _b; | |
| this.LS_KEY = key; | |
| this.maxValues = maxValues; | |
| } | |
| LocalStorageStore.prototype.get = function (key) { | |
| return this.getMap()[key] || null; | |
| }; | |
| LocalStorageStore.prototype.set = function (key, value) { | |
| var map = this.getMap(); | |
| map[key] = value; | |
| this.replace(map); | |
| }; | |
| LocalStorageStore.prototype.remove = function (key) { | |
| var map = this.getMap(); | |
| delete map[key]; | |
| this.replace(map); | |
| }; | |
| LocalStorageStore.prototype.values = function () { | |
| return lib$1.objectValues(this.getMap()); | |
| }; | |
| LocalStorageStore.prototype.clear = function () { | |
| this.replace({}); | |
| }; | |
| LocalStorageStore.prototype.replace = function (map) { | |
| try { | |
| // This is a temporary fix to support React Native which does not have localStorage. | |
| window.localStorage && localStorage.setItem(this.LS_KEY, JSON.stringify(map)); | |
| this.clean(); | |
| } | |
| catch (e) { | |
| logger.error(e); | |
| } | |
| }; | |
| LocalStorageStore.prototype.clean = function () { | |
| var map = this.getMap(); | |
| var keys = Object.keys(map); | |
| var toRemove = keys.length - this.maxValues; | |
| if (toRemove < 1) { | |
| return; | |
| } | |
| var entries = keys.map(function (key) { return ({ | |
| key: key, | |
| value: map[key] | |
| }); }); | |
| entries.sort(function (a, b) { return a.value.timestamp - b.value.timestamp; }); | |
| for (var i = 0; i < toRemove; i++) { | |
| delete map[entries[i].key]; | |
| } | |
| this.replace(map); | |
| }; | |
| LocalStorageStore.prototype.getMap = function () { | |
| try { | |
| // This is a temporary fix to support React Native which does not have localStorage. | |
| var data = window.localStorage && localStorage.getItem(this.LS_KEY); | |
| if (data) { | |
| return JSON.parse(data) || {}; | |
| } | |
| } | |
| catch (e) { | |
| logger.error(e); | |
| } | |
| return {}; | |
| }; | |
| return LocalStorageStore; | |
| }()); | |
| exports.LocalStorageStore = LocalStorageStore; | |
| }); | |
| unwrapExports(pendingEventsStore); | |
| pendingEventsStore.LocalStorageStore; | |
| var pendingEventsDispatcher = createCommonjsModule(function (module, exports) { | |
| var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { | |
| var extendStatics = function (d, b) { | |
| extendStatics = Object.setPrototypeOf || | |
| ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || | |
| function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; | |
| return extendStatics(d, b); | |
| }; | |
| return function (d, b) { | |
| extendStatics(d, b); | |
| function __() { this.constructor = d; } | |
| d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); | |
| }; | |
| })(); | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| exports.LocalStoragePendingEventsDispatcher = exports.PendingEventsDispatcher = void 0; | |
| /** | |
| * Copyright 2019, Optimizely | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| var logger = lib$2.getLogger('EventProcessor'); | |
| var PendingEventsDispatcher = /** @class */ (function () { | |
| function PendingEventsDispatcher(_a) { | |
| var eventDispatcher = _a.eventDispatcher, store = _a.store; | |
| this.dispatcher = eventDispatcher; | |
| this.store = store; | |
| } | |
| PendingEventsDispatcher.prototype.dispatchEvent = function (request, callback) { | |
| this.send({ | |
| uuid: lib$1.generateUUID(), | |
| timestamp: lib$1.getTimestamp(), | |
| request: request, | |
| }, callback); | |
| }; | |
| PendingEventsDispatcher.prototype.sendPendingEvents = function () { | |
| var _this = this; | |
| var pendingEvents = this.store.values(); | |
| logger.debug('Sending %s pending events from previous page', pendingEvents.length); | |
| pendingEvents.forEach(function (item) { | |
| try { | |
| _this.send(item, function () { }); | |
| } | |
| catch (e) { } | |
| }); | |
| }; | |
| PendingEventsDispatcher.prototype.send = function (entry, callback) { | |
| var _this = this; | |
| this.store.set(entry.uuid, entry); | |
| this.dispatcher.dispatchEvent(entry.request, function (response) { | |
| _this.store.remove(entry.uuid); | |
| callback(response); | |
| }); | |
| }; | |
| return PendingEventsDispatcher; | |
| }()); | |
| exports.PendingEventsDispatcher = PendingEventsDispatcher; | |
| var LocalStoragePendingEventsDispatcher = /** @class */ (function (_super) { | |
| __extends(LocalStoragePendingEventsDispatcher, _super); | |
| function LocalStoragePendingEventsDispatcher(_a) { | |
| var eventDispatcher = _a.eventDispatcher; | |
| return _super.call(this, { | |
| eventDispatcher: eventDispatcher, | |
| store: new pendingEventsStore.LocalStorageStore({ | |
| // TODO make this configurable | |
| maxValues: 100, | |
| key: 'fs_optly_pending_events', | |
| }), | |
| }) || this; | |
| } | |
| return LocalStoragePendingEventsDispatcher; | |
| }(PendingEventsDispatcher)); | |
| exports.LocalStoragePendingEventsDispatcher = LocalStoragePendingEventsDispatcher; | |
| }); | |
| unwrapExports(pendingEventsDispatcher); | |
| pendingEventsDispatcher.LocalStoragePendingEventsDispatcher; | |
| pendingEventsDispatcher.PendingEventsDispatcher; | |
| var buildEventV1 = createCommonjsModule(function (module, exports) { | |
| var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () { | |
| __assign = Object.assign || function(t) { | |
| for (var s, i = 1, n = arguments.length; i < n; i++) { | |
| s = arguments[i]; | |
| for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | |
| t[p] = s[p]; | |
| } | |
| return t; | |
| }; | |
| return __assign.apply(this, arguments); | |
| }; | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| exports.formatEvents = exports.buildConversionEventV1 = exports.buildImpressionEventV1 = exports.makeBatchedEventV1 = void 0; | |
| var ACTIVATE_EVENT_KEY = 'campaign_activated'; | |
| var CUSTOM_ATTRIBUTE_FEATURE_TYPE = 'custom'; | |
| var BOT_FILTERING_KEY = '$opt_bot_filtering'; | |
| /** | |
| * Given an array of batchable Decision or ConversionEvent events it returns | |
| * a single EventV1 with proper batching | |
| * | |
| * @param {ProcessableEvent[]} events | |
| * @returns {EventV1} | |
| */ | |
| function makeBatchedEventV1(events) { | |
| var visitors = []; | |
| var data = events[0]; | |
| events.forEach(function (event) { | |
| if (event.type === 'conversion' || event.type === 'impression') { | |
| var visitor = makeVisitor(event); | |
| if (event.type === 'impression') { | |
| visitor.snapshots.push(makeDecisionSnapshot(event)); | |
| } | |
| else if (event.type === 'conversion') { | |
| visitor.snapshots.push(makeConversionSnapshot(event)); | |
| } | |
| visitors.push(visitor); | |
| } | |
| }); | |
| return { | |
| client_name: data.context.clientName, | |
| client_version: data.context.clientVersion, | |
| account_id: data.context.accountId, | |
| project_id: data.context.projectId, | |
| revision: data.context.revision, | |
| anonymize_ip: data.context.anonymizeIP, | |
| enrich_decisions: true, | |
| visitors: visitors, | |
| }; | |
| } | |
| exports.makeBatchedEventV1 = makeBatchedEventV1; | |
| function makeConversionSnapshot(conversion) { | |
| var tags = __assign({}, conversion.tags); | |
| delete tags['revenue']; | |
| delete tags['value']; | |
| var event = { | |
| entity_id: conversion.event.id, | |
| key: conversion.event.key, | |
| timestamp: conversion.timestamp, | |
| uuid: conversion.uuid, | |
| }; | |
| if (conversion.tags) { | |
| event.tags = conversion.tags; | |
| } | |
| if (conversion.value != null) { | |
| event.value = conversion.value; | |
| } | |
| if (conversion.revenue != null) { | |
| event.revenue = conversion.revenue; | |
| } | |
| return { | |
| events: [event], | |
| }; | |
| } | |
| function makeDecisionSnapshot(event) { | |
| var layer = event.layer, experiment = event.experiment, variation = event.variation, ruleKey = event.ruleKey, flagKey = event.flagKey, ruleType = event.ruleType, enabled = event.enabled; | |
| var layerId = layer ? layer.id : null; | |
| var experimentId = experiment ? experiment.id : null; | |
| var variationId = variation ? variation.id : null; | |
| var variationKey = variation ? variation.key : ''; | |
| return { | |
| decisions: [ | |
| { | |
| campaign_id: layerId, | |
| experiment_id: experimentId, | |
| variation_id: variationId, | |
| metadata: { | |
| flag_key: flagKey, | |
| rule_key: ruleKey, | |
| rule_type: ruleType, | |
| variation_key: variationKey, | |
| enabled: enabled, | |
| }, | |
| }, | |
| ], | |
| events: [ | |
| { | |
| entity_id: layerId, | |
| timestamp: event.timestamp, | |
| key: ACTIVATE_EVENT_KEY, | |
| uuid: event.uuid, | |
| }, | |
| ], | |
| }; | |
| } | |
| function makeVisitor(data) { | |
| var visitor = { | |
| snapshots: [], | |
| visitor_id: data.user.id, | |
| attributes: [], | |
| }; | |
| data.user.attributes.forEach(function (attr) { | |
| visitor.attributes.push({ | |
| entity_id: attr.entityId, | |
| key: attr.key, | |
| type: 'custom', | |
| value: attr.value, | |
| }); | |
| }); | |
| if (typeof data.context.botFiltering === 'boolean') { | |
| visitor.attributes.push({ | |
| entity_id: BOT_FILTERING_KEY, | |
| key: BOT_FILTERING_KEY, | |
| type: CUSTOM_ATTRIBUTE_FEATURE_TYPE, | |
| value: data.context.botFiltering, | |
| }); | |
| } | |
| return visitor; | |
| } | |
| /** | |
| * Event for usage with v1 logtier | |
| * | |
| * @export | |
| * @interface EventBuilderV1 | |
| */ | |
| function buildImpressionEventV1(data) { | |
| var visitor = makeVisitor(data); | |
| visitor.snapshots.push(makeDecisionSnapshot(data)); | |
| return { | |
| client_name: data.context.clientName, | |
| client_version: data.context.clientVersion, | |
| account_id: data.context.accountId, | |
| project_id: data.context.projectId, | |
| revision: data.context.revision, | |
| anonymize_ip: data.context.anonymizeIP, | |
| enrich_decisions: true, | |
| visitors: [visitor], | |
| }; | |
| } | |
| exports.buildImpressionEventV1 = buildImpressionEventV1; | |
| function buildConversionEventV1(data) { | |
| var visitor = makeVisitor(data); | |
| visitor.snapshots.push(makeConversionSnapshot(data)); | |
| return { | |
| client_name: data.context.clientName, | |
| client_version: data.context.clientVersion, | |
| account_id: data.context.accountId, | |
| project_id: data.context.projectId, | |
| revision: data.context.revision, | |
| anonymize_ip: data.context.anonymizeIP, | |
| enrich_decisions: true, | |
| visitors: [visitor], | |
| }; | |
| } | |
| exports.buildConversionEventV1 = buildConversionEventV1; | |
| function formatEvents(events) { | |
| return { | |
| url: 'https://logx.optimizely.com/v1/events', | |
| httpVerb: 'POST', | |
| params: makeBatchedEventV1(events), | |
| }; | |
| } | |
| exports.formatEvents = formatEvents; | |
| }); | |
| unwrapExports(buildEventV1); | |
| buildEventV1.formatEvents; | |
| buildEventV1.buildConversionEventV1; | |
| buildEventV1.buildImpressionEventV1; | |
| buildEventV1.makeBatchedEventV1; | |
| var requestTracker = createCommonjsModule(function (module, exports) { | |
| /** | |
| * Copyright 2020, Optimizely | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| /** | |
| * RequestTracker keeps track of in-flight requests for EventProcessor using | |
| * an internal counter. It exposes methods for adding a new request to be | |
| * tracked, and getting a Promise representing the completion of currently | |
| * tracked requests. | |
| */ | |
| var RequestTracker = /** @class */ (function () { | |
| function RequestTracker() { | |
| this.reqsInFlightCount = 0; | |
| this.reqsCompleteResolvers = []; | |
| } | |
| /** | |
| * Track the argument request (represented by a Promise). reqPromise will feed | |
| * into the state of Promises returned by onRequestsComplete. | |
| * @param {Promise<void>} reqPromise | |
| */ | |
| RequestTracker.prototype.trackRequest = function (reqPromise) { | |
| var _this = this; | |
| this.reqsInFlightCount++; | |
| var onReqComplete = function () { | |
| _this.reqsInFlightCount--; | |
| if (_this.reqsInFlightCount === 0) { | |
| _this.reqsCompleteResolvers.forEach(function (resolver) { return resolver(); }); | |
| _this.reqsCompleteResolvers = []; | |
| } | |
| }; | |
| reqPromise.then(onReqComplete, onReqComplete); | |
| }; | |
| /** | |
| * Return a Promise that fulfills after all currently-tracked request promises | |
| * are resolved. | |
| * @return {Promise<void>} | |
| */ | |
| RequestTracker.prototype.onRequestsComplete = function () { | |
| var _this = this; | |
| return new Promise(function (resolve) { | |
| if (_this.reqsInFlightCount === 0) { | |
| resolve(); | |
| } | |
| else { | |
| _this.reqsCompleteResolvers.push(resolve); | |
| } | |
| }); | |
| }; | |
| return RequestTracker; | |
| }()); | |
| exports.default = RequestTracker; | |
| }); | |
| unwrapExports(requestTracker); | |
| var v1EventProcessor = createCommonjsModule(function (module, exports) { | |
| var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) { | |
| function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | |
| return new (P || (P = Promise))(function (resolve, reject) { | |
| function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | |
| function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | |
| function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | |
| step((generator = generator.apply(thisArg, _arguments || [])).next()); | |
| }); | |
| }; | |
| var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) { | |
| var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | |
| return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | |
| function verb(n) { return function (v) { return step([n, v]); }; } | |
| function step(op) { | |
| if (f) throw new TypeError("Generator is already executing."); | |
| while (_) try { | |
| 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; | |
| if (y = 0, t) op = [op[0] & 2, t.value]; | |
| switch (op[0]) { | |
| case 0: case 1: t = op; break; | |
| case 4: _.label++; return { value: op[1], done: false }; | |
| case 5: _.label++; y = op[1]; op = [0]; continue; | |
| case 7: op = _.ops.pop(); _.trys.pop(); continue; | |
| default: | |
| if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | |
| if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | |
| if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | |
| if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | |
| if (t[2]) _.ops.pop(); | |
| _.trys.pop(); continue; | |
| } | |
| op = body.call(thisArg, _); | |
| } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | |
| if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | |
| } | |
| }; | |
| var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { | |
| return (mod && mod.__esModule) ? mod : { "default": mod }; | |
| }; | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| exports.LogTierV1EventProcessor = void 0; | |
| /** | |
| * Copyright 2019-2020, Optimizely | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| var requestTracker_1 = __importDefault(requestTracker); | |
| var logger = lib$2.getLogger('LogTierV1EventProcessor'); | |
| var LogTierV1EventProcessor = /** @class */ (function () { | |
| function LogTierV1EventProcessor(_a) { | |
| var dispatcher = _a.dispatcher, _b = _a.flushInterval, flushInterval = _b === void 0 ? eventProcessor.DEFAULT_FLUSH_INTERVAL : _b, _c = _a.batchSize, batchSize = _c === void 0 ? eventProcessor.DEFAULT_BATCH_SIZE : _c, notificationCenter = _a.notificationCenter; | |
| this.dispatcher = dispatcher; | |
| this.notificationCenter = notificationCenter; | |
| this.requestTracker = new requestTracker_1.default(); | |
| flushInterval = eventProcessor.validateAndGetFlushInterval(flushInterval); | |
| batchSize = eventProcessor.validateAndGetBatchSize(batchSize); | |
| this.queue = eventProcessor.getQueue(batchSize, flushInterval, this.drainQueue.bind(this), events.areEventContextsEqual); | |
| } | |
| LogTierV1EventProcessor.prototype.drainQueue = function (buffer) { | |
| var _this = this; | |
| var reqPromise = new Promise(function (resolve) { | |
| logger.debug('draining queue with %s events', buffer.length); | |
| if (buffer.length === 0) { | |
| resolve(); | |
| return; | |
| } | |
| var formattedEvent = buildEventV1.formatEvents(buffer); | |
| _this.dispatcher.dispatchEvent(formattedEvent, function () { | |
| resolve(); | |
| }); | |
| eventProcessor.sendEventNotification(_this.notificationCenter, formattedEvent); | |
| }); | |
| this.requestTracker.trackRequest(reqPromise); | |
| return reqPromise; | |
| }; | |
| LogTierV1EventProcessor.prototype.process = function (event) { | |
| this.queue.enqueue(event); | |
| }; | |
| LogTierV1EventProcessor.prototype.stop = function () { | |
| // swallow - an error stopping this queue shouldn't prevent this from stopping | |
| try { | |
| this.queue.stop(); | |
| return this.requestTracker.onRequestsComplete(); | |
| } | |
| catch (e) { | |
| logger.error('Error stopping EventProcessor: "%s"', e.message, e); | |
| } | |
| return Promise.resolve(); | |
| }; | |
| LogTierV1EventProcessor.prototype.start = function () { | |
| return __awaiter(this, void 0, void 0, function () { | |
| return __generator(this, function (_a) { | |
| this.queue.start(); | |
| return [2 /*return*/]; | |
| }); | |
| }); | |
| }; | |
| return LogTierV1EventProcessor; | |
| }()); | |
| exports.LogTierV1EventProcessor = LogTierV1EventProcessor; | |
| }); | |
| unwrapExports(v1EventProcessor); | |
| v1EventProcessor.LogTierV1EventProcessor; | |
| var lib = createCommonjsModule(function (module, exports) { | |
| /** | |
| * Copyright 2019-2020, Optimizely | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) { | |
| if (k2 === undefined) k2 = k; | |
| Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); | |
| }) : (function(o, m, k, k2) { | |
| if (k2 === undefined) k2 = k; | |
| o[k2] = m[k]; | |
| })); | |
| var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) { | |
| for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); | |
| }; | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| __exportStar(events, exports); | |
| __exportStar(eventProcessor, exports); | |
| __exportStar(eventDispatcher, exports); | |
| __exportStar(managed, exports); | |
| __exportStar(pendingEventsDispatcher, exports); | |
| __exportStar(buildEventV1, exports); | |
| __exportStar(v1EventProcessor, exports); | |
| }); | |
| unwrapExports(lib); | |
| var config = createCommonjsModule(function (module, exports) { | |
| /** | |
| * Copyright 2019-2020, Optimizely | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| exports.DEFAULT_UPDATE_INTERVAL = 5 * 60 * 1000; // 5 minutes | |
| exports.MIN_UPDATE_INTERVAL = 1000; | |
| exports.DEFAULT_URL_TEMPLATE = "https://cdn.optimizely.com/datafiles/%s.json"; | |
| exports.DEFAULT_AUTHENTICATED_URL_TEMPLATE = "https://config.optimizely.com/datafiles/auth/%s.json"; | |
| exports.BACKOFF_BASE_WAIT_SECONDS_BY_ERROR_COUNT = [0, 8, 16, 32, 64, 128, 256, 512]; | |
| exports.REQUEST_TIMEOUT_MS = 60 * 1000; // 1 minute | |
| }); | |
| unwrapExports(config); | |
| config.DEFAULT_UPDATE_INTERVAL; | |
| config.MIN_UPDATE_INTERVAL; | |
| config.DEFAULT_URL_TEMPLATE; | |
| config.DEFAULT_AUTHENTICATED_URL_TEMPLATE; | |
| config.BACKOFF_BASE_WAIT_SECONDS_BY_ERROR_COUNT; | |
| config.REQUEST_TIMEOUT_MS; | |
| var browserRequest = createCommonjsModule(function (module, exports) { | |
| /** | |
| * Copyright 2019-2020, Optimizely | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| var logger = lib$2.getLogger('DatafileManager'); | |
| var GET_METHOD = 'GET'; | |
| var READY_STATE_DONE = 4; | |
| function parseHeadersFromXhr(req) { | |
| var allHeadersString = req.getAllResponseHeaders(); | |
| if (allHeadersString === null) { | |
| return {}; | |
| } | |
| var headerLines = allHeadersString.split('\r\n'); | |
| var headers = {}; | |
| headerLines.forEach(function (headerLine) { | |
| var separatorIndex = headerLine.indexOf(': '); | |
| if (separatorIndex > -1) { | |
| var headerName = headerLine.slice(0, separatorIndex); | |
| var headerValue = headerLine.slice(separatorIndex + 2); | |
| if (headerValue.length > 0) { | |
| headers[headerName] = headerValue; | |
| } | |
| } | |
| }); | |
| return headers; | |
| } | |
| function setHeadersInXhr(headers, req) { | |
| Object.keys(headers).forEach(function (headerName) { | |
| var header = headers[headerName]; | |
| req.setRequestHeader(headerName, header); | |
| }); | |
| } | |
| function makeGetRequest(reqUrl, headers) { | |
| var req = new XMLHttpRequest(); | |
| var responsePromise = new Promise(function (resolve, reject) { | |
| req.open(GET_METHOD, reqUrl, true); | |
| setHeadersInXhr(headers, req); | |
| req.onreadystatechange = function () { | |
| if (req.readyState === READY_STATE_DONE) { | |
| var statusCode = req.status; | |
| if (statusCode === 0) { | |
| reject(new Error('Request error')); | |
| return; | |
| } | |
| var headers_1 = parseHeadersFromXhr(req); | |
| var resp = { | |
| statusCode: req.status, | |
| body: req.responseText, | |
| headers: headers_1, | |
| }; | |
| resolve(resp); | |
| } | |
| }; | |
| req.timeout = config.REQUEST_TIMEOUT_MS; | |
| req.ontimeout = function () { | |
| logger.error('Request timed out'); | |
| }; | |
| req.send(); | |
| }); | |
| return { | |
| responsePromise: responsePromise, | |
| abort: function () { | |
| req.abort(); | |
| }, | |
| }; | |
| } | |
| exports.makeGetRequest = makeGetRequest; | |
| }); | |
| unwrapExports(browserRequest); | |
| browserRequest.makeGetRequest; | |
| var eventEmitter = createCommonjsModule(function (module, exports) { | |
| /** | |
| * Copyright 2019-2020, Optimizely | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| var EventEmitter = /** @class */ (function () { | |
| function EventEmitter() { | |
| this.listeners = {}; | |
| this.listenerId = 1; | |
| } | |
| EventEmitter.prototype.on = function (eventName, listener) { | |
| var _this = this; | |
| if (!this.listeners[eventName]) { | |
| this.listeners[eventName] = {}; | |
| } | |
| var currentListenerId = String(this.listenerId); | |
| this.listenerId++; | |
| this.listeners[eventName][currentListenerId] = listener; | |
| return function () { | |
| if (_this.listeners[eventName]) { | |
| delete _this.listeners[eventName][currentListenerId]; | |
| } | |
| }; | |
| }; | |
| EventEmitter.prototype.emit = function (eventName, arg) { | |
| var listeners = this.listeners[eventName]; | |
| if (listeners) { | |
| Object.keys(listeners).forEach(function (listenerId) { | |
| var listener = listeners[listenerId]; | |
| listener(arg); | |
| }); | |
| } | |
| }; | |
| EventEmitter.prototype.removeAllListeners = function () { | |
| this.listeners = {}; | |
| }; | |
| return EventEmitter; | |
| }()); | |
| exports.default = EventEmitter; | |
| // TODO: Create a typed event emitter for use in TS only (not JS) | |
| }); | |
| unwrapExports(eventEmitter); | |
| var backoffController = createCommonjsModule(function (module, exports) { | |
| /** | |
| * Copyright 2019-2020, Optimizely | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| function randomMilliseconds() { | |
| return Math.round(Math.random() * 1000); | |
| } | |
| var BackoffController = /** @class */ (function () { | |
| function BackoffController() { | |
| this.errorCount = 0; | |
| } | |
| BackoffController.prototype.getDelay = function () { | |
| if (this.errorCount === 0) { | |
| return 0; | |
| } | |
| var baseWaitSeconds = config.BACKOFF_BASE_WAIT_SECONDS_BY_ERROR_COUNT[Math.min(config.BACKOFF_BASE_WAIT_SECONDS_BY_ERROR_COUNT.length - 1, this.errorCount)]; | |
| return baseWaitSeconds * 1000 + randomMilliseconds(); | |
| }; | |
| BackoffController.prototype.countError = function () { | |
| if (this.errorCount < config.BACKOFF_BASE_WAIT_SECONDS_BY_ERROR_COUNT.length - 1) { | |
| this.errorCount++; | |
| } | |
| }; | |
| BackoffController.prototype.reset = function () { | |
| this.errorCount = 0; | |
| }; | |
| return BackoffController; | |
| }()); | |
| exports.default = BackoffController; | |
| }); | |
| unwrapExports(backoffController); | |
| var httpPollingDatafileManager = createCommonjsModule(function (module, exports) { | |
| /** | |
| * Copyright 2019-2020, Optimizely | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () { | |
| __assign = Object.assign || function(t) { | |
| for (var s, i = 1, n = arguments.length; i < n; i++) { | |
| s = arguments[i]; | |
| for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | |
| t[p] = s[p]; | |
| } | |
| return t; | |
| }; | |
| return __assign.apply(this, arguments); | |
| }; | |
| var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { | |
| return (mod && mod.__esModule) ? mod : { "default": mod }; | |
| }; | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| var eventEmitter_1 = __importDefault(eventEmitter); | |
| var backoffController_1 = __importDefault(backoffController); | |
| var logger = lib$2.getLogger('DatafileManager'); | |
| var UPDATE_EVT = 'update'; | |
| function isValidUpdateInterval(updateInterval) { | |
| return updateInterval >= config.MIN_UPDATE_INTERVAL; | |
| } | |
| function isSuccessStatusCode(statusCode) { | |
| return statusCode >= 200 && statusCode < 400; | |
| } | |
| var noOpKeyValueCache = { | |
| get: function () { | |
| return Promise.resolve(''); | |
| }, | |
| set: function () { | |
| return Promise.resolve(); | |
| }, | |
| contains: function () { | |
| return Promise.resolve(false); | |
| }, | |
| remove: function () { | |
| return Promise.resolve(); | |
| }, | |
| }; | |
| var HttpPollingDatafileManager = /** @class */ (function () { | |
| function HttpPollingDatafileManager(config$1) { | |
| var _this = this; | |
| var configWithDefaultsApplied = __assign({}, this.getConfigDefaults(), config$1); | |
| var datafile = configWithDefaultsApplied.datafile, _a = configWithDefaultsApplied.autoUpdate, autoUpdate = _a === void 0 ? false : _a, sdkKey = configWithDefaultsApplied.sdkKey, _b = configWithDefaultsApplied.updateInterval, updateInterval = _b === void 0 ? config.DEFAULT_UPDATE_INTERVAL : _b, _c = configWithDefaultsApplied.urlTemplate, urlTemplate = _c === void 0 ? config.DEFAULT_URL_TEMPLATE : _c, _d = configWithDefaultsApplied.cache, cache = _d === void 0 ? noOpKeyValueCache : _d; | |
| this.cache = cache; | |
| this.cacheKey = 'opt-datafile-' + sdkKey; | |
| this.isReadyPromiseSettled = false; | |
| this.readyPromiseResolver = function () { }; | |
| this.readyPromiseRejecter = function () { }; | |
| this.readyPromise = new Promise(function (resolve, reject) { | |
| _this.readyPromiseResolver = resolve; | |
| _this.readyPromiseRejecter = reject; | |
| }); | |
| if (datafile) { | |
| this.currentDatafile = datafile; | |
| if (!sdkKey) { | |
| this.resolveReadyPromise(); | |
| } | |
| } | |
| else { | |
| this.currentDatafile = ''; | |
| } | |
| this.isStarted = false; | |
| this.datafileUrl = lib$1.sprintf(urlTemplate, sdkKey); | |
| this.emitter = new eventEmitter_1.default(); | |
| this.autoUpdate = autoUpdate; | |
| if (isValidUpdateInterval(updateInterval)) { | |
| this.updateInterval = updateInterval; | |
| } | |
| else { | |
| logger.warn('Invalid updateInterval %s, defaulting to %s', updateInterval, config.DEFAULT_UPDATE_INTERVAL); | |
| this.updateInterval = config.DEFAULT_UPDATE_INTERVAL; | |
| } | |
| this.currentTimeout = null; | |
| this.currentRequest = null; | |
| this.backoffController = new backoffController_1.default(); | |
| this.syncOnCurrentRequestComplete = false; | |
| } | |
| HttpPollingDatafileManager.prototype.get = function () { | |
| return this.currentDatafile; | |
| }; | |
| HttpPollingDatafileManager.prototype.start = function () { | |
| if (!this.isStarted) { | |
| logger.debug('Datafile manager started'); | |
| this.isStarted = true; | |
| this.backoffController.reset(); | |
| this.setDatafileFromCacheIfAvailable(); | |
| this.syncDatafile(); | |
| } | |
| }; | |
| HttpPollingDatafileManager.prototype.stop = function () { | |
| logger.debug('Datafile manager stopped'); | |
| this.isStarted = false; | |
| if (this.currentTimeout) { | |
| clearTimeout(this.currentTimeout); | |
| this.currentTimeout = null; | |
| } | |
| this.emitter.removeAllListeners(); | |
| if (this.currentRequest) { | |
| this.currentRequest.abort(); | |
| this.currentRequest = null; | |
| } | |
| return Promise.resolve(); | |
| }; | |
| HttpPollingDatafileManager.prototype.onReady = function () { | |
| return this.readyPromise; | |
| }; | |
| HttpPollingDatafileManager.prototype.on = function (eventName, listener) { | |
| return this.emitter.on(eventName, listener); | |
| }; | |
| HttpPollingDatafileManager.prototype.onRequestRejected = function (err) { | |
| if (!this.isStarted) { | |
| return; | |
| } | |
| this.backoffController.countError(); | |
| if (err instanceof Error) { | |
| logger.error('Error fetching datafile: %s', err.message, err); | |
| } | |
| else if (typeof err === 'string') { | |
| logger.error('Error fetching datafile: %s', err); | |
| } | |
| else { | |
| logger.error('Error fetching datafile'); | |
| } | |
| }; | |
| HttpPollingDatafileManager.prototype.onRequestResolved = function (response) { | |
| if (!this.isStarted) { | |
| return; | |
| } | |
| if (typeof response.statusCode !== 'undefined' && isSuccessStatusCode(response.statusCode)) { | |
| this.backoffController.reset(); | |
| } | |
| else { | |
| this.backoffController.countError(); | |
| } | |
| this.trySavingLastModified(response.headers); | |
| var datafile = this.getNextDatafileFromResponse(response); | |
| if (datafile !== '') { | |
| logger.info('Updating datafile from response'); | |
| this.currentDatafile = datafile; | |
| this.cache.set(this.cacheKey, datafile); | |
| if (!this.isReadyPromiseSettled) { | |
| this.resolveReadyPromise(); | |
| } | |
| else { | |
| var datafileUpdate = { | |
| datafile: datafile, | |
| }; | |
| this.emitter.emit(UPDATE_EVT, datafileUpdate); | |
| } | |
| } | |
| }; | |
| HttpPollingDatafileManager.prototype.onRequestComplete = function () { | |
| if (!this.isStarted) { | |
| return; | |
| } | |
| this.currentRequest = null; | |
| if (!this.isReadyPromiseSettled && !this.autoUpdate) { | |
| // We will never resolve ready, so reject it | |
| this.rejectReadyPromise(new Error('Failed to become ready')); | |
| } | |
| if (this.autoUpdate && this.syncOnCurrentRequestComplete) { | |
| this.syncDatafile(); | |
| } | |
| this.syncOnCurrentRequestComplete = false; | |
| }; | |
| HttpPollingDatafileManager.prototype.syncDatafile = function () { | |
| if (this.lastResponseLastModified) { | |
| this.lastResponseLastModified; | |
| } | |
| return; | |
| }; | |
| HttpPollingDatafileManager.prototype.resolveReadyPromise = function () { | |
| this.readyPromiseResolver(); | |
| this.isReadyPromiseSettled = true; | |
| }; | |
| HttpPollingDatafileManager.prototype.rejectReadyPromise = function (err) { | |
| this.readyPromiseRejecter(err); | |
| this.isReadyPromiseSettled = true; | |
| }; | |
| HttpPollingDatafileManager.prototype.scheduleNextUpdate = function () { | |
| var _this = this; | |
| var currentBackoffDelay = this.backoffController.getDelay(); | |
| var nextUpdateDelay = Math.max(currentBackoffDelay, this.updateInterval); | |
| logger.debug('Scheduling sync in %s ms', nextUpdateDelay); | |
| this.currentTimeout = setTimeout(function () { | |
| if (_this.currentRequest) { | |
| _this.syncOnCurrentRequestComplete = true; | |
| } | |
| else { | |
| _this.syncDatafile(); | |
| } | |
| }, nextUpdateDelay); | |
| }; | |
| HttpPollingDatafileManager.prototype.getNextDatafileFromResponse = function (response) { | |
| logger.debug('Response status code: %s', response.statusCode); | |
| if (typeof response.statusCode === 'undefined') { | |
| return ''; | |
| } | |
| if (response.statusCode === 304) { | |
| return ''; | |
| } | |
| if (isSuccessStatusCode(response.statusCode)) { | |
| return response.body; | |
| } | |
| return ''; | |
| }; | |
| HttpPollingDatafileManager.prototype.trySavingLastModified = function (headers) { | |
| var lastModifiedHeader = headers['last-modified'] || headers['Last-Modified']; | |
| if (typeof lastModifiedHeader !== 'undefined') { | |
| this.lastResponseLastModified = lastModifiedHeader; | |
| logger.debug('Saved last modified header value from response: %s', this.lastResponseLastModified); | |
| } | |
| }; | |
| HttpPollingDatafileManager.prototype.setDatafileFromCacheIfAvailable = function () { | |
| var _this = this; | |
| this.cache.get(this.cacheKey).then(function (datafile) { | |
| if (_this.isStarted && !_this.isReadyPromiseSettled && datafile !== '') { | |
| logger.debug('Using datafile from cache'); | |
| _this.currentDatafile = datafile; | |
| _this.resolveReadyPromise(); | |
| } | |
| }); | |
| }; | |
| return HttpPollingDatafileManager; | |
| }()); | |
| exports.default = HttpPollingDatafileManager; | |
| }); | |
| unwrapExports(httpPollingDatafileManager); | |
| var browserDatafileManager = createCommonjsModule(function (module, exports) { | |
| /** | |
| * Copyright 2019-2020, Optimizely | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () { | |
| var extendStatics = function (d, b) { | |
| extendStatics = Object.setPrototypeOf || | |
| ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || | |
| function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; | |
| return extendStatics(d, b); | |
| }; | |
| return function (d, b) { | |
| extendStatics(d, b); | |
| function __() { this.constructor = d; } | |
| d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); | |
| }; | |
| })(); | |
| var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) { | |
| return (mod && mod.__esModule) ? mod : { "default": mod }; | |
| }; | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| var httpPollingDatafileManager_1 = __importDefault(httpPollingDatafileManager); | |
| var BrowserDatafileManager = /** @class */ (function (_super) { | |
| __extends(BrowserDatafileManager, _super); | |
| function BrowserDatafileManager() { | |
| return _super !== null && _super.apply(this, arguments) || this; | |
| } | |
| BrowserDatafileManager.prototype.makeGetRequest = function (reqUrl, headers) { | |
| return browserRequest.makeGetRequest(reqUrl, headers); | |
| }; | |
| BrowserDatafileManager.prototype.getConfigDefaults = function () { | |
| return { | |
| autoUpdate: false, | |
| }; | |
| }; | |
| return BrowserDatafileManager; | |
| }(httpPollingDatafileManager_1.default)); | |
| exports.default = BrowserDatafileManager; | |
| }); | |
| unwrapExports(browserDatafileManager); | |
| var index_browser = createCommonjsModule(function (module, exports) { | |
| /** | |
| * Copyright 2019-2020, Optimizely | |
| * | |
| * Licensed under the Apache License, Version 2.0 (the "License"); | |
| * you may not use this file except in compliance with the License. | |
| * You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, software | |
| * distributed under the License is distributed on an "AS IS" BASIS, | |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| * See the License for the specific language governing permissions and | |
| * limitations under the License. | |
| */ | |
| Object.defineProperty(exports, "__esModule", { value: true }); | |
| exports.HttpPollingDatafileManager = browserDatafileManager.default; | |
| }); | |
| unwrapExports(index_browser); | |
| index_browser.HttpPollingDatafileManager; | |
| var murmurhash = createCommonjsModule(function (module) { | |
| (function(){ | |
| /** | |
| * JS Implementation of MurmurHash2 | |
| * | |
| * @author <a href="mailto:[email protected]">Gary Court</a> | |
| * @see http://github.com/garycourt/murmurhash-js | |
| * @author <a href="mailto:[email protected]">Austin Appleby</a> | |
| * @see http://sites.google.com/site/murmurhash/ | |
| * | |
| * @param {string} str ASCII only | |
| * @param {number} seed Positive integer only | |
| * @return {number} 32-bit positive integer hash | |
| */ | |
| function MurmurHashV2(str, seed) { | |
| var | |
| l = str.length, | |
| h = seed ^ l, | |
| i = 0, | |
| k; | |
| while (l >= 4) { | |
| k = | |
| ((str.charCodeAt(i) & 0xff)) | | |
| ((str.charCodeAt(++i) & 0xff) << 8) | | |
| ((str.charCodeAt(++i) & 0xff) << 16) | | |
| ((str.charCodeAt(++i) & 0xff) << 24); | |
| k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); | |
| k ^= k >>> 24; | |
| k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16)); | |
| h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k; | |
| l -= 4; | |
| ++i; | |
| } | |
| switch (l) { | |
| case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16; | |
| case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8; | |
| case 1: h ^= (str.charCodeAt(i) & 0xff); | |
| h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); | |
| } | |
| h ^= h >>> 13; | |
| h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)); | |
| h ^= h >>> 15; | |
| return h >>> 0; | |
| } | |
| /** | |
| * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) | |
| * | |
| * @author <a href="mailto:[email protected]">Gary Court</a> | |
| * @see http://github.com/garycourt/murmurhash-js | |
| * @author <a href="mailto:[email protected]">Austin Appleby</a> | |
| * @see http://sites.google.com/site/murmurhash/ | |
| * | |
| * @param {string} key ASCII only | |
| * @param {number} seed Positive integer only | |
| * @return {number} 32-bit positive integer hash | |
| */ | |
| function MurmurHashV3(key, seed) { | |
| var remainder, bytes, h1, h1b, c1, c2, k1, i; | |
| remainder = key.length & 3; // key.length % 4 | |
| bytes = key.length - remainder; | |
| h1 = seed; | |
| c1 = 0xcc9e2d51; | |
| c2 = 0x1b873593; | |
| i = 0; | |
| while (i < bytes) { | |
| k1 = | |
| ((key.charCodeAt(i) & 0xff)) | | |
| ((key.charCodeAt(++i) & 0xff) << 8) | | |
| ((key.charCodeAt(++i) & 0xff) << 16) | | |
| ((key.charCodeAt(++i) & 0xff) << 24); | |
| ++i; | |
| k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff; | |
| k1 = (k1 << 15) | (k1 >>> 17); | |
| k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff; | |
| h1 ^= k1; | |
| h1 = (h1 << 13) | (h1 >>> 19); | |
| h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff; | |
| h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16)); | |
| } | |
| k1 = 0; | |
| switch (remainder) { | |
| case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; | |
| case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; | |
| case 1: k1 ^= (key.charCodeAt(i) & 0xff); | |
| k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; | |
| k1 = (k1 << 15) | (k1 >>> 17); | |
| k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; | |
| h1 ^= k1; | |
| } | |
| h1 ^= key.length; | |
| h1 ^= h1 >>> 16; | |
| h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff; | |
| h1 ^= h1 >>> 13; | |
| h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff; | |
| h1 ^= h1 >>> 16; | |
| return h1 >>> 0; | |
| } | |
| var murmur = MurmurHashV3; | |
| murmur.v2 = MurmurHashV2; | |
| murmur.v3 = MurmurHashV3; | |
| { | |
| module.exports = murmur; | |
| } | |
| }()); | |
| }); | |
| var optimizely_browser_min = createCommonjsModule(function (module, exports) { | |
| Object.defineProperty(exports,"__esModule",{value:!0});var e,t=lib$2,r=lib,i=lib$1,n=index_browser,o=(e=murmurhash)&&"object"==typeof e&&"default"in e?e.default:e,s=function(){return (s=Object.assign||function(e){for(var t,r=1,i=arguments.length;r<i;r++)for(var n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)};function a(){for(var e=0,t=0,r=arguments.length;t<r;t++)e+=arguments[t].length;var i=Array(e),n=0;for(t=0;t<r;t++)for(var o=arguments[t],s=0,a=o.length;s<a;s++,n++)i[n]=o[s];return i}var u={NOTSET:0,DEBUG:1,INFO:2,WARNING:3,ERROR:4},l={CONDITION_EVALUATOR_ERROR:"%s: Error evaluating audience condition of type %s: %s",DATAFILE_AND_SDK_KEY_MISSING:"%s: You must provide at least one of sdkKey or datafile. Cannot start Optimizely",EXPERIMENT_KEY_NOT_IN_DATAFILE:"%s: Experiment key %s is not in datafile.",FEATURE_NOT_IN_DATAFILE:"%s: Feature key %s is not in datafile.",IMPROPERLY_FORMATTED_EXPERIMENT:"%s: Experiment key %s is improperly formatted.",INVALID_ATTRIBUTES:"%s: Provided attributes are in an invalid format.",INVALID_BUCKETING_ID:"%s: Unable to generate hash for bucketing ID %s: %s",INVALID_DATAFILE:"%s: Datafile is invalid - property %s: %s",INVALID_DATAFILE_MALFORMED:"%s: Datafile is invalid because it is malformed.",INVALID_CONFIG:"%s: Provided Optimizely config is in an invalid format.",INVALID_JSON:"%s: JSON object is not valid.",INVALID_ERROR_HANDLER:'%s: Provided "errorHandler" is in an invalid format.',INVALID_EVENT_DISPATCHER:'%s: Provided "eventDispatcher" is in an invalid format.',INVALID_EVENT_TAGS:"%s: Provided event tags are in an invalid format.",INVALID_EXPERIMENT_KEY:"%s: Experiment key %s is not in datafile. It is either invalid, paused, or archived.",INVALID_EXPERIMENT_ID:"%s: Experiment ID %s is not in datafile.",INVALID_GROUP_ID:"%s: Group ID %s is not in datafile.",INVALID_LOGGER:'%s: Provided "logger" is in an invalid format.',INVALID_ROLLOUT_ID:"%s: Invalid rollout ID %s attached to feature %s",INVALID_USER_ID:"%s: Provided user ID is in an invalid format.",INVALID_USER_PROFILE_SERVICE:"%s: Provided user profile service instance is in an invalid format: %s.",NO_DATAFILE_SPECIFIED:"%s: No datafile specified. Cannot start optimizely.",NO_JSON_PROVIDED:"%s: No JSON object to validate against schema.",NO_VARIATION_FOR_EXPERIMENT_KEY:"%s: No variation key %s defined in datafile for experiment %s.",UNDEFINED_ATTRIBUTE:"%s: Provided attribute: %s has an undefined value.",UNRECOGNIZED_ATTRIBUTE:"%s: Unrecognized attribute %s provided. Pruning before sending event to Optimizely.",UNABLE_TO_CAST_VALUE:"%s: Unable to cast value %s to type %s, returning null.",USER_NOT_IN_FORCED_VARIATION:"%s: User %s is not in the forced variation map. Cannot remove their forced variation.",USER_PROFILE_LOOKUP_ERROR:'%s: Error while looking up user profile for user ID "%s": %s.',USER_PROFILE_SAVE_ERROR:'%s: Error while saving user profile for user ID "%s": %s.',VARIABLE_KEY_NOT_IN_DATAFILE:'%s: Variable with key "%s" associated with feature with key "%s" is not in datafile.',VARIATION_ID_NOT_IN_DATAFILE:"%s: No variation ID %s defined in datafile for experiment %s.",VARIATION_ID_NOT_IN_DATAFILE_NO_EXPERIMENT:"%s: Variation ID %s is not in the datafile.",INVALID_INPUT_FORMAT:"%s: Provided %s is in an invalid format.",INVALID_DATAFILE_VERSION:"%s: This version of the JavaScript SDK does not support the given datafile version: %s",INVALID_VARIATION_KEY:"%s: Provided variation key is in an invalid format."},E={ACTIVATE_USER:"%s: Activating user %s in experiment %s.",DISPATCH_CONVERSION_EVENT:"%s: Dispatching conversion event to URL %s with params %s.",DISPATCH_IMPRESSION_EVENT:"%s: Dispatching impression event to URL %s with params %s.",DEPRECATED_EVENT_VALUE:"%s: Event value is deprecated in %s call.",EVENT_KEY_NOT_FOUND:"%s: Event key %s is not in datafile.",EXPERIMENT_NOT_RUNNING:"%s: Experiment %s is not running.",FEATURE_ENABLED_FOR_USER:"%s: Feature %s is enabled for user %s.",FEATURE_NOT_ENABLED_FOR_USER:"%s: Feature %s is not enabled for user %s.",FEATURE_HAS_NO_EXPERIMENTS:"%s: Feature %s is not attached to any experiments.",FAILED_TO_PARSE_VALUE:'%s: Failed to parse event value "%s" from event tags.',FAILED_TO_PARSE_REVENUE:'%s: Failed to parse revenue value "%s" from event tags.',FORCED_BUCKETING_FAILED:"%s: Variation key %s is not in datafile. Not activating user %s.",INVALID_OBJECT:"%s: Optimizely object is not valid. Failing %s.",INVALID_CLIENT_ENGINE:"%s: Invalid client engine passed: %s. Defaulting to node-sdk.",INVALID_DEFAULT_DECIDE_OPTIONS:"%s: Provided default decide options is not an array.",INVALID_DECIDE_OPTIONS:"%s: Provided decide options is not an array. Using default decide options.",INVALID_VARIATION_ID:"%s: Bucketed into an invalid variation ID. Returning null.",NOTIFICATION_LISTENER_EXCEPTION:"%s: Notification listener for (%s) threw exception: %s",NO_ROLLOUT_EXISTS:"%s: There is no rollout of feature %s.",NOT_ACTIVATING_USER:"%s: Not activating user %s for experiment %s.",NOT_TRACKING_USER:"%s: Not tracking user %s.",PARSED_REVENUE_VALUE:'%s: Parsed revenue value "%s" from event tags.',PARSED_NUMERIC_VALUE:'%s: Parsed event value "%s" from event tags.',RETURNING_STORED_VARIATION:'%s: Returning previously activated variation "%s" of experiment "%s" for user "%s" from user profile.',ROLLOUT_HAS_NO_EXPERIMENTS:"%s: Rollout of feature %s has no experiments",SAVED_VARIATION:'%s: Saved variation "%s" of experiment "%s" for user "%s".',SAVED_VARIATION_NOT_FOUND:"%s: User %s was previously bucketed into variation with ID %s for experiment %s, but no matching variation was found.",SHOULD_NOT_DISPATCH_ACTIVATE:'%s: Experiment %s is not in "Running" state. Not activating user.',SKIPPING_JSON_VALIDATION:"%s: Skipping JSON schema validation.",TRACK_EVENT:"%s: Tracking event %s for user %s.",UNRECOGNIZED_DECIDE_OPTION:"%s: Unrecognized decide option %s provided.",USER_ASSIGNED_TO_EXPERIMENT_BUCKET:"%s: Assigned bucket %s to user with bucketing ID %s.",USER_BUCKETED_INTO_EXPERIMENT_IN_GROUP:"%s: User %s is in experiment %s of group %s.",USER_BUCKETED_INTO_TARGETING_RULE:"%s: User %s bucketed into targeting rule %s.",USER_IN_FEATURE_EXPERIMENT:"%s: User %s is in variation %s of experiment %s on the feature %s.",USER_IN_ROLLOUT:"%s: User %s is in rollout of feature %s.",USER_BUCKETED_INTO_EVERYONE_TARGETING_RULE:"%s: User %s bucketed into everyone targeting rule.",USER_NOT_BUCKETED_INTO_EVERYONE_TARGETING_RULE:"%s: User %s not bucketed into everyone targeting rule due to traffic allocation.",USER_NOT_BUCKETED_INTO_EXPERIMENT_IN_GROUP:"%s: User %s is not in experiment %s of group %s.",USER_NOT_BUCKETED_INTO_ANY_EXPERIMENT_IN_GROUP:"%s: User %s is not in any experiment of group %s.",USER_NOT_BUCKETED_INTO_TARGETING_RULE:"%s User %s not bucketed into targeting rule %s due to traffic allocation. Trying everyone rule.",USER_NOT_IN_FEATURE_EXPERIMENT:"%s: User %s is not in any experiment on the feature %s.",USER_NOT_IN_ROLLOUT:"%s: User %s is not in rollout of feature %s.",USER_FORCED_IN_VARIATION:"%s: User %s is forced in variation %s.",USER_MAPPED_TO_FORCED_VARIATION:"%s: Set variation %s for experiment %s and user %s in the forced variation map.",USER_DOESNT_MEET_CONDITIONS_FOR_TARGETING_RULE:"%s: User %s does not meet conditions for targeting rule %s.",USER_MEETS_CONDITIONS_FOR_TARGETING_RULE:"%s: User %s meets conditions for targeting rule %s.",USER_HAS_VARIATION:"%s: User %s is in variation %s of experiment %s.",USER_HAS_FORCED_VARIATION:"%s: Variation %s is mapped to experiment %s and user %s in the forced variation map.",USER_HAS_NO_VARIATION:"%s: User %s is in no variation of experiment %s.",USER_HAS_NO_FORCED_VARIATION:"%s: User %s is not in the forced variation map.",USER_HAS_NO_FORCED_VARIATION_FOR_EXPERIMENT:"%s: No experiment %s mapped to user %s in the forced variation map.",USER_NOT_IN_ANY_EXPERIMENT:"%s: User %s is not in any experiment of group %s.",USER_NOT_IN_EXPERIMENT:"%s: User %s does not meet conditions to be in experiment %s.",USER_RECEIVED_DEFAULT_VARIABLE_VALUE:'%s: User "%s" is not in any variation or rollout rule. Returning default value for variable "%s" of feature flag "%s".',FEATURE_NOT_ENABLED_RETURN_DEFAULT_VARIABLE_VALUE:'%s: Feature "%s" is not enabled for user %s. Returning the default variable value "%s".',VARIABLE_NOT_USED_RETURN_DEFAULT_VARIABLE_VALUE:'%s: Variable "%s" is not used in variation "%s". Returning default value.',USER_RECEIVED_VARIABLE_VALUE:'%s: Got variable value "%s" for variable "%s" of feature flag "%s"',VALID_DATAFILE:"%s: Datafile is valid.",VALID_USER_PROFILE_SERVICE:"%s: Valid user profile service provided.",VARIATION_REMOVED_FOR_USER:"%s: Variation mapped to experiment %s has been removed for user %s.",VARIABLE_REQUESTED_WITH_WRONG_TYPE:'%s: Requested variable type "%s", but variable is of type "%s". Use correct API to retrieve value. Returning None.',VALID_BUCKETING_ID:'%s: BucketingId is valid: "%s"',BUCKETING_ID_NOT_STRING:"%s: BucketingID attribute is not a string. Defaulted to userId",EVALUATING_AUDIENCE:'%s: Starting to evaluate audience "%s" with conditions: %s.',EVALUATING_AUDIENCES_COMBINED:'%s: Evaluating audiences for %s "%s": %s.',AUDIENCE_EVALUATION_RESULT:'%s: Audience "%s" evaluated to %s.',AUDIENCE_EVALUATION_RESULT_COMBINED:"%s: Audiences for %s %s collectively evaluated to %s.",MISSING_ATTRIBUTE_VALUE:'%s: Audience condition %s evaluated to UNKNOWN because no value was passed for user attribute "%s".',UNEXPECTED_CONDITION_VALUE:"%s: Audience condition %s evaluated to UNKNOWN because the condition value is not supported.",UNEXPECTED_TYPE:'%s: Audience condition %s evaluated to UNKNOWN because a value of type "%s" was passed for user attribute "%s".',UNEXPECTED_TYPE_NULL:'%s: Audience condition %s evaluated to UNKNOWN because a null value was passed for user attribute "%s".',UNKNOWN_CONDITION_TYPE:"%s: Audience condition %s has an unknown condition type. You may need to upgrade to a newer release of the Optimizely SDK.",UNKNOWN_MATCH_TYPE:"%s: Audience condition %s uses an unknown match type. You may need to upgrade to a newer release of the Optimizely SDK.",UPDATED_OPTIMIZELY_CONFIG:"%s: Updated Optimizely config to revision %s (project id %s)",OUT_OF_BOUNDS:'%s: Audience condition %s evaluated to UNKNOWN because the number value for user attribute "%s" is not in the range [-2^53, +2^53].',UNABLE_TO_ATTACH_UNLOAD:'%s: unable to bind optimizely.close() to page unload event: "%s"'},f={REVENUE:"revenue",VALUE:"value"},p={BOT_FILTERING:"$opt_bot_filtering",BUCKETING_ID:"$opt_bucketing_id",STICKY_BUCKETING_KEY:"$opt_experiment_bucket_map",USER_AGENT:"$opt_user_agent"},I=["node-sdk","react-sdk","javascript-sdk"],_=i.NOTIFICATION_TYPES,g={AB_TEST:"ab-test",FEATURE:"feature",FEATURE_TEST:"feature-test",FEATURE_VARIABLE:"feature-variable",ALL_FEATURE_VARIABLES:"all-feature-variables",FLAG:"flag"},c={FEATURE_TEST:"feature-test",ROLLOUT:"rollout",EXPERIMENT:"experiment"},d={RULE:"rule",EXPERIMENT:"experiment"},O={BOOLEAN:"boolean",DOUBLE:"double",INTEGER:"integer",STRING:"string",JSON:"json"},N={V2:"2",V3:"3",V4:"4"},R={SDK_NOT_READY:"Optimizely SDK not configured properly yet.",FLAG_KEY_INVALID:'No flag was found for key "%s".',VARIABLE_VALUE_INVALID:'Variable value for key "%s" is invalid or wrong type.'},v=Object.freeze({__proto__:null,LOG_LEVEL:u,ERROR_MESSAGES:l,LOG_MESSAGES:E,RESERVED_EVENT_KEYWORDS:f,CONTROL_ATTRIBUTES:p,JAVASCRIPT_CLIENT_ENGINE:"javascript-sdk",NODE_CLIENT_ENGINE:"node-sdk",REACT_CLIENT_ENGINE:"react-sdk",NODE_CLIENT_VERSION:"4.5.1",VALID_CLIENT_ENGINES:I,NOTIFICATION_TYPES:_,DECISION_NOTIFICATION_TYPES:g,DECISION_SOURCES:c,AUDIENCE_EVALUATION_TYPES:d,FEATURE_VARIABLE_TYPES:O,DATAFILE_VERSIONS:N,DECISION_MESSAGES:R}),h="CONFIG_VALIDATOR",T=[N.V2,N.V3,N.V4],y=function(e){if("object"==typeof e&&null!==e){var t=e,r=t.errorHandler,n=t.eventDispatcher,o=t.logger;if(r&&"function"!=typeof r.handleError)throw new Error(i.sprintf(l.INVALID_ERROR_HANDLER,h));if(n&&"function"!=typeof n.dispatchEvent)throw new Error(i.sprintf(l.INVALID_EVENT_DISPATCHER,h));if(o&&"function"!=typeof o.log)throw new Error(i.sprintf(l.INVALID_LOGGER,h));return !0}throw new Error(i.sprintf(l.INVALID_CONFIG,h))},A=function(e){if(!e)throw new Error(i.sprintf(l.NO_DATAFILE_SPECIFIED,h));if("string"==typeof e)try{e=JSON.parse(e);}catch(e){throw new Error(i.sprintf(l.INVALID_DATAFILE_MALFORMED,h))}if("object"==typeof e&&!Array.isArray(e)&&null!==e&&-1===T.indexOf(e.version))throw new Error(i.sprintf(l.INVALID_DATAFILE_VERSION,h,e.version));return e},U={handleError:function(){}},L=function(e){return Object.keys(e).map((function(t){return encodeURIComponent(t)+"="+encodeURIComponent(e[t])})).join("&")},D={dispatchEvent:function(e,t){var r,i=e.url,n=e.params;"POST"===e.httpVerb?((r=new XMLHttpRequest).open("POST",i,!0),r.setRequestHeader("Content-Type","application/json"),r.onreadystatechange=function(){if(4===r.readyState&&t&&"function"==typeof t)try{t({statusCode:r.status});}catch(e){}},r.send(JSON.stringify(n))):(i+="?wxhr=true",n&&(i+="&"+L(n)),(r=new XMLHttpRequest).open("GET",i,!0),r.onreadystatechange=function(){if(4===r.readyState&&t&&"function"==typeof t)try{t();}catch(e){}},r.send());}};function S(){}S.prototype.log=function(){};var m,V={createLogger:function(e){return new t.ConsoleLogHandler(e)},createNoOpLogger:function(){return new S}};function C(e,t,r){return {variationKey:null,enabled:!1,variables:{},ruleKey:null,flagKey:e,userContext:t,reasons:r}}(m=exports.OptimizelyDecideOption||(exports.OptimizelyDecideOption={})).DISABLE_DECISION_EVENT="DISABLE_DECISION_EVENT",m.ENABLED_FLAGS_ONLY="ENABLED_FLAGS_ONLY",m.IGNORE_USER_PROFILE_SERVICE="IGNORE_USER_PROFILE_SERVICE",m.INCLUDE_REASONS="INCLUDE_REASONS",m.EXCLUDE_VARIABLES="EXCLUDE_VARIABLES";var P=function(){function e(e){var t,r=e.optimizely,i=e.userId,n=e.attributes;this.optimizely=r,this.userId=i,this.attributes=null!==(t=s({},n))&&void 0!==t?t:{};}return e.prototype.setAttribute=function(e,t){this.attributes[e]=t;},e.prototype.getUserId=function(){return this.userId},e.prototype.getAttributes=function(){return s({},this.attributes)},e.prototype.getOptimizely=function(){return this.optimizely},e.prototype.decide=function(e,t){return void 0===t&&(t=[]),this.optimizely.decide(this.cloneUserContext(),e,t)},e.prototype.decideForKeys=function(e,t){return void 0===t&&(t=[]),this.optimizely.decideForKeys(this.cloneUserContext(),e,t)},e.prototype.decideAll=function(e){return void 0===e&&(e=[]),this.optimizely.decideAll(this.cloneUserContext(),e)},e.prototype.trackEvent=function(e,t){this.optimizely.track(e,this.userId,this.attributes,t);},e.prototype.cloneUserContext=function(){return new e({optimizely:this.getOptimizely(),userId:this.getUserId(),attributes:this.getAttributes()})},e}(),b=Math.pow(2,53);var F={assign:function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(!e)return {};if("function"==typeof Object.assign)return Object.assign.apply(Object,a([e],t));for(var i=Object(e),n=0;n<t.length;n++){var o=t[n];if(null!=o)for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(i[s]=o[s]);}return i},currentTimestamp:function(){return Math.round((new Date).getTime())},isSafeInteger:function(e){return "number"==typeof e&&Math.abs(e)<=b},keyBy:function(e,t){return e?i.keyBy(e,(function(e){return e[t]})):{}},uuid:i.generateUUID,isNumber:function(e){return "number"==typeof e}},M="PROJECT_CONFIG";var k=function(e,t){void 0===t&&(t=null);var r,n,o=(r=e,(n=F.assign({},r)).audiences=(r.audiences||[]).map((function(e){return F.assign({},e)})),n.experiments=(r.experiments||[]).map((function(e){return F.assign({},e)})),n.featureFlags=(r.featureFlags||[]).map((function(e){return F.assign({},e)})),n.groups=(r.groups||[]).map((function(e){var t=F.assign({},e);return t.experiments=(e.experiments||[]).map((function(e){return F.assign({},e)})),t})),n.rollouts=(r.rollouts||[]).map((function(e){var t=F.assign({},e);return t.experiments=(e.experiments||[]).map((function(e){return F.assign({},e)})),t})),n);return o.__datafileStr=null===t?JSON.stringify(e):t,(o.audiences||[]).forEach((function(e){e.conditions=JSON.parse(e.conditions);})),o.audiencesById=F.keyBy(o.audiences,"id"),F.assign(o.audiencesById,F.keyBy(o.typedAudiences,"id")),o.attributeKeyMap=F.keyBy(o.attributes,"key"),o.eventKeyMap=F.keyBy(o.events,"key"),o.groupIdMap=F.keyBy(o.groups,"id"),Object.keys(o.groupIdMap||{}).forEach((function(e){(o.groupIdMap[e].experiments||[]).forEach((function(t){o.experiments.push(F.assign(t,{groupId:e}));}));})),o.rolloutIdMap=F.keyBy(o.rollouts||[],"id"),i.objectValues(o.rolloutIdMap||{}).forEach((function(e){(e.experiments||[]).forEach((function(e){o.experiments.push(e),e.variationKeyMap=F.keyBy(e.variations,"key");}));})),o.experimentKeyMap=F.keyBy(o.experiments,"key"),o.experimentIdMap=F.keyBy(o.experiments,"id"),o.variationIdMap={},o.variationVariableUsageMap={},(o.experiments||[]).forEach((function(e){e.variationKeyMap=F.keyBy(e.variations,"key"),F.assign(o.variationIdMap,F.keyBy(e.variations,"id")),i.objectValues(e.variationKeyMap||{}).forEach((function(e){e.variables&&(o.variationVariableUsageMap[e.id]=F.keyBy(e.variables,"id"));}));})),o.experimentFeatureMap={},o.featureKeyMap=F.keyBy(o.featureFlags||[],"key"),i.objectValues(o.featureKeyMap||{}).forEach((function(e){e.variables.forEach((function(e){e.type===O.STRING&&e.subType===O.JSON&&(e.type=O.JSON,delete e.subType);})),e.variableKeyMap=F.keyBy(e.variables,"key"),(e.experimentIds||[]).forEach((function(t){o.experimentFeatureMap[t]?o.experimentFeatureMap[t].push(e.id):o.experimentFeatureMap[t]=[e.id];var r=o.experimentIdMap[t];r.groupId&&!e.groupId&&(e.groupId=r.groupId);}));})),o},B=function(e,t){var r=e.experimentKeyMap[t];if(!r)throw new Error(i.sprintf(l.INVALID_EXPERIMENT_KEY,M,t));return r.id},x=function(e,t){var r=e.experimentKeyMap[t];if(!r)throw new Error(i.sprintf(l.INVALID_EXPERIMENT_KEY,M,t));return r.status},K=function(e,t){return "Running"===x(e,t)},G=function(e,t,r){var i=e.experimentKeyMap[t];return i.variationKeyMap.hasOwnProperty(r)?i.variationKeyMap[r].id:null},w=function(e,t){if(e.experimentKeyMap.hasOwnProperty(t)){var r=e.experimentKeyMap[t];if(r)return r}throw new Error(i.sprintf(l.EXPERIMENT_KEY_NOT_IN_DATAFILE,M,t))},j=function(e,t,r){if(e.featureKeyMap.hasOwnProperty(t)){var n=e.featureKeyMap[t];if(n)return n}return r.log(u.ERROR,i.sprintf(l.FEATURE_NOT_IN_DATAFILE,M,t)),null},Y=function(e,t,r,n){var o=e.featureKeyMap[t];if(!o)return n.log(u.ERROR,i.sprintf(l.FEATURE_NOT_IN_DATAFILE,M,t)),null;var s=o.variableKeyMap[r];return s||(n.log(u.ERROR,i.sprintf(l.VARIABLE_KEY_NOT_IN_DATAFILE,M,r,t)),null)},H=function(e,t,r,n){if(!t||!r)return null;if(!e.variationVariableUsageMap.hasOwnProperty(r.id))return n.log(u.ERROR,i.sprintf(l.VARIATION_ID_NOT_IN_DATAFILE_NO_EXPERIMENT,M,r.id)),null;var o=e.variationVariableUsageMap[r.id][t.id];return o?o.value:null},X=function(e,t,r){var n;switch(t){case O.BOOLEAN:"true"!==e&&"false"!==e?(r.log(u.ERROR,i.sprintf(l.UNABLE_TO_CAST_VALUE,M,e,t)),n=null):n="true"===e;break;case O.INTEGER:n=parseInt(e,10),isNaN(n)&&(r.log(u.ERROR,i.sprintf(l.UNABLE_TO_CAST_VALUE,M,e,t)),n=null);break;case O.DOUBLE:n=parseFloat(e),isNaN(n)&&(r.log(u.ERROR,i.sprintf(l.UNABLE_TO_CAST_VALUE,M,e,t)),n=null);break;case O.JSON:try{n=JSON.parse(e);}catch(o){r.log(u.ERROR,i.sprintf(l.UNABLE_TO_CAST_VALUE,M,e,t)),n=null;}break;default:n=e;}return n},z=function(e,t){return e.eventKeyMap.hasOwnProperty(t)},J=function(e,t){return e.experimentFeatureMap.hasOwnProperty(t)},Z=function(e){return !!e.sendFlagDecisions},W=B,q=function(e,t){var r=e.experimentIdMap[t];if(!r)throw new Error(i.sprintf(l.INVALID_EXPERIMENT_ID,M,t));return r.layerId},$=function(e,t,r){var n=e.attributeKeyMap[t],o=0===t.indexOf("$opt_");return n?(o&&r.log(u.WARN,i.sprintf("Attribute %s unexpectedly has reserved prefix %s; using attribute ID instead of reserved attribute name.",t,"$opt_")),n.id):o?t:(r.log(u.DEBUG,i.sprintf(l.UNRECOGNIZED_ATTRIBUTE,M,t)),null)},Q=function(e,t){var r=e.eventKeyMap[t];return r?r.id:null},ee=function(e,t){return "Running"===x(e,t)},te=function(e,t){var r=e.experimentKeyMap[t];if(!r)throw new Error(i.sprintf(l.INVALID_EXPERIMENT_KEY,M,t));return r.audienceConditions||r.audienceIds},re=function(e,t){return e.variationIdMap.hasOwnProperty(t)?e.variationIdMap[t].key:null},ie=G,ne=w,oe=function(e,t){var r=e.experimentKeyMap[t];if(!r)throw new Error(i.sprintf(l.INVALID_EXPERIMENT_KEY,M,t));return r.trafficAllocation},se=function(e,t,r){if(e.experimentIdMap.hasOwnProperty(t)){var n=e.experimentIdMap[t];if(n)return n}return r.log(u.ERROR,i.sprintf(l.INVALID_EXPERIMENT_ID,M,t)),null},ae=function(e){return e.audiencesById},ue=function(e){return e.__datafileStr},le=function(e){var t;try{t=A(e.datafile);}catch(e){return {configObj:null,error:e}}if(e.jsonSchemaValidator)try{e.jsonSchemaValidator.validate(t),e.logger.log(u.INFO,i.sprintf(E.VALID_DATAFILE,M));}catch(e){return {configObj:null,error:e}}else e.logger.log(u.INFO,i.sprintf(E.SKIPPING_JSON_VALIDATION,M));var r=[t];return "string"==typeof e.datafile&&r.push(e.datafile),{configObj:k.apply(void 0,r),error:null}},Ee=function(){function e(t,r){this.experimentsMap=e.getExperimentsMap(t),this.featuresMap=e.getFeaturesMap(t,this.experimentsMap),this.revision=t.revision,this.datafile=r;}return e.prototype.getDatafile=function(){return this.datafile},e.getRolloutExperimentIds=function(e){return (e||[]).reduce((function(e,t){return t.experiments.forEach((function(t){e[t.id]=!0;})),e}),{})},e.getExperimentsMap=function(e){var t=this,r=this.getRolloutExperimentIds(e.rollouts),i=(e.featureFlags||[]).reduce((function(e,t){return e[t.id]=t.variables,e}),{});return (e.experiments||[]).reduce((function(n,o){return r[o.id]||(n[o.key]={id:o.id,key:o.key,variationsMap:(o.variations||[]).reduce((function(r,n){return r[n.key]={id:n.id,key:n.key,variablesMap:t.getMergedVariablesMap(e,n,o.id,i)},J(e,o.id)&&(r[n.key].featureEnabled=n.featureEnabled),r}),{})}),n}),{})},e.getMergedVariablesMap=function(e,t,r,i){var n=e.experimentFeatureMap[r],o={};if(n){var s=i[n.toString()],a=(t.variables||[]).reduce((function(e,t){return e[t.id]={id:t.id,value:t.value},e}),{});o=(s||[]).reduce((function(e,r){var i=a[r.id],n=t.featureEnabled&&i?i.value:r.defaultValue;return e[r.key]={id:r.id,key:r.key,type:r.type,value:n},e}),{});}return o},e.getFeaturesMap=function(e,t){return (e.featureFlags||[]).reduce((function(r,i){return r[i.key]={id:i.id,key:i.key,experimentsMap:(i.experimentIds||[]).reduce((function(r,i){var n=e.experimentIdMap[i].key;return r[n]=t[n],r}),{}),variablesMap:(i.variables||[]).reduce((function(e,t){return e[t.key]={id:t.id,key:t.key,type:t.type,value:t.defaultValue},e}),{})},r}),{})},e}();var fe=t.getLogger();function pe(e,t){return e instanceof Error?e.message:t||"Unknown error"}function Ie(e){try{this.__initialize(e);}catch(e){fe.error(e),this.__updateListeners=[],this.__configObj=null,this.__optimizelyConfigObj=null,this.__readyPromise=Promise.resolve({success:!1,reason:pe(e,"Error in initialize")});}}Ie.prototype.__initialize=function(e){if(this.__updateListeners=[],this.jsonSchemaValidator=e.jsonSchemaValidator,!e.datafile&&!e.sdkKey){this.__configObj=null;var t=new Error(i.sprintf(l.DATAFILE_AND_SDK_KEY_MISSING,"PROJECT_CONFIG_MANAGER"));return this.__readyPromise=Promise.resolve({success:!1,reason:pe(t)}),void fe.error(t)}var r;if(e.datafile?(r=this.__handleNewDatafile(e.datafile))&&(this.__configObj=null):this.__configObj=null,e.sdkKey){var o={sdkKey:e.sdkKey};this.__validateDatafileOptions(e.datafileOptions)&&F.assign(o,e.datafileOptions),this.__configObj&&(o.datafile=ue(this.__configObj)),this.datafileManager=new n.HttpPollingDatafileManager(o),this.datafileManager.start(),this.__readyPromise=this.datafileManager.onReady().then(this.__onDatafileManagerReadyFulfill.bind(this),this.__onDatafileManagerReadyReject.bind(this)),this.datafileManager.on("update",this.__onDatafileManagerUpdate.bind(this));}else this.__configObj?this.__readyPromise=Promise.resolve({success:!0}):this.__readyPromise=Promise.resolve({success:!1,reason:pe(r,"Invalid datafile")});},Ie.prototype.__onDatafileManagerReadyFulfill=function(){var e=this.__handleNewDatafile(this.datafileManager.get());return e?{success:!1,reason:pe(e)}:{success:!0}},Ie.prototype.__onDatafileManagerReadyReject=function(e){return {success:!1,reason:pe(e,"Failed to become ready")}},Ie.prototype.__onDatafileManagerUpdate=function(){this.__handleNewDatafile(this.datafileManager.get());},Ie.prototype.__validateDatafileOptions=function(e){return void 0===e||"object"==typeof e&&null!==e},Ie.prototype.__handleNewDatafile=function(e){var t=le({datafile:e,jsonSchemaValidator:this.jsonSchemaValidator,logger:fe}),r=t.configObj,i=t.error;i?fe.error(i):(this.__configObj?this.__configObj.revision:"null")!==r.revision&&(this.__configObj=r,this.__optimizelyConfigObj=function(e,t){return new Ee(e,t)}(this.__configObj,ue(this.__configObj)),this.__updateListeners.forEach((function(e){e(r);})));return i},Ie.prototype.getConfig=function(){return this.__configObj},Ie.prototype.getOptimizelyConfig=function(){return this.__optimizelyConfigObj},Ie.prototype.onReady=function(){return this.__readyPromise},Ie.prototype.onUpdate=function(e){return this.__updateListeners.push(e),function(){var t=this.__updateListeners.indexOf(e);t>-1&&this.__updateListeners.splice(t,1);}.bind(this)},Ie.prototype.stop=function(){this.datafileManager&&this.datafileManager.stop(),this.__updateListeners=[];};var _e=function(){function e(e){var t=this;this.logger=e.logger,this.errorHandler=e.errorHandler,this.notificationListeners={},i.objectValues(_).forEach((function(e){t.notificationListeners[e]=[];})),this.listenerId=1;}return e.prototype.addNotificationListener=function(e,t){try{if(!(i.objectValues(_).indexOf(e)>-1))return -1;this.notificationListeners[e]||(this.notificationListeners[e]=[]);var r=!1;if((this.notificationListeners[e]||[]).forEach((function(e){e.callback!==t||(r=!0);})),r)return -1;this.notificationListeners[e].push({id:this.listenerId,callback:t});var n=this.listenerId;return this.listenerId+=1,n}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),-1}},e.prototype.removeNotificationListener=function(e){var t=this;try{var r,i;if(Object.keys(this.notificationListeners).some((function(n){return (t.notificationListeners[n]||[]).every((function(t,o){return t.id!==e||(r=o,i=n,!1)})),void 0!==r&&void 0!==i})),void 0!==r&&void 0!==i)return this.notificationListeners[i].splice(r,1),!0}catch(e){this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e);}return !1},e.prototype.clearAllNotificationListeners=function(){var e=this;try{i.objectValues(_).forEach((function(t){e.notificationListeners[t]=[];}));}catch(e){this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e);}},e.prototype.clearNotificationListeners=function(e){try{this.notificationListeners[e]=[];}catch(e){this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e);}},e.prototype.sendNotifications=function(e,t){var r=this;try{(this.notificationListeners[e]||[]).forEach((function(n){var o=n.callback;try{o(t);}catch(t){r.logger.log(u.ERROR,i.sprintf(E.NOTIFICATION_LISTENER_EXCEPTION,"NOTIFICATION_CENTER",e,t.message));}}));}catch(e){this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e);}},e}();var ge=Math.pow(2,32),ce=function(e,t,r,n){var o=i.sprintf("%s%s",t,e.id),s=Oe(o);n.log(u.DEBUG,i.sprintf(E.USER_ASSIGNED_TO_EXPERIMENT_BUCKET,"BUCKETER",s,r));var a=e.trafficAllocation;return de(s,a)},de=function(e,t){for(var r=0;r<t.length;r++)if(e<t[r].endOfRange)return t[r].entityId;return null},Oe=function(e){try{var t=o.v3(e,1)/ge;return Math.floor(1e4*t)}catch(t){throw new Error(i.sprintf(l.INVALID_BUCKETING_ID,"BUCKETER",e,t.message))}},Ne={bucket:function(e){var t=[],r=e.experimentKeyMap[e.experimentKey].groupId;if(r){var n=e.groupIdMap[r];if(!n)throw new Error(i.sprintf(l.INVALID_GROUP_ID,"BUCKETER",r));if("random"===n.policy){var o=ce(n,e.bucketingId,e.userId,e.logger);if(null===o){var s=i.sprintf(E.USER_NOT_IN_ANY_EXPERIMENT,"BUCKETER",e.userId,r);return e.logger.log(u.INFO,s),t.push(s),{result:null,reasons:t}}if(o!==e.experimentId){var a=i.sprintf(E.USER_NOT_BUCKETED_INTO_EXPERIMENT_IN_GROUP,"BUCKETER",e.userId,e.experimentKey,r);return e.logger.log(u.INFO,a),t.push(a),{result:null,reasons:t}}var f=i.sprintf(E.USER_BUCKETED_INTO_EXPERIMENT_IN_GROUP,"BUCKETER",e.userId,e.experimentKey,r);e.logger.log(u.INFO,f),t.push(f);}}var p=i.sprintf("%s%s",e.bucketingId,e.experimentId),I=Oe(p),_=i.sprintf(E.USER_ASSIGNED_TO_EXPERIMENT_BUCKET,"BUCKETER",I,e.userId);e.logger.log(u.DEBUG,_),t.push(_);var g=de(I,e.trafficAllocationConfig);if(null!==g&&!e.variationIdMap[g]){if(g){var c=i.sprintf(E.INVALID_VARIATION_ID,"BUCKETER");e.logger.log(u.WARNING,c),t.push(c);}return {result:null,reasons:t}}return {result:g,reasons:t}},bucketUserIntoExperiment:ce},Re=["and","or","not"];function ve(e,t){if(Array.isArray(e)){var r=e[0],i=e.slice(1);switch("string"==typeof r&&-1===Re.indexOf(r)&&(r="or",i=e),r){case"and":return function(e,t){var r=!1;if(Array.isArray(e)){for(var i=0;i<e.length;i++){var n=ve(e[i],t);if(!1===n)return !1;null===n&&(r=!0);}return !r||null}return null}(i,t);case"not":return function(e,t){if(Array.isArray(e)&&e.length>0){var r=ve(e[0],t);return null===r?null:!r}return null}(i,t);default:return function(e,t){var r=!1;if(Array.isArray(e)){for(var i=0;i<e.length;i++){var n=ve(e[i],t);if(!0===n)return !0;null===n&&(r=!0);}return !!r&&null}return null}(i,t)}}return t(e)}var he=t.getLogger();function Te(e){return /^\d+$/.test(e)}function ye(e){var t=e.indexOf("-"),r=e.indexOf("+");return !(t<0)&&(r<0||t<r)}function Ae(e){var t=e.indexOf("-"),r=e.indexOf("+");return !(r<0)&&(t<0||r<t)}function Ue(e){var t=e,r="";if(function(e){return /\s/.test(e)}(e))return he.warn(E.UNKNOWN_MATCH_TYPE,"SEMANTIC VERSION",e),null;if(ye(e)?(t=e.substring(0,e.indexOf("-")),r=e.substring(e.indexOf("-")+1)):Ae(e)&&(t=e.substring(0,e.indexOf("+")),r=e.substring(e.indexOf("+")+1)),"string"!=typeof t||"string"!=typeof r)return null;var i=t.split(".").length-1;if(i>2)return he.warn(E.UNKNOWN_MATCH_TYPE,"SEMANTIC VERSION",e),null;var n=t.split(".");if(n.length!=i+1)return he.warn(E.UNKNOWN_MATCH_TYPE,"SEMANTIC VERSION",e),null;for(var o=0,s=n;o<s.length;o++){if(!Te(s[o]))return he.warn(E.UNKNOWN_MATCH_TYPE,"SEMANTIC VERSION",e),null}return r&&n.push(r),n}var Le="CUSTOM_ATTRIBUTE_CONDITION_EVALUATOR",De=t.getLogger(),Se=["exact","exists","gt","ge","lt","le","substring","semver_eq","semver_lt","semver_le","semver_gt","semver_ge"],me={};function Ve(e){return "string"==typeof e||"boolean"==typeof e||F.isNumber(e)}function Ce(e,t){var r=e.value,i=typeof r,n=e.name,o=t[n],s=typeof o;return !Ve(r)||F.isNumber(r)&&!F.isSafeInteger(r)?(De.warn(E.UNEXPECTED_CONDITION_VALUE,Le,JSON.stringify(e)),null):null===o?(De.debug(E.UNEXPECTED_TYPE_NULL,Le,JSON.stringify(e),n),null):Ve(o)&&i===s?F.isNumber(o)&&!F.isSafeInteger(o)?(De.warn(E.OUT_OF_BOUNDS,Le,JSON.stringify(e),n),null):r===o:(De.warn(E.UNEXPECTED_TYPE,Le,JSON.stringify(e),s,n),null)}function Pe(e,t){var r=e.name,i=t[r],n=typeof i,o=e.value;return null!==o&&F.isSafeInteger(o)?null===i?(De.debug(E.UNEXPECTED_TYPE_NULL,Le,JSON.stringify(e),r),!1):F.isNumber(i)?!!F.isSafeInteger(i)||(De.warn(E.OUT_OF_BOUNDS,Le,JSON.stringify(e),r),!1):(De.warn(E.UNEXPECTED_TYPE,Le,JSON.stringify(e),n,r),!1):(De.warn(E.UNEXPECTED_CONDITION_VALUE,Le,JSON.stringify(e)),!1)}function be(e,t){var r=e.name,i=t[r],n=typeof i,o=e.value;return "string"!=typeof o?(De.warn(E.UNEXPECTED_CONDITION_VALUE,Le,JSON.stringify(e)),null):null===i?(De.debug(E.UNEXPECTED_TYPE_NULL,Le,JSON.stringify(e),r),null):"string"!=typeof i?(De.warn(E.UNEXPECTED_TYPE,Le,JSON.stringify(e),n,r),null):function(e,t){var r=Ue(t),i=Ue(e);if(!r||!i)return null;for(var n=r.length,o=0;o<i.length;o++){if(n<=o)return ye(e)||Ae(e)?1:-1;if(Te(r[o])){var s=parseInt(r[o]),a=parseInt(i[o]);if(s>a)return 1;if(s<a)return -1}else {if(r[o]<i[o])return ye(e)&&!ye(t)?1:-1;if(r[o]>i[o])return !ye(e)&&ye(t)?-1:1}}return ye(t)&&!ye(e)?-1:0}(o,i)}me.exact=Ce,me.exists=function(e,t){var r=t[e.name];return null!=r},me.gt=function(e,t){var r=t[e.name],i=e.value;if(!Pe(e,t)||null===i)return null;return r>i},me.ge=function(e,t){var r=t[e.name],i=e.value;if(!Pe(e,t)||null===i)return null;return r>=i},me.lt=function(e,t){var r=t[e.name],i=e.value;if(!Pe(e,t)||null===i)return null;return r<i},me.le=function(e,t){var r=t[e.name],i=e.value;if(!Pe(e,t)||null===i)return null;return r<=i},me.substring=function(e,t){var r=e.name,i=t[e.name],n=typeof i,o=e.value;if("string"!=typeof o)return De.warn(E.UNEXPECTED_CONDITION_VALUE,Le,JSON.stringify(e)),null;if(null===i)return De.debug(E.UNEXPECTED_TYPE_NULL,Le,JSON.stringify(e),r),null;if("string"!=typeof i)return De.warn(E.UNEXPECTED_TYPE,Le,JSON.stringify(e),n,r),null;return -1!==i.indexOf(o)},me.semver_eq=function(e,t){var r=be(e,t);if(null===r)return null;return 0===r},me.semver_gt=function(e,t){var r=be(e,t);if(null===r)return null;return r>0},me.semver_ge=function(e,t){var r=be(e,t);if(null===r)return null;return r>=0},me.semver_lt=function(e,t){var r=be(e,t);if(null===r)return null;return r<0},me.semver_le=function(e,t){var r=be(e,t);if(null===r)return null;return r<=0};var Fe=Object.freeze({__proto__:null,evaluate:function(e,t){var r=e.match;if(void 0!==r&&-1===Se.indexOf(r))return De.warn(E.UNKNOWN_MATCH_TYPE,Le,JSON.stringify(e)),null;var i=e.name;return t.hasOwnProperty(i)||"exists"==r?(r&&me[r]||Ce)(e,t):(De.debug(E.MISSING_ATTRIBUTE_VALUE,Le,JSON.stringify(e),i),null)}}),Me=t.getLogger();function ke(e){this.typeToEvaluatorMap=F.assign({},e,{custom_attribute:Fe});}function Be(e){return "string"==typeof e&&""!==e}ke.prototype.evaluate=function(e,t,r){if(!e||0===e.length)return !0;r||(r={});var n=function(e){var n=t[e];if(n){Me.log(u.DEBUG,i.sprintf(E.EVALUATING_AUDIENCE,"AUDIENCE_EVALUATOR",e,JSON.stringify(n.conditions)));var o=ve(n.conditions,this.evaluateConditionWithUserAttributes.bind(this,r)),s=null===o?"UNKNOWN":o.toString().toUpperCase();return Me.log(u.DEBUG,i.sprintf(E.AUDIENCE_EVALUATION_RESULT,"AUDIENCE_EVALUATOR",e,s)),o}return null}.bind(this);return ve(e,n)||!1},ke.prototype.evaluateConditionWithUserAttributes=function(e,t){var r=this.typeToEvaluatorMap[t.type];if(!r)return Me.log(u.WARNING,i.sprintf(E.UNKNOWN_CONDITION_TYPE,"AUDIENCE_EVALUATOR",JSON.stringify(t))),null;try{return r.evaluate(t,e,Me)}catch(e){Me.log(u.ERROR,i.sprintf(l.CONDITION_EVALUATOR_ERROR,"AUDIENCE_EVALUATOR",t.type,e.message));}return null};var xe="DECISION_SERVICE",Ke=l,Ge=u,we=E,je=c,Ye=d;function He(e){this.audienceEvaluator=new ke(e.UNSTABLE_conditionEvaluators),this.forcedVariationMap={},this.logger=e.logger,this.userProfileService=e.userProfileService||null;}He.prototype.getVariation=function(e,t,r,n,o){void 0===o&&(o={});var s=this._getBucketingId(r,n),a=[];if(!this.__checkIfExperimentIsActive(e,t)){var u=i.sprintf(we.EXPERIMENT_NOT_RUNNING,xe,t);return this.logger.log(Ge.INFO,u),a.push(u),{result:null,reasons:a}}var l=e.experimentKeyMap[t],E=this.getForcedVariation(e,t,r);a.push.apply(a,E.reasons);var f=E.result;if(f)return {result:f,reasons:a};var p=this.__getWhitelistedVariation(l,r);a.push.apply(a,p.reasons);var I=p.result;if(I)return {result:I.key,reasons:a};var _=o[exports.OptimizelyDecideOption.IGNORE_USER_PROFILE_SERVICE];if(!_){var g=this.__resolveExperimentBucketMap(r,n);if(I=this.__getStoredVariation(e,l,r,g)){var c=i.sprintf(we.RETURNING_STORED_VARIATION,xe,I.key,t,r);return this.logger.log(Ge.INFO,c),a.push(c),{result:I.key,reasons:a}}}var d=this.__checkIfUserIsInAudience(e,t,Ye.EXPERIMENT,r,n,"");if(a.push.apply(a,d.reasons),!d.result){var O=i.sprintf(we.USER_NOT_IN_EXPERIMENT,xe,r,t);return this.logger.log(Ge.INFO,O),a.push(O),{result:null,reasons:a}}var N=this.__buildBucketerParams(e,t,s,r),R=Ne.bucket(N);a.push.apply(a,R.reasons);var v=R.result;if(!(I=e.variationIdMap[v])){var h=i.sprintf(we.USER_HAS_NO_VARIATION,xe,r,t);return this.logger.log(Ge.DEBUG,h),a.push(h),{result:null,reasons:a}}var T=i.sprintf(we.USER_HAS_VARIATION,xe,r,I.key,t);return this.logger.log(Ge.INFO,T),a.push(T),_||this.__saveUserProfile(l,I,r,g),{result:I.key,reasons:a}},He.prototype.__resolveExperimentBucketMap=function(e,t){t=t||{};var r=this.__getUserProfile(e)||{},i=t[p.STICKY_BUCKETING_KEY];return F.assign({},r.experiment_bucket_map,i)},He.prototype.__checkIfExperimentIsActive=function(e,t){return ee(e,t)},He.prototype.__getWhitelistedVariation=function(e,t){var r=[];if(e.forcedVariations&&e.forcedVariations.hasOwnProperty(t)){var n=e.forcedVariations[t];if(e.variationKeyMap.hasOwnProperty(n)){var o=i.sprintf(we.USER_FORCED_IN_VARIATION,xe,t,n);return this.logger.log(Ge.INFO,o),r.push(o),{result:e.variationKeyMap[n],reasons:r}}var s=i.sprintf(we.FORCED_BUCKETING_FAILED,xe,n,t);return this.logger.log(Ge.ERROR,s),r.push(s),{result:null,reasons:r}}return {result:null,reasons:r}},He.prototype.__checkIfUserIsInAudience=function(e,t,r,n,o,s){var a=[],u=te(e,t),l=ae(e),E=i.sprintf(we.EVALUATING_AUDIENCES_COMBINED,xe,r,s||t,JSON.stringify(u));this.logger.log(Ge.DEBUG,E),a.push(E);var f=this.audienceEvaluator.evaluate(u,l,o),p=i.sprintf(we.AUDIENCE_EVALUATION_RESULT_COMBINED,xe,r,s||t,f.toString().toUpperCase());return this.logger.log(Ge.INFO,p),a.push(p),{result:f,reasons:a}},He.prototype.__buildBucketerParams=function(e,t,r,i){var n={};return n.experimentKey=t,n.experimentId=W(e,t),n.userId=i,n.trafficAllocationConfig=oe(e,t),n.experimentKeyMap=e.experimentKeyMap,n.groupIdMap=e.groupIdMap,n.variationIdMap=e.variationIdMap,n.logger=this.logger,n.bucketingId=r,n},He.prototype.__getStoredVariation=function(e,t,r,n){if(n.hasOwnProperty(t.id)){var o=n[t.id],s=o.variation_id;if(e.variationIdMap.hasOwnProperty(s))return e.variationIdMap[o.variation_id];this.logger.log(Ge.INFO,i.sprintf(we.SAVED_VARIATION_NOT_FOUND,xe,r,s,t.key));}return null},He.prototype.__getUserProfile=function(e){var t={user_id:e,experiment_bucket_map:{}};if(!this.userProfileService)return t;try{return this.userProfileService.lookup(e)}catch(t){this.logger.log(Ge.ERROR,i.sprintf(Ke.USER_PROFILE_LOOKUP_ERROR,xe,e,t.message));}},He.prototype.__saveUserProfile=function(e,t,r,n){if(this.userProfileService)try{n[e.id]={variation_id:t.id},this.userProfileService.save({user_id:r,experiment_bucket_map:n}),this.logger.log(Ge.INFO,i.sprintf(we.SAVED_VARIATION,xe,t.key,e.key,r));}catch(e){this.logger.log(Ge.ERROR,i.sprintf(Ke.USER_PROFILE_SAVE_ERROR,xe,r,e.message));}},He.prototype.getVariationForFeature=function(e,t,r,n,o){void 0===o&&(o={});var s=[],a=this._getVariationForFeatureExperiment(e,t,r,n,o);s.push.apply(s,a.reasons);var u=a.result;if(null!==u.variation)return {result:u,reasons:s};var l=this._getVariationForRollout(e,t,r,n);s.push.apply(s,l.reasons);var E=l.result;if(null!==E.variation){var f=i.sprintf(we.USER_IN_ROLLOUT,xe,r,t.key);return this.logger.log(Ge.DEBUG,f),s.push(f),{result:E,reasons:s}}var p=i.sprintf(we.USER_NOT_IN_ROLLOUT,xe,r,t.key);return this.logger.log(Ge.DEBUG,p),s.push(p),{result:E,reasons:s}},He.prototype._getVariationForFeatureExperiment=function(e,t,r,n,o){void 0===o&&(o={});var s,a=[],u=null,l=null;if(t.hasOwnProperty("groupId")){var E=e.groupIdMap[t.groupId];E&&(u=this._getExperimentInGroup(e,E,r))&&-1!==t.experimentIds.indexOf(u.id)&&(s=this.getVariation(e,u.key,r,n,o),a.push.apply(a,s.reasons),l=s.result);}else if(t.experimentIds.length>0)(u=se(e,t.experimentIds[0],this.logger))&&(s=this.getVariation(e,u.key,r,n,o),a.push.apply(a,s.reasons),l=s.result);else {var f=i.sprintf(we.FEATURE_HAS_NO_EXPERIMENTS,xe,t.key);this.logger.log(Ge.DEBUG,f),a.push(f);}var p=null;return null!==l&&null!==u&&(p=u.variationKeyMap[l]),{result:{experiment:u,variation:p,decisionSource:je.FEATURE_TEST},reasons:a}},He.prototype._getExperimentInGroup=function(e,t,r){var n=Ne.bucketUserIntoExperiment(t,r,r,this.logger);if(n){this.logger.log(Ge.INFO,i.sprintf(we.USER_BUCKETED_INTO_EXPERIMENT_IN_GROUP,xe,r,n,t.id));var o=se(e,n,this.logger);if(o)return o}return this.logger.log(Ge.INFO,i.sprintf(we.USER_NOT_BUCKETED_INTO_ANY_EXPERIMENT_IN_GROUP,xe,r,t.id)),null},He.prototype._getVariationForRollout=function(e,t,r,n){var o=[];if(!t.rolloutId){var s=i.sprintf(we.NO_ROLLOUT_EXISTS,xe,t.key);return this.logger.log(Ge.DEBUG,s),o.push(s),{result:{experiment:null,variation:null,decisionSource:je.ROLLOUT},reasons:o}}var a=e.rolloutIdMap[t.rolloutId];if(!a){var u=i.sprintf(Ke.INVALID_ROLLOUT_ID,xe,t.rolloutId,t.key);return this.logger.log(Ge.ERROR,u),o.push(u),{result:{experiment:null,variation:null,decisionSource:je.ROLLOUT},reasons:o}}if(0===a.experiments.length){var l=i.sprintf(we.ROLLOUT_HAS_NO_EXPERIMENTS,xe,t.rolloutId);return this.logger.log(Ge.ERROR,l),o.push(l),{result:{experiment:null,variation:null,decisionSource:je.ROLLOUT},reasons:o}}var E,f,p,I,_,g,c,d,O=this._getBucketingId(r,n),N=a.experiments.length-1;for(E=0;E<N;E++){if(f=e.experimentKeyMap[a.experiments[E].key],g=E+1,d=this.__checkIfUserIsInAudience(e,f.key,Ye.RULE,r,n,g),o.push.apply(o,d.reasons),d.result){var R=i.sprintf(we.USER_MEETS_CONDITIONS_FOR_TARGETING_RULE,xe,r,g);if(this.logger.log(Ge.DEBUG,R),o.push(R),p=this.__buildBucketerParams(e,f.key,O,r),c=Ne.bucket(p),o.push.apply(o,c.reasons),I=c.result,_=e.variationIdMap[I]){var v=i.sprintf(we.USER_BUCKETED_INTO_TARGETING_RULE,xe,r,g);return this.logger.log(Ge.DEBUG,v),o.push(v),{result:{experiment:f,variation:_,decisionSource:je.ROLLOUT},reasons:o}}var h=i.sprintf(we.USER_NOT_BUCKETED_INTO_TARGETING_RULE,xe,r,g);this.logger.log(Ge.DEBUG,h),o.push(h);break}var T=i.sprintf(we.USER_DOESNT_MEET_CONDITIONS_FOR_TARGETING_RULE,xe,r,g);this.logger.log(Ge.DEBUG,T),o.push(T);}var y=e.experimentKeyMap[a.experiments[N].key],A=this.__checkIfUserIsInAudience(e,y.key,Ye.RULE,r,n,"Everyone Else");if(o.push.apply(o,A.reasons),A.result){var U=i.sprintf(we.USER_MEETS_CONDITIONS_FOR_TARGETING_RULE,xe,r,"Everyone Else");if(this.logger.log(Ge.DEBUG,U),o.push(U),p=this.__buildBucketerParams(e,y.key,O,r),c=Ne.bucket(p),o.push.apply(o,c.reasons),I=c.result,_=e.variationIdMap[I]){var L=i.sprintf(we.USER_BUCKETED_INTO_EVERYONE_TARGETING_RULE,xe,r);return this.logger.log(Ge.DEBUG,L),o.push(L),{result:{experiment:y,variation:_,decisionSource:je.ROLLOUT},reasons:o}}var D=i.sprintf(we.USER_NOT_BUCKETED_INTO_EVERYONE_TARGETING_RULE,xe,r);this.logger.log(Ge.DEBUG,D),o.push(D);}return {result:{experiment:null,variation:null,decisionSource:je.ROLLOUT},reasons:o}},He.prototype._getBucketingId=function(e,t){var r=e;return null!=t&&"object"==typeof t&&t.hasOwnProperty(p.BUCKETING_ID)&&("string"==typeof t[p.BUCKETING_ID]?(r=t[p.BUCKETING_ID],this.logger.log(Ge.DEBUG,i.sprintf(we.VALID_BUCKETING_ID,xe,r))):this.logger.log(Ge.WARNING,i.sprintf(we.BUCKETING_ID_NOT_STRING,xe))),r},He.prototype.removeForcedVariation=function(e,t,r){if(!e)throw new Error(i.sprintf(Ke.INVALID_USER_ID,xe));if(!this.forcedVariationMap.hasOwnProperty(e))throw new Error(i.sprintf(Ke.USER_NOT_IN_FORCED_VARIATION,xe,e));delete this.forcedVariationMap[e][t],this.logger.log(Ge.DEBUG,i.sprintf(we.VARIATION_REMOVED_FOR_USER,xe,r,e));},He.prototype.__setInForcedVariationMap=function(e,t,r){this.forcedVariationMap.hasOwnProperty(e)||(this.forcedVariationMap[e]={}),this.forcedVariationMap[e][t]=r,this.logger.log(Ge.DEBUG,i.sprintf(we.USER_MAPPED_TO_FORCED_VARIATION,xe,r,t,e));},He.prototype.getForcedVariation=function(e,t,r){var n,o=[],s=this.forcedVariationMap[r];if(!s)return this.logger.log(Ge.DEBUG,i.sprintf(we.USER_HAS_NO_FORCED_VARIATION,xe,r)),{result:null,reasons:o};try{var a=ne(e,t);if(!a.hasOwnProperty("id")){var u=i.sprintf(Ke.IMPROPERLY_FORMATTED_EXPERIMENT,xe,t);return this.logger.log(Ge.ERROR,u),o.push(u),{result:null,reasons:o}}n=a.id;}catch(e){return this.logger.log(Ge.ERROR,e.message),o.push(e.message),{result:null,reasons:o}}var l=s[n];if(!l)return this.logger.log(Ge.DEBUG,i.sprintf(we.USER_HAS_NO_FORCED_VARIATION_FOR_EXPERIMENT,xe,t,r)),{result:null,reasons:o};var E=re(e,l);if(E){var f=i.sprintf(we.USER_HAS_FORCED_VARIATION,xe,E,t,r);this.logger.log(Ge.DEBUG,f),o.push(f);}else this.logger.log(Ge.DEBUG,i.sprintf(we.USER_HAS_NO_FORCED_VARIATION_FOR_EXPERIMENT,xe,t,r));return {result:E,reasons:o}},He.prototype.setForcedVariation=function(e,t,r,n){if(null!=n&&!Be(n))return this.logger.log(Ge.ERROR,i.sprintf(Ke.INVALID_VARIATION_KEY,xe)),!1;var o;try{var s=ne(e,t);if(!s.hasOwnProperty("id"))return this.logger.log(Ge.ERROR,i.sprintf(Ke.IMPROPERLY_FORMATTED_EXPERIMENT,xe,t)),!1;o=s.id;}catch(e){return this.logger.log(Ge.ERROR,e.message),!1}if(null==n)try{return this.removeForcedVariation(r,o,t,this.logger),!0}catch(e){return this.logger.log(Ge.ERROR,e.message),!1}var a=ie(e,t,n);if(!a)return this.logger.log(Ge.ERROR,i.sprintf(Ke.NO_VARIATION_FOR_EXPERIMENT_KEY,xe,n,t)),!1;try{return this.__setInForcedVariationMap(r,o,a),!0}catch(e){return this.logger.log(Ge.ERROR,e.message),!1}};var Xe=f.REVENUE,ze=f.VALUE;function Je(e,t){if(e.hasOwnProperty(Xe)){var r=e[Xe],n=void 0;return "string"==typeof r?(n=parseInt(r),isNaN(n)?(t.log(u.INFO,i.sprintf(E.FAILED_TO_PARSE_REVENUE,"EVENT_TAG_UTILS",r)),null):(t.log(u.INFO,i.sprintf(E.PARSED_REVENUE_VALUE,"EVENT_TAG_UTILS",n)),n)):"number"==typeof r?(n=r,t.log(u.INFO,i.sprintf(E.PARSED_REVENUE_VALUE,"EVENT_TAG_UTILS",n)),n):null}return null}function Ze(e,t){if(e.hasOwnProperty(ze)){var r=e[ze],n=void 0;return "string"==typeof r?(n=parseFloat(r),isNaN(n)?(t.log(u.INFO,i.sprintf(E.FAILED_TO_PARSE_VALUE,"EVENT_TAG_UTILS",r)),null):(t.log(u.INFO,i.sprintf(E.PARSED_NUMERIC_VALUE,"EVENT_TAG_UTILS",n)),n)):"number"==typeof r?(n=r,t.log(u.INFO,i.sprintf(E.PARSED_NUMERIC_VALUE,"EVENT_TAG_UTILS",n)),n):null}return null}function We(e,t){return "string"==typeof e&&("string"==typeof t||"boolean"==typeof t||F.isNumber(t)&&F.isSafeInteger(t))}var qe="https://logx.optimizely.com/v1/events";function $e(e){var t=e.attributes,r=e.configObj,i=r.anonymizeIP,n=r.botFiltering;null==i&&(i=!1);var o={snapshots:[],visitor_id:e.userId,attributes:[]},s={account_id:r.accountId,project_id:r.projectId,visitors:[o],revision:r.revision,client_name:e.clientEngine,client_version:e.clientVersion,anonymize_ip:i,enrich_decisions:!0};return Object.keys(t||{}).forEach((function(r){if(We(r,t[r])){var i=$(e.configObj,r,e.logger);i&&s.visitors[0].attributes.push({entity_id:i,key:r,type:"custom",value:t[r]});}})),"boolean"==typeof n&&s.visitors[0].attributes.push({entity_id:p.BOT_FILTERING,key:p.BOT_FILTERING,type:"custom",value:n}),s}var Qe=function(e){var t={httpVerb:"POST"},r=$e(e);t.url=qe;var i=function(e,t,r,i,n,o,s){var a=null;null!==t&&(a=q(e,t));var u=re(e,r);return null===u&&(u=""),{decisions:[{campaign_id:a,experiment_id:t,variation_id:r,metadata:{flag_key:o,rule_key:i,rule_type:n,variation_key:u,enabled:s}}],events:[{entity_id:a,timestamp:F.currentTimestamp(),key:"campaign_activated",uuid:F.uuid()}]}}(e.configObj,e.experimentId,e.variationId,e.ruleKey,e.ruleType,e.flagKey,e.enabled);return r.visitors[0].snapshots.push(i),t.params=r,t},et=function(e){var t={httpVerb:"POST"},r=$e(e);t.url=qe;var i=function(e,t,r,i){var n={events:[]},o={entity_id:Q(e,t),timestamp:F.currentTimestamp(),uuid:F.uuid(),key:t};if(r){var s=Je(r,i);null!==s&&(o[f.REVENUE]=s);var a=Ze(r,i);null!==a&&(o[f.VALUE]=a),o.tags=r;}return n.events.push(o),n}(e.configObj,e.eventKey,e.eventTags,e.logger);return r.visitors[0].snapshots=[i],t.params=r,t};function tt(e){var t,r;return null!==(r=null===(t=e.experiment)||void 0===t?void 0:t.key)&&void 0!==r?r:""}function rt(e){var t,r;return null!==(r=null===(t=e.variation)||void 0===t?void 0:t.key)&&void 0!==r?r:""}function it(e){var t,r;return null!==(r=null===(t=e.variation)||void 0===t?void 0:t.featureEnabled)&&void 0!==r&&r}var nt=t.getLogger("EVENT_BUILDER");function ot(e,t){var r=[];return Object.keys(t||{}).forEach((function(i){if(We(i,t[i])){var n=$(e,i,nt);n&&r.push({entityId:n,key:i,value:t[i]});}})),r}var st={createEventProcessor:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return new(r.LogTierV1EventProcessor.bind.apply(r.LogTierV1EventProcessor,a([void 0],e)))},LocalStoragePendingEventsDispatcher:r.LocalStoragePendingEventsDispatcher};var at="USER_PROFILE_SERVICE_VALIDATOR";var ut=function(){function e(e){var t,r=this,n=e.clientEngine;-1===I.indexOf(n)&&(e.logger.log(u.INFO,i.sprintf(E.INVALID_CLIENT_ENGINE,"OPTIMIZELY",n)),n="node-sdk"),this.clientEngine=n,this.clientVersion=e.clientVersion||"4.5.1",this.errorHandler=e.errorHandler,this.eventDispatcher=e.eventDispatcher,this.isOptimizelyConfigValid=e.isValidInstance,this.logger=e.logger;var o=null!==(t=e.defaultDecideOptions)&&void 0!==t?t:[];Array.isArray(o)||(this.logger.log(u.DEBUG,i.sprintf(E.INVALID_DEFAULT_DECIDE_OPTIONS,"OPTIMIZELY")),o=[]);var s={};o.forEach((function(e){exports.OptimizelyDecideOption[e]?s[e]=!0:r.logger.log(u.WARNING,i.sprintf(E.UNRECOGNIZED_DECIDE_OPTION,"OPTIMIZELY",e));})),this.defaultDecideOptions=s,this.projectConfigManager=function(e){return new Ie(e)}({datafile:e.datafile,datafileOptions:e.datafileOptions,jsonSchemaValidator:e.jsonSchemaValidator,sdkKey:e.sdkKey}),this.disposeOnUpdate=this.projectConfigManager.onUpdate((function(e){r.logger.log(u.INFO,i.sprintf(E.UPDATED_OPTIMIZELY_CONFIG,"OPTIMIZELY",e.revision,e.projectId)),r.notificationCenter.sendNotifications(_.OPTIMIZELY_CONFIG_UPDATE);}));var a=this.projectConfigManager.onReady(),f=null;if(e.userProfileService)try{(function(e){if("object"==typeof e&&null!==e){if("function"!=typeof e.lookup)throw new Error(i.sprintf(l.INVALID_USER_PROFILE_SERVICE,at,"Missing function 'lookup'"));if("function"!=typeof e.save)throw new Error(i.sprintf(l.INVALID_USER_PROFILE_SERVICE,at,"Missing function 'save'"));return !0}throw new Error(i.sprintf(l.INVALID_USER_PROFILE_SERVICE,at))})(e.userProfileService)&&(f=e.userProfileService,this.logger.log(u.INFO,i.sprintf(E.VALID_USER_PROFILE_SERVICE,"OPTIMIZELY")));}catch(e){this.logger.log(u.WARNING,e.message);}this.decisionService=new He({userProfileService:f,logger:this.logger,UNSTABLE_conditionEvaluators:e.UNSTABLE_conditionEvaluators}),this.notificationCenter=function(e){return new _e(e)}({logger:this.logger,errorHandler:this.errorHandler});var p={dispatcher:this.eventDispatcher,flushInterval:e.eventFlushInterval,batchSize:e.eventBatchSize,maxQueueSize:e.eventMaxQueueSize,notificationCenter:this.notificationCenter};this.eventProcessor=st.createEventProcessor(p);var g=this.eventProcessor.start();this.readyPromise=Promise.all([a,g]).then((function(e){return e[0]})),this.readyTimeouts={},this.nextReadyTimeoutId=0;}return e.prototype.isValidInstance=function(){return this.isOptimizelyConfigValid&&!!this.projectConfigManager.getConfig()},e.prototype.activate=function(e,t,r){try{if(!this.isValidInstance())return this.logger.log(u.ERROR,i.sprintf(E.INVALID_OBJECT,"OPTIMIZELY","activate")),null;if(!this.validateInputs({experiment_key:e,user_id:t},r))return this.notActivatingExperiment(e,t);var n=this.projectConfigManager.getConfig();if(!n)return null;try{var o=this.getVariation(e,t,r);if(null===o)return this.notActivatingExperiment(e,t);if(!K(n,e)){var s=i.sprintf(E.SHOULD_NOT_DISPATCH_ACTIVATE,"OPTIMIZELY",e);return this.logger.log(u.DEBUG,s),o}var a=w(n,e),l={experiment:a,variation:a.variationKeyMap[o],decisionSource:c.EXPERIMENT};return this.sendImpressionEvent(l,"",t,!0,r),o}catch(r){this.logger.log(u.ERROR,r.message);var f=i.sprintf(E.NOT_ACTIVATING_USER,"OPTIMIZELY",t,e);return this.logger.log(u.INFO,f),this.errorHandler.handleError(r),null}}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),null}},e.prototype.sendImpressionEvent=function(e,t,r,i,n){var o=this.projectConfigManager.getConfig();if(o){var s=function(e){var t=e.configObj,r=e.decisionObj,i=e.userId,n=e.flagKey,o=e.enabled,s=e.userAttributes,a=e.clientEngine,u=e.clientVersion,l=r.decisionSource,E=tt(r),f=rt(r),p=null,I=null;""!==E&&""!==f&&(I=ie(t,E,f)),""!==E&&(p=W(t,E));var _=null;return null!==p&&(_=q(t,p)),{type:"impression",timestamp:F.currentTimestamp(),uuid:F.uuid(),user:{id:i,attributes:ot(t,s)},context:{accountId:t.accountId,projectId:t.projectId,revision:t.revision,clientName:a,clientVersion:u,anonymizeIP:t.anonymizeIP||!1,botFiltering:t.botFiltering},layer:{id:_},experiment:{id:p,key:E},variation:{id:I,key:f},ruleKey:E,flagKey:n,ruleType:l,enabled:o}}({decisionObj:e,flagKey:t,enabled:i,userId:r,userAttributes:n,clientEngine:this.clientEngine,clientVersion:this.clientVersion,configObj:o});this.eventProcessor.process(s),this.emitNotificationCenterActivate(e,t,r,i,n);}},e.prototype.emitNotificationCenterActivate=function(e,t,r,i,n){var o=this.projectConfigManager.getConfig();if(o){var s=e.decisionSource,a=tt(e),u=rt(e),l=null,E=null;""!==a&&""!==u&&(E=G(o,a,u),l=B(o,a));var f,p={attributes:n,clientEngine:this.clientEngine,clientVersion:this.clientVersion,configObj:o,experimentId:l,ruleKey:a,flagKey:t,ruleType:s,userId:r,enabled:i,variationId:E,logger:this.logger},I=Qe(p),g=o.experimentKeyMap[a];g&&g.variationKeyMap&&""!==u&&(f=g.variationKeyMap[u]),this.notificationCenter.sendNotifications(_.ACTIVATE,{experiment:g,userId:r,attributes:n,variation:f,logEvent:I});}},e.prototype.track=function(e,t,r,n){try{if(!this.isValidInstance())return void this.logger.log(u.ERROR,i.sprintf(E.INVALID_OBJECT,"OPTIMIZELY","track"));if(!this.validateInputs({user_id:t,event_key:e},r,n))return;var o=this.projectConfigManager.getConfig();if(!o)return;if(!z(o,e))return this.logger.log(u.WARNING,i.sprintf(E.EVENT_KEY_NOT_FOUND,"OPTIMIZELY",e)),void this.logger.log(u.WARNING,i.sprintf(E.NOT_TRACKING_USER,"OPTIMIZELY",t));var s=function(e){var t=e.configObj,r=e.userId,i=e.userAttributes,n=e.clientEngine,o=e.clientVersion,s=e.eventKey,a=e.eventTags,u=Q(t,s),l=null,E=null;return a&&(l=Je(a,nt),E=Ze(a,nt)),{type:"conversion",timestamp:F.currentTimestamp(),uuid:F.uuid(),user:{id:r,attributes:ot(t,i)},context:{accountId:t.accountId,projectId:t.projectId,revision:t.revision,clientName:n,clientVersion:o,anonymizeIP:t.anonymizeIP||!1,botFiltering:t.botFiltering},event:{id:u,key:s},revenue:l,value:E,tags:a}}({eventKey:e,eventTags:n=this.filterEmptyValues(n),userId:t,userAttributes:r,clientEngine:this.clientEngine,clientVersion:this.clientVersion,configObj:o});this.logger.log(u.INFO,i.sprintf(E.TRACK_EVENT,"OPTIMIZELY",e,t)),this.eventProcessor.process(s),this.emitNotificationCenterTrack(e,t,r,n);}catch(e){this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e);var a=i.sprintf(E.NOT_TRACKING_USER,"OPTIMIZELY",t);this.logger.log(u.ERROR,a);}},e.prototype.emitNotificationCenterTrack=function(e,t,r,i){try{var n=this.projectConfigManager.getConfig();if(!n)return;var o={attributes:r,clientEngine:this.clientEngine,clientVersion:this.clientVersion,configObj:n,eventKey:e,eventTags:i,logger:this.logger,userId:t},s=et(o);this.notificationCenter.sendNotifications(_.TRACK,{eventKey:e,userId:t,attributes:r,eventTags:i,logEvent:s});}catch(e){this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e);}},e.prototype.getVariation=function(e,t,r){try{if(!this.isValidInstance())return this.logger.log(u.ERROR,i.sprintf(E.INVALID_OBJECT,"OPTIMIZELY","getVariation")),null;try{if(!this.validateInputs({experiment_key:e,user_id:t},r))return null;var n=this.projectConfigManager.getConfig();if(!n)return null;var o=n.experimentKeyMap[e];if(!o)return this.logger.log(u.DEBUG,i.sprintf(l.INVALID_EXPERIMENT_KEY,"OPTIMIZELY",e)),null;var s=this.decisionService.getVariation(n,e,t,r).result,a=J(n,o.id)?g.FEATURE_TEST:g.AB_TEST;return this.notificationCenter.sendNotifications(_.DECISION,{type:a,userId:t,attributes:r||{},decisionInfo:{experimentKey:e,variationKey:s}}),s}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),null}}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),null}},e.prototype.setForcedVariation=function(e,t,r){if(!this.validateInputs({experiment_key:e,user_id:t}))return !1;var i=this.projectConfigManager.getConfig();if(!i)return !1;try{return this.decisionService.setForcedVariation(i,e,t,r)}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),!1}},e.prototype.getForcedVariation=function(e,t){if(!this.validateInputs({experiment_key:e,user_id:t}))return null;var r=this.projectConfigManager.getConfig();if(!r)return null;try{return this.decisionService.getForcedVariation(r,e,t).result}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),null}},e.prototype.validateInputs=function(e,t,r){try{if(e.hasOwnProperty("user_id")){var n=e.user_id;if("string"!=typeof n||null===n||"undefined"===n)throw new Error(i.sprintf(l.INVALID_INPUT_FORMAT,"OPTIMIZELY","user_id"));delete e.user_id;}return Object.keys(e).forEach((function(t){if(!Be(e[t]))throw new Error(i.sprintf(l.INVALID_INPUT_FORMAT,"OPTIMIZELY",t))})),t&&function(e){if("object"!=typeof e||Array.isArray(e)||null===e)throw new Error(i.sprintf(l.INVALID_ATTRIBUTES,"ATTRIBUTES_VALIDATOR"));Object.keys(e).forEach((function(t){if(void 0===e[t])throw new Error(i.sprintf(l.UNDEFINED_ATTRIBUTE,"ATTRIBUTES_VALIDATOR",t))}));}(t),r&&function(e){if("object"!=typeof e||Array.isArray(e)||null===e)throw new Error(i.sprintf(l.INVALID_EVENT_TAGS,"EVENT_TAGS_VALIDATOR"))}(r),!0}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),!1}},e.prototype.notActivatingExperiment=function(e,t){var r=i.sprintf(E.NOT_ACTIVATING_USER,"OPTIMIZELY",t,e);return this.logger.log(u.INFO,r),null},e.prototype.filterEmptyValues=function(e){for(var t in e)!e.hasOwnProperty(t)||null!==e[t]&&void 0!==e[t]||delete e[t];return e},e.prototype.isFeatureEnabled=function(e,t,r){try{if(!this.isValidInstance())return this.logger.log(u.ERROR,i.sprintf(E.INVALID_OBJECT,"OPTIMIZELY","isFeatureEnabled")),!1;if(!this.validateInputs({feature_key:e,user_id:t},r))return !1;var n=this.projectConfigManager.getConfig();if(!n)return !1;var o=j(n,e,this.logger);if(!o)return !1;var s={},a=this.decisionService.getVariationForFeature(n,o,t,r).result,l=a.decisionSource,f=tt(a),p=rt(a),I=it(a);l===c.FEATURE_TEST&&(s={experimentKey:f,variationKey:p}),(l===c.FEATURE_TEST||l===c.ROLLOUT&&Z(n))&&this.sendImpressionEvent(a,o.key,t,I,r),!0===I?this.logger.log(u.INFO,i.sprintf(E.FEATURE_ENABLED_FOR_USER,"OPTIMIZELY",e,t)):(this.logger.log(u.INFO,i.sprintf(E.FEATURE_NOT_ENABLED_FOR_USER,"OPTIMIZELY",e,t)),I=!1);var d={featureKey:e,featureEnabled:I,source:a.decisionSource,sourceInfo:s};return this.notificationCenter.sendNotifications(_.DECISION,{type:g.FEATURE,userId:t,attributes:r||{},decisionInfo:d}),I}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),!1}},e.prototype.getEnabledFeatures=function(e,t){var r=this;try{var n=[];if(!this.isValidInstance())return this.logger.log(u.ERROR,i.sprintf(E.INVALID_OBJECT,"OPTIMIZELY","getEnabledFeatures")),n;if(!this.validateInputs({user_id:e}))return n;var o=this.projectConfigManager.getConfig();return o?(i.objectValues(o.featureKeyMap).forEach((function(i){r.isFeatureEnabled(i.key,e,t)&&n.push(i.key);})),n):n}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),[]}},e.prototype.getFeatureVariable=function(e,t,r,n){try{return this.isValidInstance()?this.getFeatureVariableForType(e,t,null,r,n):(this.logger.log(u.ERROR,i.sprintf(E.INVALID_OBJECT,"OPTIMIZELY","getFeatureVariable")),null)}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),null}},e.prototype.getFeatureVariableForType=function(e,t,r,n,o){if(!this.validateInputs({feature_key:e,variable_key:t,user_id:n},o))return null;var s=this.projectConfigManager.getConfig();if(!s)return null;var a=j(s,e,this.logger);if(!a)return null;var l=Y(s,e,t,this.logger);if(!l)return null;if(r&&l.type!==r)return this.logger.log(u.WARNING,i.sprintf(E.VARIABLE_REQUESTED_WITH_WRONG_TYPE,"OPTIMIZELY",r,l.type)),null;var f=this.decisionService.getVariationForFeature(s,a,n,o).result,p=it(f),I=this.getFeatureVariableValueFromVariation(e,p,f.variation,l,n),d={};return f.decisionSource===c.FEATURE_TEST&&null!==f.experiment&&null!==f.variation&&(d={experimentKey:f.experiment.key,variationKey:f.variation.key}),this.notificationCenter.sendNotifications(_.DECISION,{type:g.FEATURE_VARIABLE,userId:n,attributes:o||{},decisionInfo:{featureKey:e,featureEnabled:p,source:f.decisionSource,variableKey:t,variableValue:I,variableType:l.type,sourceInfo:d}}),I},e.prototype.getFeatureVariableValueFromVariation=function(e,t,r,n,o){var s=this.projectConfigManager.getConfig();if(!s)return null;var a=n.defaultValue;if(null!==r){var l=H(s,n,r,this.logger);null!==l?t?(a=l,this.logger.log(u.INFO,i.sprintf(E.USER_RECEIVED_VARIABLE_VALUE,"OPTIMIZELY",a,n.key,e))):this.logger.log(u.INFO,i.sprintf(E.FEATURE_NOT_ENABLED_RETURN_DEFAULT_VARIABLE_VALUE,"OPTIMIZELY",e,o,a)):this.logger.log(u.INFO,i.sprintf(E.VARIABLE_NOT_USED_RETURN_DEFAULT_VARIABLE_VALUE,"OPTIMIZELY",n.key,r.key));}else this.logger.log(u.INFO,i.sprintf(E.USER_RECEIVED_DEFAULT_VARIABLE_VALUE,"OPTIMIZELY",o,n.key,e));return X(a,n.type,this.logger)},e.prototype.getFeatureVariableBoolean=function(e,t,r,n){try{return this.isValidInstance()?this.getFeatureVariableForType(e,t,O.BOOLEAN,r,n):(this.logger.log(u.ERROR,i.sprintf(E.INVALID_OBJECT,"OPTIMIZELY","getFeatureVariableBoolean")),null)}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),null}},e.prototype.getFeatureVariableDouble=function(e,t,r,n){try{return this.isValidInstance()?this.getFeatureVariableForType(e,t,O.DOUBLE,r,n):(this.logger.log(u.ERROR,i.sprintf(E.INVALID_OBJECT,"OPTIMIZELY","getFeatureVariableDouble")),null)}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),null}},e.prototype.getFeatureVariableInteger=function(e,t,r,n){try{return this.isValidInstance()?this.getFeatureVariableForType(e,t,O.INTEGER,r,n):(this.logger.log(u.ERROR,i.sprintf(E.INVALID_OBJECT,"OPTIMIZELY","getFeatureVariableInteger")),null)}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),null}},e.prototype.getFeatureVariableString=function(e,t,r,n){try{return this.isValidInstance()?this.getFeatureVariableForType(e,t,O.STRING,r,n):(this.logger.log(u.ERROR,i.sprintf(E.INVALID_OBJECT,"OPTIMIZELY","getFeatureVariableString")),null)}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),null}},e.prototype.getFeatureVariableJSON=function(e,t,r,n){try{return this.isValidInstance()?this.getFeatureVariableForType(e,t,O.JSON,r,n):(this.logger.log(u.ERROR,i.sprintf(E.INVALID_OBJECT,"OPTIMIZELY","getFeatureVariableJSON")),null)}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),null}},e.prototype.getAllFeatureVariables=function(e,t,r){var n=this;try{if(!this.isValidInstance())return this.logger.log(u.ERROR,i.sprintf(E.INVALID_OBJECT,"OPTIMIZELY","getAllFeatureVariables")),null;if(!this.validateInputs({feature_key:e,user_id:t},r))return null;var o=this.projectConfigManager.getConfig();if(!o)return null;var s=j(o,e,this.logger);if(!s)return null;var a=this.decisionService.getVariationForFeature(o,s,t,r).result,l=it(a),f={};s.variables.forEach((function(r){f[r.key]=n.getFeatureVariableValueFromVariation(e,l,a.variation,r,t);}));var p={};return a.decisionSource===c.FEATURE_TEST&&null!==a.experiment&&null!==a.variation&&(p={experimentKey:a.experiment.key,variationKey:a.variation.key}),this.notificationCenter.sendNotifications(_.DECISION,{type:g.ALL_FEATURE_VARIABLES,userId:t,attributes:r||{},decisionInfo:{featureKey:e,featureEnabled:l,source:a.decisionSource,variableValues:f,sourceInfo:p}}),f}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),null}},e.prototype.getOptimizelyConfig=function(){try{return this.projectConfigManager.getConfig()?this.projectConfigManager.getOptimizelyConfig():null}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),null}},e.prototype.close=function(){var e=this;try{var t=this.eventProcessor.stop();return this.disposeOnUpdate&&(this.disposeOnUpdate(),this.disposeOnUpdate=null),this.projectConfigManager&&this.projectConfigManager.stop(),Object.keys(this.readyTimeouts).forEach((function(t){var r=e.readyTimeouts[t];clearTimeout(r.readyTimeout),r.onClose();})),this.readyTimeouts={},t.then((function(){return {success:!0}}),(function(e){return {success:!1,reason:String(e)}}))}catch(e){return this.logger.log(u.ERROR,e.message),this.errorHandler.handleError(e),Promise.resolve({success:!1,reason:String(e)})}},e.prototype.onReady=function(e){var t,r,n=this;"object"==typeof e&&null!==e&&void 0!==e.timeout&&(t=e.timeout),F.isSafeInteger(t)||(t=3e4);var o=new Promise((function(e){r=e;})),s=this.nextReadyTimeoutId;this.nextReadyTimeoutId++;var a=setTimeout((function(){delete n.readyTimeouts[s],r({success:!1,reason:i.sprintf("onReady timeout expired after %s ms",t)});}),t);return this.readyTimeouts[s]={readyTimeout:a,onClose:function(){r({success:!1,reason:"Instance closed"});}},this.readyPromise.then((function(){clearTimeout(a),delete n.readyTimeouts[s],r({success:!0});})),Promise.race([this.readyPromise,o])},e.prototype.createUserContext=function(e,t){return this.validateInputs({user_id:e},t)?new P({optimizely:this,userId:e,attributes:t}):null},e.prototype.decide=function(e,t,r){var n,o,s,a,f=this;void 0===r&&(r=[]);var p=this.projectConfigManager.getConfig(),I=[];if(!this.isValidInstance()||!p)return I.push(R.SDK_NOT_READY),this.logger.log(u.INFO,i.sprintf(E.INVALID_OBJECT,"OPTIMIZELY","decide")),C(t,e,I);var d=p.featureKeyMap[t];if(!d)return I.push(i.sprintf(R.FLAG_KEY_INVALID,t)),this.logger.log(u.ERROR,i.sprintf(l.FEATURE_NOT_IN_DATAFILE,"OPTIMIZELY",t)),C(t,e,I);var O=e.getUserId(),N=e.getAttributes(),v=this.getAllDecideOptions(r),h=this.decisionService.getVariationForFeature(p,d,O,N,v);I.push.apply(I,h.reasons);var T=h.result,y=T.decisionSource,A=null!==(o=null===(n=T.experiment)||void 0===n?void 0:n.key)&&void 0!==o?o:null,U=null!==(a=null===(s=T.variation)||void 0===s?void 0:s.key)&&void 0!==a?a:null,L=it(T);!0===L?this.logger.log(u.INFO,i.sprintf(E.FEATURE_ENABLED_FOR_USER,"OPTIMIZELY",t,O)):this.logger.log(u.INFO,i.sprintf(E.FEATURE_NOT_ENABLED_FOR_USER,"OPTIMIZELY",t,O));var D={},S=!1;v[exports.OptimizelyDecideOption.EXCLUDE_VARIABLES]||d.variables.forEach((function(e){D[e.key]=f.getFeatureVariableValueFromVariation(t,L,T.variation,e,O);})),!v[exports.OptimizelyDecideOption.DISABLE_DECISION_EVENT]&&(y===c.FEATURE_TEST||y===c.ROLLOUT&&Z(p))&&(this.sendImpressionEvent(T,t,O,L,N),S=!0);var m=v[exports.OptimizelyDecideOption.INCLUDE_REASONS]?I:[],V={flagKey:t,enabled:L,variationKey:U,ruleKey:A,variables:D,reasons:m,decisionEventDispatched:S};return this.notificationCenter.sendNotifications(_.DECISION,{type:g.FLAG,userId:O,attributes:N,decisionInfo:V}),{variationKey:U,enabled:L,variables:D,ruleKey:A,flagKey:t,userContext:e,reasons:m}},e.prototype.getAllDecideOptions=function(e){var t=this,r=s({},this.defaultDecideOptions);return Array.isArray(e)?e.forEach((function(e){exports.OptimizelyDecideOption[e]?r[e]=!0:t.logger.log(u.WARNING,i.sprintf(E.UNRECOGNIZED_DECIDE_OPTION,"OPTIMIZELY",e));})):this.logger.log(u.DEBUG,i.sprintf(E.INVALID_DECIDE_OPTIONS,"OPTIMIZELY")),r},e.prototype.decideForKeys=function(e,t,r){var n=this;void 0===r&&(r=[]);var o={};if(!this.isValidInstance())return this.logger.log(u.ERROR,i.sprintf(E.INVALID_OBJECT,"OPTIMIZELY","decideForKeys")),o;if(0===t.length)return o;var s=this.getAllDecideOptions(r);return t.forEach((function(t){var i=n.decide(e,t,r);s[exports.OptimizelyDecideOption.ENABLED_FLAGS_ONLY]&&!i.enabled||(o[t]=i);})),o},e.prototype.decideAll=function(e,t){void 0===t&&(t=[]);var r=this.projectConfigManager.getConfig();if(!this.isValidInstance()||!r)return this.logger.log(u.ERROR,i.sprintf(E.INVALID_OBJECT,"OPTIMIZELY","decideAll")),{};var n=Object.keys(r.featureKeyMap);return this.decideForKeys(e,n,t)},e}(),lt=function(e){return !("number"!=typeof e||!F.isSafeInteger(e))&&e>=1},Et=function(e){return !("number"!=typeof e||!F.isSafeInteger(e))&&e>0},ft=t.getLogger();t.setLogHandler(V.createLogger()),t.setLogLevel(t.LogLevel.INFO);var pt=!1,It=function(e){try{e.errorHandler&&t.setErrorHandler(e.errorHandler),e.logger&&(t.setLogHandler(e.logger),t.setLogLevel(t.LogLevel.NOTSET)),void 0!==e.logLevel&&t.setLogLevel(e.logLevel);try{y(e),e.isValidInstance=!0;}catch(t){ft.error(t),e.isValidInstance=!1;}var i=void 0;null==e.eventDispatcher?(i=new r.LocalStoragePendingEventsDispatcher({eventDispatcher:D}),pt||(i.sendPendingEvents(),pt=!0)):i=e.eventDispatcher;var n=e.eventBatchSize,o=e.eventFlushInterval;lt(e.eventBatchSize)||(ft.warn("Invalid eventBatchSize %s, defaulting to %s",e.eventBatchSize,10),n=10),Et(e.eventFlushInterval)||(ft.warn("Invalid eventFlushInterval %s, defaulting to %s",e.eventFlushInterval,1e3),o=1e3);var a=s(s({clientEngine:"javascript-sdk",eventDispatcher:i},e),{eventBatchSize:n,eventFlushInterval:o,logger:ft,errorHandler:t.getErrorHandler()}),u=new ut(a);try{if("function"==typeof window.addEventListener){var l="onpagehide"in window?"pagehide":"unload";window.addEventListener(l,(function(){u.close();}),!1);}}catch(e){ft.error(E.UNABLE_TO_ATTACH_UNLOAD,"INDEX_BROWSER",e.message);}return u}catch(e){return ft.error(e),null}},_t=function(){pt=!1;},gt={logging:V,errorHandler:U,eventDispatcher:D,enums:v,setLogger:t.setLogHandler,setLogLevel:t.setLogLevel,createInstance:It,__internalResetRetryState:_t,OptimizelyDecideOption:exports.OptimizelyDecideOption};Object.defineProperty(exports,"setLogLevel",{enumerable:!0,get:function(){return t.setLogLevel}}),Object.defineProperty(exports,"setLogger",{enumerable:!0,get:function(){return t.setLogHandler}}),exports.__internalResetRetryState=_t,exports.createInstance=It,exports.default=gt,exports.enums=v,exports.errorHandler=U,exports.eventDispatcher=D,exports.logging=V; | |
| //# sourceMappingURL=optimizely.browser.min.js.map | |
| }); | |
| unwrapExports(optimizely_browser_min); | |
| optimizely_browser_min.OptimizelyDecideOption; | |
| optimizely_browser_min.setLogLevel; | |
| optimizely_browser_min.setLogger; | |
| optimizely_browser_min.__internalResetRetryState; | |
| var optimizely_browser_min_5 = optimizely_browser_min.createInstance; | |
| optimizely_browser_min.enums; | |
| optimizely_browser_min.errorHandler; | |
| optimizely_browser_min.eventDispatcher; | |
| optimizely_browser_min.logging; | |
| const defaultDataFile = { | |
| version: "4", | |
| rollouts: [ | |
| { | |
| experiments: [ | |
| { | |
| status: "Running", | |
| audienceConditions: [], | |
| audienceIds: [], | |
| variations: [ | |
| { | |
| variables: [ | |
| { id: "1077", value: "false" }, | |
| { | |
| id: "1078", | |
| value: '{"primaryKey":"default primary key value"}', | |
| }, | |
| { id: "1079", value: "Default String Value" }, | |
| ], | |
| id: "4279", | |
| key: "off", | |
| featureEnabled: false, | |
| }, | |
| ], | |
| forcedVariations: {}, | |
| key: "default-rollout-1587-20224906730", | |
| layerId: "default-layer-rollout-1587-20224906730", | |
| trafficAllocation: [{ entityId: "4279", endOfRange: 10000 }], | |
| id: "default-rollout-1587-20224906730", | |
| }, | |
| ], | |
| id: "rollout-1587-20224906730", | |
| }, | |
| ], | |
| typedAudiences: [], | |
| anonymizeIP: true, | |
| projectId: "20224828075", | |
| variables: [], | |
| featureFlags: [ | |
| { | |
| experimentIds: ["9300000003724"], | |
| rolloutId: "rollout-1587-20224906730", | |
| variables: [ | |
| { | |
| defaultValue: "false", | |
| type: "boolean", | |
| id: "1077", | |
| key: "boolean_variable", | |
| }, | |
| { | |
| subType: "json", | |
| defaultValue: '{"primaryKey":"default primary key value"}', | |
| type: "string", | |
| id: "1078", | |
| key: "json_variable", | |
| }, | |
| { | |
| defaultValue: "Default String Value", | |
| type: "string", | |
| id: "1079", | |
| key: "string_variable", | |
| }, | |
| ], | |
| id: "1587", | |
| key: "edge_worker_development", | |
| }, | |
| ], | |
| experiments: [ | |
| { | |
| status: "Running", | |
| audienceConditions: [], | |
| audienceIds: [], | |
| variations: [ | |
| { variables: [], id: "4279", key: "off", featureEnabled: false }, | |
| { | |
| variables: [ | |
| { id: "1077", value: "true" }, | |
| { | |
| id: "1078", | |
| value: '{"primaryKey":"variation 1 primary key value"}', | |
| }, | |
| { id: "1079", value: "Default String Value Variation #1" }, | |
| ], | |
| id: "4282", | |
| key: "variation__1", | |
| featureEnabled: true, | |
| }, | |
| { | |
| variables: [ | |
| { id: "1077", value: "true" }, | |
| { | |
| id: "1078", | |
| value: '{"primaryKey":"variation 2 default primary key value"}', | |
| }, | |
| { id: "1079", value: "Default String Value Variation #2" }, | |
| ], | |
| id: "4281", | |
| key: "variation__2", | |
| featureEnabled: true, | |
| }, | |
| ], | |
| forcedVariations: {}, | |
| key: "experiment", | |
| layerId: "9300000003724", | |
| trafficAllocation: [ | |
| { entityId: "4279", endOfRange: 3333 }, | |
| { entityId: "4281", endOfRange: 6667 }, | |
| { entityId: "4282", endOfRange: 10000 }, | |
| ], | |
| id: "9300000003724", | |
| }, | |
| ], | |
| audiences: [ | |
| { | |
| conditions: | |
| '["or", {"match": "exact", "name": "$opt_dummy_attribute", "type": "custom_attribute", "value": "$opt_dummy_value"}]', | |
| id: "$opt_dummy_audience", | |
| name: "Optimizely-Generated Audience for Backwards Compatibility", | |
| }, | |
| ], | |
| groups: [], | |
| attributes: [{ id: "20230887117", key: "testing_attribute" }], | |
| botFiltering: false, | |
| accountId: "8543082612", | |
| events: [ | |
| { | |
| experimentIds: ["9300000003724"], | |
| id: "20238065441", | |
| key: "testing_event", | |
| }, | |
| ], | |
| revision: "10", | |
| }; | |
| function generateUUID() { | |
| return lib_1(); | |
| } | |
| async function getDataFile(inDevelopment, sdkKey) { | |
| let datafile = "{}"; | |
| if (inDevelopment) { | |
| return JSON.stringify(defaultDataFile); | |
| } | |
| try { | |
| const datafileResponse = await httpRequest( | |
| `https://cdn.optimizely.com/datafiles/${sdkKey}.json` | |
| ); | |
| if (datafileResponse.ok) { | |
| datafile = await datafileResponse.json(); | |
| logger$1.log("Using remote datafile"); | |
| } else { | |
| logger$1.log( | |
| "Unable to retrieve datafile due to invalid status code: %s", | |
| datafileResponse.status | |
| ); | |
| } | |
| } catch (err) { | |
| logger$1.log("Unable to retrieve datafile due to error: %s", err.message); | |
| } | |
| return datafile; | |
| } | |
| //export const generateUserId = (): string => uuidv4() | |
| //request as parameter, returns string | |
| function storedExperiments(_experiments_) { | |
| const experiments = (_experiments_ || "") | |
| .split(delimeter) | |
| .filter((str) => str && str.length > 0 && str !== "null") | |
| .map((str) => { | |
| const [name, variation] = str.split(ev); | |
| return { name, variation }; | |
| }); | |
| console.log("Experiments from cookie", JSON.stringify(experiments)); | |
| return experiments; | |
| } | |
| var urlSearchParams_node = createCommonjsModule(function (module) { | |
| function URLSearchParams(query) { | |
| var | |
| index, key, value, | |
| pairs, i, length, | |
| dict = Object.create(null) | |
| ; | |
| this[secret] = dict; | |
| if (!query) return; | |
| if (typeof query === 'string') { | |
| if (query.charAt(0) === '?') { | |
| query = query.slice(1); | |
| } | |
| for ( | |
| pairs = query.split('&'), | |
| i = 0, | |
| length = pairs.length; i < length; i++ | |
| ) { | |
| value = pairs[i]; | |
| index = value.indexOf('='); | |
| if (-1 < index) { | |
| appendTo( | |
| dict, | |
| decode(value.slice(0, index)), | |
| decode(value.slice(index + 1)) | |
| ); | |
| } else if (value.length){ | |
| appendTo( | |
| dict, | |
| decode(value), | |
| '' | |
| ); | |
| } | |
| } | |
| } else { | |
| if (isArray(query)) { | |
| for ( | |
| i = 0, | |
| length = query.length; i < length; i++ | |
| ) { | |
| value = query[i]; | |
| appendTo(dict, value[0], value[1]); | |
| } | |
| } else if (query.forEach) { | |
| query.forEach(addEach, dict); | |
| } else { | |
| for (key in query) { | |
| appendTo(dict, key, query[key]); | |
| } | |
| } | |
| } | |
| } | |
| var | |
| isArray = Array.isArray, | |
| URLSearchParamsProto = URLSearchParams.prototype, | |
| find = /[!'\(\)~]|%20|%00/g, | |
| plus = /\+/g, | |
| replace = { | |
| '!': '%21', | |
| "'": '%27', | |
| '(': '%28', | |
| ')': '%29', | |
| '~': '%7E', | |
| '%20': '+', | |
| '%00': '\x00' | |
| }, | |
| replacer = function (match) { | |
| return replace[match]; | |
| }, | |
| secret = '__URLSearchParams__:' + Math.random() | |
| ; | |
| function addEach(value, key) { | |
| /* jshint validthis:true */ | |
| appendTo(this, key, value); | |
| } | |
| function appendTo(dict, name, value) { | |
| var res = isArray(value) ? value.join(',') : value; | |
| if (name in dict) | |
| dict[name].push(res); | |
| else | |
| dict[name] = [res]; | |
| } | |
| function decode(str) { | |
| return decodeURIComponent(str.replace(plus, ' ')); | |
| } | |
| function encode(str) { | |
| return encodeURIComponent(str).replace(find, replacer); | |
| } | |
| URLSearchParamsProto.append = function append(name, value) { | |
| appendTo(this[secret], name, value); | |
| }; | |
| URLSearchParamsProto.delete = function del(name) { | |
| delete this[secret][name]; | |
| }; | |
| URLSearchParamsProto.get = function get(name) { | |
| var dict = this[secret]; | |
| return name in dict ? dict[name][0] : null; | |
| }; | |
| URLSearchParamsProto.getAll = function getAll(name) { | |
| var dict = this[secret]; | |
| return name in dict ? dict[name].slice(0) : []; | |
| }; | |
| URLSearchParamsProto.has = function has(name) { | |
| return name in this[secret]; | |
| }; | |
| URLSearchParamsProto.set = function set(name, value) { | |
| this[secret][name] = ['' + value]; | |
| }; | |
| URLSearchParamsProto.forEach = function forEach(callback, thisArg) { | |
| var dict = this[secret]; | |
| Object.getOwnPropertyNames(dict).forEach(function(name) { | |
| dict[name].forEach(function(value) { | |
| callback.call(thisArg, value, name, this); | |
| }, this); | |
| }, this); | |
| }; | |
| /* | |
| URLSearchParamsProto.toBody = function() { | |
| return new Blob( | |
| [this.toString()], | |
| {type: 'application/x-www-form-urlencoded'} | |
| ); | |
| }; | |
| */ | |
| URLSearchParamsProto.toJSON = function toJSON() { | |
| return {}; | |
| }; | |
| URLSearchParamsProto.toString = function toString() { | |
| var dict = this[secret], query = [], i, key, name, value; | |
| for (key in dict) { | |
| name = encode(key); | |
| for ( | |
| i = 0, | |
| value = dict[key]; | |
| i < value.length; i++ | |
| ) { | |
| query.push(name + '=' + encode(value[i])); | |
| } | |
| } | |
| return query.join('&'); | |
| }; | |
| URLSearchParams = (module.exports = commonjsGlobal.URLSearchParams || URLSearchParams); | |
| (function (URLSearchParamsProto) { | |
| var iterable = (function () { | |
| try { | |
| return !!Symbol.iterator; | |
| } catch(error) { | |
| return false; | |
| } | |
| }()); | |
| // mostly related to issue #24 | |
| if (!('forEach' in URLSearchParamsProto)) { | |
| URLSearchParamsProto.forEach = function forEach(callback, thisArg) { | |
| var names = Object.create(null); | |
| this.toString() | |
| .replace(/=[\s\S]*?(?:&|$)/g, '=') | |
| .split('=') | |
| .forEach(function (name) { | |
| if (!name.length || name in names) return; | |
| (names[name] = this.getAll(name)).forEach(function(value) { | |
| callback.call(thisArg, value, name, this); | |
| }, this); | |
| }, this); | |
| }; | |
| } | |
| if (!('keys' in URLSearchParamsProto)) { | |
| URLSearchParamsProto.keys = function keys() { | |
| var items = []; | |
| this.forEach(function(value, name) { items.push(name); }); | |
| var iterator = { | |
| next: function() { | |
| var value = items.shift(); | |
| return {done: value === undefined, value: value}; | |
| } | |
| }; | |
| if (iterable) { | |
| iterator[Symbol.iterator] = function() { | |
| return iterator; | |
| }; | |
| } | |
| return iterator; | |
| }; | |
| } | |
| if (!('values' in URLSearchParamsProto)) { | |
| URLSearchParamsProto.values = function values() { | |
| var items = []; | |
| this.forEach(function(value) { items.push(value); }); | |
| var iterator = { | |
| next: function() { | |
| var value = items.shift(); | |
| return {done: value === undefined, value: value}; | |
| } | |
| }; | |
| if (iterable) { | |
| iterator[Symbol.iterator] = function() { | |
| return iterator; | |
| }; | |
| } | |
| return iterator; | |
| }; | |
| } | |
| if (!('entries' in URLSearchParamsProto)) { | |
| URLSearchParamsProto.entries = function entries() { | |
| var items = []; | |
| this.forEach(function(value, name) { items.push([name, value]); }); | |
| var iterator = { | |
| next: function() { | |
| var value = items.shift(); | |
| return {done: value === undefined, value: value}; | |
| } | |
| }; | |
| if (iterable) { | |
| iterator[Symbol.iterator] = function() { | |
| return iterator; | |
| }; | |
| } | |
| return iterator; | |
| }; | |
| } | |
| if (iterable && !(Symbol.iterator in URLSearchParamsProto)) { | |
| URLSearchParamsProto[Symbol.iterator] = URLSearchParamsProto.entries; | |
| } | |
| if (!('sort' in URLSearchParamsProto)) { | |
| URLSearchParamsProto.sort = function sort() { | |
| var | |
| entries = this.entries(), | |
| entry = entries.next(), | |
| done = entry.done, | |
| keys = [], | |
| values = Object.create(null), | |
| i, key, value | |
| ; | |
| while (!done) { | |
| value = entry.value; | |
| key = value[0]; | |
| keys.push(key); | |
| if (!(key in values)) { | |
| values[key] = []; | |
| } | |
| values[key].push(value[1]); | |
| entry = entries.next(); | |
| done = entry.done; | |
| } | |
| // not the champion in efficiency | |
| // but these two bits just do the job | |
| keys.sort(); | |
| for (i = 0; i < keys.length; i++) { | |
| this.delete(keys[i]); | |
| } | |
| for (i = 0; i < keys.length; i++) { | |
| key = keys[i]; | |
| this.append(key, values[key].shift()); | |
| } | |
| }; | |
| } | |
| }(URLSearchParams.prototype)); | |
| }); | |
| var urlPattern = createCommonjsModule(function (module, exports) { | |
| // Generated by CoffeeScript 1.10.0 | |
| var slice = [].slice; | |
| (function(root, factory) { | |
| if (exports !== null) { | |
| return module.exports = factory(); | |
| } else { | |
| return root.UrlPattern = factory(); | |
| } | |
| })(commonjsGlobal, function() { | |
| var P, UrlPattern, astNodeContainsSegmentsForProvidedParams, astNodeToNames, astNodeToRegexString, baseAstNodeToRegexString, concatMap, defaultOptions, escapeForRegex, getParam, keysAndValuesToObject, newParser, regexGroupCount, stringConcatMap, stringify; | |
| escapeForRegex = function(string) { | |
| return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); | |
| }; | |
| concatMap = function(array, f) { | |
| var i, length, results; | |
| results = []; | |
| i = -1; | |
| length = array.length; | |
| while (++i < length) { | |
| results = results.concat(f(array[i])); | |
| } | |
| return results; | |
| }; | |
| stringConcatMap = function(array, f) { | |
| var i, length, result; | |
| result = ''; | |
| i = -1; | |
| length = array.length; | |
| while (++i < length) { | |
| result += f(array[i]); | |
| } | |
| return result; | |
| }; | |
| regexGroupCount = function(regex) { | |
| return (new RegExp(regex.toString() + '|')).exec('').length - 1; | |
| }; | |
| keysAndValuesToObject = function(keys, values) { | |
| var i, key, length, object, value; | |
| object = {}; | |
| i = -1; | |
| length = keys.length; | |
| while (++i < length) { | |
| key = keys[i]; | |
| value = values[i]; | |
| if (value == null) { | |
| continue; | |
| } | |
| if (object[key] != null) { | |
| if (!Array.isArray(object[key])) { | |
| object[key] = [object[key]]; | |
| } | |
| object[key].push(value); | |
| } else { | |
| object[key] = value; | |
| } | |
| } | |
| return object; | |
| }; | |
| P = {}; | |
| P.Result = function(value, rest) { | |
| this.value = value; | |
| this.rest = rest; | |
| }; | |
| P.Tagged = function(tag, value) { | |
| this.tag = tag; | |
| this.value = value; | |
| }; | |
| P.tag = function(tag, parser) { | |
| return function(input) { | |
| var result, tagged; | |
| result = parser(input); | |
| if (result == null) { | |
| return; | |
| } | |
| tagged = new P.Tagged(tag, result.value); | |
| return new P.Result(tagged, result.rest); | |
| }; | |
| }; | |
| P.regex = function(regex) { | |
| return function(input) { | |
| var matches, result; | |
| matches = regex.exec(input); | |
| if (matches == null) { | |
| return; | |
| } | |
| result = matches[0]; | |
| return new P.Result(result, input.slice(result.length)); | |
| }; | |
| }; | |
| P.sequence = function() { | |
| var parsers; | |
| parsers = 1 <= arguments.length ? slice.call(arguments, 0) : []; | |
| return function(input) { | |
| var i, length, parser, rest, result, values; | |
| i = -1; | |
| length = parsers.length; | |
| values = []; | |
| rest = input; | |
| while (++i < length) { | |
| parser = parsers[i]; | |
| result = parser(rest); | |
| if (result == null) { | |
| return; | |
| } | |
| values.push(result.value); | |
| rest = result.rest; | |
| } | |
| return new P.Result(values, rest); | |
| }; | |
| }; | |
| P.pick = function() { | |
| var indexes, parsers; | |
| indexes = arguments[0], parsers = 2 <= arguments.length ? slice.call(arguments, 1) : []; | |
| return function(input) { | |
| var array, result; | |
| result = P.sequence.apply(P, parsers)(input); | |
| if (result == null) { | |
| return; | |
| } | |
| array = result.value; | |
| result.value = array[indexes]; | |
| return result; | |
| }; | |
| }; | |
| P.string = function(string) { | |
| var length; | |
| length = string.length; | |
| return function(input) { | |
| if (input.slice(0, length) === string) { | |
| return new P.Result(string, input.slice(length)); | |
| } | |
| }; | |
| }; | |
| P.lazy = function(fn) { | |
| var cached; | |
| cached = null; | |
| return function(input) { | |
| if (cached == null) { | |
| cached = fn(); | |
| } | |
| return cached(input); | |
| }; | |
| }; | |
| P.baseMany = function(parser, end, stringResult, atLeastOneResultRequired, input) { | |
| var endResult, parserResult, rest, results; | |
| rest = input; | |
| results = stringResult ? '' : []; | |
| while (true) { | |
| if (end != null) { | |
| endResult = end(rest); | |
| if (endResult != null) { | |
| break; | |
| } | |
| } | |
| parserResult = parser(rest); | |
| if (parserResult == null) { | |
| break; | |
| } | |
| if (stringResult) { | |
| results += parserResult.value; | |
| } else { | |
| results.push(parserResult.value); | |
| } | |
| rest = parserResult.rest; | |
| } | |
| if (atLeastOneResultRequired && results.length === 0) { | |
| return; | |
| } | |
| return new P.Result(results, rest); | |
| }; | |
| P.many1 = function(parser) { | |
| return function(input) { | |
| return P.baseMany(parser, null, false, true, input); | |
| }; | |
| }; | |
| P.concatMany1Till = function(parser, end) { | |
| return function(input) { | |
| return P.baseMany(parser, end, true, true, input); | |
| }; | |
| }; | |
| P.firstChoice = function() { | |
| var parsers; | |
| parsers = 1 <= arguments.length ? slice.call(arguments, 0) : []; | |
| return function(input) { | |
| var i, length, parser, result; | |
| i = -1; | |
| length = parsers.length; | |
| while (++i < length) { | |
| parser = parsers[i]; | |
| result = parser(input); | |
| if (result != null) { | |
| return result; | |
| } | |
| } | |
| }; | |
| }; | |
| newParser = function(options) { | |
| var U; | |
| U = {}; | |
| U.wildcard = P.tag('wildcard', P.string(options.wildcardChar)); | |
| U.optional = P.tag('optional', P.pick(1, P.string(options.optionalSegmentStartChar), P.lazy(function() { | |
| return U.pattern; | |
| }), P.string(options.optionalSegmentEndChar))); | |
| U.name = P.regex(new RegExp("^[" + options.segmentNameCharset + "]+")); | |
| U.named = P.tag('named', P.pick(1, P.string(options.segmentNameStartChar), P.lazy(function() { | |
| return U.name; | |
| }))); | |
| U.escapedChar = P.pick(1, P.string(options.escapeChar), P.regex(/^./)); | |
| U["static"] = P.tag('static', P.concatMany1Till(P.firstChoice(P.lazy(function() { | |
| return U.escapedChar; | |
| }), P.regex(/^./)), P.firstChoice(P.string(options.segmentNameStartChar), P.string(options.optionalSegmentStartChar), P.string(options.optionalSegmentEndChar), U.wildcard))); | |
| U.token = P.lazy(function() { | |
| return P.firstChoice(U.wildcard, U.optional, U.named, U["static"]); | |
| }); | |
| U.pattern = P.many1(P.lazy(function() { | |
| return U.token; | |
| })); | |
| return U; | |
| }; | |
| defaultOptions = { | |
| escapeChar: '\\', | |
| segmentNameStartChar: ':', | |
| segmentValueCharset: 'a-zA-Z0-9-_~ %', | |
| segmentNameCharset: 'a-zA-Z0-9', | |
| optionalSegmentStartChar: '(', | |
| optionalSegmentEndChar: ')', | |
| wildcardChar: '*' | |
| }; | |
| baseAstNodeToRegexString = function(astNode, segmentValueCharset) { | |
| if (Array.isArray(astNode)) { | |
| return stringConcatMap(astNode, function(node) { | |
| return baseAstNodeToRegexString(node, segmentValueCharset); | |
| }); | |
| } | |
| switch (astNode.tag) { | |
| case 'wildcard': | |
| return '(.*?)'; | |
| case 'named': | |
| return "([" + segmentValueCharset + "]+)"; | |
| case 'static': | |
| return escapeForRegex(astNode.value); | |
| case 'optional': | |
| return '(?:' + baseAstNodeToRegexString(astNode.value, segmentValueCharset) + ')?'; | |
| } | |
| }; | |
| astNodeToRegexString = function(astNode, segmentValueCharset) { | |
| if (segmentValueCharset == null) { | |
| segmentValueCharset = defaultOptions.segmentValueCharset; | |
| } | |
| return '^' + baseAstNodeToRegexString(astNode, segmentValueCharset) + '$'; | |
| }; | |
| astNodeToNames = function(astNode) { | |
| if (Array.isArray(astNode)) { | |
| return concatMap(astNode, astNodeToNames); | |
| } | |
| switch (astNode.tag) { | |
| case 'wildcard': | |
| return ['_']; | |
| case 'named': | |
| return [astNode.value]; | |
| case 'static': | |
| return []; | |
| case 'optional': | |
| return astNodeToNames(astNode.value); | |
| } | |
| }; | |
| getParam = function(params, key, nextIndexes, sideEffects) { | |
| var index, maxIndex, result, value; | |
| if (sideEffects == null) { | |
| sideEffects = false; | |
| } | |
| value = params[key]; | |
| if (value == null) { | |
| if (sideEffects) { | |
| throw new Error("no values provided for key `" + key + "`"); | |
| } else { | |
| return; | |
| } | |
| } | |
| index = nextIndexes[key] || 0; | |
| maxIndex = Array.isArray(value) ? value.length - 1 : 0; | |
| if (index > maxIndex) { | |
| if (sideEffects) { | |
| throw new Error("too few values provided for key `" + key + "`"); | |
| } else { | |
| return; | |
| } | |
| } | |
| result = Array.isArray(value) ? value[index] : value; | |
| if (sideEffects) { | |
| nextIndexes[key] = index + 1; | |
| } | |
| return result; | |
| }; | |
| astNodeContainsSegmentsForProvidedParams = function(astNode, params, nextIndexes) { | |
| var i, length; | |
| if (Array.isArray(astNode)) { | |
| i = -1; | |
| length = astNode.length; | |
| while (++i < length) { | |
| if (astNodeContainsSegmentsForProvidedParams(astNode[i], params, nextIndexes)) { | |
| return true; | |
| } | |
| } | |
| return false; | |
| } | |
| switch (astNode.tag) { | |
| case 'wildcard': | |
| return getParam(params, '_', nextIndexes, false) != null; | |
| case 'named': | |
| return getParam(params, astNode.value, nextIndexes, false) != null; | |
| case 'static': | |
| return false; | |
| case 'optional': | |
| return astNodeContainsSegmentsForProvidedParams(astNode.value, params, nextIndexes); | |
| } | |
| }; | |
| stringify = function(astNode, params, nextIndexes) { | |
| if (Array.isArray(astNode)) { | |
| return stringConcatMap(astNode, function(node) { | |
| return stringify(node, params, nextIndexes); | |
| }); | |
| } | |
| switch (astNode.tag) { | |
| case 'wildcard': | |
| return getParam(params, '_', nextIndexes, true); | |
| case 'named': | |
| return getParam(params, astNode.value, nextIndexes, true); | |
| case 'static': | |
| return astNode.value; | |
| case 'optional': | |
| if (astNodeContainsSegmentsForProvidedParams(astNode.value, params, nextIndexes)) { | |
| return stringify(astNode.value, params, nextIndexes); | |
| } else { | |
| return ''; | |
| } | |
| } | |
| }; | |
| UrlPattern = function(arg1, arg2) { | |
| var groupCount, options, parsed, parser, withoutWhitespace; | |
| if (arg1 instanceof UrlPattern) { | |
| this.isRegex = arg1.isRegex; | |
| this.regex = arg1.regex; | |
| this.ast = arg1.ast; | |
| this.names = arg1.names; | |
| return; | |
| } | |
| this.isRegex = arg1 instanceof RegExp; | |
| if (!(('string' === typeof arg1) || this.isRegex)) { | |
| throw new TypeError('argument must be a regex or a string'); | |
| } | |
| if (this.isRegex) { | |
| this.regex = arg1; | |
| if (arg2 != null) { | |
| if (!Array.isArray(arg2)) { | |
| throw new Error('if first argument is a regex the second argument may be an array of group names but you provided something else'); | |
| } | |
| groupCount = regexGroupCount(this.regex); | |
| if (arg2.length !== groupCount) { | |
| throw new Error("regex contains " + groupCount + " groups but array of group names contains " + arg2.length); | |
| } | |
| this.names = arg2; | |
| } | |
| return; | |
| } | |
| if (arg1 === '') { | |
| throw new Error('argument must not be the empty string'); | |
| } | |
| withoutWhitespace = arg1.replace(/\s+/g, ''); | |
| if (withoutWhitespace !== arg1) { | |
| throw new Error('argument must not contain whitespace'); | |
| } | |
| options = { | |
| escapeChar: (arg2 != null ? arg2.escapeChar : void 0) || defaultOptions.escapeChar, | |
| segmentNameStartChar: (arg2 != null ? arg2.segmentNameStartChar : void 0) || defaultOptions.segmentNameStartChar, | |
| segmentNameCharset: (arg2 != null ? arg2.segmentNameCharset : void 0) || defaultOptions.segmentNameCharset, | |
| segmentValueCharset: (arg2 != null ? arg2.segmentValueCharset : void 0) || defaultOptions.segmentValueCharset, | |
| optionalSegmentStartChar: (arg2 != null ? arg2.optionalSegmentStartChar : void 0) || defaultOptions.optionalSegmentStartChar, | |
| optionalSegmentEndChar: (arg2 != null ? arg2.optionalSegmentEndChar : void 0) || defaultOptions.optionalSegmentEndChar, | |
| wildcardChar: (arg2 != null ? arg2.wildcardChar : void 0) || defaultOptions.wildcardChar | |
| }; | |
| parser = newParser(options); | |
| parsed = parser.pattern(arg1); | |
| if (parsed == null) { | |
| throw new Error("couldn't parse pattern"); | |
| } | |
| if (parsed.rest !== '') { | |
| throw new Error("could only partially parse pattern"); | |
| } | |
| this.ast = parsed.value; | |
| this.regex = new RegExp(astNodeToRegexString(this.ast, options.segmentValueCharset)); | |
| this.names = astNodeToNames(this.ast); | |
| }; | |
| UrlPattern.prototype.match = function(url) { | |
| var groups, match; | |
| match = this.regex.exec(url); | |
| if (match == null) { | |
| return null; | |
| } | |
| groups = match.slice(1); | |
| if (this.names) { | |
| return keysAndValuesToObject(this.names, groups); | |
| } else { | |
| return groups; | |
| } | |
| }; | |
| UrlPattern.prototype.stringify = function(params) { | |
| if (params == null) { | |
| params = {}; | |
| } | |
| if (this.isRegex) { | |
| throw new Error("can't stringify patterns generated from a regex"); | |
| } | |
| if (params !== Object(params)) { | |
| throw new Error("argument must be an object or undefined"); | |
| } | |
| return stringify(this.ast, params, {}); | |
| }; | |
| UrlPattern.escapeForRegex = escapeForRegex; | |
| UrlPattern.concatMap = concatMap; | |
| UrlPattern.stringConcatMap = stringConcatMap; | |
| UrlPattern.regexGroupCount = regexGroupCount; | |
| UrlPattern.keysAndValuesToObject = keysAndValuesToObject; | |
| UrlPattern.P = P; | |
| UrlPattern.newParser = newParser; | |
| UrlPattern.defaultOptions = defaultOptions; | |
| UrlPattern.astNodeToRegexString = astNodeToRegexString; | |
| UrlPattern.astNodeToNames = astNodeToNames; | |
| UrlPattern.getParam = getParam; | |
| UrlPattern.astNodeContainsSegmentsForProvidedParams = astNodeContainsSegmentsForProvidedParams; | |
| UrlPattern.stringify = stringify; | |
| return UrlPattern; | |
| }); | |
| }); | |
| const developmentKey = "FFSer7NqrCooeLkyZP39s"; | |
| const inDevelopment = true; | |
| const userProfileCookieName = "optimizely_ak_ew_user_profile"; | |
| const userIdVariable = "PMUSER_USER_ID"; | |
| const qpFlagName = "flags"; | |
| const qpUserIdName = "user_id"; | |
| const qpAttributeName = "attributes"; | |
| let optimizely; | |
| let userProfileCookie = {}; | |
| let userId = ""; | |
| let flagKey = ""; | |
| let attributes = {}; | |
| let qpFlags = []; | |
| let qpAttributes = []; | |
| let qpUserId = ""; | |
| let user; | |
| let decision; | |
| let htmlResponse = ""; | |
| let validationMessages = []; | |
| const optimizelyEventDispatcher = { | |
| dispatchEvent(event, callback) { | |
| const options = {}; | |
| options.method = "POST"; | |
| options.headers = { "Content-Type": "application/json" }; | |
| options.body = JSON.stringify(event.params); | |
| const url = "https://ew-optly-agent.optimizely.com/v1/events"; | |
| httpRequest(url, options) | |
| .then((response) => callback(response)) | |
| .catch(() => { | |
| logger$1.log('failure "%s"', ex.message, ex); | |
| callback(); | |
| }); | |
| }, | |
| }; | |
| function onClientResponse$1(request, response) { | |
| // try { | |
| // const cookies = new Cookies(request.getHeader("Cookie")); | |
| // cookies.delete(userIdCookie); | |
| // cookies.delete(rule); | |
| // cookies.add(userIdCookie, userId); | |
| // cookies.add(ruleCookie, rule); | |
| // const setCookie = []; | |
| // setCookie.push( | |
| // new SetCookie({ | |
| // name: userIdCookie, | |
| // value: userId, | |
| // path: "/", | |
| // maxAge: cookieExpirationSecs, | |
| // }).toHeader() | |
| // ); | |
| // setCookie.push( | |
| // new SetCookie({ | |
| // name: ruleCookie, | |
| // value: rule, | |
| // path: "/", | |
| // maxAge: cookieExpirationSecs, | |
| // }).toHeader() | |
| // ); | |
| // response.setHeader("Set-Cookie", setCookieHeaders); | |
| // response.setHeader( | |
| // "X-Hello-World", | |
| // "From Akamai EdgeWorkers and Simone via Optimizely" | |
| // ); | |
| // } catch (err) { | |
| // logger.log("Error in onClientResponse: %s", err.message); | |
| // } | |
| } | |
| function getFormattedMessage(messageName, messageValue) { | |
| let result = { Message: "Message value is missing" }; | |
| if (messageName && messageValue) { | |
| result = { messageName: messageValue }; | |
| } | |
| return JSON.stringify(result); | |
| } | |
| async function optimizelyInit(sdkKey) { | |
| const datafile = await getDataFile(inDevelopment, sdkKey); | |
| logger$1.log("Attempting to initialize the Optimizely instance"); | |
| let optlySettings = { | |
| sdkKey: developmentKey , | |
| datafile: datafile, | |
| eventDispatcher: optimizelyEventDispatcher, | |
| eventBatchSize: 1, | |
| eventFlushInterval: 1, | |
| }; | |
| { | |
| delete optlySettings.sdkKey; | |
| } | |
| optimizely = optimizely_browser_min_5(optlySettings); | |
| if (!optimizely) { | |
| logger$1.log("The Optimizely instance could not be initialized."); | |
| } else { | |
| logger$1.log("The Optimizely instance was successfully initialized."); | |
| } | |
| } | |
| function newExperiments(existingExperiments) { | |
| (process.env.ALL_EXPERIMENTS || "") | |
| .split(",") | |
| .filter( | |
| (name) => | |
| !existingExperiments.some((experiment) => experiment.name === name) | |
| ); | |
| } | |
| new urlPattern('/ew-agent(/*)'); | |
| async function onClientRequest$1(request) { | |
| // Look for any previous cookies set | |
| let cookies = new Cookies(request.getHeader("Cookie") || ""); | |
| const experiments = storedExperiments(request); | |
| newExperiments(experiments); | |
| (process.env.CURRENT_EXPERIMENTS || "").split(","); | |
| let tempCookieValue = cookies.get(userProfileCookieName); | |
| try { | |
| let userProfileCookie = JSON.stringify(tempCookieValue); | |
| } catch (err) { | |
| validationMessages.push( | |
| getFormattedMessage( | |
| "user_profile_cookie", | |
| "Unable to parse user profile cookie object. The User will be treated as new." | |
| ) | |
| ); | |
| logger$1.log("Unable to parse user profile cookie: %s", err.message); | |
| } | |
| try { | |
| // Create query parames object | |
| const params = new urlSearchParams_node(request.query); | |
| // Check for previous User ID in cookie | |
| let cookieUserIdValue = ""; | |
| if ( | |
| userProfileCookie && | |
| userProfileCookie[userIdVariable] && | |
| typeof userProfileCookie[userIdVariable] === "string" | |
| ) { | |
| cookieUserIdValue = userProfileCookie[userIdVariable]; | |
| } | |
| // Extract and store temp query parameters | |
| qpUserId = params.get(qpUserIdName); | |
| userId = qpUserId || cookieUserIdValue || `${generateUUID()}`; | |
| request.setVariable(userIdVariable, userId); | |
| logger$1.log("Active user identifier [userId]: %s", userId); | |
| // Temp | |
| let _qpFlags = params.get(qpFlagName); | |
| let _qpAttributes = params.get(qpAttributeName); | |
| logger$1.log("Attributes from query parameters: %s", _qpAttributes); | |
| // Parse flags from query parameters | |
| // let qpFlagKey = ""; | |
| qpUserId = params.get(qpUserIdName); | |
| if (!_qpFlags) { | |
| try { | |
| qpFlags = _qpFlags.split(","); | |
| } catch (error) { | |
| qpFlags = []; | |
| logger$1.log("Unable to obtain a valid decision: %s", reasons); | |
| } | |
| } | |
| // Only one flag is supported for now. need to discuss with product team. | |
| if (qpFlags && qpFlags.length > 0) { | |
| flagKey = qpFlags[0]; | |
| } else { | |
| flagKey = "edge_worker_development"; | |
| } | |
| // Parse attributes from query parameters | |
| if (_qpAttributes) { | |
| try { | |
| qpAttributes = _qpAttributes.split(","); | |
| //logger.log("Attributes from query parameters: %s", _qpAttributes); | |
| //logger.log("Attributes from query parameters split: %s", qpAttributes.join()); | |
| } catch (error) { | |
| qpAttributes = []; | |
| logger$1.log( | |
| "Unable to parse query params for Attributes: %s", | |
| _qpAttributes | |
| ); | |
| } | |
| } | |
| // Render attributes from query parameters | |
| // ToDo - Add validation | |
| if (qpAttributes && qpAttributes.length > 0) { | |
| for (const singleAttribute of qpAttributes) { | |
| const splitAttribute = singleAttribute.split("||"); | |
| attributes[splitAttribute[0]] = splitAttribute[1]; | |
| } | |
| logger$1.log("Attributes JSON: %s", JSON.stringify(attributes)); | |
| } else { | |
| attributes = {}; | |
| } | |
| await optimizelyInit(); | |
| user = optimizely.createUserContext(userId, attributes); | |
| decision = user.decide(flagKey); | |
| let variationKey = decision["variationKey"]; | |
| let reasons = decision["reasons"]; | |
| if (!reasons) { | |
| logger$1.log("Unable to obtain a valid decision: %s", reasons); | |
| } | |
| htmlResponse = | |
| "<html><body>" + | |
| "<h1>User: " + | |
| userId + | |
| "</h1>" + | |
| "<h2>Experience: " + | |
| variationKey + | |
| "</h2>" + | |
| "<h3>Reasons: " + | |
| reasons + | |
| // "</h3>" + | |
| // "<h3>Query Parameters: " + | |
| // qpUserId + | |
| // " -- " + | |
| // qpFlags.join() + | |
| "</h3>" + | |
| "<h3>Attributes: " + | |
| JSON.stringify(attributes) + | |
| "</h3>" + | |
| "</body></html>"; | |
| logger$1.log("Successfully completed evaluating the flag %s", flagKey); | |
| request.respondWith(200, {}, htmlResponse); | |
| } catch (err) { | |
| logger$1.log( | |
| "Failed to complete processing operations within onClientRequest: %s", | |
| err.message | |
| ); | |
| } | |
| //request.setVariable(htmlVariable, htmlResponse); | |
| } | |
| async function responseProvider$1(request) { | |
| } | |
| var edgeworker = { onClientResponse: onClientResponse$1, onClientRequest: onClientRequest$1, responseProvider: responseProvider$1 }; | |
| async function onClientRequest(request) { | |
| await edgeworker.onClientRequest(request); | |
| } | |
| async function onClientResponse(request, response) { | |
| await edgeworker.onClientResponse(request, response); | |
| } | |
| async function responseProvider(request) { | |
| return await edgeworker.responseProvider(request); | |
| } | |
| export { onClientRequest, onClientResponse, responseProvider }; | |
| var window = commonjsGlobal; var setTimeout = function(){}; var clearTimeout = new function(){}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment