UNPKG

webcom

Version:

Webcom library

1,251 lines (1,028 loc) 536 kB
/*! * Webcom. Build realtime apps. Share and sync data instantly between your clients * * Module name: Webcom * Version: 3.8.0 * Created: 2025-06-26T13:38:18.226Z * * Copyright (C) <2015-2025> Orange * * This software is confidential and proprietary information of Orange. * You shall not disclose such Confidential Information and shall use it only in * accordance with the terms of the agreement you entered into. * Unauthorized copying of this file, via any medium is strictly prohibited. * * If you are Orange employee you shall use this software in accordance with * the Orange Source Charter (http://opensource.itn.ftgroup/index.php/Orange_Source_Charter) */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else { var a = factory(); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(this, () => { return /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ /***/ "./src/api/LogManager.js": /*!*******************************!*\ !*** ./src/api/LogManager.js ***! \*******************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "LOGGER_PREFIX_PADDING": () => (/* binding */ LOGGER_PREFIX_PADDING), /* harmony export */ "_LogManager": () => (/* binding */ _LogManager), /* harmony export */ "createLogger": () => (/* binding */ createLogger), /* harmony export */ "default": () => (/* binding */ LogManager) /* harmony export */ }); /* harmony import */ var _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/toConsumableArray */ "./node_modules/@babel/runtime/helpers/esm/toConsumableArray.js"); /* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); /* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/esm/createClass.js"); /* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "./node_modules/@babel/runtime/helpers/esm/slicedToArray.js"); /* harmony import */ var _util_Logger__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util/Logger */ "./src/util/Logger.js"); /* harmony import */ var _dependencies_console__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../dependencies/console */ "./src/dependencies/console.js"); /* harmony import */ var _util_validation__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/validation */ "./src/util/validation.js"); var DISABLED = -1; var LOGGER_PREFIX_PADDING = " "; var displayTimestamp = false; var loggerPrefixWidth = 15; var allLoggers = []; var loggersByDomain = {}; var enabledLoggers = {}; var disabledLoggers = {}; var LEAF_KEY = "_leaf_"; function _fqdn(path) { return path ? path.split(".") : []; } function _abilitySettings(path) { return { disabledDepth: _findDeepest(path, disabledLoggers), enabledDepth: _findDeepest(path, enabledLoggers) }; } function _registerLogger(logger) { var path = logger.fqdn; _setAt(path, loggersByDomain, logger); allLoggers.push(logger); var _abilitySettings2 = _abilitySettings(path), disabledDepth = _abilitySettings2.disabledDepth, enabledDepth = _abilitySettings2.enabledDepth; logger.setLevel(enabledDepth >= disabledDepth ? level : DISABLED); } function _setAt(path, tree, value, clear) { var i = 0; while (i < path.length) { var segment = path[i++]; if (!tree.hasOwnProperty(segment)) { tree[segment] = {}; } tree = tree[segment]; } if (clear) { Object.keys(tree).forEach(function (it) { return delete tree[it]; }); } tree[LEAF_KEY] = value; } function _unsetAt(path, tree) { var i = 0; while (i < path.length) { var segment = path[i++]; if (tree.hasOwnProperty(segment)) { tree = tree[segment]; } else { return; } } delete tree[LEAF_KEY]; } function _findDeepest(path, tree) { var depth = -1; var i = 0; do { if (tree.hasOwnProperty(LEAF_KEY)) { depth = i; } } while (i < path.length && (tree = tree[path[i++]])); return depth; } function _forAll(tree, action) { Object.entries(tree || {}).forEach(function (_ref) { var _ref2 = (0,_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_3__["default"])(_ref, 2), key = _ref2[0], value = _ref2[1]; if (key === LEAF_KEY) { action(value); } else { _forAll(value, action); } }); } function _findAllAt(path, tree) { var result = []; var i = 0; while (tree && i < path.length) { tree = tree[path[i++]]; } _forAll(tree, function (value) { return result.push(value); }); return result; } function updateDisplayTimestamp(value) { displayTimestamp = value; allLoggers.forEach(function (logger) { return logger.displayTimestamp = displayTimestamp; }); } var _LogManager = "LogManager"; var LogManager = function () { function LogManager() { (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__["default"])(this, LogManager); } (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__["default"])(LogManager, null, [{ key: "enable", value: function enable(prefix) { (0,_util_validation__WEBPACK_IMPORTED_MODULE_6__.checkArgs)([_LogManager, ".enable"], arguments, (0,_util_validation__WEBPACK_IMPORTED_MODULE_6__.optional)(_util_validation__WEBPACK_IMPORTED_MODULE_6__.string)); var path = _fqdn(prefix); var _abilitySettings3 = _abilitySettings(path), enabledDepth = _abilitySettings3.enabledDepth, disabledDepth = _abilitySettings3.disabledDepth; if (enabledDepth <= disabledDepth) { if (disabledDepth < 0) { LogManager.disable(); } _setAt(path, enabledLoggers, true, true); _unsetAt(path, disabledLoggers); _findAllAt(path, loggersByDomain).forEach(function (it) { return it.setLevel(level); }); } } }, { key: "disable", value: function disable(prefix) { (0,_util_validation__WEBPACK_IMPORTED_MODULE_6__.checkArgs)([_LogManager, ".disable"], arguments, (0,_util_validation__WEBPACK_IMPORTED_MODULE_6__.optional)(_util_validation__WEBPACK_IMPORTED_MODULE_6__.string)); var path = _fqdn(prefix); var _abilitySettings4 = _abilitySettings(path), enabledDepth = _abilitySettings4.enabledDepth, disabledDepth = _abilitySettings4.disabledDepth; if (disabledDepth <= enabledDepth) { _setAt(path, disabledLoggers, true, true); _unsetAt(path, enabledLoggers); _findAllAt(path, loggersByDomain).forEach(function (it) { return it.setLevel(DISABLED); }); } } }, { key: "showTimestamp", value: function showTimestamp() { (0,_util_validation__WEBPACK_IMPORTED_MODULE_6__.checkArgs)([_LogManager, ".showTimestamp"], arguments); updateDisplayTimestamp(true); } }, { key: "hideTimestamp", value: function hideTimestamp() { (0,_util_validation__WEBPACK_IMPORTED_MODULE_6__.checkArgs)([_LogManager, ".hideTimestamp"], arguments); updateDisplayTimestamp(false); } }, { key: "setPrefixWidth", value: function setPrefixWidth(width) { (0,_util_validation__WEBPACK_IMPORTED_MODULE_6__.checkArgs)([_LogManager, ".setPrefixWidth"], arguments, _util_validation__WEBPACK_IMPORTED_MODULE_6__.finiteNumber); if (width < 0) { width = 0; } else if (width > LOGGER_PREFIX_PADDING.length) { width = LOGGER_PREFIX_PADDING.length; } loggerPrefixWidth = width; allLoggers.forEach(function (logger) { return logger.setPrefixWidth(loggerPrefixWidth); }); } }, { key: "level", get: function get() { return level; }, set: function set(value) { (0,_util_validation__WEBPACK_IMPORTED_MODULE_6__.checkArgs)([_LogManager, ".level"], arguments, _util_validation__WEBPACK_IMPORTED_MODULE_6__.finiteNumber); if (value > DISABLED && value !== level) { allLoggers.forEach(function (logger) { return logger.updateLevel(value); }); level = value; } } }, { key: "LOG", get: function get() { return 4; } }, { key: "INFO", get: function get() { return 3; } }, { key: "WARN", get: function get() { return 2; } }, { key: "ERROR", get: function get() { return 1; } }, { key: "NONE", get: function get() { return 0; } }, { key: "debugOnCallback", value: function debugOnCallback(name) { var NAME = name && name.toUpperCase(); return function (snapshot, prev) { return _dependencies_console__WEBPACK_IMPORTED_MODULE_5__.console.log("********** UPDATE ".concat(NAME || snapshot.ref().pathString(), " **********"), snapshot.toString(), prev ? "[<<".concat(prev, "]") : ""); }; } }, { key: "debugOnCompletionCallback", value: function debugOnCompletionCallback(name, result) { var NAME = name && name.toUpperCase(); return function (error) { if (error) { _dependencies_console__WEBPACK_IMPORTED_MODULE_5__.console.log("********** REVOKED ".concat(NAME, " **********"), error); } else { _dependencies_console__WEBPACK_IMPORTED_MODULE_5__.console.log("********** COMPLETED ".concat(NAME, " **********")); } return result; }; } }, { key: "debugOnCallbackWithCancel", value: function debugOnCallbackWithCancel(name) { var NAME = name && name.toUpperCase(); return [LogManager.debugOnCallback(name), function (error) { return _dependencies_console__WEBPACK_IMPORTED_MODULE_5__.console.log.apply(_dependencies_console__WEBPACK_IMPORTED_MODULE_5__.console, ["********** COMPLETE ".concat(NAME, " **********")].concat((0,_babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0__["default"])(error ? ["FAILED:", error.code, error.message] : ["cancelled"]))); }]; } }]); return LogManager; }(); function createLogger(name, prefix) { var fqdn = _fqdn(name); var logger = new _util_Logger__WEBPACK_IMPORTED_MODULE_4__["default"](fqdn, prefix || fqdn[fqdn.length - 1], displayTimestamp, loggerPrefixWidth); _registerLogger(logger); return logger; } var level = true ? LogManager.LOG : 0; /***/ }), /***/ "./src/api/Webcom.js": /*!***************************!*\ !*** ./src/api/Webcom.js ***! \***************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "_Webcom": () => (/* binding */ _Webcom), /* harmony export */ "_logger": () => (/* binding */ _logger), /* harmony export */ "default": () => (/* binding */ Webcom) /* harmony export */ }); /* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); /* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/esm/createClass.js"); /* harmony import */ var _WebcomApp__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./WebcomApp */ "./src/api/WebcomApp.js"); /* harmony import */ var _LogManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./LogManager */ "./src/api/LogManager.js"); /* harmony import */ var _dependencies_dependencies__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../dependencies/dependencies */ "./src/dependencies/dependencies.js"); /* harmony import */ var _util_validation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/validation */ "./src/util/validation.js"); /* harmony import */ var _util_nextPushId__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util/nextPushId */ "./src/util/nextPushId.js"); var _Webcom = "Webcom"; var Webcom = function () { function Webcom() { (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, Webcom); this._init.apply(this, arguments); } (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(Webcom, [{ key: "_init", value: function _init() { (0,_util_validation__WEBPACK_IMPORTED_MODULE_5__.throwError)(["new ", _Webcom], "this static class cannot be instantiated"); } }], [{ key: "SDK_VERSION", get: function get() { return "3.8.0"; } }, { key: "Log", get: function get() { return _LogManager__WEBPACK_IMPORTED_MODULE_3__["default"]; } }, { key: "App", value: function App(appId, config) { return new _WebcomApp__WEBPACK_IMPORTED_MODULE_2__["default"](appId, config); } }, { key: "getUniqueKeyDate", value: function getUniqueKeyDate(key) { return new Date((0,_util_nextPushId__WEBPACK_IMPORTED_MODULE_6__.pushIdDateTime)(key)); } }, { key: "dependencies", get: function get() { return _dependencies_dependencies__WEBPACK_IMPORTED_MODULE_4__.dependencies; } }]); return Webcom; }(); var _logger = (0,_LogManager__WEBPACK_IMPORTED_MODULE_3__.createLogger)("api.Webcom", _Webcom); /***/ }), /***/ "./src/api/WebcomApp.js": /*!******************************!*\ !*** ./src/api/WebcomApp.js ***! \******************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "REGULAR_CONFIGURATION": () => (/* binding */ REGULAR_CONFIGURATION), /* harmony export */ "appStorageKey": () => (/* binding */ appStorageKey), /* harmony export */ "default": () => (/* binding */ WebcomApp), /* harmony export */ "fullyQualifiedAppIdentifier": () => (/* binding */ fullyQualifiedAppIdentifier) /* harmony export */ }); /* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "./node_modules/@babel/runtime/helpers/esm/slicedToArray.js"); /* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); /* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/esm/createClass.js"); /* harmony import */ var _util_validation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../util/validation */ "./src/util/validation.js"); /* harmony import */ var _LogManager__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./LogManager */ "./src/api/LogManager.js"); /* harmony import */ var _util_is__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util/is */ "./src/util/is.js"); var _WebcomApp = "WebcomApp"; var WebcomApp = function () { function WebcomApp(appId) { var configuration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__["default"])(this, WebcomApp); (0,_util_validation__WEBPACK_IMPORTED_MODULE_3__.checkArgs)(["new ", _WebcomApp], arguments, (0,_util_validation__WEBPACK_IMPORTED_MODULE_3__.matches)(/^[a-z0-9](?:[-a-z0-9]{0,38}[a-z0-9])?$/), (0,_util_validation__WEBPACK_IMPORTED_MODULE_3__.optional)((0,_util_validation__WEBPACK_IMPORTED_MODULE_3__.either)(_util_validation__WEBPACK_IMPORTED_MODULE_3__.object, _util_validation__WEBPACK_IMPORTED_MODULE_3__.string))); this._logger = (0,_LogManager__WEBPACK_IMPORTED_MODULE_4__.createLogger)("api.WebcomApp", _WebcomApp); this._services = {}; this.appId = appId; this.config = {}; if ((0,_util_is__WEBPACK_IMPORTED_MODULE_5__.isString)(configuration)) { configuration = Object.keys(REGULAR_CONFIGURATION).reduce(function (acc, serviceKey) { acc[serviceKey] = { baseUrl: configuration }; return acc; }, {}); } this._fillConfig(configuration); this._logger.log("Initialized %s with options %s", appId, JSON.stringify(this.config)); } (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__["default"])(WebcomApp, [{ key: "dispose", value: function dispose() { (0,_util_validation__WEBPACK_IMPORTED_MODULE_3__.checkArgs)([_WebcomApp, "#dispose"], arguments); Object.values(this._services).forEach(function (it) { return it._dispose(); }); this._services = {}; } }, { key: "_fillConfig", value: function _fillConfig(configuration) { this_fillRegularConfig.call(this, configuration, REGULAR_CONFIGURATION); } }, { key: "toString", value: function toString() { return "".concat(this.appId, "{").concat(Object.keys(this._services).join(","), "}"); } }]); return WebcomApp; }(); function this_fillRegularConfig(inConfig, defaults) { var _this = this; var fill = function fill(thisConfig, inConfig, defaults, path) { var propertyPath = function propertyPath(key) { return "".concat(_WebcomApp, ".Configuration.").concat(path.concat(key).join(".")); }; inConfig = Object.assign({}, inConfig); Object.entries(defaults).forEach(function (_ref) { var _ref2 = (0,_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0__["default"])(_ref, 2), property = _ref2[0], defaultValueDescriptor = _ref2[1]; if (defaultValueDescriptor instanceof Object && !(defaultValueDescriptor instanceof Array)) { thisConfig[property] = thisConfig[property] || {}; fill(thisConfig[property], inConfig[property] || {}, defaultValueDescriptor, path.concat(property)); } else { var inValue = inConfig[property]; var defaultValue = function defaultValue() { return defaultValueDescriptor.length ? defaultValueDescriptor[0] : defaultValueDescriptor; }; var map = defaultValueDescriptor[1] || function (x) { return x; }; try { thisConfig[property] = map(inValue === undefined ? thisConfig[property] === undefined ? defaultValue() : thisConfig[property] : inValue); } catch (e) { var prefix = propertyPath(property); if (e.value === undefined) { (0,_util_validation__WEBPACK_IMPORTED_MODULE_3__.throwError)(prefix, e.message); } else { _this._logger.warn("%s: %s", prefix, e.message); thisConfig[property] = e.value; } } } delete inConfig[property]; }); Object.keys(inConfig).forEach(function (key) { return _this._logger.warn("%s: unknown config key", propertyPath(key)); }); }; fill(this.config, inConfig, defaults, []); } function fullyQualifiedAppIdentifier(app, config) { var baseUrl = config.baseUrl; return "/".concat(baseUrl.protocol.slice(0, -1), "/").concat(baseUrl.host, "/").concat(app.appId, "/"); } function appStorageKey(app, key, config) { return "".concat(config.key, ":").concat(key, ":").concat(fullyQualifiedAppIdentifier(app, config)); } var REGULAR_CONFIGURATION = {}; /***/ }), /***/ "./src/api/WebcomService.js": /*!**********************************!*\ !*** ./src/api/WebcomService.js ***! \**********************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "between": () => (/* binding */ between), /* harmony export */ "check": () => (/* binding */ check), /* harmony export */ "parseUrl": () => (/* binding */ parseUrl), /* harmony export */ "this_warnIfNotSecure": () => (/* binding */ this_warnIfNotSecure) /* harmony export */ }); /* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "./node_modules/@babel/runtime/helpers/esm/slicedToArray.js"); /* harmony import */ var _dependencies_device__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../dependencies/_device */ "./src/dependencies/_device.js"); /* harmony import */ var _util_globalThis__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util/globalThis */ "./src/util/globalThis.js"); function this_warnIfNotSecure(url) { if (url.protocol === "http:" && _dependencies_device__WEBPACK_IMPORTED_MODULE_1__.isWebBrowser && window.location.protocol === "https:") { this._logger.warn("Insecure access to a Webcom service from a secure page. Please setup your service with an https protocol."); } } var URL_PATTERN_ = new RegExp("^(?:([^:]+:)//)?(?:[^/@]+@)?([^/:]+(?::\\d+)?)(?:/.*)?$"); var DEFAULT_PROTOCOL = "https:"; var DEFAULT_HOST = "io.datasync.orange.com"; function parseUrl(url) { if (url && (_util_globalThis__WEBPACK_IMPORTED_MODULE_2__.globalObject.URL && url instanceof URL || url.href && url.protocol && url.host)) { return url; } else { var match = url ? URL_PATTERN_.exec(url) : [DEFAULT_HOST, undefined, DEFAULT_HOST]; if (match) { var _match = (0,_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0__["default"])(match, 3), href = _match[0], protocol = _match[1], host = _match[2]; if (!protocol) { protocol = DEFAULT_PROTOCOL; href = "".concat(protocol, "//").concat(href); } return { href: href, protocol: protocol, host: host }; } else { throw new Error("cannot parse base URL: ".concat(url)); } } } function check(checker, mapper) { return function (i) { var error = checker(i); if (error) { throw new Error(error); } else { return mapper ? mapper(i) : i; } }; } function between(low, high, cut) { return function (i) { if (low !== undefined && i < low) { var message = "must be higher than ".concat(low); throw cut ? { value: low, message: message } : new Error(message); } else if (high !== undefined && i > high) { var _message = "must be lower than ".concat(high); throw cut ? { value: high, message: _message } : new Error(_message); } return i; }; } /***/ }), /***/ "./src/auth/AuthenticationImpl.js": /*!****************************************!*\ !*** ./src/auth/AuthenticationImpl.js ***! \****************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ AuthenticationImpl), /* harmony export */ "notifySubscription": () => (/* binding */ notifySubscription), /* harmony export */ "this_ongoingOAuthSession": () => (/* binding */ this_ongoingOAuthSession) /* harmony export */ }); /* harmony import */ var _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/toConsumableArray */ "./node_modules/@babel/runtime/helpers/esm/toConsumableArray.js"); /* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "./node_modules/@babel/runtime/helpers/esm/slicedToArray.js"); /* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); /* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/esm/createClass.js"); /* harmony import */ var _api_Authentication__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./api/Authentication */ "./src/auth/api/Authentication.js"); /* harmony import */ var _dependencies_timeout__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../dependencies/timeout */ "./src/dependencies/timeout.js"); /* harmony import */ var _network_Errors__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../network/Errors */ "./src/network/Errors.js"); /* harmony import */ var _util_JSONStorage__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../util/JSONStorage */ "./src/util/JSONStorage.js"); /* harmony import */ var _util_object__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../util/object */ "./src/util/object.js"); /* harmony import */ var _util_is__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../util/is */ "./src/util/is.js"); /* harmony import */ var _util_string__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../util/string */ "./src/util/string.js"); /* harmony import */ var _network_HttpRequest__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../network/HttpRequest */ "./src/network/HttpRequest.js"); /* harmony import */ var _dependencies_device__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../dependencies/_device */ "./src/dependencies/_device.js"); /* harmony import */ var _util_validation__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../util/validation */ "./src/util/validation.js"); /* harmony import */ var _api_WebcomService__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../api/WebcomService */ "./src/api/WebcomService.js"); /* harmony import */ var _api_LogManager__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../api/LogManager */ "./src/api/LogManager.js"); /* harmony import */ var _api_Webcom__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./api/Webcom */ "./src/auth/api/Webcom.js"); /* harmony import */ var _util_fn__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../util/fn */ "./src/util/fn.js"); /* harmony import */ var _api_WebcomApp__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../api/WebcomApp */ "./src/api/WebcomApp.js"); var USER_DENIED_ERROR = { code: "USER_DENIED", message: "The user aborted authentication" }; var POPUP_FAILED_ERROR = function POPUP_FAILED_ERROR(url) { return { code: "POPUP_FAILED", message: "Could not open popup at ".concat(url) }; }; var OAuthProviderPopupFeatures = { 'facebook': { height: 650, width: 680 }, 'google': { height: 460, width: 490 }, 'github': { height: 760, width: 340 }, 'gitlab': { height: 710, width: 800 }, 'orange': { height: 700, width: 1000 }, 'mobileconnectOFR': { height: 540, width: 700 } }; var OAuthPopupFeatures = { 'menubar': 0, 'location': 0, 'resizable': 0, 'scrollbars': 1, 'status': 0, 'dialog': 1, 'width': 700, 'height': 375 }; function storageKey(app, keySuffix) { var config = app.config[_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication]; return (0,_util_is__WEBPACK_IMPORTED_MODULE_9__.isString)(config.storage) ? config.storage : (0,_api_WebcomApp__WEBPACK_IMPORTED_MODULE_18__.appStorageKey)(app, "state", config) + keySuffix; } function readInitialState(app, keySuffix) { var config = app.config[_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication]; return config.initialState || ((0,_util_is__WEBPACK_IMPORTED_MODULE_9__.isFunction)(config.storage) ? {} : _util_JSONStorage__WEBPACK_IMPORTED_MODULE_7__.persistentStorage.get(storageKey(app, keySuffix))); } function stateStorage(app, keySuffix) { var config = app.config[_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication]; if ((0,_util_is__WEBPACK_IMPORTED_MODULE_9__.isFunction)(config.storage)) { return function (value) { return config.storage(JSON.stringify(value)); }; } else { var key = storageKey(app, keySuffix); return function (value) { return value && !value.isUnauthenticated() ? _util_JSONStorage__WEBPACK_IMPORTED_MODULE_7__.persistentStorage.set(key, value) : _util_JSONStorage__WEBPACK_IMPORTED_MODULE_7__.persistentStorage.remove(key); }; } } function notifySubscription(callback, error, state) { (0,_dependencies_timeout__WEBPACK_IMPORTED_MODULE_5__.setTimeout)(function () { return callback(error, state); }); } function this_ongoingOAuthSession() { return _dependencies_device__WEBPACK_IMPORTED_MODULE_12__.isWebBrowser && (_util_JSONStorage__WEBPACK_IMPORTED_MODULE_7__.sessionStorage.get(this._oauthSessionKey) || _util_JSONStorage__WEBPACK_IMPORTED_MODULE_7__.persistentStorage.get(this._oauthSessionKey)); } var AuthenticationImpl = function () { function AuthenticationImpl(application) { (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__["default"])(this, AuthenticationImpl); this._logger = (0,_api_LogManager__WEBPACK_IMPORTED_MODULE_15__.createLogger)("api.Authentication", _api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication); this._logger.log("Initializing with options ".concat(JSON.stringify(application.config[_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication]))); this._app = application; this._init(application); } (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__["default"])(AuthenticationImpl, [{ key: "_init", value: function _init(application) { var config = application.config[_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication]; _api_WebcomService__WEBPACK_IMPORTED_MODULE_14__.this_warnIfNotSecure.call(this, config.baseUrl); var keySuffix = this._logger._count; this._currentState = (0,_api_Authentication__WEBPACK_IMPORTED_MODULE_4__.importStateFromJson)(readInitialState(application, keySuffix)); this._authStateSetter = stateStorage(application, keySuffix); this._oauthSessionKey = (0,_api_WebcomApp__WEBPACK_IMPORTED_MODULE_18__.appStorageKey)(application, "ongoing", config) + keySuffix; this.isAuthContextual = false; this._firstSubscriptions = []; this._lastSubscriptions = []; this._authRoute = "".concat(config.baseUrl.href, "/auth/v2/").concat(application.appId); this._resumeAuthState(); this._logger.log("Initialized for appId %s", application.appId); } }, { key: "_dispose", value: function _dispose() {} }, { key: "currentState", get: function get() { return this._currentState; }, set: function set(value) { if (!this._currentState.isSameAs(value)) { this._currentState = (0,_api_Authentication__WEBPACK_IMPORTED_MODULE_4__.exportState)(value); this._authStateSetter(this._currentState); this._notifyErrorOrAuthStateChanged(null, value); } } }, { key: "_resumeAuthState", value: function _resumeAuthState() { var _this = this; if (_dependencies_device__WEBPACK_IMPORTED_MODULE_12__.isWebBrowser) { if (_util_JSONStorage__WEBPACK_IMPORTED_MODULE_7__.persistentStorage.get(this._oauthSessionKey) === "popup") { document.body.style.display = "none"; _util_JSONStorage__WEBPACK_IMPORTED_MODULE_7__.persistentStorage.set(this._oauthSessionKey, (0,_util_string__WEBPACK_IMPORTED_MODULE_10__.parseQuerystring)(location.search).__wcsession); window.close(); } else { var requestKey = _util_JSONStorage__WEBPACK_IMPORTED_MODULE_7__.sessionStorage.get(this._oauthSessionKey); if (requestKey) { var sessionKey = (0,_util_string__WEBPACK_IMPORTED_MODULE_10__.parseQuerystring)(location.search).__wcsession; if (sessionKey) { this._oauthSessionPromise = this.resumeSession(sessionKey, requestKey)["finally"](function () { delete _this._oauthSessionPromise; _util_JSONStorage__WEBPACK_IMPORTED_MODULE_7__.sessionStorage.remove(_this._oauthSessionKey); })["catch"](_util_fn__WEBPACK_IMPORTED_MODULE_17__.noop); return; } else { _util_JSONStorage__WEBPACK_IMPORTED_MODULE_7__.sessionStorage.remove(this._oauthSessionKey); } } } } this._logger.info("Authentication state resumed: %s", this.currentState.state); this._logger.log("Authentication details are: %o", this.currentState.details); } }, { key: "getAccountDetails", value: function getAccountDetails() { var method = [_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication, "#removeIdentity"]; try { (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.checkArgs)(method, arguments); var authDetails = this._getCurrentAuthenticationDetails(method); return this._httpGet("accounts", authDetails.uid).addHeader((0,_network_HttpRequest__WEBPACK_IMPORTED_MODULE_11__.bearerAuthorization)(authDetails.webcomAuthToken)).send().then(function (response) { var result = {}; for (var _i = 0, _Object$entries = Object.entries(response.body); _i < _Object$entries.length; _i++) { var _Object$entries$_i = (0,_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1__["default"])(_Object$entries[_i], 2), key = _Object$entries$_i[0], value = _Object$entries$_i[1]; switch (key) { case "providers": { var identities = {}; for (var _i2 = 0, _Object$entries2 = Object.entries(value); _i2 < _Object$entries2.length; _i2++) { var _Object$entries2$_i = (0,_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1__["default"])(_Object$entries2[_i2], 2), provider = _Object$entries2$_i[0], entries = _Object$entries2$_i[1]; identities[provider] = Object.keys(entries); } result.identities = identities; break; } case "createdOn": result[key] = new Date(value); break; default: result[key] = value; } } return result; }); } catch (e) { return Promise.reject(e); } } }, { key: "subscribe", value: function subscribe(callback, first) { (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.checkArgs)([_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication, "#subscribe"], arguments, _util_validation__WEBPACK_IMPORTED_MODULE_13__.func, (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.optional)(_util_validation__WEBPACK_IMPORTED_MODULE_13__.boolean)); if (first) { this._firstSubscriptions.push(callback); } else { this._lastSubscriptions.push(callback); } if (!this_ongoingOAuthSession.call(this)) { notifySubscription(callback, null, this.currentState); } else { this._logger.log('Notification not sent, because an OAuth authentication is ongoing.'); } return callback; } }, { key: "unsubscribe", value: function unsubscribe(callbackOpt) { var firstOpt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.checkArgs)([_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication, "#unsubscribe"], arguments, (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.optional)(_util_validation__WEBPACK_IMPORTED_MODULE_13__.func), (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.optional)(_util_validation__WEBPACK_IMPORTED_MODULE_13__.boolean)); var countBefore = this._firstSubscriptions.length + this._lastSubscriptions.length; var callbackFilter = function callbackFilter(callback) { return callbackOpt && callbackOpt !== callback; }; if (firstOpt !== false) { this._firstSubscriptions = this._firstSubscriptions.filter(callbackFilter); } if (firstOpt !== true) { this._lastSubscriptions = this._lastSubscriptions.filter(callbackFilter); } return countBefore - this._firstSubscriptions.length - this._lastSubscriptions.length; } }, { key: "_notifyErrorOrAuthStateChanged", value: function _notifyErrorOrAuthStateChanged(error, authState) { this._firstSubscriptions.concat(this._lastSubscriptions).forEach(function (subscription) { return notifySubscription(subscription, error, authState); }); } }, { key: "authenticationRevoked", value: function authenticationRevoked(authState, message) { (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.checkArgs)([_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication, "#authenticationRevoked"], arguments, (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.ofType)(_api_Authentication__WEBPACK_IMPORTED_MODULE_4__.State), _util_validation__WEBPACK_IMPORTED_MODULE_13__.string); var error = new Error("Authentication was revoked by the server: ".concat(message)); error.code = "AUTH_REVOKED"; this._notifyErrorOrAuthStateChanged(error, null); this.currentState = authState; } }, { key: "resumeSession", value: function resumeSession(sessionKey, requestKey) { (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.checkArgs)("AuthenticationImpl#resumeSession", arguments, _util_validation__WEBPACK_IMPORTED_MODULE_13__.string, _util_validation__WEBPACK_IMPORTED_MODULE_13__.string); this._logger.info("fetching authentication state from an ongoing OAuth2 session..."); return (0,_network_HttpRequest__WEBPACK_IMPORTED_MODULE_11__.post)(this._authRoute, "session").addJson({ sessionKey: sessionKey, requestKey: requestKey }).send().then(this._updateStateFromHttpResponse(), this._notifyErrorFromHttpResponse.bind(this)); } }, { key: "_extendHttpRequest", value: function _extendHttpRequest(request) { var _this2 = this; var extendedRequest = request; extendedRequest.addAuthContext = function () { var authContext = _this2._contextAuthToken(); return authContext ? request.addHeader((0,_network_HttpRequest__WEBPACK_IMPORTED_MODULE_11__.bearerAuthorization)(authContext)) : request; }; return extendedRequest; } }, { key: "_httpGet", value: function _httpGet() { for (var _len = arguments.length, urlSegments = new Array(_len), _key = 0; _key < _len; _key++) { urlSegments[_key] = arguments[_key]; } return this._extendHttpRequest(_network_HttpRequest__WEBPACK_IMPORTED_MODULE_11__.get.apply(void 0, [this._authRoute].concat(urlSegments))); } }, { key: "_httpPost", value: function _httpPost() { for (var _len2 = arguments.length, urlSegments = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { urlSegments[_key2] = arguments[_key2]; } return this._extendHttpRequest(_network_HttpRequest__WEBPACK_IMPORTED_MODULE_11__.post.apply(void 0, [this._authRoute].concat(urlSegments))); } }, { key: "_httpPut", value: function _httpPut() { for (var _len3 = arguments.length, urlSegments = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { urlSegments[_key3] = arguments[_key3]; } return this._extendHttpRequest(_network_HttpRequest__WEBPACK_IMPORTED_MODULE_11__.put.apply(void 0, [this._authRoute].concat(urlSegments))); } }, { key: "_httpDelete", value: function _httpDelete() { for (var _len4 = arguments.length, urlSegments = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { urlSegments[_key4] = arguments[_key4]; } return this._extendHttpRequest(_network_HttpRequest__WEBPACK_IMPORTED_MODULE_11__.deleteHttpRequest.apply(void 0, [this._authRoute].concat(urlSegments))); } }, { key: "_updateStateFromHttpResponse", value: function _updateStateFromHttpResponse() { var _this3 = this; var extractAuthInfo = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function (x) { return x; }; return function (response) { var _extractAuthInfo = extractAuthInfo(response), _extractAuthInfo$body = _extractAuthInfo.body, token = _extractAuthInfo$body.token, user = _extractAuthInfo$body.user; if (token) { user.webcomAuthToken = token; _this3.currentState = (0,_api_Authentication__WEBPACK_IMPORTED_MODULE_4__.VALID_AUTHENTICATION)(user); return new Promise(function (resolve) { return (0,_dependencies_timeout__WEBPACK_IMPORTED_MODULE_5__.setTimeout)(function () { return resolve(user); }); }); } else { throw (0,_network_Errors__WEBPACK_IMPORTED_MODULE_6__.format)({ code: "UNEXPECTED_RESPONSE", message: "the 'token' property is missing." }); } }; } }, { key: "_notifyErrorFromHttpResponse", value: function _notifyErrorFromHttpResponse(error) { this._notifyErrorOrAuthStateChanged(error, null); throw error; } }, { key: "useCurrentContextForNextAuthOperation", value: function useCurrentContextForNextAuthOperation() { (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.checkArgs)([_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication, "#useCurrentContextForNextAuthOperation"], arguments); this.isAuthContextual = true; } }, { key: "useNewContextForNextAuthOperation", value: function useNewContextForNextAuthOperation() { (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.checkArgs)([_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication, "#useNewContextForNextAuthOperation"], arguments); this.isAuthContextual = false; } }, { key: "_contextAuthToken", value: function _contextAuthToken() { var currentAuth = this.isAuthContextual ? this.currentState.details : null; this.isAuthContextual = false; return currentAuth && currentAuth.webcomAuthToken; } }, { key: "signInWithToken", value: function signInWithToken(token) { try { (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.checkArgs)([_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication, "#signInWithToken"], arguments, _util_validation__WEBPACK_IMPORTED_MODULE_13__.string); return this._httpGet("decode").addHeader((0,_network_HttpRequest__WEBPACK_IMPORTED_MODULE_11__.bearerAuthorization)(token)).send().then(this._updateStateFromHttpResponse(function (_ref) { var body = _ref.body; return { body: { token: token, user: body.data } }; }), this._notifyErrorFromHttpResponse.bind(this)); } catch (e) { return Promise.reject(e); } } }, { key: "signInAsGuest", value: function signInAsGuest() { try { (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.checkArgs)([_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication, "#signInAsGuest"], arguments); return this._httpPost("anonymous", "signin").addAuthContext().send().then(this._updateStateFromHttpResponse(), this._notifyErrorFromHttpResponse.bind(this)); } catch (e) { return Promise.reject(e); } } }, { key: "signInWithCredentials", value: function signInWithCredentials(provider, credentials) { try { (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.checkArgs)([_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication, "#signInWithCredentials"], arguments, _util_validation__WEBPACK_IMPORTED_MODULE_13__.string, _util_validation__WEBPACK_IMPORTED_MODULE_13__.object); return this._httpPost(provider, "signin").addAuthContext().addJson(credentials).send().then(this._updateStateFromHttpResponse(), this._notifyErrorFromHttpResponse.bind(this)); } catch (e) { return Promise.reject(e); } } }, { key: "sendOtp", value: function sendOtp(provider, id, message) { try { (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.checkArgs)([_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication, "#sendOtp"], arguments, _util_validation__WEBPACK_IMPORTED_MODULE_13__.string, _util_validation__WEBPACK_IMPORTED_MODULE_13__.string, (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.optional)(_util_validation__WEBPACK_IMPORTED_MODULE_13__.object)); return this._httpPost(provider, "otps").addQueryParameters(message).addJson(id).send().then(function (_ref2) { var body = _ref2.body; return body; }); } catch (e) { return Promise.reject(e); } } }, { key: "signInWithCustomProvider", value: function signInWithCustomProvider(provider, credentials) { try { (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.checkArgs)([_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication, "#signInWithCustomProvider"], arguments, _util_validation__WEBPACK_IMPORTED_MODULE_13__.string, _util_validation__WEBPACK_IMPORTED_MODULE_13__.string); return this._httpPost("custom.".concat(provider), "signin").addAuthContext().addForm({ token: credentials }).send().then(this._updateStateFromHttpResponse(), this._notifyErrorFromHttpResponse.bind(this)); } catch (e) { return Promise.reject(e); } } }, { key: "signInWithOAuth", value: function signInWithOAuth(provider) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; try { (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.checkArgs)([_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication, "#signInWithOAuth"], arguments, _util_validation__WEBPACK_IMPORTED_MODULE_13__.string, (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.optional)(_util_validation__WEBPACK_IMPORTED_MODULE_13__.object)); options.mode = options.mode || 'popup'; var mode = options.mode; if (mode === 'code') { return this._loginViaOAuthCode(provider, options); } else { return this._loginViaOAuth(provider, options); } } catch (e) { return Promise.reject(e); } } }, { key: "signInWithWassup", value: function signInWithWassup(options) { try { (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.checkArgs)([_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication, "#signInWithWassup"], arguments, _util_validation__WEBPACK_IMPORTED_MODULE_13__.object); return this._httpPost("wassup", "signin").addAuthContext().addForm(options).send().then(this._updateStateFromHttpResponse(), this._notifyErrorFromHttpResponse.bind(this)); } catch (e) { return Promise.reject(e); } } }, { key: "signOut", value: function signOut() { try { (0,_util_validation__WEBPACK_IMPORTED_MODULE_13__.checkArgs)([_api_Authentication__WEBPACK_IMPORTED_MODULE_4__._Authentication, "#signOut"], arguments); this.currentState = _api_Authentication__WEBPACK_IMPORTED_MODULE_4__.NO_AUTHENTICATION; return new Promise(function (resolve) { return (0,_dependencies_timeout__WEBPACK_IMPORTED_MODULE_5__.setTimeout)(function () { return resolve(); }); }); } catch (e) { return Promise.reject(e); } } }, { key: "_loginViaOAuthCode", value: function _loginViaOAuthCode(provider, options) { if (!options.code || !options.state) { this._logger.warn('authWithOAuth(): options.code or options.state is missing!'); } return this._httpGet(provider, "callback").addQueryParameters(options).send().then(this._updateStateFromHttpResponse(), this._notifyErrorFromHttpResponse.bind(this)); } }, { key: "_loginViaOAuth", value: function _loginViaOAuth(provider, options) { if (this_ongoingOAuthSession.call(this)) { return this._oauthSessionPromise || Promise.reject((0,_network_Errors__WEBPACK_IMPORTED_MODULE_6__.format)({ code: "ONGOING_OAUTH", message: "An OAuth authentication is already ongoing" })); } var redirectMode = !_dependencies_device__WEBPACK_IMPORTED_MODULE_12__.isWebBrowser || options.mode === "redirect" || _util_is__WEBPACK_IMPORTED_MODULE_9__.isSpecialBrowser(); options.token = this._contextAuthToken(); options.mode = "redirect"; if (!options.to && _dependencies_device__WEBPACK_IMPORTED_MODULE_12__.isWebBrowser) { options.to = location.href.replace(/[?&]__wcsession=[^&]