New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

react-splitz

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-splitz - npm Package Compare versions

Comparing version
1.0.2
to
2.0.0
+878
cjs/react-splitz.development.js
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var React = _interopDefault(require('react'));
var PropTypes = _interopDefault(require('prop-types'));
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
return function () {
var Super = _getPrototypeOf(Derived),
result;
if (_isNativeReflectConstruct()) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var seedRandom = createCommonjsModule(function (module) {
var width = 256;// each RC4 output is 0 <= x < 256
var chunks = 6;// at least six RC4 outputs for each double
var digits = 52;// there are 52 significant digits in a double
var pool = [];// pool: entropy pool starts empty
var GLOBAL = typeof commonjsGlobal === 'undefined' ? window : commonjsGlobal;
//
// The following constants are related to IEEE 754 limits.
//
var startdenom = Math.pow(width, chunks),
significance = Math.pow(2, digits),
overflow = significance * 2,
mask = width - 1;
var oldRandom = Math.random;
//
// seedrandom()
// This is the seedrandom function described above.
//
module.exports = function(seed, options) {
if (options && options.global === true) {
options.global = false;
Math.random = module.exports(seed, options);
options.global = true;
return Math.random;
}
var use_entropy = (options && options.entropy) || false;
var key = [];
// Flatten the seed string or build one from local entropy if needed.
var shortseed = mixkey(flatten(
use_entropy ? [seed, tostring(pool)] :
0 in arguments ? seed : autoseed(), 3), key);
// Use the seed to initialize an ARC4 generator.
var arc4 = new ARC4(key);
// Mix the randomness into accumulated entropy.
mixkey(tostring(arc4.S), pool);
// Override Math.random
// This function returns a random double in [0, 1) that contains
// randomness in every bit of the mantissa of the IEEE 754 value.
return function() { // Closure to return a random double:
var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
d = startdenom, // and denominator d = 2 ^ 48.
x = 0; // and no 'extra last byte'.
while (n < significance) { // Fill up all significant digits by
n = (n + x) * width; // shifting numerator and
d *= width; // denominator and generating a
x = arc4.g(1); // new least-significant-byte.
}
while (n >= overflow) { // To avoid rounding up, before adding
n /= 2; // last byte, shift everything
d /= 2; // right using integer Math until
x >>>= 1; // we have exactly the desired bits.
}
return (n + x) / d; // Form the number within [0, 1).
};
};
module.exports.resetGlobal = function () {
Math.random = oldRandom;
};
//
// ARC4
//
// An ARC4 implementation. The constructor takes a key in the form of
// an array of at most (width) integers that should be 0 <= x < (width).
//
// The g(count) method returns a pseudorandom integer that concatenates
// the next (count) outputs from ARC4. Its return value is a number x
// that is in the range 0 <= x < (width ^ count).
//
/** @constructor */
function ARC4(key) {
var t, keylen = key.length,
me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
// The empty key [] is treated as [0].
if (!keylen) { key = [keylen++]; }
// Set up S using the standard key scheduling algorithm.
while (i < width) {
s[i] = i++;
}
for (i = 0; i < width; i++) {
s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
s[j] = t;
}
// The "g" method returns the next (count) outputs as one number.
(me.g = function(count) {
// Using instance members instead of closure state nearly doubles speed.
var t, r = 0,
i = me.i, j = me.j, s = me.S;
while (count--) {
t = s[i = mask & (i + 1)];
r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
}
me.i = i; me.j = j;
return r;
// For robust unpredictability discard an initial batch of values.
// See http://www.rsa.com/rsalabs/node.asp?id=2009
})(width);
}
//
// flatten()
// Converts an object tree to nested arrays of strings.
//
function flatten(obj, depth) {
var result = [], typ = (typeof obj)[0], prop;
if (depth && typ == 'o') {
for (prop in obj) {
try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
}
}
return (result.length ? result : typ == 's' ? obj : obj + '\0');
}
//
// mixkey()
// Mixes a string seed into a key that is an array of integers, and
// returns a shortened string seed that is equivalent to the result key.
//
function mixkey(seed, key) {
var stringseed = seed + '', smear, j = 0;
while (j < stringseed.length) {
key[mask & j] =
mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
}
return tostring(key);
}
//
// autoseed()
// Returns an object for autoseeding, using window.crypto if available.
//
/** @param {Uint8Array=} seed */
function autoseed(seed) {
try {
GLOBAL.crypto.getRandomValues(seed = new Uint8Array(width));
return tostring(seed);
} catch (e) {
return [+new Date, GLOBAL, GLOBAL.navigator && GLOBAL.navigator.plugins,
GLOBAL.screen, tostring(pool)];
}
}
//
// tostring()
// Converts an array of charcodes to a string
//
function tostring(a) {
return String.fromCharCode.apply(0, a);
}
//
// When seedrandom.js is loaded, we immediately mix a few bits
// from the built-in RNG into the entropy pool. Because we do
// not want to intefere with determinstic PRNG state later,
// seedrandom will not call Math.random on its own again after
// initialization.
//
mixkey(Math.random(), pool);
});
var seedRandom_1 = seedRandom.resetGlobal;
var STATE_COOKIE = 'react_splitz';
// for a given experiment with the name prop name specified.
function addExperimentsToProps(state, mapExperimentsToProps) {
var subscribedExperiments = {};
for (var _i = 0, _Object$entries = Object.entries(mapExperimentsToProps); _i < _Object$entries.length; _i++) {
var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
propName = _Object$entries$_i[0],
experimentName = _Object$entries$_i[1];
var runningExperiment = state[experimentName];
if (runningExperiment) {
subscribedExperiments[propName] = {
variant: runningExperiment.chosenVariantName
};
}
}
return subscribedExperiments;
}
function inBrowser() {
return (typeof window === "undefined" ? "undefined" : _typeof(window)) === 'object' && window !== 'null';
}
function warning(message) {
/* eslint-disable no-console */
if (typeof console !== 'undefined' && typeof console.error === 'function') {
console.error(message);
}
/* eslint-enable no-console */
try {
// This error was thrown as a convenience so that if you enable
// "break on all exceptions" in your console,
// it would pause the execution at this line.
throw new Error(message);
/* eslint-disable no-empty */
} catch (e) {}
/* eslint-enable no-empty */
}
var cookie = {
get: function get(name) {
if (inBrowser()) {
var eq = name + '=',
ca = document.cookie.split(';');
var c = null;
for (var i = 0; i < ca.length; i += 1) {
c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(eq) === 0) {
return decodeURIComponent(c.substring(eq.length, c.length));
}
}
}
return null;
},
set: function set(name, value) {
var days = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 365;
if (inBrowser()) {
var key = name + '=' + encodeURIComponent(value),
path = 'path=/',
date = new Date();
date.setTime(date.getTime() + days * (1000 * 60 * 60 * 24));
var expires = 'expires=' + date.toGMTString();
document.cookie = [key, expires, path].join(';');
}
}
};
function randomIntBetween() {
var min = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
var seed = arguments.length > 2 ? arguments[2] : undefined;
var random; // Make chosen variant predictable if seed exists
if (seed) {
random = seedRandom(seed)();
}
return Math.floor((random || Math.random()) * (max - min + 1)) + min;
} // Add weighted probability to items in an array
function applyWeightsToVariants(list) {
var weightedList = [];
var weightCount = 0;
list.forEach(function (variant) {
var weight = variant.weight;
var multiples = 1;
if (weight) {
multiples = weight * 10;
weightCount++;
}
for (var j = 0; j < multiples; j++) {
weightedList.push(variant);
}
});
if (weightCount > 0 && weightCount < list.length) {
warning('Ensure that experiments with weights applied to variants have them applied to all variants of that experiment.');
}
return weightedList;
} // Check to make sure that the experiments being set are currently running experiments
function filterValidUpdates(activeExps, updatedExps) {
var validExps = {};
for (var _i2 = 0, _Object$entries2 = Object.entries(updatedExps); _i2 < _Object$entries2.length; _i2++) {
var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2),
experimentName = _Object$entries2$_i[0],
variantName = _Object$entries2$_i[1];
if (typeof activeExps[experimentName] === 'undefined') {
warning("Experiment \"".concat(experimentName, "\" is not a currently running experiment and therefore cannot be updated. Check your input in the 'updateExperiments function to make sure you don't have a typo."));
} else if (!getVariantByName(activeExps[experimentName].variants, variantName)) {
warning("Variant \"".concat(variantName, "\" is not defined in experiment \"").concat(experimentName, "\". Please check updateExperiments function for any typos."));
} else {
validExps[experimentName] = generateChosenExperiment({
name: experimentName,
chosenVariantName: variantName,
variants: activeExps[experimentName].variants
});
}
}
return validExps;
}
function getVariantByName(variants, name) {
return variants.filter(function (variant) {
return variant.name === name;
})[0];
}
function generateChosenExperiment(_ref) {
var variants = _ref.variants,
chosenVariantName = _ref.chosenVariantName,
name = _ref.name;
return {
name: name,
chosenVariantName: chosenVariantName,
variants: variants
};
}
function pickVariant(variants, identifier) {
// Apply probability weights to variants if they are provided and no identifier is provided
variants = identifier ? variants : applyWeightsToVariants(variants);
var chosenVariantIndex = randomIntBetween(0, variants.length - 1, identifier);
return variants[chosenVariantIndex];
} // The experimentStateCookie object should have minimal info due to cookie size constraints.
// The object keys should be the experiment name and the value should be the variant name.
function generateCookieFromState(chosenExperiments) {
var cookieState = {};
for (var _i3 = 0, _Object$entries3 = Object.entries(chosenExperiments); _i3 < _Object$entries3.length; _i3++) {
var _Object$entries3$_i = _slicedToArray(_Object$entries3[_i3], 2),
experimentName = _Object$entries3$_i[0],
chosenVariantName = _Object$entries3$_i[1].chosenVariantName;
cookieState[experimentName] = chosenVariantName;
}
return cookieState;
}
function setExperimentCookieFromState(exps, setCookie) {
setCookie = setCookie || cookie.set;
var cookieValue = generateCookieFromState(exps);
setCookie(STATE_COOKIE, JSON.stringify(cookieValue));
}
// as the `value` prop passed in to the Provider component
var ExperimentContext = React.createContext({
exps: {},
updateExperiments: function updateExperiments() {}
});
// for server-side rendering, unless you want to handle cookies yourself on the client.
// By default, it will assume you are initializing experiments on the client and use the 'document' object
function initializeExperiments(_ref) {
var disableAll = _ref.disableAll,
experiments = _ref.experiments,
getCookie = _ref.getCookie,
setCookie = _ref.setCookie,
_ref$forcedExperiment = _ref.forcedExperiments,
forcedExperiments = _ref$forcedExperiment === void 0 ? {} : _ref$forcedExperiment;
if (typeof getCookie !== 'function' || typeof setCookie !== 'function') {
throw new Error('Both `getCookie` & `setCookie` function props must be provided when rendering components on the server.');
}
if (!Array.isArray(experiments)) {
throw new Error('The `experiments` prop must be an array and provided to `TestContainer` in order to enable experiments.');
} // This object will serve as the current state for all running experiments that will be filtered and
// consumed by components within the application
var chosenExperiments = {};
if (!disableAll) {
var stateCookie = JSON.parse(getCookie(STATE_COOKIE) || '{}'); // Loop over experiments and set cookies
experiments.forEach(function (_ref2) {
var name = _ref2.name,
variants = _ref2.variants,
identifier = _ref2.identifier;
var existingVariantName = stateCookie[name];
var chosenVariantName = existingVariantName;
var chosenVariant = getVariantByName(variants, chosenVariantName); // If there's a matching forced experiment with a valid variant, let's use that value
var forcedExperimentValue = forcedExperiments[name];
var forcedVariant = getVariantByName(variants, forcedExperimentValue);
if (forcedVariant) {
chosenVariantName = forcedExperimentValue;
chosenVariant = forcedVariant;
} else if (identifier || !existingVariantName || !chosenVariant) {
chosenVariant = pickVariant(variants, identifier);
chosenVariantName = chosenVariant.name;
} // Add all relevant info of experiment and chosen variant to experiment state
chosenExperiments[name] = generateChosenExperiment({
name: name,
chosenVariantName: chosenVariant.name,
variants: variants
});
});
}
setExperimentCookieFromState(chosenExperiments, setCookie); // Here we are returning chosenExperiments with all selected/active experiment variants
return {
chosenExperiments: chosenExperiments
};
}
var TestContainer = /*#__PURE__*/function (_React$Component) {
_inherits(TestContainer, _React$Component);
var _super = _createSuper(TestContainer);
function TestContainer() {
var _this;
_classCallCheck(this, TestContainer);
_this = _super.apply(this, arguments);
_this.updateExperiments = _this.updateExperiments.bind(_assertThisInitialized(_this));
_this.state = {
exps: _this.getChosenVariants(),
updateExperiments: _this.updateExperiments
};
return _this;
}
_createClass(TestContainer, [{
key: "getChosenVariants",
value: function getChosenVariants() {
var _this$props = this.props,
experiments = _this$props.experiments,
forcedExperiments = _this$props.forcedExperiments,
disableAll = _this$props.disableAll,
getExperiments = _this$props.getExperiments;
var _this$props2 = this.props,
getCookie = _this$props2.getCookie,
setCookie = _this$props2.setCookie;
if (inBrowser()) {
getCookie = cookie.get;
setCookie = cookie.set;
}
var ExperimentInfo = initializeExperiments({
experiments: experiments,
getCookie: getCookie,
setCookie: setCookie,
forcedExperiments: forcedExperiments,
disableAll: disableAll
});
var chosenExperiments = ExperimentInfo.chosenExperiments;
if (typeof getExperiments === 'function') {
getExperiments(chosenExperiments);
}
return chosenExperiments;
} // We can update the context by using and change what active experiments
// are running with this function that is accessible to any `withTest` wrapped component
}, {
key: "updateExperiments",
value: function updateExperiments(updatedExperiments, callback) {
if (!inBrowser()) {
warning('updateExperiments() can only be called in the browser. This is a no-op. Please check the code where you are calling this function.');
return;
}
var validUpdates = filterValidUpdates(this.state.exps, updatedExperiments);
var newExpState = _objectSpread2({}, this.state.exps, {}, validUpdates);
this.setState({
exps: newExpState
}, function () {
if (typeof callback === 'function') {
return callback();
}
}); // Set new cookie state
setExperimentCookieFromState(newExpState);
}
}, {
key: "render",
value: function render() {
return /*#__PURE__*/React.createElement(ExperimentContext.Provider, {
value: this.state
}, React.Children.only(this.props.children));
}
}]);
return TestContainer;
}(React.Component);
{
TestContainer.propTypes = {
children: PropTypes.element.isRequired,
experiments: PropTypes.arrayOf(PropTypes.object),
getCookie: PropTypes.func,
setCookie: PropTypes.func,
forcedExperiments: PropTypes.object,
disableAll: PropTypes.bool,
getExperiments: PropTypes.func
};
}
// it cares about and maps those experiments to the props of that component.
// Uses React's context API to achieve this
function withTest(mapExperimentsToProps, options) {
options = options || {};
return function (WrappedComponent) {
function TestWrapper(props) {
var forwardedRef = props.forwardedRef,
rest = _objectWithoutProperties(props, ["forwardedRef"]);
return /*#__PURE__*/React.createElement(ExperimentContext.Consumer, null, function (expState) {
var exps = expState.exps,
updateExperiments = expState.updateExperiments;
var subscribedExperiments = addExperimentsToProps(exps, mapExperimentsToProps);
var additionalProps = {};
if (options.updateExperiments) {
additionalProps.updateExperiments = updateExperiments;
} // In addition to adding experiments as props to wrapped component, also pass down any props
// passed in through to the HOC
return /*#__PURE__*/React.createElement(WrappedComponent, _extends({}, subscribedExperiments, rest, {
ref: forwardedRef
}, additionalProps));
});
}
{
TestWrapper.propTypes = {
forwardedRef: PropTypes.oneOfType([PropTypes.func, PropTypes.shape({
current: PropTypes.elementType
})])
};
}
var WrapperComponent = React.memo(TestWrapper);
return React.forwardRef(function forwardRef(props, ref) {
return /*#__PURE__*/React.createElement(WrapperComponent, _extends({}, props, {
forwardedRef: ref
}));
});
};
}
var useExperiment = function useExperiment(experimentName) {
var expContext = React.useContext(ExperimentContext);
var _expContext$exps = expContext.exps,
exps = _expContext$exps === void 0 ? {} : _expContext$exps,
updateExperiments = expContext.updateExperiments;
var experiment = exps[experimentName];
var updateDecorator = function updateDecorator(variant) {
updateExperiments(_defineProperty({}, experimentName, variant));
};
return {
variant: experiment && experiment.chosenVariantName,
updateExperiments: updateDecorator
};
};
exports.TestContainer = TestContainer;
exports.useExperiment = useExperiment;
exports.withTest = withTest;
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=(e=require("react"))&&"object"==typeof e&&"default"in e?e.default:e;function n(e){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(){return(a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}function u(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function c(e){return(c=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function f(e,t){return(f=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function s(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function p(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function l(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function h(e,t){return!t||"object"!=typeof t&&"function"!=typeof t?l(e):t}function d(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(e)))return;var n=[],r=!0,o=!1,i=void 0;try{for(var a,u=e[Symbol.iterator]();!(r=(a=u.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){o=!0,i=e}finally{try{r||null==u.return||u.return()}finally{if(o)throw i}}return n}(e,t)||function(e,t){if(!e)return;if("string"==typeof e)return y(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return y(e,t)}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}require("prop-types");var m="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var v=function(e,t){return e(t={exports:{}},t.exports),t.exports}((function(e){var t=[],n=void 0===m?window:m,r=Math.pow(256,6),o=Math.pow(2,52),i=2*o,a=Math.random;function u(e){var t,n=e.length,r=this,o=0,i=r.i=r.j=0,a=r.S=[];for(n||(e=[n++]);o<256;)a[o]=o++;for(o=0;o<256;o++)a[o]=a[i=255&i+e[o%n]+(t=a[o])],a[i]=t;(r.g=function(e){for(var t,n=0,o=r.i,i=r.j,a=r.S;e--;)t=a[o=255&o+1],n=256*n+a[255&(a[o]=a[i=255&i+t])+(a[i]=t)];return r.i=o,r.j=i,n})(256)}function c(e,t){var n,r=[],o=(typeof e)[0];if(t&&"o"==o)for(n in e)try{r.push(c(e[n],t-1))}catch(e){}return r.length?r:"s"==o?e:e+"\0"}function f(e,t){for(var n,r=e+"",o=0;o<r.length;)t[255&o]=255&(n^=19*t[255&o])+r.charCodeAt(o++);return p(t)}function s(e){try{return n.crypto.getRandomValues(e=new Uint8Array(256)),p(e)}catch(e){return[+new Date,n,n.navigator&&n.navigator.plugins,n.screen,p(t)]}}function p(e){return String.fromCharCode.apply(0,e)}e.exports=function(n,a){if(a&&!0===a.global)return a.global=!1,Math.random=e.exports(n,a),a.global=!0,Math.random;var l=a&&a.entropy||!1,h=[],d=(f(c(l?[n,p(t)]:0 in arguments?n:s(),3),h),new u(h));return f(p(d.S),t),function(){for(var e=d.g(6),t=r,n=0;e<o;)e=256*(e+n),t*=256,n=d.g(1);for(;e>=i;)e/=2,t/=2,n>>>=1;return(e+n)/t}},e.exports.resetGlobal=function(){Math.random=a},f(Math.random(),t)}));v.resetGlobal;function b(){return"object"===("undefined"==typeof window?"undefined":n(window))&&"null"!==window}function g(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}var w={get:function(e){if(b())for(var t=e+"=",n=document.cookie.split(";"),r=null,o=0;o<n.length;o+=1){for(r=n[o];" "===r.charAt(0);)r=r.substring(1,r.length);if(0===r.indexOf(t))return decodeURIComponent(r.substring(t.length,r.length))}return null},set:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:365;if(b()){var r=e+"="+encodeURIComponent(t),o="path=/",i=new Date;i.setTime(i.getTime()+864e5*n);var a="expires="+i.toGMTString();document.cookie=[r,a,o].join(";")}}};function x(e,t){return e.filter((function(e){return e.name===t}))[0]}function O(e){var t=e.variants,n=e.chosenVariantName;return{name:e.name,chosenVariantName:n,variants:t}}function j(e,t){var n,r,o;return(e=t?e:(r=[],o=0,(n=e).forEach((function(e){var t=e.weight,n=1;t&&(n=10*t,o++);for(var i=0;i<n;i++)r.push(e)})),o>0&&o<n.length&&g("Ensure that experiments with weights applied to variants have them applied to all variants of that experiment."),r))[function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=arguments.length>2?arguments[2]:void 0;return r&&(e=v(r)()),Math.floor((e||Math.random())*(n-t+1))+t}(0,e.length-1,t)]}function E(e,t){t=t||w.set;var n=function(e){for(var t={},n=0,r=Object.entries(e);n<r.length;n++){var o=d(r[n],2),i=o[0],a=o[1].chosenVariantName;t[i]=a}return t}(e);t("react_splitz",JSON.stringify(n))}var C=t.createContext({exps:{},updateExperiments:function(){}});var S=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&f(e,t)}(v,t.Component);var n,a,p,y,m=(n=v,function(){var e,t=c(n);if(s()){var r=c(this).constructor;e=Reflect.construct(t,arguments,r)}else e=t.apply(this,arguments);return h(this,e)});function v(){var e;return r(this,v),(e=m.apply(this,arguments)).updateExperiments=e.updateExperiments.bind(l(e)),e.state={exps:e.getChosenVariants(),updateExperiments:e.updateExperiments},e}return a=v,(p=[{key:"getChosenVariants",value:function(){var e=this.props,t=e.experiments,n=e.forcedExperiments,r=e.disableAll,o=e.getExperiments,i=this.props,a=i.getCookie,u=i.setCookie;b()&&(a=w.get,u=w.set);var c=function(e){var t=e.disableAll,n=e.experiments,r=e.getCookie,o=e.setCookie,i=e.forcedExperiments,a=void 0===i?{}:i;if("function"!=typeof r||"function"!=typeof o)throw new Error("Both `getCookie` & `setCookie` function props must be provided when rendering components on the server.");if(!Array.isArray(n))throw new Error("The `experiments` prop must be an array and provided to `TestContainer` in order to enable experiments.");var u={};if(!t){var c=JSON.parse(r("react_splitz")||"{}");n.forEach((function(e){var t=e.name,n=e.variants,r=e.identifier,o=c[t],i=o,f=x(n,i),s=a[t],p=x(n,s);p?(i=s,f=p):!r&&o&&f||(i=(f=j(n,r)).name),u[t]=O({name:t,chosenVariantName:f.name,variants:n})}))}return E(u,o),{chosenExperiments:u}}({experiments:t,getCookie:a,setCookie:u,forcedExperiments:n,disableAll:r}).chosenExperiments;return"function"==typeof o&&o(c),c}},{key:"updateExperiments",value:function(e,t){if(b()){var n=function(e,t){for(var n={},r=0,o=Object.entries(t);r<o.length;r++){var i=d(o[r],2),a=i[0],u=i[1];void 0===e[a]?g('Experiment "'.concat(a,"\" is not a currently running experiment and therefore cannot be updated. Check your input in the 'updateExperiments function to make sure you don't have a typo.")):x(e[a].variants,u)?n[a]=O({name:a,chosenVariantName:u,variants:e[a].variants}):g('Variant "'.concat(u,'" is not defined in experiment "').concat(a,'". Please check updateExperiments function for any typos.'))}return n}(this.state.exps,e),r=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?u(Object(n),!0).forEach((function(t){i(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):u(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({},this.state.exps,{},n);this.setState({exps:r},(function(){if("function"==typeof t)return t()})),E(r)}else g("updateExperiments() can only be called in the browser. This is a no-op. Please check the code where you are calling this function.")}},{key:"render",value:function(){return t.createElement(C.Provider,{value:this.state},t.Children.only(this.props.children))}}])&&o(a.prototype,p),y&&o(a,y),v}();exports.TestContainer=S,exports.useExperiment=function(e){var n=t.useContext(C),r=n.exps,o=void 0===r?{}:r,a=n.updateExperiments,u=o[e];return{variant:u&&u.chosenVariantName,updateExperiments:function(t){a(i({},e,t))}}},exports.withTest=function(e,n){return n=n||{},function(r){var o=t.memo((function(o){var i=o.forwardedRef,u=p(o,["forwardedRef"]);return t.createElement(C.Consumer,null,(function(o){var c=o.exps,f=o.updateExperiments,s=function(e,t){for(var n={},r=0,o=Object.entries(t);r<o.length;r++){var i=d(o[r],2),a=i[0],u=e[i[1]];u&&(n[a]={variant:u.chosenVariantName})}return n}(c,e),p={};return n.updateExperiments&&(p.updateExperiments=f),t.createElement(r,a({},s,u,{ref:i},p))}))}));return t.forwardRef((function(e,n){return t.createElement(o,a({},e,{forwardedRef:n}))}))}};
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react-splitz.production.min.js');
} else {
module.exports = require('./cjs/react-splitz.development.js');
}
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('prop-types')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'prop-types'], factory) :
(global = global || self, factory(global.ReactSplitz = {}, global.React, global.PropTypes));
}(this, (function (exports, React, PropTypes) { 'use strict';
React = React && Object.prototype.hasOwnProperty.call(React, 'default') ? React['default'] : React;
PropTypes = PropTypes && Object.prototype.hasOwnProperty.call(PropTypes, 'default') ? PropTypes['default'] : PropTypes;
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
return function () {
var Super = _getPrototypeOf(Derived),
result;
if (_isNativeReflectConstruct()) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var seedRandom = createCommonjsModule(function (module) {
var width = 256;// each RC4 output is 0 <= x < 256
var chunks = 6;// at least six RC4 outputs for each double
var digits = 52;// there are 52 significant digits in a double
var pool = [];// pool: entropy pool starts empty
var GLOBAL = typeof commonjsGlobal === 'undefined' ? window : commonjsGlobal;
//
// The following constants are related to IEEE 754 limits.
//
var startdenom = Math.pow(width, chunks),
significance = Math.pow(2, digits),
overflow = significance * 2,
mask = width - 1;
var oldRandom = Math.random;
//
// seedrandom()
// This is the seedrandom function described above.
//
module.exports = function(seed, options) {
if (options && options.global === true) {
options.global = false;
Math.random = module.exports(seed, options);
options.global = true;
return Math.random;
}
var use_entropy = (options && options.entropy) || false;
var key = [];
// Flatten the seed string or build one from local entropy if needed.
var shortseed = mixkey(flatten(
use_entropy ? [seed, tostring(pool)] :
0 in arguments ? seed : autoseed(), 3), key);
// Use the seed to initialize an ARC4 generator.
var arc4 = new ARC4(key);
// Mix the randomness into accumulated entropy.
mixkey(tostring(arc4.S), pool);
// Override Math.random
// This function returns a random double in [0, 1) that contains
// randomness in every bit of the mantissa of the IEEE 754 value.
return function() { // Closure to return a random double:
var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
d = startdenom, // and denominator d = 2 ^ 48.
x = 0; // and no 'extra last byte'.
while (n < significance) { // Fill up all significant digits by
n = (n + x) * width; // shifting numerator and
d *= width; // denominator and generating a
x = arc4.g(1); // new least-significant-byte.
}
while (n >= overflow) { // To avoid rounding up, before adding
n /= 2; // last byte, shift everything
d /= 2; // right using integer Math until
x >>>= 1; // we have exactly the desired bits.
}
return (n + x) / d; // Form the number within [0, 1).
};
};
module.exports.resetGlobal = function () {
Math.random = oldRandom;
};
//
// ARC4
//
// An ARC4 implementation. The constructor takes a key in the form of
// an array of at most (width) integers that should be 0 <= x < (width).
//
// The g(count) method returns a pseudorandom integer that concatenates
// the next (count) outputs from ARC4. Its return value is a number x
// that is in the range 0 <= x < (width ^ count).
//
/** @constructor */
function ARC4(key) {
var t, keylen = key.length,
me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
// The empty key [] is treated as [0].
if (!keylen) { key = [keylen++]; }
// Set up S using the standard key scheduling algorithm.
while (i < width) {
s[i] = i++;
}
for (i = 0; i < width; i++) {
s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
s[j] = t;
}
// The "g" method returns the next (count) outputs as one number.
(me.g = function(count) {
// Using instance members instead of closure state nearly doubles speed.
var t, r = 0,
i = me.i, j = me.j, s = me.S;
while (count--) {
t = s[i = mask & (i + 1)];
r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
}
me.i = i; me.j = j;
return r;
// For robust unpredictability discard an initial batch of values.
// See http://www.rsa.com/rsalabs/node.asp?id=2009
})(width);
}
//
// flatten()
// Converts an object tree to nested arrays of strings.
//
function flatten(obj, depth) {
var result = [], typ = (typeof obj)[0], prop;
if (depth && typ == 'o') {
for (prop in obj) {
try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
}
}
return (result.length ? result : typ == 's' ? obj : obj + '\0');
}
//
// mixkey()
// Mixes a string seed into a key that is an array of integers, and
// returns a shortened string seed that is equivalent to the result key.
//
function mixkey(seed, key) {
var stringseed = seed + '', smear, j = 0;
while (j < stringseed.length) {
key[mask & j] =
mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
}
return tostring(key);
}
//
// autoseed()
// Returns an object for autoseeding, using window.crypto if available.
//
/** @param {Uint8Array=} seed */
function autoseed(seed) {
try {
GLOBAL.crypto.getRandomValues(seed = new Uint8Array(width));
return tostring(seed);
} catch (e) {
return [+new Date, GLOBAL, GLOBAL.navigator && GLOBAL.navigator.plugins,
GLOBAL.screen, tostring(pool)];
}
}
//
// tostring()
// Converts an array of charcodes to a string
//
function tostring(a) {
return String.fromCharCode.apply(0, a);
}
//
// When seedrandom.js is loaded, we immediately mix a few bits
// from the built-in RNG into the entropy pool. Because we do
// not want to intefere with determinstic PRNG state later,
// seedrandom will not call Math.random on its own again after
// initialization.
//
mixkey(Math.random(), pool);
});
var seedRandom_1 = seedRandom.resetGlobal;
var STATE_COOKIE = 'react_splitz';
// for a given experiment with the name prop name specified.
function addExperimentsToProps(state, mapExperimentsToProps) {
var subscribedExperiments = {};
for (var _i = 0, _Object$entries = Object.entries(mapExperimentsToProps); _i < _Object$entries.length; _i++) {
var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
propName = _Object$entries$_i[0],
experimentName = _Object$entries$_i[1];
var runningExperiment = state[experimentName];
if (runningExperiment) {
subscribedExperiments[propName] = {
variant: runningExperiment.chosenVariantName
};
}
}
return subscribedExperiments;
}
function inBrowser() {
return (typeof window === "undefined" ? "undefined" : _typeof(window)) === 'object' && window !== 'null';
}
function warning(message) {
/* eslint-disable no-console */
if (typeof console !== 'undefined' && typeof console.error === 'function') {
console.error(message);
}
/* eslint-enable no-console */
try {
// This error was thrown as a convenience so that if you enable
// "break on all exceptions" in your console,
// it would pause the execution at this line.
throw new Error(message);
/* eslint-disable no-empty */
} catch (e) {}
/* eslint-enable no-empty */
}
var cookie = {
get: function get(name) {
if (inBrowser()) {
var eq = name + '=',
ca = document.cookie.split(';');
var c = null;
for (var i = 0; i < ca.length; i += 1) {
c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(eq) === 0) {
return decodeURIComponent(c.substring(eq.length, c.length));
}
}
}
return null;
},
set: function set(name, value) {
var days = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 365;
if (inBrowser()) {
var key = name + '=' + encodeURIComponent(value),
path = 'path=/',
date = new Date();
date.setTime(date.getTime() + days * (1000 * 60 * 60 * 24));
var expires = 'expires=' + date.toGMTString();
document.cookie = [key, expires, path].join(';');
}
}
};
function randomIntBetween() {
var min = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
var seed = arguments.length > 2 ? arguments[2] : undefined;
var random; // Make chosen variant predictable if seed exists
if (seed) {
random = seedRandom(seed)();
}
return Math.floor((random || Math.random()) * (max - min + 1)) + min;
} // Add weighted probability to items in an array
function applyWeightsToVariants(list) {
var weightedList = [];
var weightCount = 0;
list.forEach(function (variant) {
var weight = variant.weight;
var multiples = 1;
if (weight) {
multiples = weight * 10;
weightCount++;
}
for (var j = 0; j < multiples; j++) {
weightedList.push(variant);
}
});
if (weightCount > 0 && weightCount < list.length) {
warning('Ensure that experiments with weights applied to variants have them applied to all variants of that experiment.');
}
return weightedList;
} // Check to make sure that the experiments being set are currently running experiments
function filterValidUpdates(activeExps, updatedExps) {
var validExps = {};
for (var _i2 = 0, _Object$entries2 = Object.entries(updatedExps); _i2 < _Object$entries2.length; _i2++) {
var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2),
experimentName = _Object$entries2$_i[0],
variantName = _Object$entries2$_i[1];
if (typeof activeExps[experimentName] === 'undefined') {
warning("Experiment \"".concat(experimentName, "\" is not a currently running experiment and therefore cannot be updated. Check your input in the 'updateExperiments function to make sure you don't have a typo."));
} else if (!getVariantByName(activeExps[experimentName].variants, variantName)) {
warning("Variant \"".concat(variantName, "\" is not defined in experiment \"").concat(experimentName, "\". Please check updateExperiments function for any typos."));
} else {
validExps[experimentName] = generateChosenExperiment({
name: experimentName,
chosenVariantName: variantName,
variants: activeExps[experimentName].variants
});
}
}
return validExps;
}
function getVariantByName(variants, name) {
return variants.filter(function (variant) {
return variant.name === name;
})[0];
}
function generateChosenExperiment(_ref) {
var variants = _ref.variants,
chosenVariantName = _ref.chosenVariantName,
name = _ref.name;
return {
name: name,
chosenVariantName: chosenVariantName,
variants: variants
};
}
function pickVariant(variants, identifier) {
// Apply probability weights to variants if they are provided and no identifier is provided
variants = identifier ? variants : applyWeightsToVariants(variants);
var chosenVariantIndex = randomIntBetween(0, variants.length - 1, identifier);
return variants[chosenVariantIndex];
} // The experimentStateCookie object should have minimal info due to cookie size constraints.
// The object keys should be the experiment name and the value should be the variant name.
function generateCookieFromState(chosenExperiments) {
var cookieState = {};
for (var _i3 = 0, _Object$entries3 = Object.entries(chosenExperiments); _i3 < _Object$entries3.length; _i3++) {
var _Object$entries3$_i = _slicedToArray(_Object$entries3[_i3], 2),
experimentName = _Object$entries3$_i[0],
chosenVariantName = _Object$entries3$_i[1].chosenVariantName;
cookieState[experimentName] = chosenVariantName;
}
return cookieState;
}
function setExperimentCookieFromState(exps, setCookie) {
setCookie = setCookie || cookie.set;
var cookieValue = generateCookieFromState(exps);
setCookie(STATE_COOKIE, JSON.stringify(cookieValue));
}
// as the `value` prop passed in to the Provider component
var ExperimentContext = React.createContext({
exps: {},
updateExperiments: function updateExperiments() {}
});
// for server-side rendering, unless you want to handle cookies yourself on the client.
// By default, it will assume you are initializing experiments on the client and use the 'document' object
function initializeExperiments(_ref) {
var disableAll = _ref.disableAll,
experiments = _ref.experiments,
getCookie = _ref.getCookie,
setCookie = _ref.setCookie,
_ref$forcedExperiment = _ref.forcedExperiments,
forcedExperiments = _ref$forcedExperiment === void 0 ? {} : _ref$forcedExperiment;
if (typeof getCookie !== 'function' || typeof setCookie !== 'function') {
throw new Error('Both `getCookie` & `setCookie` function props must be provided when rendering components on the server.');
}
if (!Array.isArray(experiments)) {
throw new Error('The `experiments` prop must be an array and provided to `TestContainer` in order to enable experiments.');
} // This object will serve as the current state for all running experiments that will be filtered and
// consumed by components within the application
var chosenExperiments = {};
if (!disableAll) {
var stateCookie = JSON.parse(getCookie(STATE_COOKIE) || '{}'); // Loop over experiments and set cookies
experiments.forEach(function (_ref2) {
var name = _ref2.name,
variants = _ref2.variants,
identifier = _ref2.identifier;
var existingVariantName = stateCookie[name];
var chosenVariantName = existingVariantName;
var chosenVariant = getVariantByName(variants, chosenVariantName); // If there's a matching forced experiment with a valid variant, let's use that value
var forcedExperimentValue = forcedExperiments[name];
var forcedVariant = getVariantByName(variants, forcedExperimentValue);
if (forcedVariant) {
chosenVariantName = forcedExperimentValue;
chosenVariant = forcedVariant;
} else if (identifier || !existingVariantName || !chosenVariant) {
chosenVariant = pickVariant(variants, identifier);
chosenVariantName = chosenVariant.name;
} // Add all relevant info of experiment and chosen variant to experiment state
chosenExperiments[name] = generateChosenExperiment({
name: name,
chosenVariantName: chosenVariant.name,
variants: variants
});
});
}
setExperimentCookieFromState(chosenExperiments, setCookie); // Here we are returning chosenExperiments with all selected/active experiment variants
return {
chosenExperiments: chosenExperiments
};
}
var TestContainer = /*#__PURE__*/function (_React$Component) {
_inherits(TestContainer, _React$Component);
var _super = _createSuper(TestContainer);
function TestContainer() {
var _this;
_classCallCheck(this, TestContainer);
_this = _super.apply(this, arguments);
_this.updateExperiments = _this.updateExperiments.bind(_assertThisInitialized(_this));
_this.state = {
exps: _this.getChosenVariants(),
updateExperiments: _this.updateExperiments
};
return _this;
}
_createClass(TestContainer, [{
key: "getChosenVariants",
value: function getChosenVariants() {
var _this$props = this.props,
experiments = _this$props.experiments,
forcedExperiments = _this$props.forcedExperiments,
disableAll = _this$props.disableAll,
getExperiments = _this$props.getExperiments;
var _this$props2 = this.props,
getCookie = _this$props2.getCookie,
setCookie = _this$props2.setCookie;
if (inBrowser()) {
getCookie = cookie.get;
setCookie = cookie.set;
}
var ExperimentInfo = initializeExperiments({
experiments: experiments,
getCookie: getCookie,
setCookie: setCookie,
forcedExperiments: forcedExperiments,
disableAll: disableAll
});
var chosenExperiments = ExperimentInfo.chosenExperiments;
if (typeof getExperiments === 'function') {
getExperiments(chosenExperiments);
}
return chosenExperiments;
} // We can update the context by using and change what active experiments
// are running with this function that is accessible to any `withTest` wrapped component
}, {
key: "updateExperiments",
value: function updateExperiments(updatedExperiments, callback) {
if (!inBrowser()) {
warning('updateExperiments() can only be called in the browser. This is a no-op. Please check the code where you are calling this function.');
return;
}
var validUpdates = filterValidUpdates(this.state.exps, updatedExperiments);
var newExpState = _objectSpread2({}, this.state.exps, {}, validUpdates);
this.setState({
exps: newExpState
}, function () {
if (typeof callback === 'function') {
return callback();
}
}); // Set new cookie state
setExperimentCookieFromState(newExpState);
}
}, {
key: "render",
value: function render() {
return /*#__PURE__*/React.createElement(ExperimentContext.Provider, {
value: this.state
}, React.Children.only(this.props.children));
}
}]);
return TestContainer;
}(React.Component);
// it cares about and maps those experiments to the props of that component.
// Uses React's context API to achieve this
function withTest(mapExperimentsToProps, options) {
options = options || {};
return function (WrappedComponent) {
function TestWrapper(props) {
var forwardedRef = props.forwardedRef,
rest = _objectWithoutProperties(props, ["forwardedRef"]);
return /*#__PURE__*/React.createElement(ExperimentContext.Consumer, null, function (expState) {
var exps = expState.exps,
updateExperiments = expState.updateExperiments;
var subscribedExperiments = addExperimentsToProps(exps, mapExperimentsToProps);
var additionalProps = {};
if (options.updateExperiments) {
additionalProps.updateExperiments = updateExperiments;
} // In addition to adding experiments as props to wrapped component, also pass down any props
// passed in through to the HOC
return /*#__PURE__*/React.createElement(WrappedComponent, _extends({}, subscribedExperiments, rest, {
ref: forwardedRef
}, additionalProps));
});
}
var WrapperComponent = React.memo(TestWrapper);
return React.forwardRef(function forwardRef(props, ref) {
return /*#__PURE__*/React.createElement(WrapperComponent, _extends({}, props, {
forwardedRef: ref
}));
});
};
}
var useExperiment = function useExperiment(experimentName) {
var expContext = React.useContext(ExperimentContext);
var _expContext$exps = expContext.exps,
exps = _expContext$exps === void 0 ? {} : _expContext$exps,
updateExperiments = expContext.updateExperiments;
var experiment = exps[experimentName];
var updateDecorator = function updateDecorator(variant) {
updateExperiments(_defineProperty({}, experimentName, variant));
};
return {
variant: experiment && experiment.chosenVariantName,
updateExperiments: updateDecorator
};
};
exports.TestContainer = TestContainer;
exports.useExperiment = useExperiment;
exports.withTest = withTest;
Object.defineProperty(exports, '__esModule', { value: true });
})));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("prop-types")):"function"==typeof define&&define.amd?define(["exports","react","prop-types"],t):t((e=e||self).ReactSplitz={},e.React,e.PropTypes)}(this,(function(e,t,n){"use strict";function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function u(){return(u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}function c(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function f(e){return(f=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function s(e,t){return(s=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function p(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function l(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function d(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function h(e,t){return!t||"object"!=typeof t&&"function"!=typeof t?d(e):t}function y(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(e)))return;var n=[],r=!0,o=!1,i=void 0;try{for(var a,u=e[Symbol.iterator]();!(r=(a=u.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){o=!0,i=e}finally{try{r||null==u.return||u.return()}finally{if(o)throw i}}return n}(e,t)||function(e,t){if(!e)return;if("string"==typeof e)return m(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return m(e,t)}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function m(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}t=t&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t,n=n&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n;var v="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var b=function(e,t){return e(t={exports:{}},t.exports),t.exports}((function(e){var t=[],n=void 0===v?window:v,r=Math.pow(256,6),o=Math.pow(2,52),i=2*o,a=Math.random;function u(e){var t,n=e.length,r=this,o=0,i=r.i=r.j=0,a=r.S=[];for(n||(e=[n++]);o<256;)a[o]=o++;for(o=0;o<256;o++)a[o]=a[i=255&i+e[o%n]+(t=a[o])],a[i]=t;(r.g=function(e){for(var t,n=0,o=r.i,i=r.j,a=r.S;e--;)t=a[o=255&o+1],n=256*n+a[255&(a[o]=a[i=255&i+t])+(a[i]=t)];return r.i=o,r.j=i,n})(256)}function c(e,t){var n,r=[],o=(typeof e)[0];if(t&&"o"==o)for(n in e)try{r.push(c(e[n],t-1))}catch(e){}return r.length?r:"s"==o?e:e+"\0"}function f(e,t){for(var n,r=e+"",o=0;o<r.length;)t[255&o]=255&(n^=19*t[255&o])+r.charCodeAt(o++);return p(t)}function s(e){try{return n.crypto.getRandomValues(e=new Uint8Array(256)),p(e)}catch(e){return[+new Date,n,n.navigator&&n.navigator.plugins,n.screen,p(t)]}}function p(e){return String.fromCharCode.apply(0,e)}e.exports=function(n,a){if(a&&!0===a.global)return a.global=!1,Math.random=e.exports(n,a),a.global=!0,Math.random;var l=a&&a.entropy||!1,d=[],h=(f(c(l?[n,p(t)]:0 in arguments?n:s(),3),d),new u(d));return f(p(h.S),t),function(){for(var e=h.g(6),t=r,n=0;e<o;)e=256*(e+n),t*=256,n=h.g(1);for(;e>=i;)e/=2,t/=2,n>>>=1;return(e+n)/t}},e.exports.resetGlobal=function(){Math.random=a},f(Math.random(),t)}));b.resetGlobal;function g(){return"object"===("undefined"==typeof window?"undefined":r(window))&&"null"!==window}function w(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}var x={get:function(e){if(g())for(var t=e+"=",n=document.cookie.split(";"),r=null,o=0;o<n.length;o+=1){for(r=n[o];" "===r.charAt(0);)r=r.substring(1,r.length);if(0===r.indexOf(t))return decodeURIComponent(r.substring(t.length,r.length))}return null},set:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:365;if(g()){var r=e+"="+encodeURIComponent(t),o="path=/",i=new Date;i.setTime(i.getTime()+864e5*n);var a="expires="+i.toGMTString();document.cookie=[r,a,o].join(";")}}};function O(e,t){return e.filter((function(e){return e.name===t}))[0]}function j(e){var t=e.variants,n=e.chosenVariantName;return{name:e.name,chosenVariantName:n,variants:t}}function E(e,t){var n,r,o;return(e=t?e:(r=[],o=0,(n=e).forEach((function(e){var t=e.weight,n=1;t&&(n=10*t,o++);for(var i=0;i<n;i++)r.push(e)})),o>0&&o<n.length&&w("Ensure that experiments with weights applied to variants have them applied to all variants of that experiment."),r))[function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=arguments.length>2?arguments[2]:void 0;return r&&(e=b(r)()),Math.floor((e||Math.random())*(n-t+1))+t}(0,e.length-1,t)]}function S(e,t){t=t||x.set;var n=function(e){for(var t={},n=0,r=Object.entries(e);n<r.length;n++){var o=y(r[n],2),i=o[0],a=o[1].chosenVariantName;t[i]=a}return t}(e);t("react_splitz",JSON.stringify(n))}var C=t.createContext({exps:{},updateExperiments:function(){}});var P=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&s(e,t)}(v,e);var n,r,u,l,m=(n=v,function(){var e,t=f(n);if(p()){var r=f(this).constructor;e=Reflect.construct(t,arguments,r)}else e=t.apply(this,arguments);return h(this,e)});function v(){var e;return o(this,v),(e=m.apply(this,arguments)).updateExperiments=e.updateExperiments.bind(d(e)),e.state={exps:e.getChosenVariants(),updateExperiments:e.updateExperiments},e}return r=v,(u=[{key:"getChosenVariants",value:function(){var e=this.props,t=e.experiments,n=e.forcedExperiments,r=e.disableAll,o=e.getExperiments,i=this.props,a=i.getCookie,u=i.setCookie;g()&&(a=x.get,u=x.set);var c=function(e){var t=e.disableAll,n=e.experiments,r=e.getCookie,o=e.setCookie,i=e.forcedExperiments,a=void 0===i?{}:i;if("function"!=typeof r||"function"!=typeof o)throw new Error("Both `getCookie` & `setCookie` function props must be provided when rendering components on the server.");if(!Array.isArray(n))throw new Error("The `experiments` prop must be an array and provided to `TestContainer` in order to enable experiments.");var u={};if(!t){var c=JSON.parse(r("react_splitz")||"{}");n.forEach((function(e){var t=e.name,n=e.variants,r=e.identifier,o=c[t],i=o,f=O(n,i),s=a[t],p=O(n,s);p?(i=s,f=p):!r&&o&&f||(i=(f=E(n,r)).name),u[t]=j({name:t,chosenVariantName:f.name,variants:n})}))}return S(u,o),{chosenExperiments:u}}({experiments:t,getCookie:a,setCookie:u,forcedExperiments:n,disableAll:r}).chosenExperiments;return"function"==typeof o&&o(c),c}},{key:"updateExperiments",value:function(e,t){if(g()){var n=function(e,t){for(var n={},r=0,o=Object.entries(t);r<o.length;r++){var i=y(o[r],2),a=i[0],u=i[1];void 0===e[a]?w('Experiment "'.concat(a,"\" is not a currently running experiment and therefore cannot be updated. Check your input in the 'updateExperiments function to make sure you don't have a typo.")):O(e[a].variants,u)?n[a]=j({name:a,chosenVariantName:u,variants:e[a].variants}):w('Variant "'.concat(u,'" is not defined in experiment "').concat(a,'". Please check updateExperiments function for any typos.'))}return n}(this.state.exps,e),r=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?c(Object(n),!0).forEach((function(t){a(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):c(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({},this.state.exps,{},n);this.setState({exps:r},(function(){if("function"==typeof t)return t()})),S(r)}else w("updateExperiments() can only be called in the browser. This is a no-op. Please check the code where you are calling this function.")}},{key:"render",value:function(){return t.createElement(C.Provider,{value:this.state},t.Children.only(this.props.children))}}])&&i(r.prototype,u),l&&i(r,l),v}(t.Component);e.TestContainer=P,e.useExperiment=function(e){var n=t.useContext(C),r=n.exps,o=void 0===r?{}:r,i=n.updateExperiments,u=o[e];return{variant:u&&u.chosenVariantName,updateExperiments:function(t){i(a({},e,t))}}},e.withTest=function(e,n){return n=n||{},function(r){var o=t.memo((function(o){var i=o.forwardedRef,a=l(o,["forwardedRef"]);return t.createElement(C.Consumer,null,(function(o){var c=o.exps,f=o.updateExperiments,s=function(e,t){for(var n={},r=0,o=Object.entries(t);r<o.length;r++){var i=y(o[r],2),a=i[0],u=e[i[1]];u&&(n[a]={variant:u.chosenVariantName})}return n}(c,e),p={};return n.updateExperiments&&(p.updateExperiments=f),t.createElement(r,u({},s,a,{ref:i},p))}))}));return t.forwardRef((function(e,n){return t.createElement(o,u({},e,{forwardedRef:n}))}))}},Object.defineProperty(e,"__esModule",{value:!0})}));
+36
-29
{
"name": "react-splitz",
"version": "1.0.2",
"version": "2.0.0",
"description": "A/B & Multivariate Testing library for React projects",

@@ -13,14 +13,16 @@ "keywords": [

],
"main": "dist/index.js",
"main": "index.js",
"files": [
"/dist"
"TestContainer",
"withTest",
"cjs",
"umd"
],
"scripts": {
"build-modules": "npm install",
"test": "jest",
"coverage": "rimraf ./coverage && jest --coverage && open coverage/lcov-report/index.html",
"coverage-only": "rimraf ./coverage && jest --coverage",
"build-dev": "NODE_ENV=development webpack",
"build-prod": "NODE_ENV=production webpack",
"build": "npm run build-prod && npm run build-dev",
"test": "TEST=true jest",
"coverage": "rimraf ./coverage && TEST=true jest --coverage && open coverage/lcov-report/index.html",
"coverage-only": "TEST=true rimraf ./coverage && TEST=true jest --coverage",
"build": "rollup -c",
"inspect-bundle": "INSPECT_BUNDLE=true npm run build-prod",
"format": "prettier --trailing-comma es5 --single-quote --write 'src/**/*.js'",

@@ -35,28 +37,31 @@ "lint": "echo Linting code... && eslint ."

"devDependencies": {
"@babel/core": "^7.1.2",
"@babel/preset-env": "^7.1.0",
"@babel/preset-react": "^7.0.0",
"@babel/core": "^7.9.0",
"@babel/preset-env": "^7.9.0",
"@babel/preset-react": "^7.9.4",
"@rollup/plugin-commonjs": "^11.0.2",
"@rollup/plugin-node-resolve": "^7.1.1",
"@rollup/plugin-replace": "^2.3.1",
"babel-core": "^7.0.0-bridge.0",
"babel-eslint": "^10.0.1",
"babel-jest": "^23.6.0",
"babel-loader": "^8.0.4",
"enzyme": "^3.7.0",
"enzyme-adapter-react-16": "^1.7.0",
"eslint": "^5.7.0",
"eslint-plugin-react": "^7.11.1",
"husky": "^1.1.2",
"jest": "^23.6.0",
"babel-eslint": "^10.1.0",
"babel-jest": "^25.2.6",
"babel-loader": "^8.1.0",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"eslint": "^5.16.0",
"eslint-plugin-react": "^7.19.0",
"husky": "^1.3.1",
"jest": "^25.2.6",
"lint-staged": "^7.3.0",
"pre-push": "^0.1.1",
"prettier": "1.14.3",
"prop-types": "^15.6.2",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"rimraf": "^2.6.2",
"webpack": "^4.22.0",
"webpack-cli": "^3.1.2"
"prop-types": "^15.7.2",
"rimraf": "^2.7.1",
"rollup": "^2.3.2",
"rollup-plugin-babel": "^4.4.0",
"rollup-plugin-terser": "^5.3.0",
"rollup-plugin-visualizer": "^3.3.2"
},
"peerDependencies": {
"react": ">= 16.3.0 < 17",
"react-dom": ">= 16.3.0 < 17"
"react": ">= 16.8.0 < 17",
"react-dom": ">= 16.8.0 < 17"
},

@@ -80,4 +85,6 @@ "husky": {

"dependencies": {
"react": "^16.13.1",
"react-dom": "^16.13.1",
"seed-random": "^2.2.0"
}
}

@@ -1,7 +0,7 @@

# React Splitz
# React Splitz 📊📈
React Splitz is an A/B and multivariate testing tool for react projects
React Splitz is an A/B and multivariate testing tool for react applications.
It enables you to set and manage persistent experiments in your app and easily subscribe and access them from any component via component props we know and love. It also offers full support for **server-side rendering**
so you're able to use it in your **universal** web apps as well.
Easy way to set and manage persistent experiments in your app and make careful changes to your user experiences while collecting data on the results. Subscribe and access experiments from any component via component props or hooks that we all know and love. It also offers full support for **server-side rendering**
so you're able to use it in your **universal** web apps as well. Very performant and lightweight (~ **3.9kb** minified/gzipped).

@@ -16,3 +16,3 @@ ## Installation

or using **yarn**:
Using **yarn**:

@@ -23,2 +23,14 @@ ```bash

or **UMD** build (`ReactSplitz` as the global variable)
```bash
// Development build
<script src="https://unpkg.com/react-splitz@2/umd/react-splitz.development.js"></script>
```
```bash
// Production build
<script src="https://unpkg.com/react-splitz@2/umd/react-splitz.production.min.js"></script>
```
## Setup

@@ -43,3 +55,3 @@

* application it might make more sense to move this array to a config file
* and import it here.
* or retrieve it from an API and import it here.
**/

@@ -120,2 +132,19 @@

## Using hooks
Instead of using the `withTest` Higher Order component (HOC) you can use the `useExperiment` hook to subscribe to an experiment. Here's an example.
```js
// Import 'useExperiment' hook here
import { useExperiment } from 'react-splitz';
function MyComponent(props) {
const { variant } = useExperiment('signup-btn-color');
// Use variant here to decide how to markup your UI
}
```
> **Note:** Hooks require React version 16.8 or later
## Weighted Experiments

@@ -122,0 +151,0 @@

'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./main.production.min.js');
} else {
module.exports = require('./main.development.js');
}

Sorry, the diff of this file is too big to display

!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.ReactSplitz=t(require("react")):e.ReactSplitz=t(e.react)}(window,function(e){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=6)}([function(t,n){t.exports=e},function(e,t,n){e.exports=n(3)()},function(e,t,n){"use strict";(function(t){var n=256,r=[],o=void 0===t?window:t,i=Math.pow(n,6),a=Math.pow(2,52),u=2*a,c=n-1,f=Math.random;function p(e,t){for(var n,r=e+"",o=0;o<r.length;)t[c&o]=c&(n^=19*t[c&o])+r.charCodeAt(o++);return s(t)}function s(e){return String.fromCharCode.apply(0,e)}e.exports=function(t,f){if(f&&!0===f.global)return f.global=!1,Math.random=e.exports(t,f),f.global=!0,Math.random;var l=[],y=(p(function e(t,n){var r,o=[],i=(typeof t)[0];if(n&&"o"==i)for(r in t)try{o.push(e(t[r],n-1))}catch(e){}return o.length?o:"s"==i?t:t+"\0"}(f&&f.entropy||!1?[t,s(r)]:0 in arguments?t:function(e){try{return o.crypto.getRandomValues(e=new Uint8Array(n)),s(e)}catch(e){return[+new Date,o,o.navigator&&o.navigator.plugins,o.screen,s(r)]}}(),3),l),new function(e){var t,r=e.length,o=this,i=0,a=o.i=o.j=0,u=o.S=[];r||(e=[r++]);for(;i<n;)u[i]=i++;for(i=0;i<n;i++)u[i]=u[a=c&a+e[i%r]+(t=u[i])],u[a]=t;(o.g=function(e){for(var t,r=0,i=o.i,a=o.j,u=o.S;e--;)t=u[i=c&i+1],r=r*n+u[c&(u[i]=u[a=c&a+t])+(u[a]=t)];return o.i=i,o.j=a,r})(n)}(l));return p(s(y.S),r),function(){for(var e=y.g(6),t=i,r=0;e<a;)e=(e+r)*n,t*=n,r=y.g(1);for(;e>=u;)e/=2,t/=2,r>>>=1;return(e+r)/t}},e.exports.resetGlobal=function(){Math.random=f},p(Math.random(),r)}).call(this,n(5))},function(e,t,n){"use strict";var r=n(4);function o(){}e.exports=function(){function e(e,t,n,o,i,a){if(a!==r){var u=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw u.name="Invariant Violation",u}}function t(){return e}e.isRequired=e;var n={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t};return n.checkPropTypes=o,n.PropTypes=n,n}},function(e,t,n){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){"use strict";n.r(t);var r=n(0),o=n.n(r),i=n(1),a=n.n(i),u=n(2),c=n.n(u);function f(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=[],r=!0,o=!1,i=void 0;try{for(var a,u=e[Symbol.iterator]();!(r=(a=u.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){o=!0,i=e}finally{try{r||null==u.return||u.return()}finally{if(o)throw i}}return n}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function p(e){return(p="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function s(){return"object"===("undefined"==typeof window?"undefined":p(window))&&"null"!==window}function l(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(e){}}var y=function(e){if(s())for(var t=e+"=",n=document.cookie.split(";"),r=null,o=0;o<n.length;o+=1){for(r=n[o];" "===r.charAt(0);)r=r.substring(1,r.length);if(0===r.indexOf(t))return decodeURIComponent(r.substring(t.length,r.length))}return null},d=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:365;if(s()){var r=e+"="+encodeURIComponent(t),o=new Date;o.setTime(o.getTime()+864e5*n);var i="expires="+o.toGMTString();document.cookie=[r,i,"path=/"].join(";")}};function h(e,t){return e.filter(function(e){return e.name===t})[0]}function b(e){var t=e.variants,n=e.chosenVariantName;return{name:e.name,chosenVariantName:n,variants:t}}function m(e,t){return(e=t?e:function(e){var t=[];return e.forEach(function(e){for(var n=e.weight,r=n?10*n:1,o=0;o<r;o++)t.push(e)}),t}(e))[function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=arguments.length>2?arguments[2]:void 0;return r&&(e=c()(r)()),Math.floor((e||Math.random())*(n-t+1))+t}(0,e.length-1,t)]}function v(e){for(var t={},n=Object.entries(e),r=0;r<n.length;r++){var o=f(n[r],2),i=o[0],a=o[1].chosenVariantName;t[i]=a}return t}var g="react_splitz";o.a.createContext({exps:{},updateExperiments:function(){}});function x(e){return(x="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function w(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function O(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function j(e){return(j=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function E(e,t){return(E=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function S(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}var _=function(e){function t(){var e;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),(e=function(e,t){return!t||"object"!==x(t)&&"function"!=typeof t?S(e):t}(this,j(t).apply(this,arguments))).updateExperiments=e.updateExperiments.bind(S(S(e))),e.state={exps:e.getChosenVariants(),updateExperiments:e.updateExperiments},e}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&E(e,t)}(t,r["Component"]),function(e,t,n){t&&O(e.prototype,t),n&&O(e,n)}(t,[{key:"getChosenVariants",value:function(){var e=this.props,t=e.experiments,n=e.forcedExperiments,r=e.disableAll,o=e.getExperiments,i=this.props,a=i.getCookie,u=i.setCookie;s()&&(a=y,u=d);var c=function(e){var t=e.disableAll,n=e.experiments,r=e.getCookie,o=e.setCookie,i=e.forcedExperiments,a=void 0===i?{}:i;if("function"!=typeof r||"function"!=typeof o)throw new Error("Both `getCookie` & `setCookie` function props must be provided when rendering components on the server.");if(!Array.isArray(n))throw new Error("The `experiments` prop must be an array and provided to `TestContainer` in order to enable experiments.");var u={};if(!t){var c=JSON.parse(r(g)||"{}");n.forEach(function(e){var t=e.name,n=e.variants,r=e.identifier,o=c[t],i=o,f=h(n,i),p=a[t],s=h(n,p);s?(i=p,f=s):!r&&o&&f||(i=(f=m(n,r)).name),u[t]=b({name:t,chosenVariantName:f.name,variants:n})})}var f=v(u);return o(g,JSON.stringify(f)),{chosenExperiments:u}}({experiments:t,getCookie:a,setCookie:u,forcedExperiments:n,disableAll:r}).chosenExperiments;return"function"==typeof o&&o(c),c}},{key:"updateExperiments",value:function(e,t){if(s()){var n=function(e,t){for(var n={},r=Object.entries(t),o=0;o<r.length;o++){var i=f(r[o],2),a=i[0],u=i[1];void 0===e[a]?l('Experiment "'.concat(a,"\" is not a currently running experiment and therefore cannot be updated. Check your input in the 'updateExperiments function to make sure you don't have a typo.")):h(e[a].variants,u)?n[a]=b({name:a,chosenVariantName:u,variants:e[a].variants}):l('Variant "'.concat(u,'" is not defined in experiment "').concat(a,'". Please check updateExperiments function for any typos.'))}return n}(this.state.exps,e),r=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){w(e,t,n[t])})}return e}({},this.state.exps,n);this.setState({exps:r},function(){if("function"==typeof t)return t()});var o=v(r);d(g,JSON.stringify(o))}else l("updateExperiments() can only be called in the browser. This is a no-op. Please check the code where you are calling this function.")}},{key:"render",value:function(){return o.a.createElement(I.Provider,{value:this.state},o.a.Children.only(this.props.children))}}]),t}();_.propTypes={children:a.a.element.isRequired,experiments:a.a.arrayOf(a.a.object),getCookie:a.a.func,setCookie:a.a.func,forcedExperiments:a.a.object,disableAll:a.a.bool,getExperiments:a.a.func};var C=_;function P(e){return(P="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function k(){return(k=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}function T(e,t){if(null==e)return{};var n,r,o=function(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function R(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function M(e,t){return!t||"object"!==P(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function A(e){return(A=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function V(e,t){return(V=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function N(e,t){return t=t||{},function(n){var i=function(i){function a(){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,a),M(this,A(a).apply(this,arguments))}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&V(e,t)}(a,r["Component"]),function(e,t,n){t&&R(e.prototype,t),n&&R(e,n)}(a,[{key:"render",value:function(){var r=this.props,i=r.forwardRef,a=T(r,["forwardRef"]);return o.a.createElement(I.Consumer,null,function(r){var u=r.exps,c=r.updateExperiments,f=function(e,t){var n={};return Object.keys(t).forEach(function(r){var o=t[r],i=e[o];i&&(n[r]={variant:i.chosenVariantName})}),n}(u,e),p={};return t.updateExperiments&&(p.updateExperiments=c),o.a.createElement(n,k({},f,a,{ref:i},p))})}}]),a}();return o.a.forwardRef(function(e,t){return o.a.createElement(i,k({},e,{forwardRef:t}))})}}n.d(t,"ExperimentContext",function(){return I}),n.d(t,"TestContainer",function(){return C}),n.d(t,"withTest",function(){return N});var I=o.a.createContext({exps:{},updateExperiments:function(){}})}])});