UNPKG

tggl-client

Version:

Tggl Typescript SDK for client and server

360 lines (359 loc) 16.2 kB
"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 __values = (this && this.__values) || function(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); }; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.TgglLocalClient = void 0; var tggl_core_1 = require("tggl-core"); var validation_1 = require("./validation"); var apiCall_1 = require("./apiCall"); var TgglReporting_1 = require("./TgglReporting"); var TgglLocalClient = /** @class */ (function () { function TgglLocalClient(apiKey, options) { if (options === void 0) { options = {}; } var _a, _b, _c, _d, _e, _f; this.apiKey = apiKey; this.pollingInterval = 0; this.fetchID = 0; this.lastSuccessfulFetchID = 0; this.lastSuccessfulFetchResponse = null; this.onConfigChangeCallbacks = new Map(); this.onFetchSuccessfulCallbacks = new Map(); this.onFetchFailCallbacks = new Map(); this.log = true; if (options.url) { this.url = options.url; } else if (options.baseUrl) { this.url = options.baseUrl + '/config'; } else { this.url = 'https://api.tggl.io/config'; } this.config = (_a = options.initialConfig) !== null && _a !== void 0 ? _a : new Map(); this.log = (_b = options.log) !== null && _b !== void 0 ? _b : true; var reportingOptions = options.reporting && typeof options.reporting === 'object' ? options.reporting : {}; this.reporting = options.reporting === false ? null : new TgglReporting_1.TgglReporting({ apiKey: (_c = reportingOptions.apiKey) !== null && _c !== void 0 ? _c : apiKey, app: reportingOptions.app, appPrefix: (_d = reportingOptions.appPrefix) !== null && _d !== void 0 ? _d : "js-client:".concat(TgglReporting_1.PACKAGE_VERSION, "/TgglLocalClient"), url: reportingOptions.url, baseUrl: (_e = reportingOptions.baseUrl) !== null && _e !== void 0 ? _e : options.baseUrl, reportInterval: reportingOptions.reportInterval, }); this.startPolling((_f = options.pollingInterval) !== null && _f !== void 0 ? _f : 0); } TgglLocalClient.prototype.onConfigChange = function (callback) { var _this = this; var id = Math.random(); this.onConfigChangeCallbacks.set(id, callback); return function () { _this.onConfigChangeCallbacks.delete(id); }; }; TgglLocalClient.prototype.onFetchSuccessful = function (callback) { var _this = this; var id = Math.random(); this.onFetchSuccessfulCallbacks.set(id, callback); return function () { _this.onFetchSuccessfulCallbacks.delete(id); }; }; TgglLocalClient.prototype.onFetchFail = function (callback) { var _this = this; var id = Math.random(); this.onFetchFailCallbacks.set(id, callback); return function () { _this.onFetchFailCallbacks.delete(id); }; }; TgglLocalClient.prototype.startPolling = function (pollingInterval) { var _this = this; this.pollingInterval = pollingInterval; if (pollingInterval > 0) { this.fetchConfig().catch(function (err) { if (_this.log) { console.error(err); } }); } else { this.cancelNextPolling(); } }; TgglLocalClient.prototype.stopPolling = function () { this.startPolling(0); }; TgglLocalClient.prototype.planNextPolling = function () { var _this = this; if (this.pollingInterval > 0 && !this.timeoutID) { this.timeoutID = setTimeout(function () { return __awaiter(_this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, this.fetchConfig().catch(function (err) { if (_this.log) { console.error(err); } })]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }, this.pollingInterval); } }; TgglLocalClient.prototype.cancelNextPolling = function () { if (this.timeoutID) { clearTimeout(this.timeoutID); this.timeoutID = undefined; } }; TgglLocalClient.prototype.waitForLastFetchToFinish = function () { return __awaiter(this, void 0, void 0, function () { var _a, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: _a = this.fetchPromise; if (!_a) return [3 /*break*/, 2]; _b = this.fetchID; return [4 /*yield*/, this.fetchPromise]; case 1: _a = _b !== (_c.sent()); _c.label = 2; case 2: if (!_a) return [3 /*break*/, 3]; return [3 /*break*/, 0]; case 3: return [2 /*return*/]; } }); }); }; TgglLocalClient.prototype.fetchConfig = function () { var _a, _b; return __awaiter(this, void 0, void 0, function () { var fetchID, done, response, _c, _d, callback, error_1, _e, _f, callback; var e_1, _g, e_2, _h; return __generator(this, function (_j) { switch (_j.label) { case 0: fetchID = ++this.fetchID; done = function () { return null; }; this.fetchPromise = new Promise(function (resolve) { done = function () { return resolve(fetchID); }; }); _j.label = 1; case 1: _j.trys.push([1, 5, 6, 7]); this.cancelNextPolling(); return [4 /*yield*/, (0, apiCall_1.apiCall)({ url: this.url, apiKey: this.apiKey, method: 'get', })]; case 2: response = _j.sent(); try { for (_c = __values(this.onFetchSuccessfulCallbacks.values()), _d = _c.next(); !_d.done; _d = _c.next()) { callback = _d.value; callback(); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_d && !_d.done && (_g = _c.return)) _g.call(_c); } finally { if (e_1) throw e_1.error; } } if (fetchID > this.lastSuccessfulFetchID) { this.lastSuccessfulFetchID = fetchID; this.lastSuccessfulFetchResponse = response; } if (!(fetchID !== this.fetchID)) return [3 /*break*/, 4]; return [4 /*yield*/, this.waitForLastFetchToFinish()]; case 3: _j.sent(); return [2 /*return*/, this.config]; case 4: return [3 /*break*/, 7]; case 5: error_1 = _j.sent(); try { for (_e = __values(this.onFetchFailCallbacks.values()), _f = _e.next(); !_f.done; _f = _e.next()) { callback = _f.value; callback(error_1); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_f && !_f.done && (_h = _e.return)) _h.call(_e); } finally { if (e_2) throw e_2.error; } } throw new Error("Invalid response from Tggl: ".concat( // @ts-ignore (_b = (_a = error_1.error) !== null && _a !== void 0 ? _a : error_1.message) !== null && _b !== void 0 ? _b : JSON.stringify(error_1))); case 6: // If this is the last fetch that was started, we can update the config if (fetchID === this.fetchID && this.lastSuccessfulFetchResponse) { this.setRawConfig(this.lastSuccessfulFetchResponse); } done(); this.planNextPolling(); return [7 /*endfinally*/]; case 7: return [2 /*return*/, this.config]; } }); }); }; TgglLocalClient.prototype.getConfig = function () { return this.config; }; TgglLocalClient.prototype.setConfig = function (config) { this.config = config; }; TgglLocalClient.prototype.setRawConfig = function (flags) { var e_3, _a, e_4, _b; var _this = this; var configChanged = this.onConfigChangeCallbacks.size > 0 && (flags.length !== this.config.size || !flags.every(function (flag) { return JSON.stringify(_this.config.get(flag.slug)) === JSON.stringify(flag); })); this.config.clear(); try { for (var flags_1 = __values(flags), flags_1_1 = flags_1.next(); !flags_1_1.done; flags_1_1 = flags_1.next()) { var flag = flags_1_1.value; this.config.set(flag.slug, flag); } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (flags_1_1 && !flags_1_1.done && (_a = flags_1.return)) _a.call(flags_1); } finally { if (e_3) throw e_3.error; } } if (configChanged) { try { for (var _c = __values(this.onConfigChangeCallbacks.values()), _d = _c.next(); !_d.done; _d = _c.next()) { var callback = _d.value; callback(this.config); } } catch (e_4_1) { e_4 = { error: e_4_1 }; } finally { try { if (_d && !_d.done && (_b = _c.return)) _b.call(_c); } finally { if (e_4) throw e_4.error; } } } }; TgglLocalClient.prototype.get = function (context, slug, defaultValue) { var _a, _b; (0, validation_1.assertValidContext)(context); var flag = this.config.get(slug); var rawValue = flag ? (0, tggl_core_1.evalFlag)(context, flag) : undefined; var value = rawValue === undefined ? defaultValue : rawValue; (_a = this.reporting) === null || _a === void 0 ? void 0 : _a.reportFlag(String(slug), { default: defaultValue, value: value, }); (_b = this.reporting) === null || _b === void 0 ? void 0 : _b.reportContext(context); return value; }; TgglLocalClient.prototype.getActiveFlags = function (context) { var e_5, _a; var _b; var result = {}; try { for (var _c = __values(this.config.entries()), _d = _c.next(); !_d.done; _d = _c.next()) { var _e = __read(_d.value, 2), slug = _e[0], flag = _e[1]; var value = (0, tggl_core_1.evalFlag)(context, flag); if (value !== undefined) { result[slug] = value; } } } catch (e_5_1) { e_5 = { error: e_5_1 }; } finally { try { if (_d && !_d.done && (_a = _c.return)) _a.call(_c); } finally { if (e_5) throw e_5.error; } } (_b = this.reporting) === null || _b === void 0 ? void 0 : _b.reportContext(context); return result; }; return TgglLocalClient; }()); exports.TgglLocalClient = TgglLocalClient;