Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@devcycle/js-client-sdk

Package Overview
Dependencies
Maintainers
6
Versions
73
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@devcycle/js-client-sdk - npm Package Compare versions

Comparing version 1.13.9 to 1.13.10

4

package.json
{
"name": "@devcycle/js-client-sdk",
"version": "1.13.9",
"version": "1.13.10",
"description": "The Javascript Client SDK for DevCycle",

@@ -20,3 +20,3 @@ "author": "",

"uuid": "^8.3.2",
"@devcycle/types": "1.1.15",
"@devcycle/types": "1.1.16",
"@nestjs/class-validator": "0.13.4",

@@ -23,0 +23,0 @@ "class-transformer": "0.5.1",

"use strict";
var __awaiter = (this && this.__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 = (this && this.__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 (g && (g = 0, op[0] && (_ = 0)), _) 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 };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheStore = void 0;
const types_1 = require("./types");
class CacheStore {
constructor(storage, logger) {
var types_1 = require("./types");
var CacheStore = /** @class */ (function () {
function CacheStore(storage, logger) {
this.store = storage;
this.logger = logger;
}
getConfigKey(user) {
CacheStore.prototype.getConfigKey = function (user) {
return user.isAnonymous
? types_1.StoreKey.AnonymousConfig
: types_1.StoreKey.IdentifiedConfig;
}
getConfigUserIdKey(user) {
return `${this.getConfigKey(user)}.user_id`;
}
getConfigFetchDateKey(user) {
return `${this.getConfigKey(user)}.fetch_date`;
}
async loadConfigUserId(user) {
const userIdKey = this.getConfigUserIdKey(user);
return this.store.load(userIdKey);
}
async loadConfigFetchDate(user) {
const fetchDateKey = this.getConfigFetchDateKey(user);
const fetchDate = (await this.store.load(fetchDateKey)) || '0';
return parseInt(fetchDate, 10);
}
saveConfig(data, user, dateFetched) {
};
CacheStore.prototype.getConfigUserIdKey = function (user) {
return "".concat(this.getConfigKey(user), ".user_id");
};
CacheStore.prototype.getConfigFetchDateKey = function (user) {
return "".concat(this.getConfigKey(user), ".fetch_date");
};
CacheStore.prototype.loadConfigUserId = function (user) {
return __awaiter(this, void 0, void 0, function () {
var userIdKey;
return __generator(this, function (_a) {
userIdKey = this.getConfigUserIdKey(user);
return [2 /*return*/, this.store.load(userIdKey)];
});
});
};
CacheStore.prototype.loadConfigFetchDate = function (user) {
return __awaiter(this, void 0, void 0, function () {
var fetchDateKey, fetchDate;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
fetchDateKey = this.getConfigFetchDateKey(user);
return [4 /*yield*/, this.store.load(fetchDateKey)];
case 1:
fetchDate = (_a.sent()) || '0';
return [2 /*return*/, parseInt(fetchDate, 10)];
}
});
});
};
CacheStore.prototype.saveConfig = function (data, user, dateFetched) {
var _a;
const configKey = this.getConfigKey(user);
const fetchDateKey = this.getConfigFetchDateKey(user);
const userIdKey = this.getConfigUserIdKey(user);
var configKey = this.getConfigKey(user);
var fetchDateKey = this.getConfigFetchDateKey(user);
var userIdKey = this.getConfigUserIdKey(user);
this.store.save(configKey, data);

@@ -39,4 +90,4 @@ this.store.save(fetchDateKey, dateFetched);

(_a = this.logger) === null || _a === void 0 ? void 0 : _a.info('Successfully saved config to local storage');
}
isBucketedUserConfig(object) {
};
CacheStore.prototype.isBucketedUserConfig = function (object) {
if (!object || typeof object !== 'object')

@@ -50,29 +101,45 @@ return false;

'variables' in object);
}
async loadConfig(user, configCacheTTL = 604800000) {
};
CacheStore.prototype.loadConfig = function (user, configCacheTTL) {
var _a, _b, _c, _d;
const userId = await this.loadConfigUserId(user);
if (user.user_id !== userId) {
(_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`Skipping cached config: no config for user ID ${user.user_id}`);
return null;
}
const cachedFetchDate = await this.loadConfigFetchDate(user);
const isConfigCacheTTLExpired = Date.now() - cachedFetchDate > configCacheTTL;
if (isConfigCacheTTLExpired) {
(_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug('Skipping cached config: last fetched date is too old');
return null;
}
const configKey = await this.getConfigKey(user);
const config = await this.store.load(configKey);
if (config === null || config === undefined) {
(_c = this.logger) === null || _c === void 0 ? void 0 : _c.debug('Skipping cached config: no config found');
return null;
}
if (!this.isBucketedUserConfig(config)) {
(_d = this.logger) === null || _d === void 0 ? void 0 : _d.debug(`Skipping cached config: invalid config found: ${JSON.stringify(config)}`);
return null;
}
return config;
}
saveUser(user) {
if (configCacheTTL === void 0) { configCacheTTL = 604800000; }
return __awaiter(this, void 0, void 0, function () {
var userId, cachedFetchDate, isConfigCacheTTLExpired, configKey, config;
return __generator(this, function (_e) {
switch (_e.label) {
case 0: return [4 /*yield*/, this.loadConfigUserId(user)];
case 1:
userId = _e.sent();
if (user.user_id !== userId) {
(_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug("Skipping cached config: no config for user ID ".concat(user.user_id));
return [2 /*return*/, null];
}
return [4 /*yield*/, this.loadConfigFetchDate(user)];
case 2:
cachedFetchDate = _e.sent();
isConfigCacheTTLExpired = Date.now() - cachedFetchDate > configCacheTTL;
if (isConfigCacheTTLExpired) {
(_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug('Skipping cached config: last fetched date is too old');
return [2 /*return*/, null];
}
return [4 /*yield*/, this.getConfigKey(user)];
case 3:
configKey = _e.sent();
return [4 /*yield*/, this.store.load(configKey)];
case 4:
config = _e.sent();
if (config === null || config === undefined) {
(_c = this.logger) === null || _c === void 0 ? void 0 : _c.debug('Skipping cached config: no config found');
return [2 /*return*/, null];
}
if (!this.isBucketedUserConfig(config)) {
(_d = this.logger) === null || _d === void 0 ? void 0 : _d.debug("Skipping cached config: invalid config found: ".concat(JSON.stringify(config)));
return [2 /*return*/, null];
}
return [2 /*return*/, config];
}
});
});
};
CacheStore.prototype.saveUser = function (user) {
var _a;

@@ -84,20 +151,32 @@ if (!user) {

(_a = this.logger) === null || _a === void 0 ? void 0 : _a.info('Successfully saved user to local storage');
}
async loadUser() {
return this.store.load(types_1.StoreKey.User);
}
saveAnonUserId(userId) {
};
CacheStore.prototype.loadUser = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, this.store.load(types_1.StoreKey.User)];
});
});
};
CacheStore.prototype.saveAnonUserId = function (userId) {
var _a;
this.store.save(types_1.StoreKey.AnonUserId, userId);
(_a = this.logger) === null || _a === void 0 ? void 0 : _a.info('Successfully saved anonymous user id to local storage');
}
async loadAnonUserId() {
return await this.store.load(types_1.StoreKey.AnonUserId);
}
removeAnonUserId() {
};
CacheStore.prototype.loadAnonUserId = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.store.load(types_1.StoreKey.AnonUserId)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
CacheStore.prototype.removeAnonUserId = function () {
this.store.remove(types_1.StoreKey.AnonUserId);
}
}
};
return CacheStore;
}());
exports.CacheStore = CacheStore;
exports.default = CacheStore;
//# sourceMappingURL=CacheStore.js.map
"use strict";
var __assign = (this && this.__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 __awaiter = (this && this.__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 = (this && this.__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 (g && (g = 0, op[0] && (_ = 0)), _) 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 = (this && this.__importDefault) || function (mod) {

@@ -7,23 +54,22 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.DevCycleClient = exports.isDeferredOptions = void 0;
const Variable_1 = require("./Variable");
const Request_1 = require("./Request");
const CacheStore_1 = __importDefault(require("./CacheStore"));
const DefaultStorage_1 = __importDefault(require("./DefaultStorage"));
const User_1 = require("./User");
const EventQueue_1 = require("./EventQueue");
const utils_1 = require("./utils");
const EventEmitter_1 = require("./EventEmitter");
const types_1 = require("@devcycle/types");
const ConfigRequestConsolidator_1 = require("./ConfigRequestConsolidator");
const logger_1 = require("./logger");
const StreamingConnection_1 = require("./StreamingConnection");
const isDeferredOptions = (arg) => {
var Variable_1 = require("./Variable");
var Request_1 = require("./Request");
var CacheStore_1 = __importDefault(require("./CacheStore"));
var DefaultStorage_1 = __importDefault(require("./DefaultStorage"));
var User_1 = require("./User");
var EventQueue_1 = require("./EventQueue");
var utils_1 = require("./utils");
var EventEmitter_1 = require("./EventEmitter");
var types_1 = require("@devcycle/types");
var ConfigRequestConsolidator_1 = require("./ConfigRequestConsolidator");
var logger_1 = require("./logger");
var StreamingConnection_1 = require("./StreamingConnection");
var isDeferredOptions = function (arg) {
return !!arg && 'deferInitialization' in arg;
};
exports.isDeferredOptions = isDeferredOptions;
class DevCycleClient {
get isInitialized() {
return this._isInitialized;
}
constructor(sdkKey, userOrOptions, optionsArg = {}) {
var DevCycleClient = /** @class */ (function () {
function DevCycleClient(sdkKey, userOrOptions, optionsArg) {
if (optionsArg === void 0) { optionsArg = {}; }
var _this = this;
this._isInitialized = false;

@@ -40,44 +86,66 @@ this.userSaved = false;

*/
this.clientInitialization = async (initialUser) => {
this.clientInitialization = function (initialUser) { return __awaiter(_this, void 0, void 0, function () {
var storedAnonymousId, err_1;
var _this = this;
var _a, _b;
if (this.initializeTriggered || this._closing) {
return this;
}
this.initializeTriggered = true;
const storedAnonymousId = await this.store.loadAnonUserId();
this.user = new User_1.DVCPopulatedUser(initialUser, this.options, undefined, storedAnonymousId);
await this.getConfigCache(this.user);
// set up requestConsolidator and hook up callback methods
this.requestConsolidator = new ConfigRequestConsolidator_1.ConfigRequestConsolidator((user, extraParams) => (0, Request_1.getConfigJson)(this.sdkKey, user, this.logger, this.options, extraParams), (config, user) => this.handleConfigReceived(config, user, Date.now()), this.user);
try {
await this.requestConsolidator.queue(this.user);
}
catch (err) {
this.eventEmitter.emitInitialized(false);
this.eventEmitter.emitError(err);
return this;
}
finally {
this.resolveOnInitialized(this);
this.logger.info('Client initialized');
}
this.eventEmitter.emitInitialized(true);
if (initialUser.isAnonymous) {
this.store.saveAnonUserId(this.user.user_id);
}
else {
this.store.removeAnonUserId();
}
if ((_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.sse) === null || _b === void 0 ? void 0 : _b.url) {
if (!this.options.disableRealtimeUpdates) {
this.streamingConnection = new StreamingConnection_1.StreamingConnection(this.config.sse.url, this.onSSEMessage.bind(this), this.logger);
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
if (this.initializeTriggered || this._closing) {
return [2 /*return*/, this];
}
this.initializeTriggered = true;
return [4 /*yield*/, this.store.loadAnonUserId()];
case 1:
storedAnonymousId = _c.sent();
this.user = new User_1.DVCPopulatedUser(initialUser, this.options, undefined, storedAnonymousId);
return [4 /*yield*/, this.getConfigCache(this.user)
// set up requestConsolidator and hook up callback methods
];
case 2:
_c.sent();
// set up requestConsolidator and hook up callback methods
this.requestConsolidator = new ConfigRequestConsolidator_1.ConfigRequestConsolidator(function (user, extraParams) {
return (0, Request_1.getConfigJson)(_this.sdkKey, user, _this.logger, _this.options, extraParams);
}, function (config, user) {
return _this.handleConfigReceived(config, user, Date.now());
}, this.user);
_c.label = 3;
case 3:
_c.trys.push([3, 5, 6, 7]);
return [4 /*yield*/, this.requestConsolidator.queue(this.user)];
case 4:
_c.sent();
return [3 /*break*/, 7];
case 5:
err_1 = _c.sent();
this.eventEmitter.emitInitialized(false);
this.eventEmitter.emitError(err_1);
return [2 /*return*/, this];
case 6:
this.resolveOnInitialized(this);
this.logger.info('Client initialized');
return [7 /*endfinally*/];
case 7:
this.eventEmitter.emitInitialized(true);
if (initialUser.isAnonymous) {
this.store.saveAnonUserId(this.user.user_id);
}
else {
this.store.removeAnonUserId();
}
if ((_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.sse) === null || _b === void 0 ? void 0 : _b.url) {
if (!this.options.disableRealtimeUpdates) {
this.streamingConnection = new StreamingConnection_1.StreamingConnection(this.config.sse.url, this.onSSEMessage.bind(this), this.logger);
}
else {
this.logger.info('Disabling Realtime Updates based on Initialization parameter');
}
}
return [2 /*return*/, this];
}
else {
this.logger.info('Disabling Realtime Updates based on Initialization parameter');
}
}
return this;
};
let user;
let options = optionsArg;
});
}); };
var user;
var options = optionsArg;
if ((0, exports.isDeferredOptions)(userOrOptions)) {

@@ -98,5 +166,5 @@ options = userOrOptions;

this.registerVisibilityChangeHandler();
this.onInitialized = new Promise((resolve, reject) => {
this.resolveOnInitialized = (value) => {
this._isInitialized = true;
this.onInitialized = new Promise(function (resolve, reject) {
_this.resolveOnInitialized = function (value) {
_this._isInitialized = true;
resolve(value);

@@ -112,11 +180,11 @@ };

if (!(options === null || options === void 0 ? void 0 : options.reactNative) && typeof window !== 'undefined') {
this.windowMessageHandler = (event) => {
const message = event.data;
this.windowMessageHandler = function (event) {
var message = event.data;
if ((message === null || message === void 0 ? void 0 : message.type) === 'DVC.optIn.saved') {
this.refetchConfig(false);
_this.refetchConfig(false);
}
};
window.addEventListener('message', this.windowMessageHandler);
this.windowPageHideHandler = () => {
this.flushEvents();
this.windowPageHideHandler = function () {
_this.flushEvents();
};

@@ -126,11 +194,19 @@ window.addEventListener('pagehide', this.windowPageHideHandler);

}
onClientInitialized(onInitialized) {
Object.defineProperty(DevCycleClient.prototype, "isInitialized", {
get: function () {
return this._isInitialized;
},
enumerable: false,
configurable: true
});
DevCycleClient.prototype.onClientInitialized = function (onInitialized) {
var _this = this;
if (onInitialized && typeof onInitialized === 'function') {
this.onInitialized
.then(() => onInitialized(null, this))
.catch((err) => onInitialized(err));
.then(function () { return onInitialized(null, _this); })
.catch(function (err) { return onInitialized(err); });
return;
}
return this.onInitialized;
}
};
/**

@@ -145,4 +221,5 @@ * Get variable object associated with Features. Use the variable's key to fetch the DVCVariable object.

*/
variable(key, defaultValue) {
var _a, _b;
DevCycleClient.prototype.variable = function (key, defaultValue) {
var _a;
var _b, _c;
if (defaultValue === undefined || defaultValue === null) {

@@ -152,7 +229,7 @@ throw new Error('Default value is a required param');

// this will throw if type is invalid
const type = (0, types_1.getVariableTypeFromValue)(defaultValue, key, this.logger, true);
const defaultValueKey = typeof defaultValue === 'string'
var type = (0, types_1.getVariableTypeFromValue)(defaultValue, key, this.logger, true);
var defaultValueKey = typeof defaultValue === 'string'
? defaultValue
: JSON.stringify(defaultValue);
let variable;
var variable;
if (this.variableDefaultMap[key] &&

@@ -163,6 +240,6 @@ this.variableDefaultMap[key][defaultValueKey]) {

else {
const configVariable = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.variables) === null || _b === void 0 ? void 0 : _b[key];
const data = {
key,
defaultValue,
var configVariable = (_c = (_b = this.config) === null || _b === void 0 ? void 0 : _b.variables) === null || _c === void 0 ? void 0 : _c[key];
var data = {
key: key,
defaultValue: defaultValue,
};

@@ -175,10 +252,7 @@ if (configVariable) {

else {
this.logger.warn(`Type mismatch for variable ${key}. Expected ${type}, got ${configVariable.type}`);
this.logger.warn("Type mismatch for variable ".concat(key, ". Expected ").concat(type, ", got ").concat(configVariable.type));
}
}
variable = new Variable_1.DVCVariable(data);
this.variableDefaultMap[key] = {
[defaultValueKey]: variable,
...this.variableDefaultMap[key],
};
this.variableDefaultMap[key] = __assign((_a = {}, _a[defaultValueKey] = variable, _a), this.variableDefaultMap[key]);
}

@@ -188,4 +262,4 @@ this.trackVariableEvaluated(variable);

return variable;
}
trackVariableEvaluated(variable) {
};
DevCycleClient.prototype.trackVariableEvaluated = function (variable) {
var _a, _b;

@@ -195,3 +269,3 @@ if (this.options.disableAutomaticEventLogging)

try {
const variableFromConfig = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.variables) === null || _b === void 0 ? void 0 : _b[variable.key];
var variableFromConfig = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.variables) === null || _b === void 0 ? void 0 : _b[variable.key];
this.eventQueue.queueAggregateEvent({

@@ -211,5 +285,5 @@ type: variable.isDefaulted

this.eventEmitter.emitError(e);
this.logger.warn(`Error with queueing aggregate events ${e}`);
this.logger.warn("Error with queueing aggregate events ".concat(e));
}
}
};
/**

@@ -222,64 +296,82 @@ * Get a variable's value associated with a Feature. Use the variable's key to fetch the variable's value.

*/
variableValue(key, defaultValue) {
DevCycleClient.prototype.variableValue = function (key, defaultValue) {
return this.variable(key, defaultValue).value;
}
identifyUser(user, callback) {
const promise = this._identifyUser(user);
};
DevCycleClient.prototype.identifyUser = function (user, callback) {
var promise = this._identifyUser(user);
if (callback && typeof callback == 'function') {
promise
.then((variables) => callback(null, variables))
.catch((err) => callback(err, null));
.then(function (variables) { return callback(null, variables); })
.catch(function (err) { return callback(err, null); });
return;
}
return promise;
}
async _identifyUser(user) {
};
DevCycleClient.prototype._identifyUser = function (user) {
var _a;
let updatedUser;
if (this.options.deferInitialization && !this.initializeTriggered) {
await this.clientInitialization(user);
return ((_a = this.config) === null || _a === void 0 ? void 0 : _a.variables) || {};
}
this.eventQueue.flushEvents();
try {
await this.onInitialized;
const storedAnonymousId = await this.store.loadAnonUserId();
if (this.user && user.user_id === this.user.user_id) {
updatedUser = this.user.updateUser(user, this.options);
}
else {
updatedUser = new User_1.DVCPopulatedUser(user, this.options, undefined, storedAnonymousId);
}
const config = await this.requestConsolidator.queue(updatedUser);
if (user.isAnonymous || !user.user_id) {
this.store.saveAnonUserId(updatedUser.user_id);
}
return config.variables || {};
}
catch (err) {
this.eventEmitter.emitError(err);
throw err;
}
}
resetUser(callback) {
let oldAnonymousId;
const anonUser = new User_1.DVCPopulatedUser({ isAnonymous: true }, this.options);
const promise = new Promise((resolve, reject) => {
this.eventQueue.flushEvents();
this.onInitialized
.then(() => this.store.loadAnonUserId())
.then((cachedAnonId) => {
this.store.removeAnonUserId();
return __awaiter(this, void 0, void 0, function () {
var updatedUser, storedAnonymousId, config, err_2;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!(this.options.deferInitialization && !this.initializeTriggered)) return [3 /*break*/, 2];
return [4 /*yield*/, this.clientInitialization(user)];
case 1:
_b.sent();
return [2 /*return*/, ((_a = this.config) === null || _a === void 0 ? void 0 : _a.variables) || {}];
case 2:
this.eventQueue.flushEvents();
_b.label = 3;
case 3:
_b.trys.push([3, 7, , 8]);
return [4 /*yield*/, this.onInitialized];
case 4:
_b.sent();
return [4 /*yield*/, this.store.loadAnonUserId()];
case 5:
storedAnonymousId = _b.sent();
if (this.user && user.user_id === this.user.user_id) {
updatedUser = this.user.updateUser(user, this.options);
}
else {
updatedUser = new User_1.DVCPopulatedUser(user, this.options, undefined, storedAnonymousId);
}
return [4 /*yield*/, this.requestConsolidator.queue(updatedUser)];
case 6:
config = _b.sent();
if (user.isAnonymous || !user.user_id) {
this.store.saveAnonUserId(updatedUser.user_id);
}
return [2 /*return*/, config.variables || {}];
case 7:
err_2 = _b.sent();
this.eventEmitter.emitError(err_2);
throw err_2;
case 8: return [2 /*return*/];
}
});
});
};
DevCycleClient.prototype.resetUser = function (callback) {
var _this = this;
var oldAnonymousId;
var anonUser = new User_1.DVCPopulatedUser({ isAnonymous: true }, this.options);
var promise = new Promise(function (resolve, reject) {
_this.eventQueue.flushEvents();
_this.onInitialized
.then(function () { return _this.store.loadAnonUserId(); })
.then(function (cachedAnonId) {
_this.store.removeAnonUserId();
oldAnonymousId = cachedAnonId;
return;
})
.then(() => this.requestConsolidator.queue(anonUser))
.then((config) => {
this.store.saveAnonUserId(anonUser.user_id);
.then(function () { return _this.requestConsolidator.queue(anonUser); })
.then(function (config) {
_this.store.saveAnonUserId(anonUser.user_id);
resolve(config.variables || {});
})
.catch((e) => {
this.eventEmitter.emitError(e);
.catch(function (e) {
_this.eventEmitter.emitError(e);
if (oldAnonymousId) {
this.store.saveAnonUserId(oldAnonymousId);
_this.store.saveAnonUserId(oldAnonymousId);
}

@@ -291,8 +383,8 @@ reject(e);

promise
.then((variables) => callback(null, variables))
.catch((err) => callback(err, null));
.then(function (variables) { return callback(null, variables); })
.catch(function (err) { return callback(err, null); });
return;
}
return promise;
}
};
/**

@@ -303,16 +395,16 @@ * Retrieve data on all Features, Object mapped by feature `key`.

*/
allFeatures() {
DevCycleClient.prototype.allFeatures = function () {
var _a;
return ((_a = this.config) === null || _a === void 0 ? void 0 : _a.features) || {};
}
};
/**
* Retrieve data on all Variables, Object mapped by variable `key`.
*/
allVariables() {
DevCycleClient.prototype.allVariables = function () {
var _a;
return ((_a = this.config) === null || _a === void 0 ? void 0 : _a.variables) || {};
}
subscribe(key, handler) {
};
DevCycleClient.prototype.subscribe = function (key, handler) {
this.eventEmitter.subscribe(key, handler);
}
};
/**

@@ -324,5 +416,5 @@ * Unsubscribe to remove existing event emitter subscription.

*/
unsubscribe(key, handler) {
DevCycleClient.prototype.unsubscribe = function (key, handler) {
this.eventEmitter.unsubscribe(key, handler);
}
};
/**

@@ -333,3 +425,4 @@ * Track Event to DevCycle

*/
track(event) {
DevCycleClient.prototype.track = function (event) {
var _this = this;
if (this._closing) {

@@ -342,6 +435,6 @@ this.logger.error('Client is closing, cannot track new events.');

(0, utils_1.checkParamDefined)('type', event.type);
this.onInitialized.then(() => {
this.eventQueue.queueEvent(event);
this.onInitialized.then(function () {
_this.eventQueue.queueEvent(event);
});
}
};
/**

@@ -352,5 +445,5 @@ * Flush all queued events to DevCycle

*/
flushEvents(callback) {
return this.eventQueue.flushEvents().then(() => callback === null || callback === void 0 ? void 0 : callback());
}
DevCycleClient.prototype.flushEvents = function (callback) {
return this.eventQueue.flushEvents().then(function () { return callback === null || callback === void 0 ? void 0 : callback(); });
};
/**

@@ -361,31 +454,57 @@ * Close all open connections to DevCycle, flush any pending events and

*/
async close() {
DevCycleClient.prototype.close = function () {
var _a;
this.logger.debug('Closing client');
this._closing = true;
if (document && this.pageVisibilityHandler) {
document.removeEventListener('visibilitychange', this.pageVisibilityHandler);
}
if (this.windowMessageHandler) {
window.removeEventListener('message', this.windowMessageHandler);
}
if (this.windowPageHideHandler) {
window.removeEventListener('pagehide', this.windowPageHideHandler);
}
(_a = this.streamingConnection) === null || _a === void 0 ? void 0 : _a.close();
await this.eventQueue.close();
}
/**
* Reflects whether `close()` has been called on the client instance.
*/
get closing() {
return this._closing;
}
async refetchConfig(sse, lastModified, etag) {
await this.onInitialized;
await this.requestConsolidator.queue(null, { sse, lastModified, etag });
}
handleConfigReceived(config, user, dateFetched) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
this.logger.debug('Closing client');
this._closing = true;
if (document && this.pageVisibilityHandler) {
document.removeEventListener('visibilitychange', this.pageVisibilityHandler);
}
if (this.windowMessageHandler) {
window.removeEventListener('message', this.windowMessageHandler);
}
if (this.windowPageHideHandler) {
window.removeEventListener('pagehide', this.windowPageHideHandler);
}
(_a = this.streamingConnection) === null || _a === void 0 ? void 0 : _a.close();
return [4 /*yield*/, this.eventQueue.close()];
case 1:
_b.sent();
return [2 /*return*/];
}
});
});
};
Object.defineProperty(DevCycleClient.prototype, "closing", {
/**
* Reflects whether `close()` has been called on the client instance.
*/
get: function () {
return this._closing;
},
enumerable: false,
configurable: true
});
DevCycleClient.prototype.refetchConfig = function (sse, lastModified, etag) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.onInitialized];
case 1:
_a.sent();
return [4 /*yield*/, this.requestConsolidator.queue(null, { sse: sse, lastModified: lastModified, etag: etag })];
case 2:
_a.sent();
return [2 /*return*/];
}
});
});
};
DevCycleClient.prototype.handleConfigReceived = function (config, user, dateFetched) {
var _this = this;
var _a;
const oldConfig = this.config;
var oldConfig = this.config;
this.config = config;

@@ -399,8 +518,10 @@ this.store.saveConfig(config, user, dateFetched);

checkIfEdgeEnabled(config, this.logger, (_a = this.options) === null || _a === void 0 ? void 0 : _a.enableEdgeDB, true)) {
(0, Request_1.saveEntity)(this.user, this.sdkKey, this.logger, this.options).then((res) => this.logger.info(`Saved response entity! ${res}`));
(0, Request_1.saveEntity)(this.user, this.sdkKey, this.logger, this.options).then(function (res) {
return _this.logger.info("Saved response entity! ".concat(res));
});
}
this.userSaved = true;
}
const oldFeatures = (oldConfig === null || oldConfig === void 0 ? void 0 : oldConfig.features) || {};
const oldVariables = (oldConfig === null || oldConfig === void 0 ? void 0 : oldConfig.variables) || {};
var oldFeatures = (oldConfig === null || oldConfig === void 0 ? void 0 : oldConfig.features) || {};
var oldVariables = (oldConfig === null || oldConfig === void 0 ? void 0 : oldConfig.variables) || {};
this.eventEmitter.emitFeatureUpdates(oldFeatures, config.features);

@@ -411,8 +532,9 @@ this.eventEmitter.emitVariableUpdates(oldVariables, config.variables, this.variableDefaultMap);

}
}
onSSEMessage(message) {
};
DevCycleClient.prototype.onSSEMessage = function (message) {
var _this = this;
var _a, _b;
try {
const parsedMessage = JSON.parse(message);
const messageData = JSON.parse(parsedMessage.data);
var parsedMessage = JSON.parse(message);
var messageData = JSON.parse(parsedMessage.data);
if (!messageData) {

@@ -424,4 +546,4 @@ return;

messageData.etag !== ((_b = this.config) === null || _b === void 0 ? void 0 : _b.etag)) {
this.refetchConfig(true, messageData.lastModified, messageData.etag).catch((e) => {
this.logger.warn(`Failed to refetch config ${e}`);
this.refetchConfig(true, messageData.lastModified, messageData.etag).catch(function (e) {
_this.logger.warn("Failed to refetch config ".concat(e));
});

@@ -432,6 +554,7 @@ }

catch (e) {
this.logger.warn(`Streaming Connection: Unparseable message ${e}`);
this.logger.warn("Streaming Connection: Unparseable message ".concat(e));
}
}
registerVisibilityChangeHandler() {
};
DevCycleClient.prototype.registerVisibilityChangeHandler = function () {
var _this = this;
var _a, _b, _c;

@@ -441,24 +564,24 @@ if (typeof document === 'undefined') {

}
const inactivityDelay = ((_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.sse) === null || _b === void 0 ? void 0 : _b.inactivityDelay) || 120000;
this.pageVisibilityHandler = () => {
var inactivityDelay = ((_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.sse) === null || _b === void 0 ? void 0 : _b.inactivityDelay) || 120000;
this.pageVisibilityHandler = function () {
var _a, _b, _c;
if (!((_a = this.config) === null || _a === void 0 ? void 0 : _a.sse)) {
if (!((_a = _this.config) === null || _a === void 0 ? void 0 : _a.sse)) {
return;
}
else if (document.visibilityState === 'visible') {
if (!((_b = this.streamingConnection) === null || _b === void 0 ? void 0 : _b.isConnected())) {
this.logger.debug('Page became visible, refetching config');
this.refetchConfig(false).catch((e) => {
this.logger.warn(`Failed to refetch config ${e}`);
if (!((_b = _this.streamingConnection) === null || _b === void 0 ? void 0 : _b.isConnected())) {
_this.logger.debug('Page became visible, refetching config');
_this.refetchConfig(false).catch(function (e) {
_this.logger.warn("Failed to refetch config ".concat(e));
});
(_c = this.streamingConnection) === null || _c === void 0 ? void 0 : _c.reopen();
(_c = _this.streamingConnection) === null || _c === void 0 ? void 0 : _c.reopen();
}
window === null || window === void 0 ? void 0 : window.clearTimeout(this.inactivityHandlerId);
window === null || window === void 0 ? void 0 : window.clearTimeout(_this.inactivityHandlerId);
}
else {
window === null || window === void 0 ? void 0 : window.clearTimeout(this.inactivityHandlerId);
this.inactivityHandlerId = window === null || window === void 0 ? void 0 : window.setTimeout(() => {
window === null || window === void 0 ? void 0 : window.clearTimeout(_this.inactivityHandlerId);
_this.inactivityHandlerId = window === null || window === void 0 ? void 0 : window.setTimeout(function () {
var _a;
this.logger.debug('Page is not visible, closing streaming connection');
(_a = this.streamingConnection) === null || _a === void 0 ? void 0 : _a.close();
_this.logger.debug('Page is not visible, closing streaming connection');
(_a = _this.streamingConnection) === null || _a === void 0 ? void 0 : _a.close();
}, inactivityDelay);

@@ -468,21 +591,34 @@ }

(_c = document.addEventListener) === null || _c === void 0 ? void 0 : _c.call(document, 'visibilitychange', this.pageVisibilityHandler);
}
async getConfigCache(user) {
if (this.options.disableConfigCache) {
this.logger.info('Skipping config cache');
return;
}
const cachedConfig = await this.store.loadConfig(user, this.options.configCacheTTL);
if (cachedConfig) {
this.config = cachedConfig;
this.isConfigCached = true;
this.eventEmitter.emitFeatureUpdates({}, cachedConfig.features);
this.eventEmitter.emitVariableUpdates({}, cachedConfig.variables, this.variableDefaultMap);
this.logger.debug('Initialized with a cached config');
}
}
}
};
DevCycleClient.prototype.getConfigCache = function (user) {
return __awaiter(this, void 0, void 0, function () {
var cachedConfig;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this.options.disableConfigCache) {
this.logger.info('Skipping config cache');
return [2 /*return*/];
}
return [4 /*yield*/, this.store.loadConfig(user, this.options.configCacheTTL)];
case 1:
cachedConfig = _a.sent();
if (cachedConfig) {
this.config = cachedConfig;
this.isConfigCached = true;
this.eventEmitter.emitFeatureUpdates({}, cachedConfig.features);
this.eventEmitter.emitVariableUpdates({}, cachedConfig.variables, this.variableDefaultMap);
this.logger.debug('Initialized with a cached config');
}
return [2 /*return*/];
}
});
});
};
return DevCycleClient;
}());
exports.DevCycleClient = DevCycleClient;
const checkIfEdgeEnabled = (config, logger, enableEdgeDB, logWarning = false) => {
var checkIfEdgeEnabled = function (config, logger, enableEdgeDB, logWarning) {
var _a, _b;
if (logWarning === void 0) { logWarning = false; }
if ((_b = (_a = config.project.settings) === null || _a === void 0 ? void 0 : _a.edgeDB) === null || _b === void 0 ? void 0 : _b.enabled) {

@@ -489,0 +625,0 @@ return !!enableEdgeDB;

"use strict";
var __awaiter = (this && this.__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 = (this && this.__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 (g && (g = 0, op[0] && (_ = 0)), _) 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 };
}
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -8,4 +44,4 @@ exports.ConfigRequestConsolidator = void 0;

*/
class ConfigRequestConsolidator {
constructor(requestConfigFunction, handleConfigReceivedFunction, nextUser) {
var ConfigRequestConsolidator = /** @class */ (function () {
function ConfigRequestConsolidator(requestConfigFunction, handleConfigReceivedFunction, nextUser) {
this.requestConfigFunction = requestConfigFunction;

@@ -17,53 +53,89 @@ this.handleConfigReceivedFunction = handleConfigReceivedFunction;

}
async queue(user, requestParams) {
if (user) {
this.nextUser = user;
}
if (requestParams) {
this.requestParams = requestParams;
}
const resolver = new Promise((resolve, reject) => {
this.resolvers.push({
resolve,
reject,
ConfigRequestConsolidator.prototype.queue = function (user, requestParams) {
return __awaiter(this, void 0, void 0, function () {
var resolver;
var _this = this;
return __generator(this, function (_a) {
if (user) {
this.nextUser = user;
}
if (requestParams) {
this.requestParams = requestParams;
}
resolver = new Promise(function (resolve, reject) {
_this.resolvers.push({
resolve: resolve,
reject: reject,
});
});
if (!this.currentPromise) {
this.processQueue();
}
return [2 /*return*/, resolver];
});
});
if (!this.currentPromise) {
this.processQueue();
}
return resolver;
}
async processQueue() {
if (!this.resolvers.length) {
return;
}
const resolvers = this.resolvers.splice(0);
await this.performRequest(this.nextUser)
.then((result) => {
if (this.resolvers.length) {
// if more resolvers have been registered since this request was made,
// don't resolve anything and just make another request while keeping all the previous resolvers
this.resolvers.push(...resolvers);
}
else {
resolvers.forEach(({ resolve }) => resolve(result));
this.handleConfigReceivedFunction(result, this.nextUser);
}
})
.catch((err) => {
resolvers.forEach(({ reject }) => reject(err));
};
ConfigRequestConsolidator.prototype.processQueue = function () {
return __awaiter(this, void 0, void 0, function () {
var resolvers;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.resolvers.length) {
return [2 /*return*/];
}
resolvers = this.resolvers.splice(0);
return [4 /*yield*/, this.performRequest(this.nextUser)
.then(function (result) {
var _a;
if (_this.resolvers.length) {
// if more resolvers have been registered since this request was made,
// don't resolve anything and just make another request while keeping all the previous resolvers
(_a = _this.resolvers).push.apply(_a, resolvers);
}
else {
resolvers.forEach(function (_a) {
var resolve = _a.resolve;
return resolve(result);
});
_this.handleConfigReceivedFunction(result, _this.nextUser);
}
})
.catch(function (err) {
resolvers.forEach(function (_a) {
var reject = _a.reject;
return reject(err);
});
})];
case 1:
_a.sent();
if (this.resolvers.length) {
this.processQueue();
}
return [2 /*return*/];
}
});
});
if (this.resolvers.length) {
this.processQueue();
}
}
async performRequest(user) {
this.currentPromise = this.requestConfigFunction(user, this.requestParams ? this.requestParams : undefined);
this.requestParams = null;
const bucketedConfig = await this.currentPromise;
this.currentPromise = null;
return bucketedConfig;
}
}
};
ConfigRequestConsolidator.prototype.performRequest = function (user) {
return __awaiter(this, void 0, void 0, function () {
var bucketedConfig;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.currentPromise = this.requestConfigFunction(user, this.requestParams ? this.requestParams : undefined);
this.requestParams = null;
return [4 /*yield*/, this.currentPromise];
case 1:
bucketedConfig = _a.sent();
this.currentPromise = null;
return [2 /*return*/, bucketedConfig];
}
});
});
};
return ConfigRequestConsolidator;
}());
exports.ConfigRequestConsolidator = ConfigRequestConsolidator;
//# sourceMappingURL=ConfigRequestConsolidator.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultCacheStore = void 0;
class DefaultCacheStore {
constructor() {
var DefaultCacheStore = /** @class */ (function () {
function DefaultCacheStore() {
this.store =

@@ -11,25 +11,27 @@ typeof window !== 'undefined'

}
save(storeKey, data) {
DefaultCacheStore.prototype.save = function (storeKey, data) {
var _a;
(_a = this.store) === null || _a === void 0 ? void 0 : _a.setItem(storeKey, JSON.stringify(data));
}
load(storeKey) {
return new Promise((resolve) => {
};
DefaultCacheStore.prototype.load = function (storeKey) {
var _this = this;
return new Promise(function (resolve) {
var _a;
const item = (_a = this.store) === null || _a === void 0 ? void 0 : _a.getItem(storeKey);
var item = (_a = _this.store) === null || _a === void 0 ? void 0 : _a.getItem(storeKey);
resolve(item ? JSON.parse(item) : null);
});
}
remove(storeKey) {
};
DefaultCacheStore.prototype.remove = function (storeKey) {
var _a;
(_a = this.store) === null || _a === void 0 ? void 0 : _a.removeItem(storeKey);
}
}
};
return DefaultCacheStore;
}());
exports.DefaultCacheStore = DefaultCacheStore;
const stubbedLocalStorage = {
getItem: () => null,
setItem: () => undefined,
removeItem: () => undefined,
clear: () => undefined,
key: () => null,
var stubbedLocalStorage = {
getItem: function () { return null; },
setItem: function () { return undefined; },
removeItem: function () { return undefined; },
clear: function () { return undefined; },
key: function () { return null; },
length: 0,

@@ -36,0 +38,0 @@ };

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultStorage = void 0;
class DefaultStorage {
constructor() {
var DefaultStorage = /** @class */ (function () {
function DefaultStorage() {
this.store =

@@ -11,22 +11,24 @@ typeof window !== 'undefined'

}
save(storeKey, data) {
DefaultStorage.prototype.save = function (storeKey, data) {
this.store.setItem(storeKey, JSON.stringify(data));
}
load(storeKey) {
return new Promise((resolve) => {
const item = this.store.getItem(storeKey);
};
DefaultStorage.prototype.load = function (storeKey) {
var _this = this;
return new Promise(function (resolve) {
var item = _this.store.getItem(storeKey);
resolve(item ? JSON.parse(item) : undefined);
});
}
remove(storeKey) {
};
DefaultStorage.prototype.remove = function (storeKey) {
this.store.removeItem(storeKey);
}
}
};
return DefaultStorage;
}());
exports.DefaultStorage = DefaultStorage;
const stubbedLocalStorage = {
getItem: () => null,
setItem: () => undefined,
removeItem: () => undefined,
clear: () => undefined,
key: () => null,
var stubbedLocalStorage = {
getItem: function () { return null; },
setItem: function () { return undefined; },
removeItem: function () { return undefined; },
clear: function () { return undefined; },
key: function () { return null; },
length: 0,

@@ -33,0 +35,0 @@ };

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EventEmitter = void 0;
const utils_1 = require("./utils");
const EventNames = {
var utils_1 = require("./utils");
var EventNames = {
INITIALIZED: 'initialized',

@@ -14,3 +14,3 @@ NEW_VARIABLES: 'newVariables',

};
const isInvalidEventKey = (key) => {
var isInvalidEventKey = function (key) {
return (!Object.values(EventNames).includes(key) &&

@@ -22,7 +22,7 @@ !key.startsWith(EventNames.VARIABLE_UPDATED) &&

};
class EventEmitter {
constructor() {
var EventEmitter = /** @class */ (function () {
function EventEmitter() {
this.handlers = {};
}
subscribe(key, handler) {
EventEmitter.prototype.subscribe = function (key, handler) {
(0, utils_1.checkParamType)('key', key, 'string');

@@ -39,4 +39,4 @@ (0, utils_1.checkParamType)('handler', handler, 'function');

}
}
unsubscribe(key, handler) {
};
EventEmitter.prototype.unsubscribe = function (key, handler) {
(0, utils_1.checkParamType)('key', key, 'string');

@@ -47,3 +47,3 @@ if (isInvalidEventKey(key)) {

if (handler) {
const handlerIndex = this.handlers[key].findIndex((h) => h === handler);
var handlerIndex = this.handlers[key].findIndex(function (h) { return h === handler; });
this.handlers[key].splice(handlerIndex, 1);

@@ -54,40 +54,45 @@ }

}
}
emit(key, ...args) {
};
EventEmitter.prototype.emit = function (key) {
var _a;
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
(0, utils_1.checkParamType)('key', key, 'string');
(_a = this.handlers[key]) === null || _a === void 0 ? void 0 : _a.forEach((handler) => {
new Promise((resolve) => {
handler(...args);
(_a = this.handlers[key]) === null || _a === void 0 ? void 0 : _a.forEach(function (handler) {
new Promise(function (resolve) {
handler.apply(void 0, args);
resolve(true);
});
});
}
emitInitialized(success) {
};
EventEmitter.prototype.emitInitialized = function (success) {
this.emit(EventNames.INITIALIZED, success);
}
emitError(error) {
};
EventEmitter.prototype.emitError = function (error) {
this.emit(EventNames.ERROR, error);
}
emitConfigUpdate(newVariableSet) {
};
EventEmitter.prototype.emitConfigUpdate = function (newVariableSet) {
this.emit(EventNames.CONFIG_UPDATED, newVariableSet);
}
emitVariableEvaluated(variable) {
this.emit(`${EventNames.VARIABLE_EVALUATED}:*`, variable.key, variable);
this.emit(`${EventNames.VARIABLE_EVALUATED}:${variable.key}`, variable.key, variable);
}
emitVariableUpdates(oldVariableSet, newVariableSet, variableDefaultMap) {
const keys = new Set(Object.keys(oldVariableSet).concat(Object.keys(newVariableSet)));
let newVariables = false;
keys.forEach((key) => {
const oldVariableValue = oldVariableSet[key] && oldVariableSet[key].value;
const newVariable = newVariableSet[key];
const newVariableValue = newVariable && newVariableSet[key].value;
};
EventEmitter.prototype.emitVariableEvaluated = function (variable) {
this.emit("".concat(EventNames.VARIABLE_EVALUATED, ":*"), variable.key, variable);
this.emit("".concat(EventNames.VARIABLE_EVALUATED, ":").concat(variable.key), variable.key, variable);
};
EventEmitter.prototype.emitVariableUpdates = function (oldVariableSet, newVariableSet, variableDefaultMap) {
var _this = this;
var keys = new Set(Object.keys(oldVariableSet).concat(Object.keys(newVariableSet)));
var newVariables = false;
keys.forEach(function (key) {
var oldVariableValue = oldVariableSet[key] && oldVariableSet[key].value;
var newVariable = newVariableSet[key];
var newVariableValue = newVariable && newVariableSet[key].value;
if (JSON.stringify(oldVariableValue) !==
JSON.stringify(newVariableValue)) {
const variables = variableDefaultMap[key] &&
var variables = variableDefaultMap[key] &&
Object.values(variableDefaultMap[key]);
if (variables) {
newVariables = true;
variables.forEach((variable) => {
variables.forEach(function (variable) {
var _a;

@@ -102,26 +107,28 @@ variable.value =

}
const finalVariable = newVariable || null;
this.emit(`${EventNames.VARIABLE_UPDATED}:*`, key, finalVariable);
this.emit(`${EventNames.VARIABLE_UPDATED}:${key}`, key, finalVariable);
var finalVariable = newVariable || null;
_this.emit("".concat(EventNames.VARIABLE_UPDATED, ":*"), key, finalVariable);
_this.emit("".concat(EventNames.VARIABLE_UPDATED, ":").concat(key), key, finalVariable);
}
});
if (newVariables) {
this.emit(`${EventNames.NEW_VARIABLES}`);
this.emit("".concat(EventNames.NEW_VARIABLES));
}
}
emitFeatureUpdates(oldFeatureSet, newFeatureSet) {
const keys = Object.keys(oldFeatureSet).concat(Object.keys(newFeatureSet));
keys.forEach((key) => {
const oldFeatureVariation = oldFeatureSet[key] && oldFeatureSet[key]._variation;
const newFeature = newFeatureSet[key];
const newFeatureVariation = newFeature && newFeatureSet[key]._variation;
const finalFeature = newFeature || null;
};
EventEmitter.prototype.emitFeatureUpdates = function (oldFeatureSet, newFeatureSet) {
var _this = this;
var keys = Object.keys(oldFeatureSet).concat(Object.keys(newFeatureSet));
keys.forEach(function (key) {
var oldFeatureVariation = oldFeatureSet[key] && oldFeatureSet[key]._variation;
var newFeature = newFeatureSet[key];
var newFeatureVariation = newFeature && newFeatureSet[key]._variation;
var finalFeature = newFeature || null;
if (oldFeatureVariation !== newFeatureVariation) {
this.emit(`${EventNames.FEATURE_UPDATED}:*`, key, finalFeature);
this.emit(`${EventNames.FEATURE_UPDATED}:${key}`, key, finalFeature);
_this.emit("".concat(EventNames.FEATURE_UPDATED, ":*"), key, finalFeature);
_this.emit("".concat(EventNames.FEATURE_UPDATED, ":").concat(key), key, finalFeature);
}
});
}
}
};
return EventEmitter;
}());
exports.EventEmitter = EventEmitter;
//# sourceMappingURL=EventEmitter.js.map
"use strict";
var __awaiter = (this && this.__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 = (this && this.__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 (g && (g = 0, op[0] && (_ = 0)), _) 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 __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -7,5 +52,5 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.EventQueue = exports.EventTypes = void 0;
const Request_1 = require("./Request");
const utils_1 = require("./utils");
const chunk_1 = __importDefault(require("lodash/chunk"));
var Request_1 = require("./Request");
var utils_1 = require("./utils");
var chunk_1 = __importDefault(require("lodash/chunk"));
exports.EventTypes = {

@@ -15,4 +60,4 @@ variableEvaluated: 'variableEvaluated',

};
class EventQueue {
constructor(sdkKey, dvcClient, options) {
var EventQueue = /** @class */ (function () {
function EventQueue(sdkKey, dvcClient, options) {
var _a, _b;

@@ -25,10 +70,10 @@ this.eventQueueBatchSize = 100;

this.options = options;
const eventFlushIntervalMS = typeof options.eventFlushIntervalMS === 'number'
var eventFlushIntervalMS = typeof options.eventFlushIntervalMS === 'number'
? options.eventFlushIntervalMS
: 10 * 1000;
if (eventFlushIntervalMS < 500) {
throw new Error(`eventFlushIntervalMS: ${eventFlushIntervalMS} must be larger than 500ms`);
throw new Error("eventFlushIntervalMS: ".concat(eventFlushIntervalMS, " must be larger than 500ms"));
}
else if (eventFlushIntervalMS > 60 * 1000) {
throw new Error(`eventFlushIntervalMS: ${eventFlushIntervalMS} must be smaller than 1 minute`);
throw new Error("eventFlushIntervalMS: ".concat(eventFlushIntervalMS, " must be smaller than 1 minute"));
}

@@ -39,63 +84,84 @@ this.flushInterval = setInterval(this.flushEvents.bind(this), eventFlushIntervalMS);

if (this.flushEventQueueSize >= this.maxEventQueueSize) {
throw new Error(`flushEventQueueSize: ${this.flushEventQueueSize} must be smaller than ` +
`maxEventQueueSize: ${this.maxEventQueueSize}`);
throw new Error("flushEventQueueSize: ".concat(this.flushEventQueueSize, " must be smaller than ") +
"maxEventQueueSize: ".concat(this.maxEventQueueSize));
}
else if (this.flushEventQueueSize < 10 ||
this.flushEventQueueSize > 1000) {
throw new Error(`flushEventQueueSize: ${this.flushEventQueueSize} must be between 10 and 1000`);
throw new Error("flushEventQueueSize: ".concat(this.flushEventQueueSize, " must be between 10 and 1000"));
}
else if (this.maxEventQueueSize < 100 ||
this.maxEventQueueSize > 5000) {
throw new Error(`maxEventQueueSize: ${this.maxEventQueueSize} must be between 100 and 5000`);
throw new Error("maxEventQueueSize: ".concat(this.maxEventQueueSize, " must be between 100 and 5000"));
}
}
async flushEvents() {
const user = this.client.user;
if (!user) {
this.client.logger.warn('Skipping event flush, user has not been set yet.');
return;
}
const eventsToFlush = [...this.eventQueue];
const aggregateEventsToFlush = this.eventsFromAggregateEventMap();
eventsToFlush.push(...aggregateEventsToFlush);
if (!eventsToFlush.length) {
return;
}
this.client.logger.info(`Flush ${eventsToFlush.length} Events`);
this.eventQueue = [];
this.aggregateEventMap = {};
const eventRequests = (0, chunk_1.default)(eventsToFlush, this.eventQueueBatchSize);
for (const eventRequest of eventRequests) {
try {
const res = await (0, Request_1.publishEvents)(this.sdkKey, this.client.config || null, user, eventRequest, this.client.logger);
if (res.status === 201) {
this.client.logger.info(`DevCycle Flushed ${eventRequest.length} Events.`);
EventQueue.prototype.flushEvents = function () {
return __awaiter(this, void 0, void 0, function () {
var user, eventsToFlush, aggregateEventsToFlush, eventRequests, _i, eventRequests_1, eventRequest, res, ex_1;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
user = this.client.user;
if (!user) {
this.client.logger.warn('Skipping event flush, user has not been set yet.');
return [2 /*return*/];
}
eventsToFlush = __spreadArray([], this.eventQueue, true);
aggregateEventsToFlush = this.eventsFromAggregateEventMap();
eventsToFlush.push.apply(eventsToFlush, aggregateEventsToFlush);
if (!eventsToFlush.length) {
return [2 /*return*/];
}
this.client.logger.info("Flush ".concat(eventsToFlush.length, " Events"));
this.eventQueue = [];
this.aggregateEventMap = {};
eventRequests = (0, chunk_1.default)(eventsToFlush, this.eventQueueBatchSize);
_i = 0, eventRequests_1 = eventRequests;
_b.label = 1;
case 1:
if (!(_i < eventRequests_1.length)) return [3 /*break*/, 6];
eventRequest = eventRequests_1[_i];
_b.label = 2;
case 2:
_b.trys.push([2, 4, , 5]);
return [4 /*yield*/, (0, Request_1.publishEvents)(this.sdkKey, this.client.config || null, user, eventRequest, this.client.logger)];
case 3:
res = _b.sent();
if (res.status === 201) {
this.client.logger.info("DevCycle Flushed ".concat(eventRequest.length, " Events."));
}
else if (res.status >= 500 || res.status === 408) {
this.client.logger.warn('failed to flush events, retrying events. ' +
"Response status: ".concat(res.status, ", message: ").concat(res.statusText));
(_a = this.eventQueue).push.apply(_a, eventRequest);
}
else {
this.client.logger.error('failed to flush events, dropping events. ' +
"Response status: ".concat(res.status, ", message: ").concat(res.statusText));
}
return [3 /*break*/, 5];
case 4:
ex_1 = _b.sent();
this.client.eventEmitter.emitError(ex_1);
this.client.logger.error('failed to flush events due to error, dropping events. ' +
"Error message: ".concat(ex_1 === null || ex_1 === void 0 ? void 0 : ex_1.message));
return [3 /*break*/, 5];
case 5:
_i++;
return [3 /*break*/, 1];
case 6: return [2 /*return*/];
}
else if (res.status >= 500 || res.status === 408) {
this.client.logger.warn('failed to flush events, retrying events. ' +
`Response status: ${res.status}, message: ${res.statusText}`);
this.eventQueue.push(...eventRequest);
}
else {
this.client.logger.error('failed to flush events, dropping events. ' +
`Response status: ${res.status}, message: ${res.statusText}`);
}
}
catch (ex) {
this.client.eventEmitter.emitError(ex);
this.client.logger.error('failed to flush events due to error, dropping events. ' +
`Error message: ${ex === null || ex === void 0 ? void 0 : ex.message}`);
}
}
}
});
});
};
/**
* Queue DVCAPIEvent for producing
*/
queueEvent(event) {
EventQueue.prototype.queueEvent = function (event) {
if (this.checkEventQueueSize()) {
this.client.logger.warn(`DevCycle: Max event queue size (${this.maxEventQueueSize}) reached, dropping event: ${event}`);
this.client.logger.warn("DevCycle: Max event queue size (".concat(this.maxEventQueueSize, ") reached, dropping event: ").concat(event));
return;
}
this.eventQueue.push(event);
}
};
/**

@@ -105,5 +171,6 @@ * Queue DVCEvent that can be aggregated together, where multiple calls are aggregated

*/
queueAggregateEvent(event) {
EventQueue.prototype.queueAggregateEvent = function (event) {
var _a;
if (this.checkEventQueueSize()) {
this.client.logger.warn(`DevCycle: Max event queue size (${this.maxEventQueueSize}) reached, dropping event: ${event}`);
this.client.logger.warn("DevCycle: Max event queue size (".concat(this.maxEventQueueSize, ") reached, dropping event: ").concat(event));
return;

@@ -115,5 +182,5 @@ }

event.value = 1;
const aggEventType = this.aggregateEventMap[event.type];
var aggEventType = this.aggregateEventMap[event.type];
if (!aggEventType) {
this.aggregateEventMap[event.type] = { [event.target]: event };
this.aggregateEventMap[event.type] = (_a = {}, _a[event.target] = event, _a);
}

@@ -126,6 +193,6 @@ else if (aggEventType[event.target]) {

}
}
checkEventQueueSize() {
const aggCount = Object.values(this.aggregateEventMap).reduce((acc, v) => acc + Object.keys(v).length, 0);
const queueSize = this.eventQueue.length + aggCount;
};
EventQueue.prototype.checkEventQueueSize = function () {
var aggCount = Object.values(this.aggregateEventMap).reduce(function (acc, v) { return acc + Object.keys(v).length; }, 0);
var queueSize = this.eventQueue.length + aggCount;
if (queueSize >= this.flushEventQueueSize) {

@@ -135,17 +202,28 @@ this.flushEvents();

return queueSize >= this.maxEventQueueSize;
}
};
/**
* Turn the Aggregate Event Map into an Array of DVCAPIEvent objects for publishing.
*/
eventsFromAggregateEventMap() {
EventQueue.prototype.eventsFromAggregateEventMap = function () {
return Object.values(this.aggregateEventMap)
.map((typeMap) => Object.values(typeMap))
.map(function (typeMap) { return Object.values(typeMap); })
.flat();
}
async close() {
clearInterval(this.flushInterval);
await this.flushEvents();
}
}
};
EventQueue.prototype.close = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
clearInterval(this.flushInterval);
return [4 /*yield*/, this.flushEvents()];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
return EventQueue;
}());
exports.EventQueue = EventQueue;
//# sourceMappingURL=EventQueue.js.map

@@ -18,5 +18,6 @@ "use strict";

exports.initialize = exports.initializeDevCycle = void 0;
const Client_1 = require("./Client");
var Client_1 = require("./Client");
__exportStar(require("./types"), exports);
function initializeDevCycle(sdkKey, userOrOptions, optionsArg = {}) {
function initializeDevCycle(sdkKey, userOrOptions, optionsArg) {
if (optionsArg === void 0) { optionsArg = {}; }
// TODO: implement logger

@@ -26,4 +27,4 @@ if (typeof window === 'undefined') {

}
let options = optionsArg;
let isDeferred = false;
var options = optionsArg;
var isDeferred = false;
if ((0, Client_1.isDeferredOptions)(userOrOptions)) {

@@ -52,3 +53,3 @@ isDeferred = true;

}
let client;
var client;
if ((0, Client_1.isDeferredOptions)(userOrOptions)) {

@@ -62,4 +63,6 @@ client = new Client_1.DevCycleClient(sdkKey, userOrOptions);

.onClientInitialized()
.then(() => client.logger.info('Successfully initialized DevCycle!'))
.catch((err) => client.logger.error(`Error initializing DevCycle: ${err}`));
.then(function () { return client.logger.info('Successfully initialized DevCycle!'); })
.catch(function (err) {
return client.logger.error("Error initializing DevCycle: ".concat(err));
});
return client;

@@ -74,4 +77,4 @@ }

initialize: exports.initialize,
initializeDevCycle,
initializeDevCycle: initializeDevCycle,
};
//# sourceMappingURL=index.js.map

@@ -7,4 +7,4 @@ "use strict";

exports.dvcDefaultLogger = exports.DVCLogLevels = void 0;
const isNumber_1 = __importDefault(require("lodash/isNumber"));
const prefix = '[DevCycle]: ';
var isNumber_1 = __importDefault(require("lodash/isNumber"));
var prefix = '[DevCycle]: ';
var DVCLogLevels;

@@ -18,11 +18,13 @@ (function (DVCLogLevels) {

function dvcDefaultLogger(options) {
const minLevel = (options === null || options === void 0 ? void 0 : options.level) && (0, isNumber_1.default)(DVCLogLevels[options === null || options === void 0 ? void 0 : options.level])
var minLevel = (options === null || options === void 0 ? void 0 : options.level) && (0, isNumber_1.default)(DVCLogLevels[options === null || options === void 0 ? void 0 : options.level])
? DVCLogLevels[options === null || options === void 0 ? void 0 : options.level]
: DVCLogLevels.error;
const logWriter = (options === null || options === void 0 ? void 0 : options.logWriter) || console.log;
const errorWriter = (options === null || options === void 0 ? void 0 : options.logWriter) || console.error;
const writeLog = (message) => logWriter(prefix + message);
const writeError = (message, error) => errorWriter(prefix + message, error);
var logWriter = (options === null || options === void 0 ? void 0 : options.logWriter) || console.log;
var errorWriter = (options === null || options === void 0 ? void 0 : options.logWriter) || console.error;
var writeLog = function (message) { return logWriter(prefix + message); };
var writeError = function (message, error) {
return errorWriter(prefix + message, error);
};
// eslint-disable-next-line @typescript-eslint/no-empty-function
const noOpLog = (message) => { };
var noOpLog = function (message) { };
return {

@@ -29,0 +31,0 @@ error: DVCLogLevels.error >= minLevel ? writeError : noOpLog,

"use strict";
var __assign = (this && this.__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 __awaiter = (this && this.__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 = (this && this.__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 (g && (g = 0, op[0] && (_ = 0)), _) 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 = (this && this.__importDefault) || function (mod) {

@@ -7,8 +54,8 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

exports.saveEntity = exports.publishEvents = exports.getConfigJson = exports.patch = exports.post = exports.get = exports.baseRequestHeaders = exports.SAVE_ENTITY_PATH = exports.EVENTS_PATH = exports.CONFIG_PATH = exports.EVENT_URL = exports.CLIENT_SDK_URL = exports.HOST = void 0;
const utils_1 = require("./utils");
const axios_1 = __importDefault(require("axios"));
const axios_retry_1 = __importDefault(require("axios-retry"));
const axiosClient = axios_1.default.create({
var utils_1 = require("./utils");
var axios_1 = __importDefault(require("axios"));
var axios_retry_1 = __importDefault(require("axios-retry"));
var axiosClient = axios_1.default.create({
timeout: 5 * 1000,
validateStatus: (status) => status < 400 && status >= 200,
validateStatus: function (status) { return status < 400 && status >= 200; },
});

@@ -20,3 +67,3 @@ (0, axios_retry_1.default)(axiosClient, {

shouldResetTimeout: true,
retryCondition: (error) => {
retryCondition: function (error) {
return !error.response || (error.response.status || 0) >= 500;

@@ -31,7 +78,4 @@ },

exports.SAVE_ENTITY_PATH = '/v1/edgedb';
const baseRequestHeaders = (sdkKey) => {
return {
'Content-Type': 'application/json',
...(sdkKey ? { Authorization: sdkKey } : {}),
};
var baseRequestHeaders = function (sdkKey) {
return __assign({ 'Content-Type': 'application/json' }, (sdkKey ? { Authorization: sdkKey } : {}));
};

@@ -42,27 +86,42 @@ exports.baseRequestHeaders = baseRequestHeaders;

*/
const get = async (url) => {
return await axiosClient.request({
method: 'GET',
url: `${url}`,
headers: (0, exports.baseRequestHeaders)(),
var get = function (url) { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, axiosClient.request({
method: 'GET',
url: "".concat(url),
headers: (0, exports.baseRequestHeaders)(),
})];
case 1: return [2 /*return*/, _a.sent()];
}
});
};
}); };
exports.get = get;
const post = async (url, sdkKey, body) => {
return await axiosClient.request({
method: 'POST',
url,
data: body,
headers: (0, exports.baseRequestHeaders)(sdkKey),
var post = function (url, sdkKey, body) { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, axiosClient.request({
method: 'POST',
url: url,
data: body,
headers: (0, exports.baseRequestHeaders)(sdkKey),
})];
case 1: return [2 /*return*/, _a.sent()];
}
});
};
}); };
exports.post = post;
const patch = async (url, sdkKey, body) => {
return await axiosClient.request({
method: 'PATCH',
url,
data: body,
headers: (0, exports.baseRequestHeaders)(sdkKey),
var patch = function (url, sdkKey, body) { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, axiosClient.request({
method: 'PATCH',
url: url,
data: body,
headers: (0, exports.baseRequestHeaders)(sdkKey),
})];
case 1: return [2 /*return*/, _a.sent()];
}
});
};
}); };
exports.patch = patch;

@@ -72,72 +131,98 @@ /**

*/
const getConfigJson = async (sdkKey, user, logger, options, extraParams) => {
var getConfigJson = function (sdkKey, user, logger, options, extraParams) { return __awaiter(void 0, void 0, void 0, function () {
var queryParams, url, res, ex_1, errorString;
var _a, _b, _c;
const queryParams = new URLSearchParams({ sdkKey });
(0, utils_1.serializeUserSearchParams)(user, queryParams);
if (options === null || options === void 0 ? void 0 : options.enableEdgeDB) {
queryParams.append('enableEdgeDB', options.enableEdgeDB.toString());
}
if (extraParams === null || extraParams === void 0 ? void 0 : extraParams.sse) {
queryParams.append('sse', '1');
if (extraParams.lastModified) {
queryParams.append('sseLastModified', extraParams.lastModified.toString());
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
queryParams = new URLSearchParams({ sdkKey: sdkKey });
(0, utils_1.serializeUserSearchParams)(user, queryParams);
if (options === null || options === void 0 ? void 0 : options.enableEdgeDB) {
queryParams.append('enableEdgeDB', options.enableEdgeDB.toString());
}
if (extraParams === null || extraParams === void 0 ? void 0 : extraParams.sse) {
queryParams.append('sse', '1');
if (extraParams.lastModified) {
queryParams.append('sseLastModified', extraParams.lastModified.toString());
}
if (extraParams.etag) {
queryParams.append('sseEtag', extraParams.etag);
}
}
url = "".concat((options === null || options === void 0 ? void 0 : options.apiProxyURL) || exports.CLIENT_SDK_URL).concat(exports.CONFIG_PATH, "?") +
queryParams.toString();
_d.label = 1;
case 1:
_d.trys.push([1, 3, , 4]);
return [4 /*yield*/, (0, exports.get)(url)];
case 2:
res = _d.sent();
return [2 /*return*/, res.data];
case 3:
ex_1 = _d.sent();
errorString = JSON.stringify((_c = (_b = (_a = ex_1 === null || ex_1 === void 0 ? void 0 : ex_1.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.errors);
logger.error("Request to get config failed for url: ".concat(url, ", ") +
"response message: ".concat(ex_1.message) +
(errorString ? ", response data: ".concat(errorString) : ''));
throw new Error("Failed to download DevCycle config." +
(errorString ? " Error details: ".concat(errorString) : ''));
case 4: return [2 /*return*/];
}
if (extraParams.etag) {
queryParams.append('sseEtag', extraParams.etag);
});
}); };
exports.getConfigJson = getConfigJson;
var publishEvents = function (sdkKey, config, user, events, logger, options) { return __awaiter(void 0, void 0, void 0, function () {
var payload, res;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!sdkKey) {
throw new Error('Missing sdkKey to publish events to Events API');
}
payload = (0, utils_1.generateEventPayload)(config, user, events);
logger.info("Submit Events Payload: ".concat(JSON.stringify(payload)));
return [4 /*yield*/, (0, exports.post)("".concat((options === null || options === void 0 ? void 0 : options.apiProxyURL) || exports.EVENT_URL).concat(exports.EVENTS_PATH), sdkKey, payload)];
case 1:
res = _a.sent();
if (res.status >= 400) {
logger.error("Error posting events, status: ".concat(res.status, ", body: ").concat(res.data));
}
else {
logger.info("Posted Events, status: ".concat(res.status, ", body: ").concat(res.data));
}
return [2 /*return*/, res];
}
}
const url = `${(options === null || options === void 0 ? void 0 : options.apiProxyURL) || exports.CLIENT_SDK_URL}${exports.CONFIG_PATH}?` +
queryParams.toString();
try {
const res = await (0, exports.get)(url);
return res.data;
}
catch (ex) {
const errorString = JSON.stringify((_c = (_b = (_a = ex === null || ex === void 0 ? void 0 : ex.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.errors);
logger.error(`Request to get config failed for url: ${url}, ` +
`response message: ${ex.message}` +
(errorString ? `, response data: ${errorString}` : ''));
throw new Error(`Failed to download DevCycle config.` +
(errorString ? ` Error details: ${errorString}` : ''));
}
};
exports.getConfigJson = getConfigJson;
const publishEvents = async (sdkKey, config, user, events, logger, options) => {
if (!sdkKey) {
throw new Error('Missing sdkKey to publish events to Events API');
}
const payload = (0, utils_1.generateEventPayload)(config, user, events);
logger.info(`Submit Events Payload: ${JSON.stringify(payload)}`);
const res = await (0, exports.post)(`${(options === null || options === void 0 ? void 0 : options.apiProxyURL) || exports.EVENT_URL}${exports.EVENTS_PATH}`, sdkKey, payload);
if (res.status >= 400) {
logger.error(`Error posting events, status: ${res.status}, body: ${res.data}`);
}
else {
logger.info(`Posted Events, status: ${res.status}, body: ${res.data}`);
}
return res;
};
});
}); };
exports.publishEvents = publishEvents;
const saveEntity = async (user, sdkKey, logger, options) => {
if (!sdkKey) {
throw new Error('Missing sdkKey to save to Edge DB!');
}
if (!user || !user.user_id) {
throw new Error('Missing user to save to Edge DB!');
}
if (user.isAnonymous) {
throw new Error('Cannot save user data for an anonymous user!');
}
const res = await (0, exports.patch)(`${(options === null || options === void 0 ? void 0 : options.apiProxyURL) || exports.CLIENT_SDK_URL}${exports.SAVE_ENTITY_PATH}/${encodeURIComponent(user.user_id)}`, sdkKey, user);
if (res.status === 403) {
logger.warn('Warning: EdgeDB feature is not enabled for this project');
}
else if (res.status >= 400) {
logger.warn(`Error saving user entity, status: ${res.status}, body: ${res.data}`);
}
else {
logger.info(`Saved user entity, status: ${res.status}, body: ${res.data}`);
}
return res;
};
var saveEntity = function (user, sdkKey, logger, options) { return __awaiter(void 0, void 0, void 0, function () {
var res;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!sdkKey) {
throw new Error('Missing sdkKey to save to Edge DB!');
}
if (!user || !user.user_id) {
throw new Error('Missing user to save to Edge DB!');
}
if (user.isAnonymous) {
throw new Error('Cannot save user data for an anonymous user!');
}
return [4 /*yield*/, (0, exports.patch)("".concat((options === null || options === void 0 ? void 0 : options.apiProxyURL) || exports.CLIENT_SDK_URL).concat(exports.SAVE_ENTITY_PATH, "/").concat(encodeURIComponent(user.user_id)), sdkKey, user)];
case 1:
res = _a.sent();
if (res.status === 403) {
logger.warn('Warning: EdgeDB feature is not enabled for this project');
}
else if (res.status >= 400) {
logger.warn("Error saving user entity, status: ".concat(res.status, ", body: ").concat(res.data));
}
else {
logger.info("Saved user entity, status: ".concat(res.status, ", body: ").concat(res.data));
}
return [2 /*return*/, res];
}
});
}); };
exports.saveEntity = saveEntity;

@@ -144,0 +229,0 @@ exports.default = {

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DVCRequestEvent = void 0;
const utils_1 = require("./utils");
const EventQueue_1 = require("./EventQueue");
class DVCRequestEvent {
constructor(event, user_id, featureVars) {
const { type, target, date, value, metaData } = event;
var utils_1 = require("./utils");
var EventQueue_1 = require("./EventQueue");
var DVCRequestEvent = /** @class */ (function () {
function DVCRequestEvent(event, user_id, featureVars) {
var type = event.type, target = event.target, date = event.date, value = event.value, metaData = event.metaData;
(0, utils_1.checkParamDefined)('type', type);
const isCustomEvent = !(type in EventQueue_1.EventTypes);
var isCustomEvent = !(type in EventQueue_1.EventTypes);
this.type = isCustomEvent ? 'customEvent' : type;

@@ -20,4 +20,5 @@ this.customType = isCustomEvent ? type : undefined;

}
}
return DVCRequestEvent;
}());
exports.DVCRequestEvent = DVCRequestEvent;
//# sourceMappingURL=RequestEvent.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StreamingConnection = void 0;
class StreamingConnection {
constructor(url, onMessage, logger) {
var StreamingConnection = /** @class */ (function () {
function StreamingConnection(url, onMessage, logger) {
this.url = url;

@@ -11,3 +11,4 @@ this.onMessage = onMessage;

}
openConnection() {
StreamingConnection.prototype.openConnection = function () {
var _this = this;
if (typeof EventSource === 'undefined') {

@@ -18,17 +19,17 @@ this.logger.warn('StreamingConnection not opened. EventSource is not available.');

this.connection = new EventSource(this.url, { withCredentials: true });
this.connection.onmessage = (event) => {
this.onMessage(event.data);
this.connection.onmessage = function (event) {
_this.onMessage(event.data);
};
this.connection.onerror = () => {
this.logger.warn('StreamingConnection warning. Connection failed to establish.');
this.connection.onerror = function () {
_this.logger.warn('StreamingConnection warning. Connection failed to establish.');
};
this.connection.onopen = () => {
this.logger.debug('StreamingConnection opened');
this.connection.onopen = function () {
_this.logger.debug('StreamingConnection opened');
};
}
isConnected() {
};
StreamingConnection.prototype.isConnected = function () {
var _a, _b;
return ((_a = this.connection) === null || _a === void 0 ? void 0 : _a.readyState) === ((_b = this.connection) === null || _b === void 0 ? void 0 : _b.OPEN);
}
reopen() {
};
StreamingConnection.prototype.reopen = function () {
if (!this.isConnected()) {

@@ -38,9 +39,10 @@ this.close();

}
}
close() {
};
StreamingConnection.prototype.close = function () {
var _a;
(_a = this.connection) === null || _a === void 0 ? void 0 : _a.close();
}
}
};
return StreamingConnection;
}());
exports.StreamingConnection = StreamingConnection;
//# sourceMappingURL=StreamingConnection.js.map

@@ -7,7 +7,7 @@ "use strict";

exports.DVCPopulatedUser = void 0;
const uuid_1 = require("uuid");
const package_json_1 = __importDefault(require("../package.json"));
const ua_parser_js_1 = __importDefault(require("ua-parser-js"));
class DVCPopulatedUser {
constructor(user, options, staticData, anonymousUserId) {
var uuid_1 = require("uuid");
var package_json_1 = __importDefault(require("../package.json"));
var ua_parser_js_1 = __importDefault(require("ua-parser-js"));
var DVCPopulatedUser = /** @class */ (function () {
function DVCPopulatedUser(user, options, staticData, anonymousUserId) {
var _a;

@@ -38,7 +38,7 @@ if (((_a = user.user_id) === null || _a === void 0 ? void 0 : _a.trim()) === '') {

else {
const userAgent = new ua_parser_js_1.default(typeof window !== 'undefined'
var userAgent = new ua_parser_js_1.default(typeof window !== 'undefined'
? window.navigator.userAgent
: undefined);
const platformVersion = userAgent.getBrowser().name &&
`${userAgent.getBrowser().name} ${userAgent.getBrowser().version}`;
var platformVersion = userAgent.getBrowser().name &&
"".concat(userAgent.getBrowser().name, " ").concat(userAgent.getBrowser().version);
this.createdDate = new Date();

@@ -57,3 +57,3 @@ this.platform = (options === null || options === void 0 ? void 0 : options.reactNative) ? 'ReactNative' : 'web';

}
getStaticData() {
DVCPopulatedUser.prototype.getStaticData = function () {
return {

@@ -67,4 +67,4 @@ createdDate: this.createdDate,

};
}
updateUser(user, options) {
};
DVCPopulatedUser.prototype.updateUser = function (user, options) {
if (this.user_id !== user.user_id) {

@@ -74,5 +74,6 @@ throw new Error('Cannot update a user with a different user_id');

return new DVCPopulatedUser(user, options, this.getStaticData());
}
}
};
return DVCPopulatedUser;
}());
exports.DVCPopulatedUser = DVCPopulatedUser;
//# sourceMappingURL=User.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateEventPayload = exports.checkParamType = exports.checkIfDefined = exports.checkParamDefined = exports.serializeUserSearchParams = void 0;
const RequestEvent_1 = require("./RequestEvent");
const convertToQueryFriendlyFormat = (property) => {
var RequestEvent_1 = require("./RequestEvent");
var convertToQueryFriendlyFormat = function (property) {
if (property instanceof Date) {

@@ -14,5 +14,5 @@ return property.getTime();

};
const serializeUserSearchParams = (user, queryParams) => {
for (const key in user) {
const userProperty = convertToQueryFriendlyFormat(user[key]);
var serializeUserSearchParams = function (user, queryParams) {
for (var key in user) {
var userProperty = convertToQueryFriendlyFormat(user[key]);
if (userProperty !== null && userProperty !== undefined) {

@@ -24,9 +24,9 @@ queryParams.append(key, userProperty);

exports.serializeUserSearchParams = serializeUserSearchParams;
const checkParamDefined = (name, param) => {
var checkParamDefined = function (name, param) {
if (!(0, exports.checkIfDefined)(param)) {
throw new Error(`Missing parameter: ${name}`);
throw new Error("Missing parameter: ".concat(name));
}
};
exports.checkParamDefined = checkParamDefined;
const checkIfDefined = (variable) => {
var checkIfDefined = function (variable) {
if (variable === undefined || variable === null) {

@@ -38,8 +38,8 @@ return false;

exports.checkIfDefined = checkIfDefined;
const checkParamType = (name, param, type) => {
var checkParamType = function (name, param, type) {
if (!param) {
throw new Error(`Missing parameter: ${name}`);
throw new Error("Missing parameter: ".concat(name));
}
if (typeof param !== type) {
throw new Error(`${name} is not of type ${type}`);
throw new Error("".concat(name, " is not of type ").concat(type));
}

@@ -50,6 +50,6 @@ };

return {
events: events.map((event) => {
events: events.map(function (event) {
return new RequestEvent_1.DVCRequestEvent(event, user.user_id, config === null || config === void 0 ? void 0 : config.featureVariationMap);
}),
user,
user: user,
};

@@ -61,4 +61,4 @@ }

checkParamDefined: exports.checkParamDefined,
generateEventPayload,
generateEventPayload: generateEventPayload,
};
//# sourceMappingURL=utils.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DVCVariable = void 0;
const utils_1 = require("./utils");
class DVCVariable {
constructor(variable) {
const { key, defaultValue } = variable;
var utils_1 = require("./utils");
var DVCVariable = /** @class */ (function () {
function DVCVariable(variable) {
var key = variable.key, defaultValue = variable.defaultValue;
(0, utils_1.checkParamType)('key', key, 'string');

@@ -22,9 +22,10 @@ (0, utils_1.checkParamDefined)('defaultValue', defaultValue);

}
onUpdate(callback) {
DVCVariable.prototype.onUpdate = function (callback) {
(0, utils_1.checkParamType)('callback', callback, 'function');
this.callback = callback;
return this;
}
}
};
return DVCVariable;
}());
exports.DVCVariable = DVCVariable;
//# sourceMappingURL=Variable.js.map

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc