diff --git a/browser/components/BrowserGlue.jsm b/browser/components/BrowserGlue.jsm index bb20404e9d90..03f86f8d7e17 100644 --- a/browser/components/BrowserGlue.jsm +++ b/browser/components/BrowserGlue.jsm @@ -2023,45 +2023,6 @@ BrowserGlue.prototype = { }); }, - // Set up a listener to enable/disable the translation extension - // based on its preference. - _monitorTranslationsPref() { - const PREF = "extensions.translations.disabled"; - const ID = "firefox-translations@mozilla.org"; - const oldID = "firefox-infobar-ui-bergamot-browser-extension@browser.mt"; - - // First, try to uninstall the old extension, if exists. - (async () => { - let addon = await AddonManager.getAddonByID(oldID); - if (addon) { - addon.uninstall().catch(Cu.reportError); - } - })(); - - const _checkTranslationsPref = async () => { - let addon = await AddonManager.getAddonByID(ID); - let disabled = Services.prefs.getBoolPref(PREF, false); - if (!addon && disabled) { - // not installed, bail out early. - return; - } - if (!disabled) { - // first time install of addon and install on firefox update - addon = - (await AddonManager.maybeInstallBuiltinAddon( - ID, - "0.4.3", - "resource://builtin-addons/translations/" - )) || addon; - await addon.enable(); - } else if (addon) { - await addon.disable(); - } - }; - Services.prefs.addObserver(PREF, _checkTranslationsPref); - _checkTranslationsPref(); - }, - async _setupSearchDetection() { // There is no pref for this add-on because it shouldn't be disabled. const ID = "addons-search-detection@mozilla.com"; @@ -2332,9 +2293,6 @@ BrowserGlue.prototype = { this._monitorIonStudies(); this._setupSearchDetection(); - if (AppConstants.NIGHTLY_BUILD) { - this._monitorTranslationsPref(); - } this._monitorGPCPref(); this._monitorPrivacySegmentationPref(); }, diff --git a/browser/extensions/moz.build b/browser/extensions/moz.build index bd78a5c97041..0d4b9c356164 100644 --- a/browser/extensions/moz.build +++ b/browser/extensions/moz.build @@ -13,8 +13,3 @@ DIRS += [ "pictureinpicture", "search-detection", ] - -if CONFIG["NIGHTLY_BUILD"]: - DIRS += [ - "translations", - ] diff --git a/browser/extensions/translations/README b/browser/extensions/translations/README deleted file mode 100644 index 23a62413c45a..000000000000 --- a/browser/extensions/translations/README +++ /dev/null @@ -1,20 +0,0 @@ -This folder contains the source files for Firefox Translations, which utilizes -the proceedings from Project Bergamot [1]. - -The feature is developed as a webextension [2] which utilizes a neural machine -translation decoder [3] ported to WebAssembly in order to process the -in page translation. The translation models [4] are downloaded on-demand by the -extension, so there's no need to bundle them too. - -The folder `extension_src` contains the entire code of the extension's xpi and -the wasm module (which lies inside the folder wasm), and is automatically -generated by the `import_xpi.py` script, which is responsibile for cloning -the extension repo [2], build it, and generate the `jar.mn` package containing -all the pertinent files necessary for running it. - -For any questions, reach out to anatal@mozilla.com. - -[1] https://browser.mt/ -[2] https://github.com/mozilla-extensions/bergamot-browser-extension -[3] https://github.com/mozilla/bergamot-translator/ -[4] https://github.com/mozilla-applied-ml/bergamot-models diff --git a/browser/extensions/translations/extension/_locales/cs/messages.json b/browser/extensions/translations/extension/_locales/cs/messages.json deleted file mode 100644 index 0107ae4b62c8..000000000000 --- a/browser/extensions/translations/extension/_locales/cs/messages.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "extensionName": { - "message": "Firefox Translations", - "description": "Name of the extension" - }, - "extensionDescription": { - "message": "Neuronový strojový překlad v prohlížeči", - "description": "Description of the extension." - }, - "currentlyDownloadingTranslationEngine": { - "message": "Stahování překladače", - "description": "Informs the user that the translations feature is currently downloading the translation engine." - }, - "currentlyDownloadingLanguageModel": { - "message": "Stahování jazykového modelu", - "description": "Informs the user that the translations feature is currently downloading the language model files." - }, - "detailedDownloadProgress": { - "message": "Staženo $PERCENTAGE$ % z $MB$ MB", - "description": "Informs the user how the language model file downloading is progressing.", - "placeholders": { - "percentage": { - "content": "$1", - "example": "50" - }, - "mb": { - "content": "$2", - "example": "22,2" - } - } - }, - "currentlyLoadingLanguageModel": { - "message": "Načítání jazykového modelu", - "description": "Informs the user that the translations feature is currently loading the language model files into memory." - }, - "loadedLanguageModel": { - "message": "Jazykový model načten", - "description": "Informs the user that the translations feature has loaded the language model files into memory." - }, - "partsLeftToTranslate": { - "message": "Zbývající části k přeložení: $NUM$", - "description": "Informs the user that the translations feature has $NUM$ parts left to translate.", - "placeholders": { - "num": { - "content": "$1", - "example": "3" - } - } - } -} diff --git a/browser/extensions/translations/extension/_locales/de/messages.json b/browser/extensions/translations/extension/_locales/de/messages.json deleted file mode 100644 index eb77a82716d9..000000000000 --- a/browser/extensions/translations/extension/_locales/de/messages.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "extensionName": { - "message": "Firefox Translations", - "description": "Name of the extension" - }, - "extensionDescription": { - "message": "Neurale Maschine Übersetzung für den Browser.", - "description": "Description of the extension." - }, - "currentlyDownloadingTranslationEngine": { - "message": "Derzeit Download Übersetzungs-Engine", - "description": "Informs the user that the translations feature is currently downloading the translation engine." - }, - "currentlyDownloadingLanguageModel": { - "message": "Derzeit das Sprachmodell herunterladen", - "description": "Informs the user that the translations feature is currently downloading the language model files." - }, - "detailedDownloadProgress": { - "message": "$PERCENTAGE$% von $MB$ mb heruntergeladen", - "description": "Informs the user how the language model file downloading is progressing.", - "placeholders": { - "percentage": { - "content": "$1", - "example": "50" - }, - "mb": { - "content": "$2", - "example": "22.2" - } - } - }, - "currentlyLoadingLanguageModel": { - "message": "Derzeit ladende Sprachmodell", - "description": "Informs the user that the translations feature is currently loading the language model files into memory." - }, - "loadedLanguageModel": { - "message": "Sprachmodell geladen", - "description": "Informs the user that the translations feature has loaded the language model files into memory." - }, - "partsLeftToTranslate": { - "message": "Noch zu übersetzende Teile: $NUM$", - "description": "Informs the user that the translations feature has $NUM$ parts left to translate.", - "placeholders": { - "num": { - "content": "$1", - "example": "3" - } - } - } -} diff --git a/browser/extensions/translations/extension/_locales/en_US/messages.json b/browser/extensions/translations/extension/_locales/en_US/messages.json deleted file mode 100644 index a7998edada83..000000000000 --- a/browser/extensions/translations/extension/_locales/en_US/messages.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "extensionName": { - "message": "Firefox Translations", - "description": "Name of the extension" - }, - "extensionDescription": { - "message": "Neural Machine Translation for the browser.", - "description": "Description of the extension." - }, - "currentlyDownloadingTranslationEngine": { - "message": "Currently downloading translation engine", - "description": "Informs the user that the translations feature is currently downloading the translation engine." - }, - "currentlyDownloadingLanguageModel": { - "message": "Currently downloading language model", - "description": "Informs the user that the translations feature is currently downloading the language model files." - }, - "detailedDownloadProgress": { - "message": "$PERCENTAGE$% out of $MB$ mb downloaded", - "description": "Informs the user how the language model file downloading is progressing.", - "placeholders": { - "percentage": { - "content": "$1", - "example": "50" - }, - "mb": { - "content": "$2", - "example": "22.2" - } - } - }, - "currentlyLoadingLanguageModel": { - "message": "Currently loading language model", - "description": "Informs the user that the translations feature is currently loading the language model files into memory." - }, - "loadedLanguageModel": { - "message": "Language model loaded", - "description": "Informs the user that the translations feature has loaded the language model files into memory." - }, - "partsLeftToTranslate": { - "message": "Parts left to translate: $NUM$", - "description": "Informs the user that the translations feature has $NUM$ parts left to translate.", - "placeholders": { - "num": { - "content": "$1", - "example": "3" - } - } - } -} diff --git a/browser/extensions/translations/extension/_locales/es_ES/messages.json b/browser/extensions/translations/extension/_locales/es_ES/messages.json deleted file mode 100644 index 89c38e8bed49..000000000000 --- a/browser/extensions/translations/extension/_locales/es_ES/messages.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "extensionName": { - "message": "Firefox Translations", - "description": "Name of the extension" - }, - "extensionDescription": { - "message": "Traducción de la Máquina Neural para el navegador.", - "description": "Description of the extension." - }, - "currentlyDownloadingTranslationEngine": { - "message": "Motor de traducción de descarga", - "description": "Informs the user that the translations feature is currently downloading the translation engine." - }, - "currentlyDownloadingLanguageModel": { - "message": "Actualmente descargando el modelo de idioma", - "description": "Informs the user that the translations feature is currently downloading the language model files." - }, - "detailedDownloadProgress": { - "message": "$PERCENTAGE$% de $MB$ mb descargado", - "description": "Informs the user how the language model file downloading is progressing.", - "placeholders": { - "percentage": { - "content": "$1", - "example": "50" - }, - "mb": { - "content": "$2", - "example": "22.2" - } - } - }, - "currentlyLoadingLanguageModel": { - "message": "Actualmente cargar el modelo de idioma", - "description": "Informs the user that the translations feature is currently loading the language model files into memory." - }, - "loadedLanguageModel": { - "message": "Modelo de lenguaje cargado", - "description": "Informs the user that the translations feature has loaded the language model files into memory." - }, - "partsLeftToTranslate": { - "message": "Partes que quedan para traducir: $NUM$", - "description": "Informs the user that the translations feature has $NUM$ parts left to translate.", - "placeholders": { - "num": { - "content": "$1", - "example": "3" - } - } - } -} diff --git a/browser/extensions/translations/extension/_locales/et/messages.json b/browser/extensions/translations/extension/_locales/et/messages.json deleted file mode 100644 index 032269539f34..000000000000 --- a/browser/extensions/translations/extension/_locales/et/messages.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "extensionName": { - "message": "Firefox Translations", - "description": "Name of the extension" - }, - "extensionDescription": { - "message": "Neural Machine Translation brauseri jaoks.", - "description": "Description of the extension." - }, - "currentlyDownloadingTranslationEngine": { - "message": "Praegu laaditakse tõlkemootor", - "description": "Informs the user that the translations feature is currently downloading the translation engine." - }, - "currentlyDownloadingLanguageModel": { - "message": "Praegu allalaadimine keelemudel", - "description": "Informs the user that the translations feature is currently downloading the language model files." - }, - "detailedDownloadProgress": { - "message": "$PERCENTAGE$% $MB$ mb allalaaditud", - "description": "Informs the user how the language model file downloading is progressing.", - "placeholders": { - "percentage": { - "content": "$1", - "example": "50" - }, - "mb": { - "content": "$2", - "example": "22.2" - } - } - }, - "currentlyLoadingLanguageModel": { - "message": "Praegu laadiv keelemudel", - "description": "Informs the user that the translations feature is currently loading the language model files into memory." - }, - "loadedLanguageModel": { - "message": "Keelemudel koormatud", - "description": "Informs the user that the translations feature has loaded the language model files into memory." - }, - "partsLeftToTranslate": { - "message": "Osad jätta tõlkida: $NUM$", - "description": "Informs the user that the translations feature has $NUM$ parts left to translate.", - "placeholders": { - "num": { - "content": "$1", - "example": "3" - } - } - } -} diff --git a/browser/extensions/translations/extension/_locales/ru/messages.json b/browser/extensions/translations/extension/_locales/ru/messages.json deleted file mode 100644 index 8212a54260c6..000000000000 --- a/browser/extensions/translations/extension/_locales/ru/messages.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "extensionName": { - "message": "Firefox Translations", - "description": "Name of the extension" - }, - "extensionDescription": { - "message": "Нейронный машинный перевод для браузера.", - "description": "Description of the extension." - }, - "currentlyDownloadingTranslationEngine": { - "message": "Скачивание движка перевода", - "description": "Informs the user that the translations feature is currently downloading the translation engine." - }, - "currentlyDownloadingLanguageModel": { - "message": "Скачивание языковой модели", - "description": "Informs the user that the translations feature is currently downloading the language model files." - }, - "detailedDownloadProgress": { - "message": "$PERCENTAGE$% из $MB$ МБ загружено", - "description": "Informs the user how the language model file downloading is progressing.", - "placeholders": { - "percentage": { - "content": "$1", - "example": "50" - }, - "mb": { - "content": "$2", - "example": "22.2" - } - } - }, - "currentlyLoadingLanguageModel": { - "message": "Загрузка языковой модели", - "description": "Informs the user that the translations feature is currently loading the language model files into memory." - }, - "loadedLanguageModel": { - "message": "Языковая модель загружена", - "description": "Informs the user that the translations feature has loaded the language model files into memory." - }, - "partsLeftToTranslate": { - "message": "Осталось частей для перевода: $NUM$", - "description": "Informs the user that the translations feature has $NUM$ parts left to translate.", - "placeholders": { - "num": { - "content": "$1", - "example": "3" - } - } - } -} diff --git a/browser/extensions/translations/extension/background.js b/browser/extensions/translations/extension/background.js deleted file mode 100644 index f42d8205737c..000000000000 --- a/browser/extensions/translations/extension/background.js +++ /dev/null @@ -1,10882 +0,0 @@ -/******/ (() => { // webpackBootstrap -/******/ var __webpack_modules__ = ({ - -/***/ 7882: -/*!***********************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/core/constants.js ***! - \***********************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Oo": () => (/* binding */ GLEAN_SCHEMA_VERSION), -/* harmony export */ "Q9": () => (/* binding */ GLEAN_VERSION), -/* harmony export */ "ni": () => (/* binding */ PING_INFO_STORAGE), -/* harmony export */ "xW": () => (/* binding */ CLIENT_INFO_STORAGE), -/* harmony export */ "Ei": () => (/* binding */ KNOWN_CLIENT_ID), -/* harmony export */ "ey": () => (/* binding */ DEFAULT_TELEMETRY_ENDPOINT), -/* harmony export */ "Ui": () => (/* binding */ DELETION_REQUEST_PING_NAME), -/* harmony export */ "og": () => (/* binding */ GLEAN_MAX_SOURCE_TAGS) -/* harmony export */ }); -const GLEAN_SCHEMA_VERSION = 1; -const GLEAN_VERSION = "0.15.0"; -const PING_INFO_STORAGE = "glean_ping_info"; -const CLIENT_INFO_STORAGE = "glean_client_info"; -const KNOWN_CLIENT_ID = "c0ffeec0-ffee-c0ff-eec0-ffeec0ffeec0"; -const DEFAULT_TELEMETRY_ENDPOINT = "https://incoming.telemetry.mozilla.org"; -const DELETION_REQUEST_PING_NAME = "deletion-request"; -const GLEAN_MAX_SOURCE_TAGS = 5; - - -/***/ }), - -/***/ 5639: -/*!*********************************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/core/context.js + 1 modules ***! - \*********************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "_": () => (/* binding */ Context) -}); - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/dispatcher.js -var DispatcherState; -(function (DispatcherState) { - DispatcherState[DispatcherState["Uninitialized"] = 0] = "Uninitialized"; - DispatcherState[DispatcherState["Idle"] = 1] = "Idle"; - DispatcherState[DispatcherState["Processing"] = 2] = "Processing"; - DispatcherState[DispatcherState["Stopped"] = 3] = "Stopped"; -})(DispatcherState || (DispatcherState = {})); -var Commands; -(function (Commands) { - Commands[Commands["Task"] = 0] = "Task"; - Commands[Commands["Stop"] = 1] = "Stop"; - Commands[Commands["Clear"] = 2] = "Clear"; - Commands[Commands["TestTask"] = 3] = "TestTask"; -})(Commands || (Commands = {})); -class Dispatcher { - constructor(maxPreInitQueueSize = 100) { - this.maxPreInitQueueSize = maxPreInitQueueSize; - this.queue = []; - this.state = 0; - } - getNextCommand() { - return this.queue.shift(); - } - async executeTask(task) { - try { - await task(); - } - catch (e) { - console.error("Error executing task:", e); - } - } - async execute() { - let nextCommand = this.getNextCommand(); - while (nextCommand) { - switch (nextCommand.command) { - case (1): - this.state = 3; - return; - case (2): - this.queue.forEach(c => { - if (c.command === 3) { - c.resolver(); - } - }); - this.queue = []; - this.state = 3; - return; - case (3): - await this.executeTask(nextCommand.task); - nextCommand.resolver(); - nextCommand = this.getNextCommand(); - continue; - case (0): - await this.executeTask(nextCommand.task); - nextCommand = this.getNextCommand(); - } - } - } - triggerExecution() { - if (this.state === 1 && this.queue.length > 0) { - this.state = 2; - this.currentJob = this.execute(); - this.currentJob - .then(() => { - this.currentJob = undefined; - if (this.state === 2) { - this.state = 1; - } - }) - .catch(error => { - console.error("IMPOSSIBLE: Something went wrong while the dispatcher was executing the tasks queue.", error); - }); - } - } - launchInternal(command, priorityTask = false) { - if (!priorityTask && this.state === 0) { - if (this.queue.length >= this.maxPreInitQueueSize) { - console.warn("Unable to enqueue task, pre init queue is full."); - return false; - } - } - if (priorityTask) { - this.queue.unshift(command); - } - else { - this.queue.push(command); - } - this.triggerExecution(); - return true; - } - launch(task) { - this.launchInternal({ - task, - command: 0 - }); - } - flushInit(task) { - if (this.state !== 0) { - console.warn("Attempted to initialize the Dispatcher, but it is already initialized. Ignoring."); - return; - } - if (task) { - this.launchInternal({ - task, - command: 0 - }, true); - } - this.state = 1; - this.triggerExecution(); - } - clear() { - this.launchInternal({ command: 2 }, true); - this.resume(); - } - stop() { - this.launchInternal({ command: 1 }, true); - } - resume() { - if (this.state === 3) { - this.state = 1; - this.triggerExecution(); - } - } - async testBlockOnQueue() { - return this.currentJob && await this.currentJob; - } - async testUninitialize() { - if (this.state === 0) { - return; - } - this.clear(); - await this.testBlockOnQueue(); - this.state = 0; - } - testLaunch(task) { - return new Promise((resolver, reject) => { - this.resume(); - const wasLaunched = this.launchInternal({ - resolver, - task, - command: 3 - }); - if (!wasLaunched) { - reject(); - } - }); - } -} -/* harmony default export */ const dispatcher = (Dispatcher); - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/context.js - -class Context { - constructor() { - this._initialized = false; - } - static get instance() { - if (!Context._instance) { - Context._instance = new Context(); - } - return Context._instance; - } - static async testUninitialize() { - if (Context.instance._dispatcher) { - await Context.instance._dispatcher.testUninitialize(); - } - Context.instance._dispatcher = null; - Context.initialized = false; - } - static get dispatcher() { - if (!Context.instance._dispatcher) { - Context.instance._dispatcher = new dispatcher(); - } - return Context.instance._dispatcher; - } - static set dispatcher(dispatcher) { - Context.instance._dispatcher = dispatcher; - } - static get uploadEnabled() { - return Context.instance._uploadEnabled; - } - static set uploadEnabled(upload) { - Context.instance._uploadEnabled = upload; - } - static get metricsDatabase() { - return Context.instance._metricsDatabase; - } - static set metricsDatabase(db) { - Context.instance._metricsDatabase = db; - } - static get eventsDatabase() { - return Context.instance._eventsDatabase; - } - static set eventsDatabase(db) { - Context.instance._eventsDatabase = db; - } - static get pingsDatabase() { - return Context.instance._pingsDatabase; - } - static set pingsDatabase(db) { - Context.instance._pingsDatabase = db; - } - static get errorManager() { - return Context.instance._errorManager; - } - static set errorManager(db) { - Context.instance._errorManager = db; - } - static get applicationId() { - return Context.instance._applicationId; - } - static set applicationId(id) { - Context.instance._applicationId = id; - } - static get initialized() { - return Context.instance._initialized; - } - static set initialized(init) { - Context.instance._initialized = init; - } - static get debugOptions() { - return Context.instance._debugOptions; - } - static set debugOptions(options) { - Context.instance._debugOptions = options; - } -} - - -/***/ }), - -/***/ 4511: -/*!******************************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/core/error/error_type.js ***! - \******************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "N": () => (/* binding */ ErrorType) -/* harmony export */ }); -var ErrorType; -(function (ErrorType) { - ErrorType["InvalidValue"] = "invalid_value"; - ErrorType["InvalidLabel"] = "invalid_label"; - ErrorType["InvalidState"] = "invalid_state"; - ErrorType["InvalidOverflow"] = "invalid_overflow"; -})(ErrorType || (ErrorType = {})); - - -/***/ }), - -/***/ 5318: -/*!**************************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/core/events/index.js ***! - \**************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Z": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* unused harmony export CoreEvent */ -class CoreEvent { - constructor(name) { - this.name = name; - } - get registeredPluginIdentifier() { - var _a; - return (_a = this.plugin) === null || _a === void 0 ? void 0 : _a.name; - } - registerPlugin(plugin) { - if (this.plugin) { - console.error(`Attempted to register plugin '${plugin.name}', which listens to the event '${plugin.event}'.`, `That event is already watched by plugin '${this.plugin.name}'`, `Plugin '${plugin.name}' will be ignored.`); - return; - } - this.plugin = plugin; - } - deregisterPlugin() { - this.plugin = undefined; - } - trigger(...args) { - if (this.plugin) { - return this.plugin.action(...args); - } - } -} -const CoreEvents = { - afterPingCollection: new CoreEvent("afterPingCollection") -}; -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (CoreEvents); - - -/***/ }), - -/***/ 245: -/*!*************************************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/core/metrics/events_database.js ***! - \*************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "K": () => (/* binding */ RecordedEvent), -/* harmony export */ "Z": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ 6379); - -class RecordedEvent { - constructor(category, name, timestamp, extra) { - this.category = category; - this.name = name; - this.timestamp = timestamp; - this.extra = extra; - } - static toJSONObject(e) { - return { - "category": e.category, - "name": e.name, - "timestamp": e.timestamp, - "extra": e.extra, - }; - } - static fromJSONObject(e) { - return new RecordedEvent(e["category"], e["name"], e["timestamp"], e["extra"]); - } -} -class EventsDatabase { - constructor(storage) { - this.eventsStore = new storage("events"); - } - async record(metric, value) { - if (metric.disabled) { - return; - } - for (const ping of metric.sendInPings) { - const transformFn = (v) => { - var _a; - const existing = (_a = v) !== null && _a !== void 0 ? _a : []; - existing.push(RecordedEvent.toJSONObject(value)); - return existing; - }; - await this.eventsStore.update([ping], transformFn); - } - } - async getEvents(ping, metric) { - const events = await this.getAndValidatePingData(ping); - if (events.length === 0) { - return; - } - return events - .filter((e) => { - return (e.category === metric.category) && (e.name === metric.name); - }); - } - async getAndValidatePingData(ping) { - const data = await this.eventsStore.get([ping]); - if ((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .isUndefined */ .o8)(data)) { - return []; - } - if (!Array.isArray(data)) { - console.error(`Unexpected value found for ping ${ping}: ${JSON.stringify(data)}. Clearing.`); - await this.eventsStore.delete([ping]); - return []; - } - return data.map((e) => RecordedEvent.fromJSONObject(e)); - } - async getPingEvents(ping, clearPingLifetimeData) { - const pingData = await this.getAndValidatePingData(ping); - if (clearPingLifetimeData) { - await this.eventsStore.delete([ping]); - } - if (pingData.length === 0) { - return; - } - const sortedData = pingData.sort((a, b) => { - return a.timestamp - b.timestamp; - }); - const firstTimestamp = sortedData[0].timestamp; - return sortedData.map((e) => { - const adjusted = RecordedEvent.toJSONObject(e); - adjusted["timestamp"] = e.timestamp - firstTimestamp; - return adjusted; - }); - } - async clearAll() { - await this.eventsStore.delete([]); - } -} -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (EventsDatabase); - - -/***/ }), - -/***/ 1486: -/*!***************************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/core/metrics/index.js ***! - \***************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "t": () => (/* binding */ MetricType) -/* harmony export */ }); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils.js */ 6379); -/* harmony import */ var _types_labeled_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./types/labeled.js */ 1209); -/* harmony import */ var _context_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../context.js */ 5639); - - - -class MetricType { - constructor(type, meta) { - this.type = type; - this.name = meta.name; - this.category = meta.category; - this.sendInPings = meta.sendInPings; - this.lifetime = meta.lifetime; - this.disabled = meta.disabled; - this.dynamicLabel = meta.dynamicLabel; - } - baseIdentifier() { - if (this.category.length > 0) { - return `${this.category}.${this.name}`; - } - else { - return this.name; - } - } - async identifier(metricsDatabase) { - const baseIdentifier = this.baseIdentifier(); - if (!(0,_utils_js__WEBPACK_IMPORTED_MODULE_0__/* .isUndefined */ .o8)(this.dynamicLabel)) { - return await (0,_types_labeled_js__WEBPACK_IMPORTED_MODULE_1__/* .getValidDynamicLabel */ .qd)(metricsDatabase, this); - } - else { - return baseIdentifier; - } - } - shouldRecord(uploadEnabled) { - return (uploadEnabled && !this.disabled); - } - async testGetNumRecordedErrors(errorType, ping = this.sendInPings[0]) { - return _context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.errorManager.testGetNumRecordedErrors */ ._.errorManager.testGetNumRecordedErrors(this, errorType, ping); - } -} - - -/***/ }), - -/***/ 1977: -/*!****************************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/core/metrics/metric.js ***! - \****************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "j": () => (/* binding */ Metric) -/* harmony export */ }); -class Metric { - constructor(v) { - if (!this.validate(v)) { - throw new Error("Unable to create new Metric instance, values is in unexpected format."); - } - this._inner = v; - } - get() { - return this._inner; - } - set(v) { - if (!this.validate(v)) { - console.error(`Unable to set metric to ${JSON.stringify(v)}. Value is in unexpected format. Ignoring.`); - return; - } - this._inner = v; - } -} - - -/***/ }), - -/***/ 8899: -/*!*******************************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/core/metrics/time_unit.js ***! - \*******************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Z": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -var TimeUnit; -(function (TimeUnit) { - TimeUnit["Nanosecond"] = "nanosecond"; - TimeUnit["Microsecond"] = "microsecond"; - TimeUnit["Millisecond"] = "millisecond"; - TimeUnit["Second"] = "second"; - TimeUnit["Minute"] = "minute"; - TimeUnit["Hour"] = "hour"; - TimeUnit["Day"] = "day"; -})(TimeUnit || (TimeUnit = {})); -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (TimeUnit); - - -/***/ }), - -/***/ 499: -/*!***********************************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/core/metrics/types/counter.js ***! - \***********************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "CounterMetric": () => (/* binding */ CounterMetric), -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../index.js */ 1486); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils.js */ 6379); -/* harmony import */ var _context_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../context.js */ 5639); -/* harmony import */ var _metric_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../metric.js */ 1977); -/* harmony import */ var _error_error_type_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../error/error_type.js */ 4511); - - - - - -class CounterMetric extends _metric_js__WEBPACK_IMPORTED_MODULE_4__/* .Metric */ .j { - constructor(v) { - super(v); - } - validate(v) { - if (!(0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .isInteger */ .U)(v)) { - return false; - } - if (v <= 0) { - return false; - } - return true; - } - payload() { - return this._inner; - } -} -class CounterMetricType extends _index_js__WEBPACK_IMPORTED_MODULE_0__/* .MetricType */ .t { - constructor(meta) { - super("counter", meta); - } - static async _private_addUndispatched(instance, amount) { - if (!instance.shouldRecord(_context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.uploadEnabled */ ._.uploadEnabled)) { - return; - } - if ((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .isUndefined */ .o8)(amount)) { - amount = 1; - } - if (amount <= 0) { - await _context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.errorManager.record */ ._.errorManager.record(instance, _error_error_type_js__WEBPACK_IMPORTED_MODULE_3__/* .ErrorType.InvalidValue */ .N.InvalidValue, `Added negative and zero value ${amount}`); - return; - } - const transformFn = ((amount) => { - return (v) => { - let metric; - let result; - try { - metric = new CounterMetric(v); - result = metric.get() + amount; - } - catch (_a) { - metric = new CounterMetric(amount); - result = amount; - } - if (result > Number.MAX_SAFE_INTEGER) { - result = Number.MAX_SAFE_INTEGER; - } - metric.set(result); - return metric; - }; - })(amount); - await _context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.metricsDatabase.transform */ ._.metricsDatabase.transform(instance, transformFn); - } - add(amount) { - _context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.dispatcher.launch */ ._.dispatcher.launch(async () => CounterMetricType._private_addUndispatched(this, amount)); - } - async testGetValue(ping = this.sendInPings[0]) { - let metric; - await _context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.dispatcher.testLaunch */ ._.dispatcher.testLaunch(async () => { - metric = await _context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.metricsDatabase.getMetric */ ._.metricsDatabase.getMetric(ping, this); - }); - return metric; - } -} -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (CounterMetricType); - - -/***/ }), - -/***/ 7626: -/*!************************************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/core/metrics/types/datetime.js ***! - \************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "ui": () => (/* binding */ DatetimeMetric), -/* harmony export */ "ZP": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* unused harmony export formatTimezoneOffset */ -/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../index.js */ 1486); -/* harmony import */ var _metrics_time_unit_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../metrics/time_unit.js */ 8899); -/* harmony import */ var _context_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../context.js */ 5639); -/* harmony import */ var _metric_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../metric.js */ 1977); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../utils.js */ 6379); - - - - - -function formatTimezoneOffset(timezone) { - const offset = (timezone / 60) * -1; - const sign = offset > 0 ? "+" : "-"; - const hours = Math.abs(offset).toString().padStart(2, "0"); - return `${sign}${hours}:00`; -} -class DatetimeMetric extends _metric_js__WEBPACK_IMPORTED_MODULE_4__/* .Metric */ .j { - constructor(v) { - super(v); - } - static fromDate(v, timeUnit) { - return new DatetimeMetric({ - timeUnit, - timezone: v.getTimezoneOffset(), - date: v.toISOString() - }); - } - get date() { - return new Date(this._inner.date); - } - get timezone() { - return this._inner.timezone; - } - get timeUnit() { - return this._inner.timeUnit; - } - get dateISOString() { - return this._inner.date; - } - validate(v) { - if (!(0,_utils_js__WEBPACK_IMPORTED_MODULE_3__/* .isObject */ .Kn)(v) || Object.keys(v).length !== 3) { - return false; - } - const timeUnitVerification = "timeUnit" in v && (0,_utils_js__WEBPACK_IMPORTED_MODULE_3__/* .isString */ .HD)(v.timeUnit) && Object.values(_metrics_time_unit_js__WEBPACK_IMPORTED_MODULE_1__/* .default */ .Z).includes(v.timeUnit); - const timezoneVerification = "timezone" in v && (0,_utils_js__WEBPACK_IMPORTED_MODULE_3__/* .isNumber */ .hj)(v.timezone); - const dateVerification = "date" in v && (0,_utils_js__WEBPACK_IMPORTED_MODULE_3__/* .isString */ .HD)(v.date) && v.date.length === 24 && !isNaN(Date.parse(v.date)); - if (!timeUnitVerification || !timezoneVerification || !dateVerification) { - return false; - } - return true; - } - payload() { - const extractedDateInfo = this.dateISOString.match(/\d+/g); - if (!extractedDateInfo || extractedDateInfo.length < 0) { - throw new Error("IMPOSSIBLE: Unable to extract date information from DatetimeMetric."); - } - const correctedDate = new Date(parseInt(extractedDateInfo[0]), parseInt(extractedDateInfo[1]) - 1, parseInt(extractedDateInfo[2]), parseInt(extractedDateInfo[3]) - (this.timezone / 60), parseInt(extractedDateInfo[4]), parseInt(extractedDateInfo[5]), parseInt(extractedDateInfo[6])); - const timezone = formatTimezoneOffset(this.timezone); - const year = correctedDate.getFullYear().toString().padStart(2, "0"); - const month = (correctedDate.getMonth() + 1).toString().padStart(2, "0"); - const day = correctedDate.getDate().toString().padStart(2, "0"); - if (this.timeUnit === _metrics_time_unit_js__WEBPACK_IMPORTED_MODULE_1__/* .default.Day */ .Z.Day) { - return `${year}-${month}-${day}${timezone}`; - } - const hours = correctedDate.getHours().toString().padStart(2, "0"); - if (this.timeUnit === _metrics_time_unit_js__WEBPACK_IMPORTED_MODULE_1__/* .default.Hour */ .Z.Hour) { - return `${year}-${month}-${day}T${hours}${timezone}`; - } - const minutes = correctedDate.getMinutes().toString().padStart(2, "0"); - if (this.timeUnit === _metrics_time_unit_js__WEBPACK_IMPORTED_MODULE_1__/* .default.Minute */ .Z.Minute) { - return `${year}-${month}-${day}T${hours}:${minutes}${timezone}`; - } - const seconds = correctedDate.getSeconds().toString().padStart(2, "0"); - if (this.timeUnit === _metrics_time_unit_js__WEBPACK_IMPORTED_MODULE_1__/* .default.Second */ .Z.Second) { - return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}${timezone}`; - } - const milliseconds = correctedDate.getMilliseconds().toString().padStart(3, "0"); - if (this.timeUnit === _metrics_time_unit_js__WEBPACK_IMPORTED_MODULE_1__/* .default.Millisecond */ .Z.Millisecond) { - return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}${timezone}`; - } - if (this.timeUnit === _metrics_time_unit_js__WEBPACK_IMPORTED_MODULE_1__/* .default.Microsecond */ .Z.Microsecond) { - return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}000${timezone}`; - } - return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}000000${timezone}`; - } -} -class DatetimeMetricType extends _index_js__WEBPACK_IMPORTED_MODULE_0__/* .MetricType */ .t { - constructor(meta, timeUnit) { - super("datetime", meta); - this.timeUnit = timeUnit; - } - static async _private_setUndispatched(instance, value) { - if (!instance.shouldRecord(_context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.uploadEnabled */ ._.uploadEnabled)) { - return; - } - if (!value) { - value = new Date(); - } - const truncatedDate = value; - switch (instance.timeUnit) { - case (_metrics_time_unit_js__WEBPACK_IMPORTED_MODULE_1__/* .default.Day */ .Z.Day): - truncatedDate.setMilliseconds(0); - truncatedDate.setSeconds(0); - truncatedDate.setMinutes(0); - truncatedDate.setMilliseconds(0); - case (_metrics_time_unit_js__WEBPACK_IMPORTED_MODULE_1__/* .default.Hour */ .Z.Hour): - truncatedDate.setMilliseconds(0); - truncatedDate.setSeconds(0); - truncatedDate.setMinutes(0); - case (_metrics_time_unit_js__WEBPACK_IMPORTED_MODULE_1__/* .default.Minute */ .Z.Minute): - truncatedDate.setMilliseconds(0); - truncatedDate.setSeconds(0); - case (_metrics_time_unit_js__WEBPACK_IMPORTED_MODULE_1__/* .default.Second */ .Z.Second): - truncatedDate.setMilliseconds(0); - default: - break; - } - const metric = DatetimeMetric.fromDate(value, instance.timeUnit); - await _context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.metricsDatabase.record */ ._.metricsDatabase.record(instance, metric); - } - set(value) { - _context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.dispatcher.launch */ ._.dispatcher.launch(() => DatetimeMetricType._private_setUndispatched(this, value)); - } - async testGetValueAsDatetimeMetric(ping) { - let value; - await _context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.dispatcher.testLaunch */ ._.dispatcher.testLaunch(async () => { - value = await _context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.metricsDatabase.getMetric */ ._.metricsDatabase.getMetric(ping, this); - }); - if (value) { - return new DatetimeMetric(value); - } - } - async testGetValueAsString(ping = this.sendInPings[0]) { - const metric = await this.testGetValueAsDatetimeMetric(ping); - return metric ? metric.payload() : undefined; - } - async testGetValue(ping = this.sendInPings[0]) { - const metric = await this.testGetValueAsDatetimeMetric(ping); - return metric ? metric.date : undefined; - } -} -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (DatetimeMetricType); - - -/***/ }), - -/***/ 2178: -/*!*********************************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/core/metrics/types/event.js ***! - \*********************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../index.js */ 1486); -/* harmony import */ var _events_database_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events_database.js */ 245); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils.js */ 6379); -/* harmony import */ var _context_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../context.js */ 5639); -/* harmony import */ var _error_error_type_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../error/error_type.js */ 4511); - - - - - -const MAX_LENGTH_EXTRA_KEY_VALUE = 100; -class EventMetricType extends _index_js__WEBPACK_IMPORTED_MODULE_0__/* .MetricType */ .t { - constructor(meta, allowedExtraKeys) { - super("event", meta); - this.allowedExtraKeys = allowedExtraKeys; - } - record(extra) { - _context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.dispatcher.launch */ ._.dispatcher.launch(async () => { - if (!this.shouldRecord(_context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.uploadEnabled */ ._.uploadEnabled)) { - return; - } - const timestamp = (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__/* .getMonotonicNow */ .ts)(); - let truncatedExtra = undefined; - if (extra && this.allowedExtraKeys) { - truncatedExtra = {}; - for (const [name, value] of Object.entries(extra)) { - if (this.allowedExtraKeys.includes(name)) { - truncatedExtra[name] = await (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__/* .truncateStringAtBoundaryWithError */ .hY)(this, value, MAX_LENGTH_EXTRA_KEY_VALUE); - } - else { - await _context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.errorManager.record */ ._.errorManager.record(this, _error_error_type_js__WEBPACK_IMPORTED_MODULE_4__/* .ErrorType.InvalidValue */ .N.InvalidValue, `Invalid key index: ${name}`); - continue; - } - } - } - const event = new _events_database_js__WEBPACK_IMPORTED_MODULE_1__/* .RecordedEvent */ .K(this.category, this.name, timestamp, truncatedExtra); - await _context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.eventsDatabase.record */ ._.eventsDatabase.record(this, event); - }); - } - async testGetValue(ping = this.sendInPings[0]) { - let events; - await _context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.dispatcher.testLaunch */ ._.dispatcher.testLaunch(async () => { - events = await _context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.eventsDatabase.getEvents */ ._.eventsDatabase.getEvents(ping, this); - }); - return events; - } -} -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (EventMetricType); - - -/***/ }), - -/***/ 1209: -/*!***********************************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/core/metrics/types/labeled.js ***! - \***********************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Dc": () => (/* binding */ LabeledMetric), -/* harmony export */ "lb": () => (/* binding */ combineIdentifierAndLabel), -/* harmony export */ "ho": () => (/* binding */ stripLabel), -/* harmony export */ "qd": () => (/* binding */ getValidDynamicLabel) -/* harmony export */ }); -/* unused harmony export OTHER_LABEL */ -/* harmony import */ var _metric_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../metric.js */ 1977); -/* harmony import */ var _context_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../context.js */ 5639); -/* harmony import */ var _error_error_type_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../error/error_type.js */ 4511); - - - -class LabeledMetric extends _metric_js__WEBPACK_IMPORTED_MODULE_2__/* .Metric */ .j { - constructor(v) { - super(v); - } - validate(v) { - return true; - } - payload() { - return this._inner; - } -} -const MAX_LABELS = 16; -const MAX_LABEL_LENGTH = 61; -const OTHER_LABEL = "__other__"; -const LABEL_REGEX = /^[a-z_][a-z0-9_-]{0,29}(\.[a-z_][a-z0-9_-]{0,29})*$/; -function combineIdentifierAndLabel(metricName, label) { - return `${metricName}/${label}`; -} -function stripLabel(identifier) { - return identifier.split("/")[0]; -} -async function getValidDynamicLabel(metricsDatabase, metric) { - if (metric.dynamicLabel === undefined) { - throw new Error("This point should never be reached."); - } - const key = combineIdentifierAndLabel(metric.baseIdentifier(), metric.dynamicLabel); - for (const ping of metric.sendInPings) { - if (await metricsDatabase.hasMetric(metric.lifetime, ping, metric.type, key)) { - return key; - } - } - let numUsedKeys = 0; - for (const ping of metric.sendInPings) { - numUsedKeys += await metricsDatabase.countByBaseIdentifier(metric.lifetime, ping, metric.type, metric.baseIdentifier()); - } - let hitError = false; - if (numUsedKeys >= MAX_LABELS) { - hitError = true; - } - else if (metric.dynamicLabel.length > MAX_LABEL_LENGTH) { - hitError = true; - await _context_js__WEBPACK_IMPORTED_MODULE_0__/* .Context.errorManager.record */ ._.errorManager.record(metric, _error_error_type_js__WEBPACK_IMPORTED_MODULE_1__/* .ErrorType.InvalidLabel */ .N.InvalidLabel, `Label length ${metric.dynamicLabel.length} exceeds maximum of ${MAX_LABEL_LENGTH}.`); - } - else if (!LABEL_REGEX.test(metric.dynamicLabel)) { - hitError = true; - await _context_js__WEBPACK_IMPORTED_MODULE_0__/* .Context.errorManager.record */ ._.errorManager.record(metric, _error_error_type_js__WEBPACK_IMPORTED_MODULE_1__/* .ErrorType.InvalidLabel */ .N.InvalidLabel, `Label must be snake_case, got '${metric.dynamicLabel}'.`); - } - return (hitError) - ? combineIdentifierAndLabel(metric.baseIdentifier(), OTHER_LABEL) - : key; -} -class LabeledMetricType { - constructor(meta, submetric, labels) { - return new Proxy(this, { - get: (_target, label) => { - if (labels) { - return LabeledMetricType.createFromStaticLabel(meta, submetric, labels, label); - } - return LabeledMetricType.createFromDynamicLabel(meta, submetric, label); - } - }); - } - static createFromStaticLabel(meta, submetricClass, allowedLabels, label) { - const adjustedLabel = allowedLabels.includes(label) ? label : OTHER_LABEL; - const newMeta = { - ...meta, - name: combineIdentifierAndLabel(meta.name, adjustedLabel) - }; - return new submetricClass(newMeta); - } - static createFromDynamicLabel(meta, submetricClass, label) { - const newMeta = { - ...meta, - dynamicLabel: label - }; - return new submetricClass(newMeta); - } -} -/* unused harmony default export */ var __WEBPACK_DEFAULT_EXPORT__ = ((/* unused pure expression or super */ null && (LabeledMetricType))); - - -/***/ }), - -/***/ 4717: -/*!************************************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/core/metrics/types/quantity.js ***! - \************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "QuantityMetric": () => (/* binding */ QuantityMetric), -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../index.js */ 1486); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../utils.js */ 6379); -/* harmony import */ var _context_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../context.js */ 5639); -/* harmony import */ var _metric_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../metric.js */ 1977); -/* harmony import */ var _error_error_type_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../error/error_type.js */ 4511); - - - - - -class QuantityMetric extends _metric_js__WEBPACK_IMPORTED_MODULE_4__/* .Metric */ .j { - constructor(v) { - super(v); - } - validate(v) { - if (!(0,_utils_js__WEBPACK_IMPORTED_MODULE_1__/* .isInteger */ .U)(v)) { - return false; - } - if (v < 0) { - return false; - } - return true; - } - payload() { - return this._inner; - } -} -class QuantityMetricType extends _index_js__WEBPACK_IMPORTED_MODULE_0__/* .MetricType */ .t { - constructor(meta) { - super("quantity", meta); - } - static async _private_setUndispatched(instance, value) { - if (!instance.shouldRecord(_context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.uploadEnabled */ ._.uploadEnabled)) { - return; - } - if (value < 0) { - await _context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.errorManager.record */ ._.errorManager.record(instance, _error_error_type_js__WEBPACK_IMPORTED_MODULE_3__/* .ErrorType.InvalidValue */ .N.InvalidValue, `Set negative value ${value}`); - return; - } - if (value > Number.MAX_SAFE_INTEGER) { - value = Number.MAX_SAFE_INTEGER; - } - const metric = new QuantityMetric(value); - await _context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.metricsDatabase.record */ ._.metricsDatabase.record(instance, metric); - } - set(value) { - _context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.dispatcher.launch */ ._.dispatcher.launch(() => QuantityMetricType._private_setUndispatched(this, value)); - } - async testGetValue(ping = this.sendInPings[0]) { - let metric; - await _context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.dispatcher.testLaunch */ ._.dispatcher.testLaunch(async () => { - metric = await _context_js__WEBPACK_IMPORTED_MODULE_2__/* .Context.metricsDatabase.getMetric */ ._.metricsDatabase.getMetric(ping, this); - }); - return metric; - } -} -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (QuantityMetricType); - - -/***/ }), - -/***/ 4245: -/*!**********************************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/core/metrics/types/string.js ***! - \**********************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "MAX_LENGTH_VALUE": () => (/* binding */ MAX_LENGTH_VALUE), -/* harmony export */ "StringMetric": () => (/* binding */ StringMetric), -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../index.js */ 1486); -/* harmony import */ var _context_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../context.js */ 5639); -/* harmony import */ var _metric_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../metric.js */ 1977); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils.js */ 6379); - - - - -const MAX_LENGTH_VALUE = 100; -class StringMetric extends _metric_js__WEBPACK_IMPORTED_MODULE_3__/* .Metric */ .j { - constructor(v) { - super(v); - } - validate(v) { - if (!(0,_utils_js__WEBPACK_IMPORTED_MODULE_2__/* .isString */ .HD)(v)) { - return false; - } - if (v.length > MAX_LENGTH_VALUE) { - return false; - } - return true; - } - payload() { - return this._inner; - } -} -class StringMetricType extends _index_js__WEBPACK_IMPORTED_MODULE_0__/* .MetricType */ .t { - constructor(meta) { - super("string", meta); - } - static async _private_setUndispatched(instance, value) { - if (!instance.shouldRecord(_context_js__WEBPACK_IMPORTED_MODULE_1__/* .Context.uploadEnabled */ ._.uploadEnabled)) { - return; - } - const truncatedValue = await (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__/* .truncateStringAtBoundaryWithError */ .hY)(instance, value, MAX_LENGTH_VALUE); - const metric = new StringMetric(truncatedValue); - await _context_js__WEBPACK_IMPORTED_MODULE_1__/* .Context.metricsDatabase.record */ ._.metricsDatabase.record(instance, metric); - } - set(value) { - _context_js__WEBPACK_IMPORTED_MODULE_1__/* .Context.dispatcher.launch */ ._.dispatcher.launch(() => StringMetricType._private_setUndispatched(this, value)); - } - async testGetValue(ping = this.sendInPings[0]) { - let metric; - await _context_js__WEBPACK_IMPORTED_MODULE_1__/* .Context.dispatcher.testLaunch */ ._.dispatcher.testLaunch(async () => { - metric = await _context_js__WEBPACK_IMPORTED_MODULE_1__/* .Context.metricsDatabase.getMetric */ ._.metricsDatabase.getMetric(ping, this); - }); - return metric; - } -} -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (StringMetricType); - - -/***/ }), - -/***/ 2939: -/*!************************************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/core/metrics/types/timespan.js ***! - \************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "TimespanMetric": () => (/* binding */ TimespanMetric), -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony import */ var _time_unit_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../time_unit.js */ 8899); -/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../index.js */ 1486); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../utils.js */ 6379); -/* harmony import */ var _metric_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../metric.js */ 1977); -/* harmony import */ var _context_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../context.js */ 5639); -/* harmony import */ var _error_error_type_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../error/error_type.js */ 4511); - - - - - - -class TimespanMetric extends _metric_js__WEBPACK_IMPORTED_MODULE_5__/* .Metric */ .j { - constructor(v) { - super(v); - } - get timespan() { - switch (this._inner.timeUnit) { - case _time_unit_js__WEBPACK_IMPORTED_MODULE_0__/* .default.Nanosecond */ .Z.Nanosecond: - return this._inner.timespan * 10 ** 6; - case _time_unit_js__WEBPACK_IMPORTED_MODULE_0__/* .default.Microsecond */ .Z.Microsecond: - return this._inner.timespan * 10 ** 3; - case _time_unit_js__WEBPACK_IMPORTED_MODULE_0__/* .default.Millisecond */ .Z.Millisecond: - return this._inner.timespan; - case _time_unit_js__WEBPACK_IMPORTED_MODULE_0__/* .default.Second */ .Z.Second: - return Math.round(this._inner.timespan / 1000); - case _time_unit_js__WEBPACK_IMPORTED_MODULE_0__/* .default.Minute */ .Z.Minute: - return Math.round(this._inner.timespan / 1000 / 60); - case _time_unit_js__WEBPACK_IMPORTED_MODULE_0__/* .default.Hour */ .Z.Hour: - return Math.round(this._inner.timespan / 1000 / 60 / 60); - case _time_unit_js__WEBPACK_IMPORTED_MODULE_0__/* .default.Day */ .Z.Day: - return Math.round(this._inner.timespan / 1000 / 60 / 60 / 24); - } - } - validate(v) { - if (!(0,_utils_js__WEBPACK_IMPORTED_MODULE_2__/* .isObject */ .Kn)(v) || Object.keys(v).length !== 2) { - return false; - } - const timeUnitVerification = "timeUnit" in v && (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__/* .isString */ .HD)(v.timeUnit) && Object.values(_time_unit_js__WEBPACK_IMPORTED_MODULE_0__/* .default */ .Z).includes(v.timeUnit); - const timespanVerification = "timespan" in v && (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__/* .isNumber */ .hj)(v.timespan) && v.timespan >= 0; - if (!timeUnitVerification || !timespanVerification) { - return false; - } - return true; - } - payload() { - return { - time_unit: this._inner.timeUnit, - value: this.timespan - }; - } -} -class TimespanMetricType extends _index_js__WEBPACK_IMPORTED_MODULE_1__/* .MetricType */ .t { - constructor(meta, timeUnit) { - super("timespan", meta); - this.timeUnit = timeUnit; - } - static async _private_setRawUndispatched(instance, elapsed) { - if (!instance.shouldRecord(_context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.uploadEnabled */ ._.uploadEnabled)) { - return; - } - if (!(0,_utils_js__WEBPACK_IMPORTED_MODULE_2__/* .isUndefined */ .o8)(instance.startTime)) { - await _context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.errorManager.record */ ._.errorManager.record(instance, _error_error_type_js__WEBPACK_IMPORTED_MODULE_4__/* .ErrorType.InvalidState */ .N.InvalidState, "Timespan already running. Raw value not recorded."); - return; - } - let reportValueExists = false; - const transformFn = ((elapsed) => { - return (old) => { - let metric; - try { - metric = new TimespanMetric(old); - reportValueExists = true; - } - catch (_a) { - metric = new TimespanMetric({ - timespan: elapsed, - timeUnit: instance.timeUnit, - }); - } - return metric; - }; - })(elapsed); - await _context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.metricsDatabase.transform */ ._.metricsDatabase.transform(instance, transformFn); - if (reportValueExists) { - await _context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.errorManager.record */ ._.errorManager.record(instance, _error_error_type_js__WEBPACK_IMPORTED_MODULE_4__/* .ErrorType.InvalidState */ .N.InvalidState, "Timespan value already recorded. New value discarded."); - } - } - start() { - const startTime = (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__/* .getMonotonicNow */ .ts)(); - _context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.dispatcher.launch */ ._.dispatcher.launch(async () => { - if (!this.shouldRecord(_context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.uploadEnabled */ ._.uploadEnabled)) { - return; - } - if (!(0,_utils_js__WEBPACK_IMPORTED_MODULE_2__/* .isUndefined */ .o8)(this.startTime)) { - await _context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.errorManager.record */ ._.errorManager.record(this, _error_error_type_js__WEBPACK_IMPORTED_MODULE_4__/* .ErrorType.InvalidState */ .N.InvalidState, "Timespan already started"); - return; - } - this.startTime = startTime; - return Promise.resolve(); - }); - } - stop() { - const stopTime = (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__/* .getMonotonicNow */ .ts)(); - _context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.dispatcher.launch */ ._.dispatcher.launch(async () => { - if (!this.shouldRecord(_context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.uploadEnabled */ ._.uploadEnabled)) { - this.startTime = undefined; - return; - } - if ((0,_utils_js__WEBPACK_IMPORTED_MODULE_2__/* .isUndefined */ .o8)(this.startTime)) { - await _context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.errorManager.record */ ._.errorManager.record(this, _error_error_type_js__WEBPACK_IMPORTED_MODULE_4__/* .ErrorType.InvalidState */ .N.InvalidState, "Timespan not running"); - return; - } - const elapsed = stopTime - this.startTime; - this.startTime = undefined; - if (elapsed < 0) { - await _context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.errorManager.record */ ._.errorManager.record(this, _error_error_type_js__WEBPACK_IMPORTED_MODULE_4__/* .ErrorType.InvalidState */ .N.InvalidState, "Timespan was negative."); - return; - } - await TimespanMetricType._private_setRawUndispatched(this, elapsed); - }); - } - cancel() { - _context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.dispatcher.launch */ ._.dispatcher.launch(() => { - this.startTime = undefined; - return Promise.resolve(); - }); - } - setRawNanos(elapsed) { - _context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.dispatcher.launch */ ._.dispatcher.launch(async () => { - const elapsedMillis = elapsed * 10 ** (-6); - await TimespanMetricType._private_setRawUndispatched(this, elapsedMillis); - }); - } - async testGetValue(ping = this.sendInPings[0]) { - let value; - await _context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.dispatcher.testLaunch */ ._.dispatcher.testLaunch(async () => { - value = await _context_js__WEBPACK_IMPORTED_MODULE_3__/* .Context.metricsDatabase.getMetric */ ._.metricsDatabase.getMetric(ping, this); - }); - if (value) { - return (new TimespanMetric(value)).timespan; - } - } -} -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (TimespanMetricType); - - -/***/ }), - -/***/ 8410: -/*!*****************************************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/core/pings/ping_type.js + 1 modules ***! - \*****************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -// ESM COMPAT FLAG -__webpack_require__.r(__webpack_exports__); - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "default": () => (/* binding */ ping_type) -}); - -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/constants.js -var constants = __webpack_require__(7882); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/utils.js + 5 modules -var utils = __webpack_require__(6379); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/metrics/types/counter.js -var counter = __webpack_require__(499); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/metrics/types/datetime.js -var datetime = __webpack_require__(7626); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/metrics/time_unit.js -var time_unit = __webpack_require__(8899); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/events/index.js -var events = __webpack_require__(5318); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/context.js + 1 modules -var context = __webpack_require__(5639); -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/pings/maker.js - - - - - - -const GLEAN_START_TIME = new Date(); -async function getSequenceNumber(metricsDatabase, ping) { - const seq = new counter.default({ - category: "", - name: `${ping.name}#sequence`, - sendInPings: [constants/* PING_INFO_STORAGE */.ni], - lifetime: "user", - disabled: false - }); - const currentSeqData = await metricsDatabase.getMetric(constants/* PING_INFO_STORAGE */.ni, seq); - await counter.default._private_addUndispatched(seq, 1); - if (currentSeqData) { - try { - const metric = new counter.CounterMetric(currentSeqData); - return metric.payload(); - } - catch (e) { - console.warn(`Unexpected value found for sequence number in ping ${ping.name}. Ignoring.`); - } - } - return 0; -} -async function getStartEndTimes(metricsDatabase, ping) { - const start = new datetime/* default */.ZP({ - category: "", - name: `${ping.name}#start`, - sendInPings: [constants/* PING_INFO_STORAGE */.ni], - lifetime: "user", - disabled: false - }, time_unit/* default.Minute */.Z.Minute); - const startTimeData = await metricsDatabase.getMetric(constants/* PING_INFO_STORAGE */.ni, start); - let startTime; - if (startTimeData) { - startTime = new datetime/* DatetimeMetric */.ui(startTimeData); - } - else { - startTime = datetime/* DatetimeMetric.fromDate */.ui.fromDate(GLEAN_START_TIME, time_unit/* default.Minute */.Z.Minute); - } - const endTimeData = new Date(); - await datetime/* default._private_setUndispatched */.ZP._private_setUndispatched(start, endTimeData); - const endTime = datetime/* DatetimeMetric.fromDate */.ui.fromDate(endTimeData, time_unit/* default.Minute */.Z.Minute); - return { - startTime: startTime.payload(), - endTime: endTime.payload() - }; -} -async function buildPingInfoSection(metricsDatabase, ping, reason) { - const seq = await getSequenceNumber(metricsDatabase, ping); - const { startTime, endTime } = await getStartEndTimes(metricsDatabase, ping); - const pingInfo = { - seq, - start_time: startTime, - end_time: endTime - }; - if (reason) { - pingInfo.reason = reason; - } - return pingInfo; -} -async function buildClientInfoSection(metricsDatabase, ping) { - let clientInfo = await metricsDatabase.getPingMetrics(constants/* CLIENT_INFO_STORAGE */.xW, true); - if (!clientInfo) { - console.warn("Empty client info data. Will submit anyways."); - clientInfo = {}; - } - let finalClientInfo = { - "telemetry_sdk_build": constants/* GLEAN_VERSION */.Q9 - }; - for (const metricType in clientInfo) { - finalClientInfo = { ...finalClientInfo, ...clientInfo[metricType] }; - } - if (!ping.includeClientId) { - delete finalClientInfo["client_id"]; - } - return finalClientInfo; -} -function getPingHeaders(debugOptions) { - const headers = {}; - if (debugOptions === null || debugOptions === void 0 ? void 0 : debugOptions.debugViewTag) { - headers["X-Debug-ID"] = debugOptions.debugViewTag; - } - if (debugOptions === null || debugOptions === void 0 ? void 0 : debugOptions.sourceTags) { - headers["X-Source-Tags"] = debugOptions.sourceTags.toString(); - } - if (Object.keys(headers).length > 0) { - return headers; - } -} -async function collectPing(metricsDatabase, eventsDatabase, ping, reason) { - const metricsData = await metricsDatabase.getPingMetrics(ping.name, true); - const eventsData = await eventsDatabase.getPingEvents(ping.name, true); - if (!metricsData && !eventsData) { - if (!ping.sendIfEmpty) { - console.info(`Storage for ${ping.name} empty. Bailing out.`); - return; - } - console.info(`Storage for ${ping.name} empty. Ping will still be sent.`); - } - const metrics = metricsData ? { metrics: metricsData } : {}; - const events = eventsData ? { events: eventsData } : {}; - const pingInfo = await buildPingInfoSection(metricsDatabase, ping, reason); - const clientInfo = await buildClientInfoSection(metricsDatabase, ping); - return { - ...metrics, - ...events, - ping_info: pingInfo, - client_info: clientInfo, - }; -} -function makePath(applicationId, identifier, ping) { - return `/submit/${applicationId}/${ping.name}/${constants/* GLEAN_SCHEMA_VERSION */.Oo}/${identifier}`; -} -async function collectAndStorePing(identifier, ping, reason) { - const collectedPayload = await collectPing(context/* Context.metricsDatabase */._.metricsDatabase, context/* Context.eventsDatabase */._.eventsDatabase, ping, reason); - if (!collectedPayload) { - return; - } - let modifiedPayload; - try { - modifiedPayload = await events/* default.afterPingCollection.trigger */.Z.afterPingCollection.trigger(collectedPayload); - } - catch (e) { - console.error(`Error while attempting to modify ping payload for the "${ping.name}" ping using`, `the ${JSON.stringify(events/* default.afterPingCollection.registeredPluginIdentifier */.Z.afterPingCollection.registeredPluginIdentifier)} plugin.`, "Ping will not be submitted. See more logs below.\n\n", e); - return; - } - if (context/* Context.debugOptions.logPings */._.debugOptions.logPings) { - console.info(JSON.stringify(collectedPayload, null, 2)); - } - const finalPayload = modifiedPayload ? modifiedPayload : collectedPayload; - const headers = getPingHeaders(context/* Context.debugOptions */._.debugOptions); - return context/* Context.pingsDatabase.recordPing */._.pingsDatabase.recordPing(makePath(context/* Context.applicationId */._.applicationId, identifier, ping), identifier, finalPayload, headers); -} -/* harmony default export */ const maker = (collectAndStorePing); - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/pings/ping_type.js - - - - -class PingType { - constructor(meta) { - var _a; - this.name = meta.name; - this.includeClientId = meta.includeClientId; - this.sendIfEmpty = meta.sendIfEmpty; - this.reasonCodes = (_a = meta.reasonCodes) !== null && _a !== void 0 ? _a : []; - } - isDeletionRequest() { - return this.name === constants/* DELETION_REQUEST_PING_NAME */.Ui; - } - submit(reason) { - if (this.testCallback) { - this.testCallback(reason) - .then(() => { - PingType._private_internalSubmit(this, reason, this.resolveTestPromiseFunction); - }) - .catch(e => { - console.error(`There was an error validating "${this.name}" (${reason !== null && reason !== void 0 ? reason : "no reason"}):`, e); - PingType._private_internalSubmit(this, reason, this.rejectTestPromiseFunction); - }); - } - else { - PingType._private_internalSubmit(this, reason); - } - } - static async _private_submitUndispatched(instance, reason, testResolver) { - if (!context/* Context.initialized */._.initialized) { - console.info("Glean must be initialized before submitting pings."); - return; - } - if (!context/* Context.uploadEnabled */._.uploadEnabled && !instance.isDeletionRequest()) { - console.info("Glean disabled: not submitting pings. Glean may still submit the deletion-request ping."); - return; - } - let correctedReason = reason; - if (reason && !instance.reasonCodes.includes(reason)) { - console.error(`Invalid reason code ${reason} from ${this.name}. Ignoring.`); - correctedReason = undefined; - } - const identifier = (0,utils/* generateUUIDv4 */.Ln)(); - await maker(identifier, instance, correctedReason); - if (testResolver) { - testResolver(); - instance.resolveTestPromiseFunction = undefined; - instance.rejectTestPromiseFunction = undefined; - instance.testCallback = undefined; - } - } - static _private_internalSubmit(instance, reason, testResolver) { - context/* Context.dispatcher.launch */._.dispatcher.launch(async () => { - await PingType._private_submitUndispatched(instance, reason, testResolver); - }); - } - async testBeforeNextSubmit(callbackFn) { - if (this.testCallback) { - console.error(`There is an existing test call for ping "${this.name}". Ignoring.`); - return; - } - return new Promise((resolve, reject) => { - this.resolveTestPromiseFunction = resolve; - this.rejectTestPromiseFunction = reject; - this.testCallback = callbackFn; - }); - } -} -/* harmony default export */ const ping_type = (PingType); - - -/***/ }), - -/***/ 6379: -/*!*******************************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/core/utils.js + 5 modules ***! - \*******************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "Ln": () => (/* binding */ generateUUIDv4), - "ts": () => (/* binding */ getMonotonicNow), - "jn": () => (/* binding */ isBoolean), - "U": () => (/* binding */ isInteger), - "qT": () => (/* binding */ isJSONValue), - "hj": () => (/* binding */ isNumber), - "Kn": () => (/* binding */ isObject), - "HD": () => (/* binding */ isString), - "o8": () => (/* binding */ isUndefined), - "hL": () => (/* binding */ sanitizeApplicationId), - "hY": () => (/* binding */ truncateStringAtBoundaryWithError), - "AK": () => (/* binding */ validateHeader), - "r4": () => (/* binding */ validateURL) -}); - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/node_modules/uuid/dist/esm-browser/rng.js -// Unique ID creation requires a high quality random # generator. In the browser we therefore -// require the crypto API and do not support built-in fallback to lower quality random number -// generators (like Math.random()). -var getRandomValues; -var rnds8 = new Uint8Array(16); -function rng() { - // lazy load so that environments that need to polyfill have a chance to do so - if (!getRandomValues) { - // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, - // find the complete implementation of crypto (msCrypto) on IE11. - getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto); - - if (!getRandomValues) { - throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); - } - } - - return getRandomValues(rnds8); -} -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/node_modules/uuid/dist/esm-browser/regex.js -/* harmony default export */ const regex = (/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i); -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/node_modules/uuid/dist/esm-browser/validate.js - - -function validate(uuid) { - return typeof uuid === 'string' && regex.test(uuid); -} - -/* harmony default export */ const esm_browser_validate = (validate); -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/node_modules/uuid/dist/esm-browser/stringify.js - -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ - -var byteToHex = []; - -for (var i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).substr(1)); -} - -function stringify(arr) { - var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields - - if (!esm_browser_validate(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - - return uuid; -} - -/* harmony default export */ const esm_browser_stringify = (stringify); -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/node_modules/uuid/dist/esm-browser/v4.js - - - -function v4(options, buf, offset) { - options = options || {}; - var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided - - if (buf) { - offset = offset || 0; - - for (var i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } - - return buf; - } - - return esm_browser_stringify(rnds); -} - -/* harmony default export */ const esm_browser_v4 = (v4); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/context.js + 1 modules -var context = __webpack_require__(5639); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/error/error_type.js -var error_type = __webpack_require__(4511); -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/utils.js - - - -function isJSONValue(v) { - if (isString(v) || isBoolean(v) || isNumber(v)) { - return true; - } - if (isObject(v)) { - if (Object.keys(v).length === 0) { - return true; - } - for (const key in v) { - return isJSONValue(v[key]); - } - } - if (Array.isArray(v)) { - return v.every((e) => isJSONValue(e)); - } - return false; -} -function isObject(v) { - return (typeof v === "object" && v !== null && v.constructor === Object); -} -function isUndefined(v) { - return typeof v === "undefined"; -} -function isString(v) { - return typeof v === "string"; -} -function isBoolean(v) { - return typeof v === "boolean"; -} -function isNumber(v) { - return typeof v === "number" && !isNaN(v); -} -function isInteger(v) { - return isNumber(v) && Number.isInteger(v); -} -function sanitizeApplicationId(applicationId) { - return applicationId.replace(/[^a-z0-9]+/gi, "-").toLowerCase(); -} -function validateURL(v) { - const urlPattern = /^(http|https):\/\/[a-zA-Z0-9._-]+(:\d+){0,1}(\/{0,1})$/i; - return urlPattern.test(v); -} -function validateHeader(v) { - return /^[a-z0-9-]{1,20}$/i.test(v); -} -function generateUUIDv4() { - if (typeof crypto !== "undefined") { - return esm_browser_v4(); - } - else { - return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { - const r = Math.random() * 16 | 0, v = c == "x" ? r : (r & 0x3 | 0x8); - return v.toString(16); - }); - } -} -function getMonotonicNow() { - return typeof performance === "undefined" ? Date.now() : performance.now(); -} -async function truncateStringAtBoundaryWithError(metric, value, length) { - const truncated = value.substr(0, length); - if (truncated !== value) { - await context/* Context.errorManager.record */._.errorManager.record(metric, error_type/* ErrorType.InvalidOverflow */.N.InvalidOverflow, `Value length ${value.length} exceeds maximum of ${length}.`); - } - return truncated; -} - - -/***/ }), - -/***/ 5122: -/*!**********************************************************************************!*\ - !*** ../../node_modules/@mozilla/glean/dist/webext/index/webext.js + 20 modules ***! - \**********************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -// ESM COMPAT FLAG -__webpack_require__.r(__webpack_exports__); - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "default": () => (/* binding */ index_webext) -}); - -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/constants.js -var constants = __webpack_require__(7882); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/utils.js + 5 modules -var utils = __webpack_require__(6379); -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/config.js - - -class Configuration { - constructor(config) { - this.appBuild = config === null || config === void 0 ? void 0 : config.appBuild; - this.appDisplayVersion = config === null || config === void 0 ? void 0 : config.appDisplayVersion; - this.debug = Configuration.sanitizeDebugOptions(config === null || config === void 0 ? void 0 : config.debug); - if ((config === null || config === void 0 ? void 0 : config.serverEndpoint) && !(0,utils/* validateURL */.r4)(config.serverEndpoint)) { - throw new Error(`Unable to initialize Glean, serverEndpoint ${config.serverEndpoint} is an invalid URL.`); - } - this.serverEndpoint = (config && config.serverEndpoint) - ? config.serverEndpoint : constants/* DEFAULT_TELEMETRY_ENDPOINT */.ey; - this.httpClient = config === null || config === void 0 ? void 0 : config.httpClient; - } - static sanitizeDebugOptions(debug) { - const correctedDebugOptions = debug || {}; - if ((debug === null || debug === void 0 ? void 0 : debug.debugViewTag) !== undefined && !Configuration.validateDebugViewTag(debug === null || debug === void 0 ? void 0 : debug.debugViewTag)) { - delete correctedDebugOptions["debugViewTag"]; - } - if ((debug === null || debug === void 0 ? void 0 : debug.sourceTags) !== undefined && !Configuration.validateSourceTags(debug === null || debug === void 0 ? void 0 : debug.sourceTags)) { - delete correctedDebugOptions["sourceTags"]; - } - return correctedDebugOptions; - } - static validateDebugViewTag(tag) { - const validation = (0,utils/* validateHeader */.AK)(tag); - if (!validation) { - console.error(`"${tag}" is not a valid \`debugViewTag\` value.`, "Please make sure the value passed satisfies the regex `^[a-zA-Z0-9-]{1,20}$`."); - } - return validation; - } - static validateSourceTags(tags) { - if (tags.length < 1 || tags.length > constants/* GLEAN_MAX_SOURCE_TAGS */.og) { - console.error(`A list of tags cannot contain more than ${constants/* GLEAN_MAX_SOURCE_TAGS */.og} elements.`); - return false; - } - for (const tag of tags) { - if (tag.startsWith("glean")) { - console.error("Tags starting with `glean` are reserved and must not be used."); - return false; - } - if (!(0,utils/* validateHeader */.AK)(tag)) { - return false; - } - } - return true; - } -} - -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/metrics/types/labeled.js -var labeled = __webpack_require__(1209); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/metrics/index.js -var metrics = __webpack_require__(1486); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/context.js + 1 modules -var context = __webpack_require__(5639); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/metrics/metric.js -var metric = __webpack_require__(1977); -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/metrics/types/boolean.js - - - - -class BooleanMetric extends metric/* Metric */.j { - constructor(v) { - super(v); - } - validate(v) { - return (0,utils/* isBoolean */.jn)(v); - } - payload() { - return this._inner; - } -} -class BooleanMetricType extends (/* unused pure expression or super */ null && (MetricType)) { - constructor(meta) { - super("boolean", meta); - } - set(value) { - Context.dispatcher.launch(async () => { - if (!this.shouldRecord(Context.uploadEnabled)) { - return; - } - const metric = new BooleanMetric(value); - await Context.metricsDatabase.record(this, metric); - }); - } - async testGetValue(ping = this.sendInPings[0]) { - let metric; - await Context.dispatcher.testLaunch(async () => { - metric = await Context.metricsDatabase.getMetric(ping, this); - }); - return metric; - } -} -/* harmony default export */ const types_boolean = ((/* unused pure expression or super */ null && (BooleanMetricType))); - -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/metrics/types/counter.js -var counter = __webpack_require__(499); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/metrics/types/datetime.js -var datetime = __webpack_require__(7626); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/metrics/types/quantity.js -var quantity = __webpack_require__(4717); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/metrics/types/string.js -var string = __webpack_require__(4245); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/metrics/types/timespan.js -var timespan = __webpack_require__(2939); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/error/error_type.js -var error_type = __webpack_require__(4511); -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/metrics/types/uuid.js - - - - - -const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; -class UUIDMetric extends metric/* Metric */.j { - constructor(v) { - super(v); - } - validate(v) { - if (!(0,utils/* isString */.HD)(v)) { - return false; - } - return UUID_REGEX.test(v); - } - payload() { - return this._inner; - } -} -class UUIDMetricType extends metrics/* MetricType */.t { - constructor(meta) { - super("uuid", meta); - } - static async _private_setUndispatched(instance, value) { - if (!instance.shouldRecord(context/* Context.uploadEnabled */._.uploadEnabled)) { - return; - } - if (!value) { - value = (0,utils/* generateUUIDv4 */.Ln)(); - } - let metric; - try { - metric = new UUIDMetric(value); - } - catch (_a) { - await context/* Context.errorManager.record */._.errorManager.record(instance, error_type/* ErrorType.InvalidValue */.N.InvalidValue, `"${value}" is not a valid UUID.`); - return; - } - await context/* Context.metricsDatabase.record */._.metricsDatabase.record(instance, metric); - } - set(value) { - context/* Context.dispatcher.launch */._.dispatcher.launch(() => UUIDMetricType._private_setUndispatched(this, value)); - } - generateAndSet() { - if (!this.shouldRecord(context/* Context.uploadEnabled */._.uploadEnabled)) { - return; - } - const value = (0,utils/* generateUUIDv4 */.Ln)(); - this.set(value); - return value; - } - async testGetValue(ping = this.sendInPings[0]) { - let metric; - await context/* Context.dispatcher.testLaunch */._.dispatcher.testLaunch(async () => { - metric = await context/* Context.metricsDatabase.getMetric */._.metricsDatabase.getMetric(ping, this); - }); - return metric; - } -} -/* harmony default export */ const uuid = (UUIDMetricType); - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/metrics/utils.js - - - - - - - - -const METRIC_MAP = Object.freeze({ - "boolean": BooleanMetric, - "counter": counter.CounterMetric, - "datetime": datetime/* DatetimeMetric */.ui, - "labeled_boolean": labeled/* LabeledMetric */.Dc, - "labeled_counter": labeled/* LabeledMetric */.Dc, - "labeled_string": labeled/* LabeledMetric */.Dc, - "quantity": quantity.QuantityMetric, - "string": string.StringMetric, - "timespan": timespan.TimespanMetric, - "uuid": UUIDMetric, -}); -function createMetric(type, v) { - if (!(type in METRIC_MAP)) { - throw new Error(`Unable to create metric of unknown type ${type}`); - } - return new METRIC_MAP[type](v); -} -function validateMetricInternalRepresentation(type, v) { - try { - createMetric(type, v); - return true; - } - catch (_a) { - return false; - } -} - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/metrics/database.js - - -function isValidInternalMetricsRepresentation(v) { - if ((0,utils/* isObject */.Kn)(v)) { - for (const metricType in v) { - const metrics = v[metricType]; - if ((0,utils/* isObject */.Kn)(metrics)) { - for (const metricIdentifier in metrics) { - if (!validateMetricInternalRepresentation(metricType, metrics[metricIdentifier])) { - return false; - } - } - } - else { - return false; - } - } - return true; - } - else { - return false; - } -} -function createMetricsPayload(v) { - const result = {}; - for (const metricType in v) { - const metrics = v[metricType]; - result[metricType] = {}; - for (const metricIdentifier in metrics) { - const metric = createMetric(metricType, metrics[metricIdentifier]); - result[metricType][metricIdentifier] = metric.payload(); - } - } - return result; -} -class MetricsDatabase { - constructor(storage) { - this.userStore = new storage("userLifetimeMetrics"); - this.pingStore = new storage("pingLifetimeMetrics"); - this.appStore = new storage("appLifetimeMetrics"); - } - _chooseStore(lifetime) { - switch (lifetime) { - case "user": - return this.userStore; - case "ping": - return this.pingStore; - case "application": - return this.appStore; - } - } - async record(metric, value) { - await this.transform(metric, () => value); - } - async transform(metric, transformFn) { - if (metric.disabled) { - return; - } - const store = this._chooseStore(metric.lifetime); - const storageKey = await metric.identifier(this); - for (const ping of metric.sendInPings) { - const finalTransformFn = (v) => transformFn(v).get(); - await store.update([ping, metric.type, storageKey], finalTransformFn); - } - } - async hasMetric(lifetime, ping, metricType, metricIdentifier) { - const store = this._chooseStore(lifetime); - const value = await store.get([ping, metricType, metricIdentifier]); - return !(0,utils/* isUndefined */.o8)(value); - } - async countByBaseIdentifier(lifetime, ping, metricType, metricIdentifier) { - const store = this._chooseStore(lifetime); - const pingStorage = await store.get([ping, metricType]); - if ((0,utils/* isUndefined */.o8)(pingStorage)) { - return 0; - } - return Object.keys(pingStorage).filter(n => n.startsWith(metricIdentifier)).length; - } - async getMetric(ping, metric) { - const store = this._chooseStore(metric.lifetime); - const storageKey = await metric.identifier(this); - const value = await store.get([ping, metric.type, storageKey]); - if (!(0,utils/* isUndefined */.o8)(value) && !validateMetricInternalRepresentation(metric.type, value)) { - console.error(`Unexpected value found for metric ${storageKey}: ${JSON.stringify(value)}. Clearing.`); - await store.delete([ping, metric.type, storageKey]); - return; - } - else { - return value; - } - } - async getAndValidatePingData(ping, lifetime) { - const store = this._chooseStore(lifetime); - const data = await store.get([ping]); - if ((0,utils/* isUndefined */.o8)(data)) { - return {}; - } - if (!isValidInternalMetricsRepresentation(data)) { - console.error(`Unexpected value found for ping ${ping} in ${lifetime} store: ${JSON.stringify(data)}. Clearing.`); - await store.delete([ping]); - return {}; - } - return data; - } - processLabeledMetric(snapshot, metricType, metricId, metricData) { - const newType = `labeled_${metricType}`; - const idLabelSplit = metricId.split("/", 2); - const newId = idLabelSplit[0]; - const label = idLabelSplit[1]; - if (newType in snapshot && newId in snapshot[newType]) { - const existingData = snapshot[newType][newId]; - snapshot[newType][newId] = { - ...existingData, - [label]: metricData - }; - } - else { - snapshot[newType] = { - ...snapshot[newType], - [newId]: { - [label]: metricData - } - }; - } - } - async getPingMetrics(ping, clearPingLifetimeData) { - const userData = await this.getAndValidatePingData(ping, "user"); - const pingData = await this.getAndValidatePingData(ping, "ping"); - const appData = await this.getAndValidatePingData(ping, "application"); - if (clearPingLifetimeData) { - await this.clear("ping", ping); - } - const response = {}; - for (const data of [userData, pingData, appData]) { - for (const metricType in data) { - for (const metricId in data[metricType]) { - if (metricId.includes("/")) { - this.processLabeledMetric(response, metricType, metricId, data[metricType][metricId]); - } - else { - response[metricType] = { - ...response[metricType], - [metricId]: data[metricType][metricId] - }; - } - } - } - } - if (Object.keys(response).length === 0) { - return; - } - else { - return createMetricsPayload(response); - } - } - async clear(lifetime, ping) { - const store = this._chooseStore(lifetime); - const storageIndex = ping ? [ping] : []; - await store.delete(storageIndex); - } - async clearAll() { - await this.userStore.delete([]); - await this.pingStore.delete([]); - await this.appStore.delete([]); - } -} -/* harmony default export */ const database = (MetricsDatabase); - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/pings/database.js - -function isValidPingInternalRepresentation(v) { - if ((0,utils/* isObject */.Kn)(v) && (Object.keys(v).length === 2 || Object.keys(v).length === 3)) { - const hasValidPath = "path" in v && (0,utils/* isString */.HD)(v.path); - const hasValidPayload = "payload" in v && (0,utils/* isJSONValue */.qT)(v.payload) && (0,utils/* isObject */.Kn)(v.payload); - const hasValidHeaders = (!("headers" in v)) || ((0,utils/* isJSONValue */.qT)(v.headers) && (0,utils/* isObject */.Kn)(v.headers)); - if (!hasValidPath || !hasValidPayload || !hasValidHeaders) { - return false; - } - return true; - } - return false; -} -class PingsDatabase { - constructor(store) { - this.store = new store("pings"); - } - attachObserver(observer) { - this.observer = observer; - } - async recordPing(path, identifier, payload, headers) { - const ping = { - path, - payload - }; - if (headers) { - ping.headers = headers; - } - await this.store.update([identifier], () => ping); - this.observer && this.observer.update(identifier, ping); - } - async deletePing(identifier) { - await this.store.delete([identifier]); - } - async getAllPings() { - const allStoredPings = await this.store._getWholeStore(); - const finalPings = {}; - for (const identifier in allStoredPings) { - const ping = allStoredPings[identifier]; - if (isValidPingInternalRepresentation(ping)) { - finalPings[identifier] = ping; - } - else { - console.warn("Unexpected data found in pings database. Deleting."); - await this.store.delete([identifier]); - } - } - return finalPings; - } - async scanPendingPings() { - if (!this.observer) { - return; - } - const pings = await this.getAllPings(); - for (const identifier in pings) { - this.observer.update(identifier, pings[identifier]); - } - } - async clearAll() { - await this.store.delete([]); - } -} -/* harmony default export */ const pings_database = (PingsDatabase); - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/upload/index.js - -var PingUploaderStatus; -(function (PingUploaderStatus) { - PingUploaderStatus[PingUploaderStatus["Idle"] = 0] = "Idle"; - PingUploaderStatus[PingUploaderStatus["Uploading"] = 1] = "Uploading"; - PingUploaderStatus[PingUploaderStatus["Cancelling"] = 2] = "Cancelling"; -})(PingUploaderStatus || (PingUploaderStatus = {})); -class PingUploader { - constructor(config, platform, pingsDatabase) { - this.initialized = false; - this.queue = []; - this.status = 0; - this.uploader = config.httpClient ? config.httpClient : platform.uploader; - this.platformInfo = platform.info; - this.serverEndpoint = config.serverEndpoint; - this.pingsDatabase = pingsDatabase; - } - setInitialized(state) { - this.initialized = state !== null && state !== void 0 ? state : true; - } - enqueuePing(ping) { - let isDuplicate = false; - for (const queuedPing of this.queue) { - if (queuedPing.identifier === ping.identifier) { - isDuplicate = true; - } - } - !isDuplicate && this.queue.push(ping); - } - getNextPing() { - return this.queue.shift(); - } - async preparePingForUpload(ping) { - const stringifiedBody = JSON.stringify(ping.payload); - let headers = ping.headers || {}; - headers = { - ...ping.headers, - "Content-Type": "application/json; charset=utf-8", - "Content-Length": stringifiedBody.length.toString(), - "Date": (new Date()).toISOString(), - "X-Client-Type": "Glean.js", - "X-Client-Version": constants/* GLEAN_VERSION */.Q9, - "X-Telemetry-Agent": `Glean/${constants/* GLEAN_VERSION */.Q9} (JS on ${await this.platformInfo.os()})` - }; - return { - headers, - payload: stringifiedBody - }; - } - async attemptPingUpload(ping) { - if (!this.initialized) { - console.warn("Attempted to upload a ping, but Glean is not initialized yet. Ignoring."); - return { result: 0 }; - } - const finalPing = await this.preparePingForUpload(ping); - const result = await this.uploader.post(`${this.serverEndpoint}${ping.path}`, finalPing.payload, finalPing.headers); - return result; - } - async processPingUploadResponse(identifier, response) { - const { status, result } = response; - if (status && status >= 200 && status < 300) { - console.info(`Ping ${identifier} succesfully sent ${status}.`); - await this.pingsDatabase.deletePing(identifier); - return false; - } - if (result === 1 || (status && status >= 400 && status < 500)) { - console.warn(`Unrecoverable upload failure while attempting to send ping ${identifier}. Error was ${status !== null && status !== void 0 ? status : "no status"}.`); - await this.pingsDatabase.deletePing(identifier); - return false; - } - console.warn(`Recoverable upload failure while attempting to send ping ${identifier}, will retry. Error was ${status !== null && status !== void 0 ? status : "no status"}.`); - return true; - } - async triggerUploadInternal() { - let retries = 0; - let nextPing = this.getNextPing(); - while (nextPing && this.status !== 2) { - const status = await this.attemptPingUpload(nextPing); - const shouldRetry = await this.processPingUploadResponse(nextPing.identifier, status); - if (shouldRetry) { - retries++; - this.enqueuePing(nextPing); - } - if (retries >= 3) { - console.info("Reached maximum recoverable failures for the current uploading window. You are done."); - return; - } - nextPing = this.getNextPing(); - } - } - async triggerUpload() { - if (this.status !== 0) { - return; - } - this.status = 1; - try { - this.currentJob = this.triggerUploadInternal(); - await this.currentJob; - } - finally { - this.status = 0; - } - } - async cancelUpload() { - if (this.status === 1) { - this.status = 2; - await this.currentJob; - } - return; - } - async clearPendingPingsQueue() { - await this.cancelUpload(); - this.queue = []; - } - update(identifier, ping) { - this.enqueuePing({ identifier, ...ping }); - void this.triggerUpload(); - } -} -/* harmony default export */ const upload = (PingUploader); - -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/metrics/time_unit.js -var time_unit = __webpack_require__(8899); -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/internal_metrics.js - - - - - - - -class CoreMetrics { - constructor() { - this.clientId = new uuid({ - name: "client_id", - category: "", - sendInPings: ["glean_client_info"], - lifetime: "user", - disabled: false, - }); - this.firstRunDate = new datetime/* default */.ZP({ - name: "first_run_date", - category: "", - sendInPings: ["glean_client_info"], - lifetime: "user", - disabled: false, - }, time_unit/* default.Day */.Z.Day); - this.os = new string.default({ - name: "os", - category: "", - sendInPings: ["glean_client_info"], - lifetime: "application", - disabled: false, - }); - this.osVersion = new string.default({ - name: "os_version", - category: "", - sendInPings: ["glean_client_info"], - lifetime: "application", - disabled: false, - }); - this.architecture = new string.default({ - name: "architecture", - category: "", - sendInPings: ["glean_client_info"], - lifetime: "application", - disabled: false, - }); - this.locale = new string.default({ - name: "locale", - category: "", - sendInPings: ["glean_client_info"], - lifetime: "application", - disabled: false, - }); - this.appBuild = new string.default({ - name: "app_build", - category: "", - sendInPings: ["glean_client_info"], - lifetime: "application", - disabled: false, - }); - this.appDisplayVersion = new string.default({ - name: "app_display_version", - category: "", - sendInPings: ["glean_client_info"], - lifetime: "application", - disabled: false, - }); - } - async initialize(config, platform, metricsDatabase) { - await this.initializeClientId(metricsDatabase); - await this.initializeFirstRunDate(metricsDatabase); - await string.default._private_setUndispatched(this.os, await platform.info.os()); - await string.default._private_setUndispatched(this.osVersion, await platform.info.osVersion()); - await string.default._private_setUndispatched(this.architecture, await platform.info.arch()); - await string.default._private_setUndispatched(this.locale, await platform.info.locale()); - await string.default._private_setUndispatched(this.appBuild, config.appBuild || "Unknown"); - await string.default._private_setUndispatched(this.appDisplayVersion, config.appDisplayVersion || "Unknown"); - } - async initializeClientId(metricsDatabase) { - let needNewClientId = false; - const clientIdData = await metricsDatabase.getMetric(constants/* CLIENT_INFO_STORAGE */.xW, this.clientId); - if (clientIdData) { - try { - const currentClientId = createMetric("uuid", clientIdData); - if (currentClientId.payload() === constants/* KNOWN_CLIENT_ID */.Ei) { - needNewClientId = true; - } - } - catch (_a) { - console.warn("Unexpected value found for Glean clientId. Ignoring."); - needNewClientId = true; - } - } - else { - needNewClientId = true; - } - if (needNewClientId) { - await uuid._private_setUndispatched(this.clientId, (0,utils/* generateUUIDv4 */.Ln)()); - } - } - async initializeFirstRunDate(metricsDatabase) { - const firstRunDate = await metricsDatabase.getMetric(constants/* CLIENT_INFO_STORAGE */.xW, this.firstRunDate); - if (!firstRunDate) { - await datetime/* default._private_setUndispatched */.ZP._private_setUndispatched(this.firstRunDate); - } - } -} - -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/metrics/events_database.js -var events_database = __webpack_require__(245); -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/pings/ping_type.js + 1 modules -var ping_type = __webpack_require__(8410); -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/internal_pings.js - - -class CorePings { - constructor() { - this.deletionRequest = new ping_type.default({ - name: constants/* DELETION_REQUEST_PING_NAME */.Ui, - includeClientId: true, - sendIfEmpty: true, - }); - } -} -/* harmony default export */ const internal_pings = (CorePings); - -// EXTERNAL MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/events/index.js -var events = __webpack_require__(5318); -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/events/utils.js - -function registerPluginToEvent(plugin) { - const eventName = plugin.event; - if (eventName in events/* default */.Z) { - const event = events/* default */.Z[eventName]; - event.registerPlugin(plugin); - return; - } - console.error(`Attempted to register plugin '${plugin.name}', which listens to the event '${plugin.event}'.`, "That is not a valid Glean event. Ignoring"); -} -function testResetEvents() { - for (const event in events/* default */.Z) { - events/* default */.Z[event].deregisterPlugin(); - } -} - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/error/index.js - - -function getErrorMetricForMetric(metric, error) { - const identifier = metric.baseIdentifier(); - const name = (0,labeled/* stripLabel */.ho)(identifier); - return new counter.default({ - name: (0,labeled/* combineIdentifierAndLabel */.lb)(error, name), - category: "glean.error", - lifetime: "ping", - sendInPings: metric.sendInPings, - disabled: false, - }); -} -class ErrorManager { - async record(metric, error, message, numErrors = 1) { - const errorMetric = getErrorMetricForMetric(metric, error); - console.warn(`${metric.baseIdentifier()}: ${message}`); - if (numErrors > 0) { - await counter.default._private_addUndispatched(errorMetric, numErrors); - } - else { - } - } - async testGetNumRecordedErrors(metric, error, ping) { - const errorMetric = getErrorMetricForMetric(metric, error); - const numErrors = await errorMetric.testGetValue(ping); - return numErrors || 0; - } -} - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/storage/utils.js - -function getValueFromNestedObject(obj, index) { - if (index.length === 0) { - throw Error("The index must contain at least one property to get."); - } - let target = obj; - for (const key of index) { - if ((0,utils/* isObject */.Kn)(target) && key in target) { - const temp = target[key]; - if ((0,utils/* isJSONValue */.qT)(temp)) { - target = temp; - } - } - else { - return; - } - } - return target; -} -function updateNestedObject(obj, index, transformFn) { - if (index.length === 0) { - throw Error("The index must contain at least one property to update."); - } - const returnObject = { ...obj }; - let target = returnObject; - for (const key of index.slice(0, index.length - 1)) { - if (!(0,utils/* isObject */.Kn)(target[key])) { - target[key] = {}; - } - target = target[key]; - } - const finalKey = index[index.length - 1]; - const current = target[finalKey]; - try { - const value = transformFn(current); - target[finalKey] = value; - return returnObject; - } - catch (e) { - console.error("Error while transforming stored value. Ignoring old value.", e); - target[finalKey] = transformFn(undefined); - return returnObject; - } -} -function deleteKeyFromNestedObject(obj, index) { - if (index.length === 0) { - return {}; - } - const returnObject = { ...obj }; - let target = returnObject; - for (const key of index.slice(0, index.length - 1)) { - const value = target[key]; - if (!(0,utils/* isObject */.Kn)(value)) { - throw Error("Attempted to delete an entry from an invalid index."); - } - else { - target = value; - } - } - const finalKey = index[index.length - 1]; - delete target[finalKey]; - return returnObject; -} - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/platform/test/storage.js - -let globalStore = {}; -class MockStore { - constructor(rootKey) { - this.rootKey = rootKey; - } - _getWholeStore() { - const result = globalStore[this.rootKey] || {}; - return Promise.resolve(result); - } - get(index) { - try { - const value = getValueFromNestedObject(globalStore, [this.rootKey, ...index]); - return Promise.resolve(value); - } - catch (e) { - return Promise.reject(e); - } - } - update(index, transformFn) { - try { - globalStore = updateNestedObject(globalStore, [this.rootKey, ...index], transformFn); - return Promise.resolve(); - } - catch (e) { - return Promise.reject(e); - } - } - delete(index) { - try { - globalStore = deleteKeyFromNestedObject(globalStore, [this.rootKey, ...index]); - } - catch (e) { - console.warn(e.message, "Ignoring."); - } - return Promise.resolve(); - } -} -/* harmony default export */ const storage = (MockStore); - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/platform/test/index.js - -class MockUploader { - post(_url, _body, _headers) { - const result = { - result: 2, - status: 200 - }; - return Promise.resolve(result); - } -} -const MockPlatformInfo = { - os() { - return Promise.resolve("Unknown"); - }, - osVersion() { - return Promise.resolve("Unknown"); - }, - arch() { - return Promise.resolve("Unknown"); - }, - locale() { - return Promise.resolve("Unknown"); - }, -}; -const TestPlatform = { - Storage: storage, - uploader: new MockUploader(), - info: MockPlatformInfo, - name: "test" -}; -/* harmony default export */ const test = (TestPlatform); - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/glean.js - - - - - - - - - - - - - - - - -class Glean { - constructor() { - if (!(0,utils/* isUndefined */.o8)(Glean._instance)) { - throw new Error(`Tried to instantiate Glean through \`new\`. - Use Glean.instance instead to access the Glean singleton.`); - } - this._coreMetrics = new CoreMetrics(); - this._corePings = new internal_pings(); - } - static get instance() { - if (!Glean._instance) { - Glean._instance = new Glean(); - } - return Glean._instance; - } - static get pingUploader() { - return Glean.instance._pingUploader; - } - static get coreMetrics() { - return Glean.instance._coreMetrics; - } - static get corePings() { - return Glean.instance._corePings; - } - static async onUploadEnabled() { - context/* Context.uploadEnabled */._.uploadEnabled = true; - await Glean.coreMetrics.initialize(Glean.instance._config, Glean.platform, context/* Context.metricsDatabase */._.metricsDatabase); - } - static async onUploadDisabled() { - await ping_type.default._private_submitUndispatched(Glean.corePings.deletionRequest); - context/* Context.uploadEnabled */._.uploadEnabled = false; - await Glean.clearMetrics(); - } - static async clearMetrics() { - await Glean.pingUploader.clearPendingPingsQueue(); - let firstRunDate; - try { - firstRunDate = new datetime/* DatetimeMetric */.ui(await context/* Context.metricsDatabase.getMetric */._.metricsDatabase.getMetric(constants/* CLIENT_INFO_STORAGE */.xW, Glean.coreMetrics.firstRunDate)).date; - } - catch (_a) { - firstRunDate = new Date(); - } - await context/* Context.eventsDatabase.clearAll */._.eventsDatabase.clearAll(); - await context/* Context.metricsDatabase.clearAll */._.metricsDatabase.clearAll(); - await context/* Context.pingsDatabase.clearAll */._.pingsDatabase.clearAll(); - context/* Context.uploadEnabled */._.uploadEnabled = true; - await uuid._private_setUndispatched(Glean.coreMetrics.clientId, constants/* KNOWN_CLIENT_ID */.Ei); - await datetime/* default._private_setUndispatched */.ZP._private_setUndispatched(Glean.coreMetrics.firstRunDate, firstRunDate); - context/* Context.uploadEnabled */._.uploadEnabled = false; - } - static initialize(applicationId, uploadEnabled, config) { - if (context/* Context.initialized */._.initialized) { - console.warn("Attempted to initialize Glean, but it has already been initialized. Ignoring."); - return; - } - if (applicationId.length === 0) { - console.error("Unable to initialize Glean, applicationId cannot be an empty string."); - return; - } - if (!Glean.instance._platform) { - console.error("Unable to initialize Glean, environment has not been set."); - return; - } - const correctConfig = new Configuration(config); - context/* Context.metricsDatabase */._.metricsDatabase = new database(Glean.platform.Storage); - context/* Context.eventsDatabase */._.eventsDatabase = new events_database/* default */.Z(Glean.platform.Storage); - context/* Context.pingsDatabase */._.pingsDatabase = new pings_database(Glean.platform.Storage); - context/* Context.errorManager */._.errorManager = new ErrorManager(); - Glean.instance._pingUploader = new upload(correctConfig, Glean.platform, context/* Context.pingsDatabase */._.pingsDatabase); - context/* Context.pingsDatabase.attachObserver */._.pingsDatabase.attachObserver(Glean.pingUploader); - if (config === null || config === void 0 ? void 0 : config.plugins) { - for (const plugin of config.plugins) { - registerPluginToEvent(plugin); - } - } - context/* Context.dispatcher.flushInit */._.dispatcher.flushInit(async () => { - context/* Context.applicationId */._.applicationId = (0,utils/* sanitizeApplicationId */.hL)(applicationId); - context/* Context.debugOptions */._.debugOptions = correctConfig.debug; - Glean.instance._config = correctConfig; - await context/* Context.metricsDatabase.clear */._.metricsDatabase.clear("application"); - context/* Context.initialized */._.initialized = true; - Glean.pingUploader.setInitialized(true); - if (uploadEnabled) { - await Glean.onUploadEnabled(); - } - else { - const clientId = await context/* Context.metricsDatabase.getMetric */._.metricsDatabase.getMetric(constants/* CLIENT_INFO_STORAGE */.xW, Glean.coreMetrics.clientId); - if (clientId) { - if (clientId !== constants/* KNOWN_CLIENT_ID */.Ei) { - await Glean.onUploadDisabled(); - } - } - else { - await Glean.clearMetrics(); - } - } - await context/* Context.pingsDatabase.scanPendingPings */._.pingsDatabase.scanPendingPings(); - void Glean.pingUploader.triggerUpload(); - }); - } - static get serverEndpoint() { - var _a; - return (_a = Glean.instance._config) === null || _a === void 0 ? void 0 : _a.serverEndpoint; - } - static get logPings() { - var _a, _b; - return ((_b = (_a = Glean.instance._config) === null || _a === void 0 ? void 0 : _a.debug) === null || _b === void 0 ? void 0 : _b.logPings) || false; - } - static get debugViewTag() { - var _a; - return (_a = Glean.instance._config) === null || _a === void 0 ? void 0 : _a.debug.debugViewTag; - } - static get sourceTags() { - var _a, _b; - return (_b = (_a = Glean.instance._config) === null || _a === void 0 ? void 0 : _a.debug.sourceTags) === null || _b === void 0 ? void 0 : _b.toString(); - } - static get platform() { - if (!Glean.instance._platform) { - throw new Error("IMPOSSIBLE: Attempted to access environment specific APIs before Glean was initialized."); - } - return Glean.instance._platform; - } - static setUploadEnabled(flag) { - context/* Context.dispatcher.launch */._.dispatcher.launch(async () => { - if (!context/* Context.initialized */._.initialized) { - console.error("Changing upload enabled before Glean is initialized is not supported.\n", "Pass the correct state into `Glean.initialize\n`.", "See documentation at https://mozilla.github.io/glean/book/user/general-api.html#initializing-the-glean-sdk`"); - return; - } - if (context/* Context.uploadEnabled */._.uploadEnabled !== flag) { - if (flag) { - await Glean.onUploadEnabled(); - } - else { - await Glean.onUploadDisabled(); - } - } - }); - } - static setLogPings(flag) { - context/* Context.dispatcher.launch */._.dispatcher.launch(() => { - Glean.instance._config.debug.logPings = flag; - return Promise.resolve(); - }); - } - static setDebugViewTag(value) { - if (!Configuration.validateDebugViewTag(value)) { - console.error(`Invalid \`debugViewTag\` ${value}. Ignoring.`); - return; - } - context/* Context.dispatcher.launch */._.dispatcher.launch(() => { - Glean.instance._config.debug.debugViewTag = value; - return Promise.resolve(); - }); - } - static unsetDebugViewTag() { - context/* Context.dispatcher.launch */._.dispatcher.launch(() => { - delete Glean.instance._config.debug.debugViewTag; - return Promise.resolve(); - }); - } - static setSourceTags(value) { - if (!Configuration.validateSourceTags(value)) { - console.error(`Invalid \`sourceTags\` ${value.toString()}. Ignoring.`); - return; - } - context/* Context.dispatcher.launch */._.dispatcher.launch(() => { - Glean.instance._config.debug.sourceTags = value; - return Promise.resolve(); - }); - } - static unsetSourceTags() { - context/* Context.dispatcher.launch */._.dispatcher.launch(() => { - delete Glean.instance._config.debug.sourceTags; - return Promise.resolve(); - }); - } - static setPlatform(platform) { - if (context/* Context.initialized */._.initialized) { - return; - } - if (Glean.instance._platform && Glean.instance._platform.name !== platform.name) { - console.debug(`Changing Glean platform from "${Glean.platform.name}" to "${platform.name}".`); - } - Glean.instance._platform = platform; - } - static async testInitialize(applicationId, uploadEnabled = true, config) { - Glean.setPlatform(test); - Glean.initialize(applicationId, uploadEnabled, config); - await context/* Context.dispatcher.testBlockOnQueue */._.dispatcher.testBlockOnQueue(); - } - static async testUninitialize() { - await context/* Context.testUninitialize */._.testUninitialize(); - testResetEvents(); - if (Glean.pingUploader) { - await Glean.pingUploader.clearPendingPingsQueue(); - } - } - static async testResetGlean(applicationId, uploadEnabled = true, config) { - await Glean.testUninitialize(); - try { - await context/* Context.eventsDatabase.clearAll */._.eventsDatabase.clearAll(); - await context/* Context.metricsDatabase.clearAll */._.metricsDatabase.clearAll(); - await context/* Context.pingsDatabase.clearAll */._.pingsDatabase.clearAll(); - } - catch (_a) { - } - await Glean.testInitialize(applicationId, uploadEnabled, config); - } -} -/* harmony default export */ const glean = (Glean); - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/platform/webext/storage.js - - -function stripNulls(query) { - for (const key in query) { - const curr = query[key]; - if (curr === null) { - delete query[key]; - } - if ((0,utils/* isObject */.Kn)(curr)) { - if (Object.keys(curr).length === 0) { - delete query[key]; - } - else { - stripNulls(curr); - } - } - } -} -class WebExtStore { - constructor(rootKey) { - if (typeof browser === "undefined") { - throw Error(`The web extensions store should only be user in a browser extension context. - If running is a browser different from Firefox, make sure you have installed - the webextension-polyfill peer dependency. To do so, run \`npm i webextension-polyfill\`.`); - } - this.store = browser.storage.local; - this.rootKey = rootKey; - } - async _getWholeStore() { - const result = await this.store.get({ [this.rootKey]: {} }); - return result[this.rootKey]; - } - _buildQuery(index) { - let query = null; - for (const key of [this.rootKey, ...index].reverse()) { - query = { [key]: query }; - } - return query; - } - async _buildQueryFromStore(transformFn) { - const store = await this._getWholeStore(); - return { [this.rootKey]: transformFn(store) }; - } - async get(index) { - const query = this._buildQuery(index); - const response = await this.store.get(query); - stripNulls(response); - if (!response) { - return; - } - if ((0,utils/* isJSONValue */.qT)(response)) { - if ((0,utils/* isObject */.Kn)(response)) { - return getValueFromNestedObject(response, [this.rootKey, ...index]); - } - else { - return response; - } - } - console.warn(`Unexpected value found in storage for index ${JSON.stringify(index)}. Ignoring. - ${JSON.stringify(response, null, 2)}`); - } - async update(index, transformFn) { - if (index.length === 0) { - throw Error("The index must contain at least one property to update."); - } - const query = await this._buildQueryFromStore(store => updateNestedObject(store, index, transformFn)); - return this.store.set(query); - } - async delete(index) { - try { - const query = await this._buildQueryFromStore(store => deleteKeyFromNestedObject(store, index)); - return this.store.set(query); - } - catch (e) { - console.warn("Ignoring key", e); - } - } -} -/* harmony default export */ const webext_storage = (WebExtStore); - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/core/upload/uploader.js -const DEFAULT_UPLOAD_TIMEOUT_MS = 10000; -var UploadResultStatus; -(function (UploadResultStatus) { - UploadResultStatus[UploadResultStatus["RecoverableFailure"] = 0] = "RecoverableFailure"; - UploadResultStatus[UploadResultStatus["UnrecoverableFailure"] = 1] = "UnrecoverableFailure"; - UploadResultStatus[UploadResultStatus["Success"] = 2] = "Success"; -})(UploadResultStatus || (UploadResultStatus = {})); - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/platform/webext/uploader.js - -class BrowserUploader { - async post(url, body, headers = {}) { - const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), DEFAULT_UPLOAD_TIMEOUT_MS); - let response; - try { - response = await fetch(url.toString(), { - headers, - method: "POST", - body: body, - keepalive: true, - credentials: "omit", - signal: controller.signal, - redirect: "error", - }); - } - catch (e) { - if (e instanceof DOMException) { - console.error("Timeout while attempting to upload ping.", e); - } - else if (e instanceof TypeError) { - console.error("Network error while attempting to upload ping.", e); - } - else { - console.error("Unknown error while attempting to upload ping.", e); - } - clearTimeout(timeout); - return { result: 0 }; - } - clearTimeout(timeout); - return { - result: 2, - status: response.status - }; - } -} -/* harmony default export */ const uploader = (new BrowserUploader()); - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/platform/webext/platform_info.js -const WebExtPlatformInfo = { - async os() { - const platformInfo = await browser.runtime.getPlatformInfo(); - switch (platformInfo.os) { - case "mac": - return "Darwin"; - case "win": - return "Windows"; - case "android": - return "Android"; - case "cros": - return "ChromeOS"; - case "linux": - return "Linux"; - case "openbsd": - return "OpenBSD"; - default: - return "Unknown"; - } - }, - async osVersion() { - return Promise.resolve("Unknown"); - }, - async arch() { - const platformInfo = await browser.runtime.getPlatformInfo(); - return platformInfo.arch; - }, - async locale() { - return Promise.resolve(navigator.language || "und"); - } -}; -/* harmony default export */ const platform_info = (WebExtPlatformInfo); - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/platform/webext/index.js - - - -const WebExtPlatform = { - Storage: webext_storage, - uploader: uploader, - info: platform_info, - name: "webext" -}; -/* harmony default export */ const webext = (WebExtPlatform); - -;// CONCATENATED MODULE: ../../node_modules/@mozilla/glean/dist/webext/index/webext.js - - -/* harmony default export */ const index_webext = ({ - initialize(applicationId, uploadEnabled, config) { - glean.setPlatform(webext); - glean.initialize(applicationId, uploadEnabled, config); - }, - setUploadEnabled(flag) { - glean.setUploadEnabled(flag); - }, - setLogPings(flag) { - glean.setLogPings(flag); - }, - setDebugViewTag(value) { - glean.setDebugViewTag(value); - }, - unsetDebugViewTag() { - glean.unsetDebugViewTag(); - }, - setSourceTags(value) { - glean.setSourceTags(value); - }, - unsetSourceTags() { - glean.unsetSourceTags(); - }, - async testResetGlean(applicationId, uploadEnabled = true, config) { - return glean.testResetGlean(applicationId, uploadEnabled, config); - } -}); - - -/***/ }), - -/***/ 2971: -/*!********************************************!*\ - !*** ../../node_modules/base-64/base64.js ***! - \********************************************/ -/***/ (function(module, exports, __webpack_require__) { - -/* module decorator */ module = __webpack_require__.nmd(module); -var __WEBPACK_AMD_DEFINE_RESULT__;/*! http://mths.be/base64 v0.1.0 by @mathias | MIT license */ -;(function(root) { - - // Detect free variables `exports`. - var freeExports = true && exports; - - // Detect free variable `module`. - var freeModule = true && module && - module.exports == freeExports && module; - - // Detect free variable `global`, from Node.js or Browserified code, and use - // it as `root`. - var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g; - if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { - root = freeGlobal; - } - - /*--------------------------------------------------------------------------*/ - - var InvalidCharacterError = function(message) { - this.message = message; - }; - InvalidCharacterError.prototype = new Error; - InvalidCharacterError.prototype.name = 'InvalidCharacterError'; - - var error = function(message) { - // Note: the error messages used throughout this file match those used by - // the native `atob`/`btoa` implementation in Chromium. - throw new InvalidCharacterError(message); - }; - - var TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - // http://whatwg.org/html/common-microsyntaxes.html#space-character - var REGEX_SPACE_CHARACTERS = /[\t\n\f\r ]/g; - - // `decode` is designed to be fully compatible with `atob` as described in the - // HTML Standard. http://whatwg.org/html/webappapis.html#dom-windowbase64-atob - // The optimized base64-decoding algorithm used is based on @atk’s excellent - // implementation. https://gist.github.com/atk/1020396 - var decode = function(input) { - input = String(input) - .replace(REGEX_SPACE_CHARACTERS, ''); - var length = input.length; - if (length % 4 == 0) { - input = input.replace(/==?$/, ''); - length = input.length; - } - if ( - length % 4 == 1 || - // http://whatwg.org/C#alphanumeric-ascii-characters - /[^+a-zA-Z0-9/]/.test(input) - ) { - error( - 'Invalid character: the string to be decoded is not correctly encoded.' - ); - } - var bitCounter = 0; - var bitStorage; - var buffer; - var output = ''; - var position = -1; - while (++position < length) { - buffer = TABLE.indexOf(input.charAt(position)); - bitStorage = bitCounter % 4 ? bitStorage * 64 + buffer : buffer; - // Unless this is the first of a group of 4 characters… - if (bitCounter++ % 4) { - // …convert the first 8 bits to a single ASCII character. - output += String.fromCharCode( - 0xFF & bitStorage >> (-2 * bitCounter & 6) - ); - } - } - return output; - }; - - // `encode` is designed to be fully compatible with `btoa` as described in the - // HTML Standard: http://whatwg.org/html/webappapis.html#dom-windowbase64-btoa - var encode = function(input) { - input = String(input); - if (/[^\0-\xFF]/.test(input)) { - // Note: no need to special-case astral symbols here, as surrogates are - // matched, and the input is supposed to only contain ASCII anyway. - error( - 'The string to be encoded contains characters outside of the ' + - 'Latin1 range.' - ); - } - var padding = input.length % 3; - var output = ''; - var position = -1; - var a; - var b; - var c; - var d; - var buffer; - // Make sure any padding is handled outside of the loop. - var length = input.length - padding; - - while (++position < length) { - // Read three bytes, i.e. 24 bits. - a = input.charCodeAt(position) << 16; - b = input.charCodeAt(++position) << 8; - c = input.charCodeAt(++position); - buffer = a + b + c; - // Turn the 24 bits into four chunks of 6 bits each, and append the - // matching character for each of them to the output. - output += ( - TABLE.charAt(buffer >> 18 & 0x3F) + - TABLE.charAt(buffer >> 12 & 0x3F) + - TABLE.charAt(buffer >> 6 & 0x3F) + - TABLE.charAt(buffer & 0x3F) - ); - } - - if (padding == 2) { - a = input.charCodeAt(position) << 8; - b = input.charCodeAt(++position); - buffer = a + b; - output += ( - TABLE.charAt(buffer >> 10) + - TABLE.charAt((buffer >> 4) & 0x3F) + - TABLE.charAt((buffer << 2) & 0x3F) + - '=' - ); - } else if (padding == 1) { - buffer = input.charCodeAt(position); - output += ( - TABLE.charAt(buffer >> 2) + - TABLE.charAt((buffer << 4) & 0x3F) + - '==' - ); - } - - return output; - }; - - var base64 = { - 'encode': encode, - 'decode': decode, - 'version': '0.1.0' - }; - - // Some AMD build optimizers, like r.js, check for specific condition patterns - // like the following: - if ( - true - ) { - !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { - return base64; - }).call(exports, __webpack_require__, exports, module), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else { var key; } - -}(this)); - - -/***/ }), - -/***/ 6903: -/*!*****************************************!*\ - !*** ../../node_modules/clone/clone.js ***! - \*****************************************/ -/***/ ((module) => { - -var clone = (function() { -'use strict'; - -function _instanceof(obj, type) { - return type != null && obj instanceof type; -} - -var nativeMap; -try { - nativeMap = Map; -} catch(_) { - // maybe a reference error because no `Map`. Give it a dummy value that no - // value will ever be an instanceof. - nativeMap = function() {}; -} - -var nativeSet; -try { - nativeSet = Set; -} catch(_) { - nativeSet = function() {}; -} - -var nativePromise; -try { - nativePromise = Promise; -} catch(_) { - nativePromise = function() {}; -} - -/** - * Clones (copies) an Object using deep copying. - * - * This function supports circular references by default, but if you are certain - * there are no circular references in your object, you can save some CPU time - * by calling clone(obj, false). - * - * Caution: if `circular` is false and `parent` contains circular references, - * your program may enter an infinite loop and crash. - * - * @param `parent` - the object to be cloned - * @param `circular` - set to true if the object to be cloned may contain - * circular references. (optional - true by default) - * @param `depth` - set to a number if the object is only to be cloned to - * a particular depth. (optional - defaults to Infinity) - * @param `prototype` - sets the prototype to be used when cloning an object. - * (optional - defaults to parent prototype). - * @param `includeNonEnumerable` - set to true if the non-enumerable properties - * should be cloned as well. Non-enumerable properties on the prototype - * chain will be ignored. (optional - false by default) -*/ -function clone(parent, circular, depth, prototype, includeNonEnumerable) { - if (typeof circular === 'object') { - depth = circular.depth; - prototype = circular.prototype; - includeNonEnumerable = circular.includeNonEnumerable; - circular = circular.circular; - } - // maintain two arrays for circular references, where corresponding parents - // and children have the same index - var allParents = []; - var allChildren = []; - - var useBuffer = typeof Buffer != 'undefined'; - - if (typeof circular == 'undefined') - circular = true; - - if (typeof depth == 'undefined') - depth = Infinity; - - // recurse this function so we don't reset allParents and allChildren - function _clone(parent, depth) { - // cloning null always returns null - if (parent === null) - return null; - - if (depth === 0) - return parent; - - var child; - var proto; - if (typeof parent != 'object') { - return parent; - } - - if (_instanceof(parent, nativeMap)) { - child = new nativeMap(); - } else if (_instanceof(parent, nativeSet)) { - child = new nativeSet(); - } else if (_instanceof(parent, nativePromise)) { - child = new nativePromise(function (resolve, reject) { - parent.then(function(value) { - resolve(_clone(value, depth - 1)); - }, function(err) { - reject(_clone(err, depth - 1)); - }); - }); - } else if (clone.__isArray(parent)) { - child = []; - } else if (clone.__isRegExp(parent)) { - child = new RegExp(parent.source, __getRegExpFlags(parent)); - if (parent.lastIndex) child.lastIndex = parent.lastIndex; - } else if (clone.__isDate(parent)) { - child = new Date(parent.getTime()); - } else if (useBuffer && Buffer.isBuffer(parent)) { - child = new Buffer(parent.length); - parent.copy(child); - return child; - } else if (_instanceof(parent, Error)) { - child = Object.create(parent); - } else { - if (typeof prototype == 'undefined') { - proto = Object.getPrototypeOf(parent); - child = Object.create(proto); - } - else { - child = Object.create(prototype); - proto = prototype; - } - } - - if (circular) { - var index = allParents.indexOf(parent); - - if (index != -1) { - return allChildren[index]; - } - allParents.push(parent); - allChildren.push(child); - } - - if (_instanceof(parent, nativeMap)) { - parent.forEach(function(value, key) { - var keyChild = _clone(key, depth - 1); - var valueChild = _clone(value, depth - 1); - child.set(keyChild, valueChild); - }); - } - if (_instanceof(parent, nativeSet)) { - parent.forEach(function(value) { - var entryChild = _clone(value, depth - 1); - child.add(entryChild); - }); - } - - for (var i in parent) { - var attrs; - if (proto) { - attrs = Object.getOwnPropertyDescriptor(proto, i); - } - - if (attrs && attrs.set == null) { - continue; - } - child[i] = _clone(parent[i], depth - 1); - } - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(parent); - for (var i = 0; i < symbols.length; i++) { - // Don't need to worry about cloning a symbol because it is a primitive, - // like a number or string. - var symbol = symbols[i]; - var descriptor = Object.getOwnPropertyDescriptor(parent, symbol); - if (descriptor && !descriptor.enumerable && !includeNonEnumerable) { - continue; - } - child[symbol] = _clone(parent[symbol], depth - 1); - if (!descriptor.enumerable) { - Object.defineProperty(child, symbol, { - enumerable: false - }); - } - } - } - - if (includeNonEnumerable) { - var allPropertyNames = Object.getOwnPropertyNames(parent); - for (var i = 0; i < allPropertyNames.length; i++) { - var propertyName = allPropertyNames[i]; - var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName); - if (descriptor && descriptor.enumerable) { - continue; - } - child[propertyName] = _clone(parent[propertyName], depth - 1); - Object.defineProperty(child, propertyName, { - enumerable: false - }); - } - } - - return child; - } - - return _clone(parent, depth); -} - -/** - * Simple flat clone using prototype, accepts only objects, usefull for property - * override on FLAT configuration object (no nested props). - * - * USE WITH CAUTION! This may not behave as you wish if you do not know how this - * works. - */ -clone.clonePrototype = function clonePrototype(parent) { - if (parent === null) - return null; - - var c = function () {}; - c.prototype = parent; - return new c(); -}; - -// private utility functions - -function __objToStr(o) { - return Object.prototype.toString.call(o); -} -clone.__objToStr = __objToStr; - -function __isDate(o) { - return typeof o === 'object' && __objToStr(o) === '[object Date]'; -} -clone.__isDate = __isDate; - -function __isArray(o) { - return typeof o === 'object' && __objToStr(o) === '[object Array]'; -} -clone.__isArray = __isArray; - -function __isRegExp(o) { - return typeof o === 'object' && __objToStr(o) === '[object RegExp]'; -} -clone.__isRegExp = __isRegExp; - -function __getRegExpFlags(re) { - var flags = ''; - if (re.global) flags += 'g'; - if (re.ignoreCase) flags += 'i'; - if (re.multiline) flags += 'm'; - return flags; -} -clone.__getRegExpFlags = __getRegExpFlags; - -return clone; -})(); - -if ( true && module.exports) { - module.exports = clone; -} - - -/***/ }), - -/***/ 341: -/*!****************************************!*\ - !*** ../../node_modules/jsan/index.js ***! - \****************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -module.exports = __webpack_require__(/*! ./lib */ 813); - - -/***/ }), - -/***/ 6077: -/*!********************************************!*\ - !*** ../../node_modules/jsan/lib/cycle.js ***! - \********************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -var pathGetter = __webpack_require__(/*! ./path-getter */ 3284); -var utils = __webpack_require__(/*! ./utils */ 1062); - -var WMap = typeof WeakMap !== 'undefined'? - WeakMap: - function() { - var keys = []; - var values = []; - return { - set: function(key, value) { - keys.push(key); - values.push(value); - }, - get: function(key) { - for (var i = 0; i < keys.length; i++) { - if (keys[i] === key) { - return values[i]; - } - } - } - } - }; - -// Based on https://github.com/douglascrockford/JSON-js/blob/master/cycle.js - -exports.decycle = function decycle(object, options, replacer) { - 'use strict'; - - var map = new WMap() - - var noCircularOption = !Object.prototype.hasOwnProperty.call(options, 'circular'); - var withRefs = options.refs !== false; - - return (function derez(_value, path, key) { - - // The derez recurses through the object, producing the deep copy. - - var i, // The loop counter - name, // Property name - nu; // The new object or array - - // typeof null === 'object', so go on if this value is really an object but not - // one of the weird builtin objects. - - var value = typeof replacer === 'function' ? replacer(key || '', _value) : _value; - - if (options.date && value instanceof Date) { - return {$jsan: 'd' + value.getTime()}; - } - if (options.regex && value instanceof RegExp) { - return {$jsan: 'r' + utils.getRegexFlags(value) + ',' + value.source}; - } - if (options['function'] && typeof value === 'function') { - return {$jsan: 'f' + utils.stringifyFunction(value, options['function'])} - } - if (options['nan'] && typeof value === 'number' && isNaN(value)) { - return {$jsan: 'n'} - } - if (options['infinity']) { - if (Number.POSITIVE_INFINITY === value) return {$jsan: 'i'} - if (Number.NEGATIVE_INFINITY === value) return {$jsan: 'y'} - } - if (options['undefined'] && value === undefined) { - return {$jsan: 'u'} - } - if (options['error'] && value instanceof Error) { - return {$jsan: 'e' + value.message} - } - if (options['symbol'] && typeof value === 'symbol') { - var symbolKey = Symbol.keyFor(value) - if (symbolKey !== undefined) { - return {$jsan: 'g' + symbolKey} - } - - // 'Symbol(foo)'.slice(7, -1) === 'foo' - return {$jsan: 's' + value.toString().slice(7, -1)} - } - - if (options['map'] && typeof Map === 'function' && value instanceof Map && typeof Array.from === 'function') { - return {$jsan: 'm' + JSON.stringify(decycle(Array.from(value), options, replacer))} - } - - if (options['set'] && typeof Set === 'function' && value instanceof Set && typeof Array.from === 'function') { - return {$jsan: 'l' + JSON.stringify(decycle(Array.from(value), options, replacer))} - } - - if (value && typeof value.toJSON === 'function') { - try { - value = value.toJSON(key); - } catch (error) { - var keyString = (key || '$'); - return "toJSON failed for '" + (map.get(value) || keyString) + "'"; - } - } - - if (typeof value === 'object' && value !== null && - !(value instanceof Boolean) && - !(value instanceof Date) && - !(value instanceof Number) && - !(value instanceof RegExp) && - !(value instanceof String) && - !(typeof value === 'symbol') && - !(value instanceof Error)) { - - // If the value is an object or array, look to see if we have already - // encountered it. If so, return a $ref/path object. - - if (typeof value === 'object') { - var foundPath = map.get(value); - if (foundPath) { - if (noCircularOption && withRefs) { - return {$jsan: foundPath}; - } - if (path.indexOf(foundPath) === 0) { - if (!noCircularOption) { - return typeof options.circular === 'function'? - options.circular(value, path, foundPath): - options.circular; - } - return {$jsan: foundPath}; - } - if (withRefs) return {$jsan: foundPath}; - } - map.set(value, path); - } - - - // If it is an array, replicate the array. - - if (Object.prototype.toString.apply(value) === '[object Array]') { - nu = []; - for (i = 0; i < value.length; i += 1) { - nu[i] = derez(value[i], path + '[' + i + ']', i); - } - } else { - - // If it is an object, replicate the object. - - nu = {}; - for (name in value) { - if (Object.prototype.hasOwnProperty.call(value, name)) { - var nextPath = /^\w+$/.test(name) ? - '.' + name : - '[' + JSON.stringify(name) + ']'; - nu[name] = name === '$jsan' ? [derez(value[name], path + nextPath)] : derez(value[name], path + nextPath, name); - } - } - } - return nu; - } - return value; - }(object, '$')); -}; - - -exports.retrocycle = function retrocycle($) { - 'use strict'; - - - return (function rez(value) { - - // The rez function walks recursively through the object looking for $jsan - // properties. When it finds one that has a value that is a path, then it - // replaces the $jsan object with a reference to the value that is found by - // the path. - - var i, item, name, path; - - if (value && typeof value === 'object') { - if (Object.prototype.toString.apply(value) === '[object Array]') { - for (i = 0; i < value.length; i += 1) { - item = value[i]; - if (item && typeof item === 'object') { - if (item.$jsan) { - value[i] = utils.restore(item.$jsan, $); - } else { - rez(item); - } - } - } - } else { - for (name in value) { - // base case passed raw object - if(typeof value[name] === 'string' && name === '$jsan'){ - return utils.restore(value.$jsan, $); - break; - } - else { - if (name === '$jsan') { - value[name] = value[name][0]; - } - if (typeof value[name] === 'object') { - item = value[name]; - if (item && typeof item === 'object') { - if (item.$jsan) { - value[name] = utils.restore(item.$jsan, $); - } else { - rez(item); - } - } - } - } - } - } - } - return value; - }($)); -}; - - -/***/ }), - -/***/ 813: -/*!********************************************!*\ - !*** ../../node_modules/jsan/lib/index.js ***! - \********************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -var cycle = __webpack_require__(/*! ./cycle */ 6077); - -exports.stringify = function stringify(value, replacer, space, _options) { - - if (arguments.length < 4) { - try { - if (arguments.length === 1) { - return JSON.stringify(value); - } else { - return JSON.stringify.apply(JSON, arguments); - } - } catch (e) {} - } - - var options = _options || false; - if (typeof options === 'boolean') { - options = { - 'date': options, - 'function': options, - 'regex': options, - 'undefined': options, - 'error': options, - 'symbol': options, - 'map': options, - 'set': options, - 'nan': options, - 'infinity': options - } - } - - var decycled = cycle.decycle(value, options, replacer); - if (arguments.length === 1) { - return JSON.stringify(decycled); - } else { - // decycle already handles when replacer is a function. - return JSON.stringify(decycled, Array.isArray(replacer) ? replacer : null, space); - } -} - -exports.parse = function parse(text, reviver) { - var needsRetrocycle = /"\$jsan"/.test(text); - var parsed; - if (arguments.length === 1) { - parsed = JSON.parse(text); - } else { - parsed = JSON.parse(text, reviver); - } - if (needsRetrocycle) { - parsed = cycle.retrocycle(parsed); - } - return parsed; -} - - -/***/ }), - -/***/ 3284: -/*!**************************************************!*\ - !*** ../../node_modules/jsan/lib/path-getter.js ***! - \**************************************************/ -/***/ ((module) => { - -module.exports = pathGetter; - -function pathGetter(obj, path) { - if (path !== '$') { - var paths = getPaths(path); - for (var i = 0; i < paths.length; i++) { - path = paths[i].toString().replace(/\\"/g, '"'); - if (typeof obj[path] === 'undefined' && i !== paths.length - 1) continue; - obj = obj[path]; - } - } - return obj; -} - -function getPaths(pathString) { - var regex = /(?:\.(\w+))|(?:\[(\d+)\])|(?:\["((?:[^\\"]|\\.)*)"\])/g; - var matches = []; - var match; - while (match = regex.exec(pathString)) { - matches.push( match[1] || match[2] || match[3] ); - } - return matches; -} - - -/***/ }), - -/***/ 1062: -/*!********************************************!*\ - !*** ../../node_modules/jsan/lib/utils.js ***! - \********************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -var pathGetter = __webpack_require__(/*! ./path-getter */ 3284); -var jsan = __webpack_require__(/*! ./ */ 813); - -exports.getRegexFlags = function getRegexFlags(regex) { - var flags = ''; - if (regex.ignoreCase) flags += 'i'; - if (regex.global) flags += 'g'; - if (regex.multiline) flags += 'm'; - return flags; -}; - -exports.stringifyFunction = function stringifyFunction(fn, customToString) { - if (typeof customToString === 'function') { - return customToString(fn); - } - var str = fn.toString(); - var match = str.match(/^[^{]*{|^[^=]*=>/); - var start = match ? match[0] : ' '; - var end = str[str.length - 1] === '}' ? '}' : ''; - return start.replace(/\r\n|\n/g, ' ').replace(/\s+/g, ' ') + ' /* ... */ ' + end; -}; - -exports.restore = function restore(obj, root) { - var type = obj[0]; - var rest = obj.slice(1); - switch(type) { - case '$': - return pathGetter(root, obj); - case 'r': - var comma = rest.indexOf(','); - var flags = rest.slice(0, comma); - var source = rest.slice(comma + 1); - return RegExp(source, flags); - case 'd': - return new Date(+rest); - case 'f': - var fn = function() { throw new Error("can't run jsan parsed function") }; - fn.toString = function() { return rest; }; - return fn; - case 'u': - return undefined; - case 'e': - var error = new Error(rest); - error.stack = 'Stack is unavailable for jsan parsed errors'; - return error; - case 's': - return Symbol(rest); - case 'g': - return Symbol.for(rest); - case 'm': - return new Map(jsan.parse(rest)); - case 'l': - return new Set(jsan.parse(rest)); - case 'n': - return NaN; - case 'i': - return Infinity; - case 'y': - return -Infinity; - default: - console.warn('unknown type', obj); - return obj; - } -} - - -/***/ }), - -/***/ 1299: -/*!*************************************************************!*\ - !*** ../../node_modules/linked-list/_source/linked-list.js ***! - \*************************************************************/ -/***/ ((module) => { - -"use strict"; - - -/** - * Constants. - */ - -var errorMessage; - -errorMessage = 'An argument without append, prepend, ' + - 'or detach methods was given to `List'; - -/** - * Creates a new List: A linked list is a bit like an Array, but - * knows nothing about how many items are in it, and knows only about its - * first (`head`) and last (`tail`) items. Each item (e.g. `head`, `tail`, - * &c.) knows which item comes before or after it (its more like the - * implementation of the DOM in JavaScript). - * @global - * @private - * @constructor - * @class Represents an instance of List. - */ - -function List(/*items...*/) { - if (arguments.length) { - return List.from(arguments); - } -} - -var ListPrototype; - -ListPrototype = List.prototype; - -/** - * Creates a new list from the arguments (each a list item) passed in. - * @name List.of - * @param {...ListItem} [items] - Zero or more items to attach. - * @returns {list} - A new instance of List. - */ - -List.of = function (/*items...*/) { - return List.from.call(this, arguments); -}; - -/** - * Creates a new list from the given array-like object (each a list item) - * passed in. - * @name List.from - * @param {ListItem[]} [items] - The items to append. - * @returns {list} - A new instance of List. - */ -List.from = function (items) { - var list = new this(), length, iterator, item; - - if (items && (length = items.length)) { - iterator = -1; - - while (++iterator < length) { - item = items[iterator]; - - if (item !== null && item !== undefined) { - list.append(item); - } - } - } - - return list; -}; - -/** - * List#head - * Default to `null`. - */ -ListPrototype.head = null; - -/** - * List#tail - * Default to `null`. - */ -ListPrototype.tail = null; - -/** - * Returns the list's items as an array. This does *not* detach the items. - * @name List#toArray - * @returns {ListItem[]} - An array of (still attached) ListItems. - */ -ListPrototype.toArray = function () { - var item = this.head, - result = []; - - while (item) { - result.push(item); - item = item.next; - } - - return result; -}; - -/** - * Prepends the given item to the list: Item will be the new first item - * (`head`). - * @name List#prepend - * @param {ListItem} item - The item to prepend. - * @returns {ListItem} - An instance of ListItem (the given item). - */ -ListPrototype.prepend = function (item) { - if (!item) { - return false; - } - - if (!item.append || !item.prepend || !item.detach) { - throw new Error(errorMessage + '#prepend`.'); - } - - var self, head; - - // Cache self. - self = this; - - // If self has a first item, defer prepend to the first items prepend - // method, and return the result. - head = self.head; - - if (head) { - return head.prepend(item); - } - - // ...otherwise, there is no `head` (or `tail`) item yet. - - // Detach the prependee. - item.detach(); - - // Set the prependees parent list to reference self. - item.list = self; - - // Set self's first item to the prependee, and return the item. - self.head = item; - - return item; -}; - -/** - * Appends the given item to the list: Item will be the new last item (`tail`) - * if the list had a first item, and its first item (`head`) otherwise. - * @name List#append - * @param {ListItem} item - The item to append. - * @returns {ListItem} - An instance of ListItem (the given item). - */ - -ListPrototype.append = function (item) { - if (!item) { - return false; - } - - if (!item.append || !item.prepend || !item.detach) { - throw new Error(errorMessage + '#append`.'); - } - - var self, head, tail; - - // Cache self. - self = this; - - // If self has a last item, defer appending to the last items append - // method, and return the result. - tail = self.tail; - - if (tail) { - return tail.append(item); - } - - // If self has a first item, defer appending to the first items append - // method, and return the result. - head = self.head; - - if (head) { - return head.append(item); - } - - // ...otherwise, there is no `tail` or `head` item yet. - - // Detach the appendee. - item.detach(); - - // Set the appendees parent list to reference self. - item.list = self; - - // Set self's first item to the appendee, and return the item. - self.head = item; - - return item; -}; - -/** - * Creates a new ListItem: A linked list item is a bit like DOM node: - * It knows only about its "parent" (`list`), the item before it (`prev`), - * and the item after it (`next`). - * @global - * @private - * @constructor - * @class Represents an instance of ListItem. - */ - -function ListItem() {} - -List.Item = ListItem; - -var ListItemPrototype = ListItem.prototype; - -ListItemPrototype.next = null; - -ListItemPrototype.prev = null; - -ListItemPrototype.list = null; - -/** - * Detaches the item operated on from its parent list. - * @name ListItem#detach - * @returns {ListItem} - The item operated on. - */ -ListItemPrototype.detach = function () { - // Cache self, the parent list, and the previous and next items. - var self = this, - list = self.list, - prev = self.prev, - next = self.next; - - // If the item is already detached, return self. - if (!list) { - return self; - } - - // If self is the last item in the parent list, link the lists last item - // to the previous item. - if (list.tail === self) { - list.tail = prev; - } - - // If self is the first item in the parent list, link the lists first item - // to the next item. - if (list.head === self) { - list.head = next; - } - - // If both the last and first items in the parent list are the same, - // remove the link to the last item. - if (list.tail === list.head) { - list.tail = null; - } - - // If a previous item exists, link its next item to selfs next item. - if (prev) { - prev.next = next; - } - - // If a next item exists, link its previous item to selfs previous item. - if (next) { - next.prev = prev; - } - - // Remove links from self to both the next and previous items, and to the - // parent list. - self.prev = self.next = self.list = null; - - // Return self. - return self; -}; - -/** - * Prepends the given item *before* the item operated on. - * @name ListItem#prepend - * @param {ListItem} item - The item to prepend. - * @returns {ListItem} - The item operated on, or false when that item is not - * attached. - */ -ListItemPrototype.prepend = function (item) { - if (!item || !item.append || !item.prepend || !item.detach) { - throw new Error(errorMessage + 'Item#prepend`.'); - } - - // Cache self, the parent list, and the previous item. - var self = this, - list = self.list, - prev = self.prev; - - // If self is detached, return false. - if (!list) { - return false; - } - - // Detach the prependee. - item.detach(); - - // If self has a previous item... - if (prev) { - // ...link the prependees previous item, to selfs previous item. - item.prev = prev; - - // ...link the previous items next item, to self. - prev.next = item; - } - - // Set the prependees next item to self. - item.next = self; - - // Set the prependees parent list to selfs parent list. - item.list = list; - - // Set the previous item of self to the prependee. - self.prev = item; - - // If self is the first item in the parent list, link the lists first item - // to the prependee. - if (self === list.head) { - list.head = item; - } - - // If the the parent list has no last item, link the lists last item to - // self. - if (!list.tail) { - list.tail = self; - } - - // Return the prependee. - return item; -}; - -/** - * Appends the given item *after* the item operated on. - * @name ListItem#append - * @param {ListItem} item - The item to append. - * @returns {ListItem} - The item operated on, or false when that item is not - * attached. - */ -ListItemPrototype.append = function (item) { - // If item is falsey, return false. - if (!item || !item.append || !item.prepend || !item.detach) { - throw new Error(errorMessage + 'Item#append`.'); - } - - // Cache self, the parent list, and the next item. - var self = this, - list = self.list, - next = self.next; - - // If self is detached, return false. - if (!list) { - return false; - } - - // Detach the appendee. - item.detach(); - - // If self has a next item... - if (next) { - // ...link the appendees next item, to selfs next item. - item.next = next; - - // ...link the next items previous item, to the appendee. - next.prev = item; - } - - // Set the appendees previous item to self. - item.prev = self; - - // Set the appendees parent list to selfs parent list. - item.list = list; - - // Set the next item of self to the appendee. - self.next = item; - - // If the the parent list has no last item or if self is the parent lists - // last item, link the lists last item to the appendee. - if (self === list.tail || !list.tail) { - list.tail = item; - } - - // Return the appendee. - return item; -}; - -/** - * Expose `List`. - */ - -module.exports = List; - - -/***/ }), - -/***/ 9426: -/*!***********************************************!*\ - !*** ../../node_modules/linked-list/index.js ***! - \***********************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -module.exports = __webpack_require__(/*! ./_source/linked-list.js */ 1299); - - -/***/ }), - -/***/ 8391: -/*!************************************************!*\ - !*** ../../node_modules/querystring/decode.js ***! - \************************************************/ -/***/ ((module) => { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - -// If obj.hasOwnProperty has been overridden, then calling -// obj.hasOwnProperty(prop) will break. -// See: https://github.com/joyent/node/issues/1707 -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -module.exports = function(qs, sep, eq, options) { - sep = sep || '&'; - eq = eq || '='; - var obj = {}; - - if (typeof qs !== 'string' || qs.length === 0) { - return obj; - } - - var regexp = /\+/g; - qs = qs.split(sep); - - var maxKeys = 1000; - if (options && typeof options.maxKeys === 'number') { - maxKeys = options.maxKeys; - } - - var len = qs.length; - // maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0 && len > maxKeys) { - len = maxKeys; - } - - for (var i = 0; i < len; ++i) { - var x = qs[i].replace(regexp, '%20'), - idx = x.indexOf(eq), - kstr, vstr, k, v; - - if (idx >= 0) { - kstr = x.substr(0, idx); - vstr = x.substr(idx + 1); - } else { - kstr = x; - vstr = ''; - } - - k = decodeURIComponent(kstr); - v = decodeURIComponent(vstr); - - if (!hasOwnProperty(obj, k)) { - obj[k] = v; - } else if (Array.isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; - } - } - - return obj; -}; - - -/***/ }), - -/***/ 4221: -/*!************************************************!*\ - !*** ../../node_modules/querystring/encode.js ***! - \************************************************/ -/***/ ((module) => { - -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - - -var stringifyPrimitive = function(v) { - switch (typeof v) { - case 'string': - return v; - - case 'boolean': - return v ? 'true' : 'false'; - - case 'number': - return isFinite(v) ? v : ''; - - default: - return ''; - } -}; - -module.exports = function(obj, sep, eq, name) { - sep = sep || '&'; - eq = eq || '='; - if (obj === null) { - obj = undefined; - } - - if (typeof obj === 'object') { - return Object.keys(obj).map(function(k) { - var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; - if (Array.isArray(obj[k])) { - return obj[k].map(function(v) { - return ks + encodeURIComponent(stringifyPrimitive(v)); - }).join(sep); - } else { - return ks + encodeURIComponent(stringifyPrimitive(obj[k])); - } - }).join(sep); - - } - - if (!name) return ''; - return encodeURIComponent(stringifyPrimitive(name)) + eq + - encodeURIComponent(stringifyPrimitive(obj)); -}; - - -/***/ }), - -/***/ 3329: -/*!***********************************************!*\ - !*** ../../node_modules/querystring/index.js ***! - \***********************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -exports.decode = exports.parse = __webpack_require__(/*! ./decode */ 8391); -exports.encode = exports.stringify = __webpack_require__(/*! ./encode */ 4221); - - -/***/ }), - -/***/ 4544: -/*!*****************************************************!*\ - !*** ../../node_modules/remotedev/lib/constants.js ***! - \*****************************************************/ -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -exports.__esModule = true; -var defaultSocketOptions = exports.defaultSocketOptions = { - secure: true, - hostname: 'remotedev.io', - port: 443, - autoReconnect: true, - autoReconnectOptions: { - randomness: 60000 - } -}; - -/***/ }), - -/***/ 1538: -/*!****************************************************!*\ - !*** ../../node_modules/remotedev/lib/devTools.js ***! - \****************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -exports.__esModule = true; -exports.send = undefined; -exports.extractState = extractState; -exports.generateId = generateId; -exports.start = start; -exports.connect = connect; -exports.connectViaExtension = connectViaExtension; - -var _jsan = __webpack_require__(/*! jsan */ 341); - -var _socketclusterClient = __webpack_require__(/*! socketcluster-client */ 3030); - -var _socketclusterClient2 = _interopRequireDefault(_socketclusterClient); - -var _rnHostDetect = __webpack_require__(/*! rn-host-detect */ 3084); - -var _rnHostDetect2 = _interopRequireDefault(_rnHostDetect); - -var _constants = __webpack_require__(/*! ./constants */ 4544); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var socket = undefined; -var channel = undefined; -var listeners = {}; - -function extractState(message) { - if (!message || !message.state) return undefined; - if (typeof message.state === 'string') return (0, _jsan.parse)(message.state); - return message.state; -} - -function generateId() { - return Math.random().toString(36).substr(2); -} - -function handleMessages(message) { - if (!message.payload) message.payload = message.action; - Object.keys(listeners).forEach(function (id) { - if (message.instanceId && id !== message.instanceId) return; - if (typeof listeners[id] === 'function') listeners[id](message);else listeners[id].forEach(function (fn) { - fn(message); - }); - }); -} - -function watch() { - if (channel) return; - socket.emit('login', 'master', function (err, channelName) { - if (err) { - console.log(err);return; - } - channel = socket.subscribe(channelName); - channel.watch(handleMessages); - socket.on(channelName, handleMessages); - }); -} - -function connectToServer(options) { - if (socket) return; - var socketOptions = undefined; - if (options.port) { - socketOptions = { - port: options.port, - hostname: (0, _rnHostDetect2.default)(options.hostname || 'localhost'), - secure: !!options.secure - }; - } else socketOptions = _constants.defaultSocketOptions; - socket = _socketclusterClient2.default.create(socketOptions); - watch(); -} - -function start(options) { - if (options) { - if (options.port && !options.hostname) { - options.hostname = 'localhost'; - } - } - connectToServer(options); -} - -function transformAction(action, config) { - if (action.action) return action; - var liftedAction = { timestamp: Date.now() }; - if (action) { - if (config.getActionType) liftedAction.action = config.getActionType(action);else { - if (typeof action === 'string') liftedAction.action = { type: action };else if (!action.type) liftedAction.action = { type: 'update' };else liftedAction.action = action; - } - } else { - liftedAction.action = { type: action }; - } - return liftedAction; -} - -function _send(action, state, options, type, instanceId) { - start(options); - setTimeout(function () { - var message = { - payload: state ? (0, _jsan.stringify)(state) : '', - action: type === 'ACTION' ? (0, _jsan.stringify)(transformAction(action, options)) : action, - type: type || 'ACTION', - id: socket.id, - instanceId: instanceId, - name: options.name - }; - socket.emit(socket.id ? 'log' : 'log-noid', message); - }, 0); -} - -exports.send = _send; -function connect() { - var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; - - var id = generateId(options.instanceId); - start(options); - return { - init: function init(state, action) { - _send(action || {}, state, options, 'INIT', id); - }, - subscribe: function subscribe(listener) { - if (!listener) return undefined; - if (!listeners[id]) listeners[id] = []; - listeners[id].push(listener); - - return function unsubscribe() { - var index = listeners[id].indexOf(listener); - listeners[id].splice(index, 1); - }; - }, - unsubscribe: function unsubscribe() { - delete listeners[id]; - }, - send: function send(action, payload) { - if (action) { - _send(action, payload, options, 'ACTION', id); - } else { - _send(undefined, payload, options, 'STATE', id); - } - }, - error: function error(payload) { - socket.emit({ type: 'ERROR', payload: payload, id: socket.id, instanceId: id }); - } - }; -} - -function connectViaExtension(options) { - if (options && options.remote || typeof window === 'undefined' || !window.__REDUX_DEVTOOLS_EXTENSION__) { - return connect(options); - } - return window.__REDUX_DEVTOOLS_EXTENSION__.connect(options); -} - -exports.default = { connect: connect, connectViaExtension: connectViaExtension, send: _send, extractState: extractState, generateId: generateId }; - -/***/ }), - -/***/ 8690: -/*!*************************************************!*\ - !*** ../../node_modules/remotedev/lib/index.js ***! - \*************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -"use strict"; - - -module.exports = __webpack_require__(/*! ./devTools */ 1538); - -/***/ }), - -/***/ 3084: -/*!**************************************************!*\ - !*** ../../node_modules/rn-host-detect/index.js ***! - \**************************************************/ -/***/ ((module) => { - -"use strict"; - - -/* - * It only for Debug Remotely mode for Android - * When __DEV__ === false, we can't use window.require('NativeModules') - */ -function getByRemoteConfig(hostname) { - var remoteModuleConfig = typeof window !== 'undefined' && - window.__fbBatchedBridgeConfig && - window.__fbBatchedBridgeConfig.remoteModuleConfig - - if ( - !Array.isArray(remoteModuleConfig) || - hostname !== 'localhost' && hostname !== '127.0.0.1' - ) return { hostname: hostname, passed: false } - - var result = hostname - var passed = false - remoteModuleConfig.some(function (config) { - if (!config) return false - - var name = config[0] - var content = config[1] - if ( - (name === 'AndroidConstants' || name === 'PlatformConstants') && - content && - content.ServerHost - ) { - result = content.ServerHost.split(':')[0] - passed = true - return true - } - - if ( - name === 'SourceCode' && - content && - content.scriptURL - ) { - result = content.scriptURL.replace(/https?:\/\//, '').split(':')[0] - passed = true - return true - } - return false - }) - - return { hostname: result, passed: passed } -} - -function getByRNRequirePolyfill(hostname) { - var originalWarn = console.warn - var NativeModules - var Constants - var SourceCode - if ( - typeof window === 'undefined' || - !window.__DEV__ || - typeof window.require !== 'function' || - // RN >= 0.56 - // TODO: Get NativeModules for RN >= 0.56 - window.require.name === 'metroRequire' - ) { - return hostname - } - console.warn = function() { - if ( - arguments[0] && - typeof arguments[0].indexOf == 'function' && - arguments[0].indexOf("Requiring module 'NativeModules' by name") > -1 - ) - return - return originalWarn.apply(console, arguments) - } - try { - NativeModules = window.require('NativeModules') - } catch (e) {} - console.warn = originalWarn - if (!NativeModules) return hostname - - Constants = NativeModules.PlatformConstants || NativeModules.AndroidConstants - SourceCode = NativeModules.SourceCode - - if (Constants && Constants.ServerHost) { - return Constants.ServerHost.split(':')[0] - } else if (SourceCode && SourceCode.scriptURL) { - return SourceCode.scriptURL.replace(/https?:\/\//, '').split(':')[0] - } - return hostname -} - -/* - * Get React Native server IP if hostname is `localhost` - * On Android emulator, the IP of host is `10.0.2.2` (Genymotion: 10.0.3.2) - */ -module.exports = function (hostname) { - // Check if it in React Native environment - if ( - typeof __fbBatchedBridgeConfig !== 'object' || - hostname !== 'localhost' && hostname !== '127.0.0.1' - ) { - return hostname - } - var result = getByRemoteConfig(hostname) - - // Leave if get hostname by remote config successful - if (result.passed) { - return result.hostname - } - - // Otherwise, use RN's require polyfill - return getByRNRequirePolyfill(hostname) -} - - -/***/ }), - -/***/ 5717: -/*!**********************************************!*\ - !*** ../../node_modules/sc-channel/index.js ***! - \**********************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var Emitter = __webpack_require__(/*! component-emitter */ 1113); - -var SCChannel = function (name, client, options) { - var self = this; - - Emitter.call(this); - - this.PENDING = 'pending'; - this.SUBSCRIBED = 'subscribed'; - this.UNSUBSCRIBED = 'unsubscribed'; - - this.name = name; - this.state = this.UNSUBSCRIBED; - this.client = client; - - this.options = options || {}; - this.setOptions(this.options); -}; - -SCChannel.prototype = Object.create(Emitter.prototype); - -SCChannel.prototype.setOptions = function (options) { - if (!options) { - options = {}; - } - this.waitForAuth = options.waitForAuth || false; - this.batch = options.batch || false; - - if (options.data !== undefined) { - this.data = options.data; - } -}; - -SCChannel.prototype.getState = function () { - return this.state; -}; - -SCChannel.prototype.subscribe = function (options) { - this.client.subscribe(this.name, options); -}; - -SCChannel.prototype.unsubscribe = function () { - this.client.unsubscribe(this.name); -}; - -SCChannel.prototype.isSubscribed = function (includePending) { - return this.client.isSubscribed(this.name, includePending); -}; - -SCChannel.prototype.publish = function (data, callback) { - this.client.publish(this.name, data, callback); -}; - -SCChannel.prototype.watch = function (handler) { - this.client.watch(this.name, handler); -}; - -SCChannel.prototype.unwatch = function (handler) { - this.client.unwatch(this.name, handler); -}; - -SCChannel.prototype.watchers = function () { - return this.client.watchers(this.name); -}; - -SCChannel.prototype.destroy = function () { - this.client.destroyChannel(this.name); -}; - -module.exports.X = SCChannel; - - -/***/ }), - -/***/ 1113: -/*!*****************************************************************************!*\ - !*** ../../node_modules/sc-channel/node_modules/component-emitter/index.js ***! - \*****************************************************************************/ -/***/ ((module) => { - - -/** - * Expose `Emitter`. - */ - -if (true) { - module.exports = Emitter; -} - -/** - * Initialize a new `Emitter`. - * - * @api public - */ - -function Emitter(obj) { - if (obj) return mixin(obj); -}; - -/** - * Mixin the emitter properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -function mixin(obj) { - for (var key in Emitter.prototype) { - obj[key] = Emitter.prototype[key]; - } - return obj; -} - -/** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.on = -Emitter.prototype.addEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - (this._callbacks['$' + event] = this._callbacks['$' + event] || []) - .push(fn); - return this; -}; - -/** - * Adds an `event` listener that will be invoked a single - * time then automatically removed. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.once = function(event, fn){ - function on() { - this.off(event, on); - fn.apply(this, arguments); - } - - on.fn = fn; - this.on(event, on); - return this; -}; - -/** - * Remove the given callback for `event` or all - * registered callbacks. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.off = -Emitter.prototype.removeListener = -Emitter.prototype.removeAllListeners = -Emitter.prototype.removeEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - - // all - if (0 == arguments.length) { - this._callbacks = {}; - return this; - } - - // specific event - var callbacks = this._callbacks['$' + event]; - if (!callbacks) return this; - - // remove all handlers - if (1 == arguments.length) { - delete this._callbacks['$' + event]; - return this; - } - - // remove specific handler - var cb; - for (var i = 0; i < callbacks.length; i++) { - cb = callbacks[i]; - if (cb === fn || cb.fn === fn) { - callbacks.splice(i, 1); - break; - } - } - return this; -}; - -/** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} - */ - -Emitter.prototype.emit = function(event){ - this._callbacks = this._callbacks || {}; - var args = [].slice.call(arguments, 1) - , callbacks = this._callbacks['$' + event]; - - if (callbacks) { - callbacks = callbacks.slice(0); - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args); - } - } - - return this; -}; - -/** - * Return array of callbacks for `event`. - * - * @param {String} event - * @return {Array} - * @api public - */ - -Emitter.prototype.listeners = function(event){ - this._callbacks = this._callbacks || {}; - return this._callbacks['$' + event] || []; -}; - -/** - * Check if this emitter has `event` handlers. - * - * @param {String} event - * @return {Boolean} - * @api public - */ - -Emitter.prototype.hasListeners = function(event){ - return !! this.listeners(event).length; -}; - - -/***/ }), - -/***/ 739: -/*!***********************************************!*\ - !*** ../../node_modules/sc-errors/decycle.js ***! - \***********************************************/ -/***/ ((module) => { - -// Based on https://github.com/dscape/cycle/blob/master/cycle.js - -module.exports = function decycle(object) { -// Make a deep copy of an object or array, assuring that there is at most -// one instance of each object or array in the resulting structure. The -// duplicate references (which might be forming cycles) are replaced with -// an object of the form -// {$ref: PATH} -// where the PATH is a JSONPath string that locates the first occurance. -// So, -// var a = []; -// a[0] = a; -// return JSON.stringify(JSON.decycle(a)); -// produces the string '[{"$ref":"$"}]'. - -// JSONPath is used to locate the unique object. $ indicates the top level of -// the object or array. [NUMBER] or [STRING] indicates a child member or -// property. - - var objects = [], // Keep a reference to each unique object or array - paths = []; // Keep the path to each unique object or array - - return (function derez(value, path) { - -// The derez recurses through the object, producing the deep copy. - - var i, // The loop counter - name, // Property name - nu; // The new object or array - -// typeof null === 'object', so go on if this value is really an object but not -// one of the weird builtin objects. - - if (typeof value === 'object' && value !== null && - !(value instanceof Boolean) && - !(value instanceof Date) && - !(value instanceof Number) && - !(value instanceof RegExp) && - !(value instanceof String)) { - -// If the value is an object or array, look to see if we have already -// encountered it. If so, return a $ref/path object. This is a hard way, -// linear search that will get slower as the number of unique objects grows. - - for (i = 0; i < objects.length; i += 1) { - if (objects[i] === value) { - return {$ref: paths[i]}; - } - } - -// Otherwise, accumulate the unique value and its path. - - objects.push(value); - paths.push(path); - -// If it is an array, replicate the array. - - if (Object.prototype.toString.apply(value) === '[object Array]') { - nu = []; - for (i = 0; i < value.length; i += 1) { - nu[i] = derez(value[i], path + '[' + i + ']'); - } - } else { - -// If it is an object, replicate the object. - - nu = {}; - for (name in value) { - if (Object.prototype.hasOwnProperty.call(value, name)) { - nu[name] = derez(value[name], - path + '[' + JSON.stringify(name) + ']'); - } - } - } - return nu; - } - return value; - }(object, '$')); -}; - - -/***/ }), - -/***/ 6299: -/*!*********************************************!*\ - !*** ../../node_modules/sc-errors/index.js ***! - \*********************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var decycle = __webpack_require__(/*! ./decycle */ 739); - -var isStrict = (function () { return !this; })(); - -function AuthTokenExpiredError(message, expiry) { - this.name = 'AuthTokenExpiredError'; - this.message = message; - this.expiry = expiry; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -AuthTokenExpiredError.prototype = Object.create(Error.prototype); - - -function AuthTokenInvalidError(message) { - this.name = 'AuthTokenInvalidError'; - this.message = message; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -AuthTokenInvalidError.prototype = Object.create(Error.prototype); - - -function AuthTokenNotBeforeError(message, date) { - this.name = 'AuthTokenNotBeforeError'; - this.message = message; - this.date = date; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -AuthTokenNotBeforeError.prototype = Object.create(Error.prototype); - - -// For any other auth token error. -function AuthTokenError(message) { - this.name = 'AuthTokenError'; - this.message = message; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -AuthTokenError.prototype = Object.create(Error.prototype); - - -function SilentMiddlewareBlockedError(message, type) { - this.name = 'SilentMiddlewareBlockedError'; - this.message = message; - this.type = type; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -SilentMiddlewareBlockedError.prototype = Object.create(Error.prototype); - - -function InvalidActionError(message) { - this.name = 'InvalidActionError'; - this.message = message; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -InvalidActionError.prototype = Object.create(Error.prototype); - -function InvalidArgumentsError(message) { - this.name = 'InvalidArgumentsError'; - this.message = message; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -InvalidArgumentsError.prototype = Object.create(Error.prototype); - -function InvalidOptionsError(message) { - this.name = 'InvalidOptionsError'; - this.message = message; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -InvalidOptionsError.prototype = Object.create(Error.prototype); - - -function InvalidMessageError(message) { - this.name = 'InvalidMessageError'; - this.message = message; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -InvalidMessageError.prototype = Object.create(Error.prototype); - - -function SocketProtocolError(message, code) { - this.name = 'SocketProtocolError'; - this.message = message; - this.code = code; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -SocketProtocolError.prototype = Object.create(Error.prototype); - - -function ServerProtocolError(message) { - this.name = 'ServerProtocolError'; - this.message = message; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -ServerProtocolError.prototype = Object.create(Error.prototype); - -function HTTPServerError(message) { - this.name = 'HTTPServerError'; - this.message = message; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -HTTPServerError.prototype = Object.create(Error.prototype); - - -function ResourceLimitError(message) { - this.name = 'ResourceLimitError'; - this.message = message; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -ResourceLimitError.prototype = Object.create(Error.prototype); - - -function TimeoutError(message) { - this.name = 'TimeoutError'; - this.message = message; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -TimeoutError.prototype = Object.create(Error.prototype); - - -function BadConnectionError(message, type) { - this.name = 'BadConnectionError'; - this.message = message; - this.type = type; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -BadConnectionError.prototype = Object.create(Error.prototype); - - -function BrokerError(message) { - this.name = 'BrokerError'; - this.message = message; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -BrokerError.prototype = Object.create(Error.prototype); - - -function ProcessExitError(message, code) { - this.name = 'ProcessExitError'; - this.message = message; - this.code = code; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -ProcessExitError.prototype = Object.create(Error.prototype); - - -function UnknownError(message) { - this.name = 'UnknownError'; - this.message = message; - if (Error.captureStackTrace && !isStrict) { - Error.captureStackTrace(this, arguments.callee); - } else { - this.stack = (new Error()).stack; - } -} -UnknownError.prototype = Object.create(Error.prototype); - - -// Expose all error types. - -module.exports = { - AuthTokenExpiredError: AuthTokenExpiredError, - AuthTokenInvalidError: AuthTokenInvalidError, - AuthTokenNotBeforeError: AuthTokenNotBeforeError, - AuthTokenError: AuthTokenError, - SilentMiddlewareBlockedError: SilentMiddlewareBlockedError, - InvalidActionError: InvalidActionError, - InvalidArgumentsError: InvalidArgumentsError, - InvalidOptionsError: InvalidOptionsError, - InvalidMessageError: InvalidMessageError, - SocketProtocolError: SocketProtocolError, - ServerProtocolError: ServerProtocolError, - HTTPServerError: HTTPServerError, - ResourceLimitError: ResourceLimitError, - TimeoutError: TimeoutError, - BadConnectionError: BadConnectionError, - BrokerError: BrokerError, - ProcessExitError: ProcessExitError, - UnknownError: UnknownError -}; - -module.exports.socketProtocolErrorStatuses = { - 1001: 'Socket was disconnected', - 1002: 'A WebSocket protocol error was encountered', - 1003: 'Server terminated socket because it received invalid data', - 1005: 'Socket closed without status code', - 1006: 'Socket hung up', - 1007: 'Message format was incorrect', - 1008: 'Encountered a policy violation', - 1009: 'Message was too big to process', - 1010: 'Client ended the connection because the server did not comply with extension requirements', - 1011: 'Server encountered an unexpected fatal condition', - 4000: 'Server ping timed out', - 4001: 'Client pong timed out', - 4002: 'Server failed to sign auth token', - 4003: 'Failed to complete handshake', - 4004: 'Client failed to save auth token', - 4005: 'Did not receive #handshake from client before timeout', - 4006: 'Failed to bind socket to message broker', - 4007: 'Client connection establishment timed out', - 4008: 'Server rejected handshake from client' -}; - -module.exports.socketProtocolIgnoreStatuses = { - 1000: 'Socket closed normally', - 1001: 'Socket hung up' -}; - -// Properties related to error domains cannot be serialized. -var unserializableErrorProperties = { - domain: 1, - domainEmitter: 1, - domainThrown: 1 -}; - -// Convert an error into a JSON-compatible type which can later be hydrated -// back to its *original* form. -module.exports.dehydrateError = function dehydrateError(error, includeStackTrace) { - var dehydratedError; - - if (error && typeof error === 'object') { - dehydratedError = { - message: error.message - }; - if (includeStackTrace) { - dehydratedError.stack = error.stack; - } - for (var i in error) { - if (!unserializableErrorProperties[i]) { - dehydratedError[i] = error[i]; - } - } - } else if (typeof error === 'function') { - dehydratedError = '[function ' + (error.name || 'anonymous') + ']'; - } else { - dehydratedError = error; - } - - return decycle(dehydratedError); -}; - -// Convert a dehydrated error back to its *original* form. -module.exports.hydrateError = function hydrateError(error) { - var hydratedError = null; - if (error != null) { - if (typeof error === 'object') { - hydratedError = new Error(error.message); - for (var i in error) { - if (error.hasOwnProperty(i)) { - hydratedError[i] = error[i]; - } - } - } else { - hydratedError = error; - } - } - return hydratedError; -}; - -module.exports.decycle = decycle; - - -/***/ }), - -/***/ 571: -/*!************************************************!*\ - !*** ../../node_modules/sc-formatter/index.js ***! - \************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -var validJSONStartRegex = /^[ \n\r\t]*[{\[]/; - -var arrayBufferToBase64 = function (arraybuffer) { - var bytes = new Uint8Array(arraybuffer); - var len = bytes.length; - var base64 = ''; - - for (var i = 0; i < len; i += 3) { - base64 += base64Chars[bytes[i] >> 2]; - base64 += base64Chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; - base64 += base64Chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; - base64 += base64Chars[bytes[i + 2] & 63]; - } - - if ((len % 3) === 2) { - base64 = base64.substring(0, base64.length - 1) + '='; - } else if (len % 3 === 1) { - base64 = base64.substring(0, base64.length - 2) + '=='; - } - - return base64; -}; - -var binaryToBase64Replacer = function (key, value) { - if (__webpack_require__.g.ArrayBuffer && value instanceof __webpack_require__.g.ArrayBuffer) { - return { - base64: true, - data: arrayBufferToBase64(value) - }; - } else if (__webpack_require__.g.Buffer) { - if (value instanceof __webpack_require__.g.Buffer){ - return { - base64: true, - data: value.toString('base64') - }; - } - // Some versions of Node.js convert Buffers to Objects before they are passed to - // the replacer function - Because of this, we need to rehydrate Buffers - // before we can convert them to base64 strings. - if (value && value.type === 'Buffer' && Array.isArray(value.data)) { - var rehydratedBuffer; - if (__webpack_require__.g.Buffer.from) { - rehydratedBuffer = __webpack_require__.g.Buffer.from(value.data); - } else { - rehydratedBuffer = new __webpack_require__.g.Buffer(value.data); - } - return { - base64: true, - data: rehydratedBuffer.toString('base64') - }; - } - } - return value; -}; - -// Decode the data which was transmitted over the wire to a JavaScript Object in a format which SC understands. -// See encode function below for more details. -module.exports.decode = function (input) { - if (input == null) { - return null; - } - // Leave ping or pong message as is - if (input === '#1' || input === '#2') { - return input; - } - var message = input.toString(); - - // Performance optimization to detect invalid JSON packet sooner. - if (!validJSONStartRegex.test(message)) { - return message; - } - - try { - return JSON.parse(message); - } catch (err) {} - return message; -}; - -// Encode a raw JavaScript object (which is in the SC protocol format) into a format for -// transfering it over the wire. In this case, we just convert it into a simple JSON string. -// If you want to create your own custom codec, you can encode the object into any format -// (e.g. binary ArrayBuffer or string with any kind of compression) so long as your decode -// function is able to rehydrate that object back into its original JavaScript Object format -// (which adheres to the SC protocol). -// See https://github.com/SocketCluster/socketcluster/blob/master/socketcluster-protocol.md -// for details about the SC protocol. -module.exports.encode = function (object) { - // Leave ping or pong message as is - if (object === '#1' || object === '#2') { - return object; - } - return JSON.stringify(object, binaryToBase64Replacer); -}; - - -/***/ }), - -/***/ 3030: -/*!********************************************************!*\ - !*** ../../node_modules/socketcluster-client/index.js ***! - \********************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var SCClientSocket = __webpack_require__(/*! ./lib/scclientsocket */ 7244); -var factory = __webpack_require__(/*! ./lib/factory */ 9330); - -module.exports.factory = factory; -module.exports.SCClientSocket = SCClientSocket; - -module.exports.Emitter = __webpack_require__(/*! component-emitter */ 317); - -module.exports.create = function (options) { - return factory.create(options); -}; - -module.exports.connect = module.exports.create; - -module.exports.destroy = function (socket) { - return factory.destroy(socket); -}; - -module.exports.clients = factory.clients; - -module.exports.version = '13.0.1'; - - -/***/ }), - -/***/ 512: -/*!***********************************************************!*\ - !*** ../../node_modules/socketcluster-client/lib/auth.js ***! - \***********************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var AuthEngine = function () { - this._internalStorage = {}; - this.isLocalStorageEnabled = this._checkLocalStorageEnabled(); -}; - -AuthEngine.prototype._checkLocalStorageEnabled = function () { - var err; - try { - // Some browsers will throw an error here if localStorage is disabled. - __webpack_require__.g.localStorage; - - // Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem - // throw QuotaExceededError. We're going to detect this and avoid hard to debug edge cases. - __webpack_require__.g.localStorage.setItem('__scLocalStorageTest', 1); - __webpack_require__.g.localStorage.removeItem('__scLocalStorageTest'); - } catch (e) { - err = e; - } - return !err; -}; - -AuthEngine.prototype.saveToken = function (name, token, options, callback) { - if (this.isLocalStorageEnabled && __webpack_require__.g.localStorage) { - __webpack_require__.g.localStorage.setItem(name, token); - } else { - this._internalStorage[name] = token; - } - callback && callback(null, token); -}; - -AuthEngine.prototype.removeToken = function (name, callback) { - var token; - - this.loadToken(name, function (err, authToken) { - token = authToken; - }); - - if (this.isLocalStorageEnabled && __webpack_require__.g.localStorage) { - __webpack_require__.g.localStorage.removeItem(name); - } else { - delete this._internalStorage[name]; - } - - callback && callback(null, token); -}; - -AuthEngine.prototype.loadToken = function (name, callback) { - var token; - - if (this.isLocalStorageEnabled && __webpack_require__.g.localStorage) { - token = __webpack_require__.g.localStorage.getItem(name); - } else { - token = this._internalStorage[name] || null; - } - callback(null, token); -}; - -module.exports.K = AuthEngine; - - -/***/ }), - -/***/ 9330: -/*!**************************************************************!*\ - !*** ../../node_modules/socketcluster-client/lib/factory.js ***! - \**************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var SCClientSocket = __webpack_require__(/*! ./scclientsocket */ 7244); -var scErrors = __webpack_require__(/*! sc-errors */ 6299); -var uuid = __webpack_require__(/*! uuid */ 6434); -var InvalidArgumentsError = scErrors.InvalidArgumentsError; - -var _clients = {}; - -function getMultiplexId(options) { - var protocolPrefix = options.secure ? 'https://' : 'http://'; - var queryString = ''; - if (options.query) { - if (typeof options.query == 'string') { - queryString = options.query; - } else { - var queryArray = []; - var queryMap = options.query; - for (var key in queryMap) { - if (queryMap.hasOwnProperty(key)) { - queryArray.push(key + '=' + queryMap[key]); - } - } - if (queryArray.length) { - queryString = '?' + queryArray.join('&'); - } - } - } - var host; - if (options.host) { - host = options.host; - } else { - host = options.hostname + ':' + options.port; - } - return protocolPrefix + host + options.path + queryString; -} - -function isUrlSecure() { - return __webpack_require__.g.location && location.protocol == 'https:'; -} - -function getPort(options, isSecureDefault) { - var isSecure = options.secure == null ? isSecureDefault : options.secure; - return options.port || (__webpack_require__.g.location && location.port ? location.port : isSecure ? 443 : 80); -} - -function create(options) { - var self = this; - - options = options || {}; - - if (options.host && !options.host.match(/[^:]+:\d{2,5}/)) { - throw new InvalidArgumentsError('The host option should include both' + - ' the hostname and the port number in the format "hostname:port"'); - } - - if (options.host && options.hostname) { - throw new InvalidArgumentsError('The host option should already include' + - ' the hostname and the port number in the format "hostname:port"' + - ' - Because of this, you should never use host and hostname options together'); - } - - if (options.host && options.port) { - throw new InvalidArgumentsError('The host option should already include' + - ' the hostname and the port number in the format "hostname:port"' + - ' - Because of this, you should never use host and port options together'); - } - - var isSecureDefault = isUrlSecure(); - - var opts = { - port: getPort(options, isSecureDefault), - hostname: __webpack_require__.g.location && location.hostname || 'localhost', - path: '/socketcluster/', - secure: isSecureDefault, - autoConnect: true, - autoReconnect: true, - autoSubscribeOnConnect: true, - connectTimeout: 20000, - ackTimeout: 10000, - timestampRequests: false, - timestampParam: 't', - authEngine: null, - authTokenName: 'socketCluster.authToken', - binaryType: 'arraybuffer', - multiplex: true, - pubSubBatchDuration: null, - cloneData: false - }; - for (var i in options) { - if (options.hasOwnProperty(i)) { - opts[i] = options[i]; - } - } - opts.clientMap = _clients; - - if (opts.multiplex === false) { - opts.clientId = uuid.v4(); - var socket = new SCClientSocket(opts); - _clients[opts.clientId] = socket; - return socket; - } - opts.clientId = getMultiplexId(opts); - - if (_clients[opts.clientId]) { - if (opts.autoConnect) { - _clients[opts.clientId].connect(); - } - } else { - _clients[opts.clientId] = new SCClientSocket(opts); - } - return _clients[opts.clientId]; -} - -function destroy(socket) { - socket.destroy(); -} - -module.exports = { - create: create, - destroy: destroy, - clients: _clients -}; - - -/***/ }), - -/***/ 907: -/*!***************************************************************!*\ - !*** ../../node_modules/socketcluster-client/lib/response.js ***! - \***************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var scErrors = __webpack_require__(/*! sc-errors */ 6299); -var InvalidActionError = scErrors.InvalidActionError; - -var Response = function (socket, id) { - this.socket = socket; - this.id = id; - this.sent = false; -}; - -Response.prototype._respond = function (responseData) { - if (this.sent) { - throw new InvalidActionError('Response ' + this.id + ' has already been sent'); - } else { - this.sent = true; - this.socket.send(this.socket.encode(responseData)); - } -}; - -Response.prototype.end = function (data) { - if (this.id) { - var responseData = { - rid: this.id - }; - if (data !== undefined) { - responseData.data = data; - } - this._respond(responseData); - } -}; - -Response.prototype.error = function (error, data) { - if (this.id) { - var err = scErrors.dehydrateError(error); - - var responseData = { - rid: this.id, - error: err - }; - if (data !== undefined) { - responseData.data = data; - } - - this._respond(responseData); - } -}; - -Response.prototype.callback = function (error, data) { - if (error) { - this.error(error, data); - } else { - this.end(data); - } -}; - -module.exports.H = Response; - - -/***/ }), - -/***/ 7244: -/*!*********************************************************************!*\ - !*** ../../node_modules/socketcluster-client/lib/scclientsocket.js ***! - \*********************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var Emitter = __webpack_require__(/*! component-emitter */ 317); -var SCChannel = __webpack_require__(/*! sc-channel */ 5717)/* .SCChannel */ .X; -var Response = __webpack_require__(/*! ./response */ 907)/* .Response */ .H; -var AuthEngine = __webpack_require__(/*! ./auth */ 512)/* .AuthEngine */ .K; -var formatter = __webpack_require__(/*! sc-formatter */ 571); -var SCTransport = __webpack_require__(/*! ./sctransport */ 9781)/* .SCTransport */ .U; -var querystring = __webpack_require__(/*! querystring */ 3329); -var LinkedList = __webpack_require__(/*! linked-list */ 9426); -var base64 = __webpack_require__(/*! base-64 */ 2971); -var clone = __webpack_require__(/*! clone */ 6903); - -var scErrors = __webpack_require__(/*! sc-errors */ 6299); -var InvalidArgumentsError = scErrors.InvalidArgumentsError; -var InvalidMessageError = scErrors.InvalidMessageError; -var InvalidActionError = scErrors.InvalidActionError; -var SocketProtocolError = scErrors.SocketProtocolError; -var TimeoutError = scErrors.TimeoutError; -var BadConnectionError = scErrors.BadConnectionError; - -var isBrowser = typeof window != 'undefined'; - - -var SCClientSocket = function (opts) { - var self = this; - - Emitter.call(this); - - this.id = null; - this.state = this.CLOSED; - this.authState = this.UNAUTHENTICATED; - this.signedAuthToken = null; - this.authToken = null; - this.pendingReconnect = false; - this.pendingReconnectTimeout = null; - this.preparingPendingSubscriptions = false; - this.clientId = opts.clientId; - - this.connectTimeout = opts.connectTimeout; - this.ackTimeout = opts.ackTimeout; - this.channelPrefix = opts.channelPrefix || null; - this.disconnectOnUnload = opts.disconnectOnUnload == null ? true : opts.disconnectOnUnload; - this.authTokenName = opts.authTokenName; - - // pingTimeout will be ackTimeout at the start, but it will - // be updated with values provided by the 'connect' event - this.pingTimeout = this.ackTimeout; - this.pingTimeoutDisabled = !!opts.pingTimeoutDisabled; - this.active = true; - - this._clientMap = opts.clientMap || {}; - - var maxTimeout = Math.pow(2, 31) - 1; - - var verifyDuration = function (propertyName) { - if (self[propertyName] > maxTimeout) { - throw new InvalidArgumentsError('The ' + propertyName + - ' value provided exceeded the maximum amount allowed'); - } - }; - - verifyDuration('connectTimeout'); - verifyDuration('ackTimeout'); - - this._localEvents = { - 'connect': 1, - 'connectAbort': 1, - 'close': 1, - 'disconnect': 1, - 'message': 1, - 'error': 1, - 'raw': 1, - 'kickOut': 1, - 'subscribe': 1, - 'unsubscribe': 1, - 'subscribeStateChange': 1, - 'authStateChange': 1, - 'authenticate': 1, - 'deauthenticate': 1, - 'removeAuthToken': 1, - 'subscribeRequest': 1 - }; - - this.connectAttempts = 0; - - this._emitBuffer = new LinkedList(); - this.channels = {}; - - this.options = opts; - - this._cid = 1; - - this.options.callIdGenerator = function () { - return self._cid++; - }; - - if (this.options.autoReconnect) { - if (this.options.autoReconnectOptions == null) { - this.options.autoReconnectOptions = {}; - } - - // Add properties to the this.options.autoReconnectOptions object. - // We assign the reference to a reconnectOptions variable to avoid repetition. - var reconnectOptions = this.options.autoReconnectOptions; - if (reconnectOptions.initialDelay == null) { - reconnectOptions.initialDelay = 10000; - } - if (reconnectOptions.randomness == null) { - reconnectOptions.randomness = 10000; - } - if (reconnectOptions.multiplier == null) { - reconnectOptions.multiplier = 1.5; - } - if (reconnectOptions.maxDelay == null) { - reconnectOptions.maxDelay = 60000; - } - } - - if (this.options.subscriptionRetryOptions == null) { - this.options.subscriptionRetryOptions = {}; - } - - if (this.options.authEngine) { - this.auth = this.options.authEngine; - } else { - this.auth = new AuthEngine(); - } - - if (this.options.codecEngine) { - this.codec = this.options.codecEngine; - } else { - // Default codec engine - this.codec = formatter; - } - - this.options.path = this.options.path.replace(/\/$/, '') + '/'; - - this.options.query = opts.query || {}; - if (typeof this.options.query == 'string') { - this.options.query = querystring.parse(this.options.query); - } - - this._channelEmitter = new Emitter(); - - this._unloadHandler = function () { - self.disconnect(); - }; - - if (isBrowser && this.disconnectOnUnload && __webpack_require__.g.addEventListener) { - __webpack_require__.g.addEventListener('beforeunload', this._unloadHandler, false); - } - this._clientMap[this.clientId] = this; - - if (this.options.autoConnect) { - this.connect(); - } -}; - -SCClientSocket.prototype = Object.create(Emitter.prototype); - -SCClientSocket.CONNECTING = SCClientSocket.prototype.CONNECTING = SCTransport.prototype.CONNECTING; -SCClientSocket.OPEN = SCClientSocket.prototype.OPEN = SCTransport.prototype.OPEN; -SCClientSocket.CLOSED = SCClientSocket.prototype.CLOSED = SCTransport.prototype.CLOSED; - -SCClientSocket.AUTHENTICATED = SCClientSocket.prototype.AUTHENTICATED = 'authenticated'; -SCClientSocket.UNAUTHENTICATED = SCClientSocket.prototype.UNAUTHENTICATED = 'unauthenticated'; - -SCClientSocket.PENDING = SCClientSocket.prototype.PENDING = 'pending'; - -SCClientSocket.ignoreStatuses = scErrors.socketProtocolIgnoreStatuses; -SCClientSocket.errorStatuses = scErrors.socketProtocolErrorStatuses; - -SCClientSocket.prototype._privateEventHandlerMap = { - '#publish': function (data) { - var undecoratedChannelName = this._undecorateChannelName(data.channel); - var isSubscribed = this.isSubscribed(undecoratedChannelName, true); - - if (isSubscribed) { - this._channelEmitter.emit(undecoratedChannelName, data.data); - } - }, - '#kickOut': function (data) { - var undecoratedChannelName = this._undecorateChannelName(data.channel); - var channel = this.channels[undecoratedChannelName]; - if (channel) { - Emitter.prototype.emit.call(this, 'kickOut', data.message, undecoratedChannelName); - channel.emit('kickOut', data.message, undecoratedChannelName); - this._triggerChannelUnsubscribe(channel); - } - }, - '#setAuthToken': function (data, response) { - var self = this; - - if (data) { - var triggerAuthenticate = function (err) { - if (err) { - // This is a non-fatal error, we don't want to close the connection - // because of this but we do want to notify the server and throw an error - // on the client. - response.error(err); - self._onSCError(err); - } else { - self._changeToAuthenticatedState(data.token); - response.end(); - } - }; - - this.auth.saveToken(this.authTokenName, data.token, {}, triggerAuthenticate); - } else { - response.error(new InvalidMessageError('No token data provided by #setAuthToken event')); - } - }, - '#removeAuthToken': function (data, response) { - var self = this; - - this.auth.removeToken(this.authTokenName, function (err, oldToken) { - if (err) { - // Non-fatal error - Do not close the connection - response.error(err); - self._onSCError(err); - } else { - Emitter.prototype.emit.call(self, 'removeAuthToken', oldToken); - self._changeToUnauthenticatedStateAndClearTokens(); - response.end(); - } - }); - }, - '#disconnect': function (data) { - this.transport.close(data.code, data.data); - } -}; - -SCClientSocket.prototype.getState = function () { - return this.state; -}; - -SCClientSocket.prototype.getBytesReceived = function () { - return this.transport.getBytesReceived(); -}; - -SCClientSocket.prototype.deauthenticate = function (callback) { - var self = this; - - this.auth.removeToken(this.authTokenName, function (err, oldToken) { - if (err) { - // Non-fatal error - Do not close the connection - self._onSCError(err); - } else { - Emitter.prototype.emit.call(self, 'removeAuthToken', oldToken); - if (self.state != self.CLOSED) { - self.emit('#removeAuthToken'); - } - self._changeToUnauthenticatedStateAndClearTokens(); - } - callback && callback(err); - }); -}; - -SCClientSocket.prototype.connect = SCClientSocket.prototype.open = function () { - var self = this; - - if (!this.active) { - var error = new InvalidActionError('Cannot connect a destroyed client'); - this._onSCError(error); - return; - } - - if (this.state == this.CLOSED) { - this.pendingReconnect = false; - this.pendingReconnectTimeout = null; - clearTimeout(this._reconnectTimeoutRef); - - this.state = this.CONNECTING; - Emitter.prototype.emit.call(this, 'connecting'); - - if (this.transport) { - this.transport.off(); - } - - this.transport = new SCTransport(this.auth, this.codec, this.options); - - this.transport.on('open', function (status) { - self.state = self.OPEN; - self._onSCOpen(status); - }); - - this.transport.on('error', function (err) { - self._onSCError(err); - }); - - this.transport.on('close', function (code, data) { - self.state = self.CLOSED; - self._onSCClose(code, data); - }); - - this.transport.on('openAbort', function (code, data) { - self.state = self.CLOSED; - self._onSCClose(code, data, true); - }); - - this.transport.on('event', function (event, data, res) { - self._onSCEvent(event, data, res); - }); - } -}; - -SCClientSocket.prototype.reconnect = function (code, data) { - this.disconnect(code, data); - this.connect(); -}; - -SCClientSocket.prototype.disconnect = function (code, data) { - code = code || 1000; - - if (typeof code != 'number') { - throw new InvalidArgumentsError('If specified, the code argument must be a number'); - } - - if (this.state == this.OPEN || this.state == this.CONNECTING) { - this.transport.close(code, data); - } else { - this.pendingReconnect = false; - this.pendingReconnectTimeout = null; - clearTimeout(this._reconnectTimeoutRef); - } -}; - -SCClientSocket.prototype.destroy = function (code, data) { - if (isBrowser && __webpack_require__.g.removeEventListener) { - __webpack_require__.g.removeEventListener('beforeunload', this._unloadHandler, false); - } - this.active = false; - this.disconnect(code, data); - delete this._clientMap[this.clientId]; -}; - -SCClientSocket.prototype._changeToUnauthenticatedStateAndClearTokens = function () { - if (this.authState != this.UNAUTHENTICATED) { - var oldState = this.authState; - var oldSignedToken = this.signedAuthToken; - this.authState = this.UNAUTHENTICATED; - this.signedAuthToken = null; - this.authToken = null; - - var stateChangeData = { - oldState: oldState, - newState: this.authState - }; - Emitter.prototype.emit.call(this, 'authStateChange', stateChangeData); - Emitter.prototype.emit.call(this, 'deauthenticate', oldSignedToken); - } -}; - -SCClientSocket.prototype._changeToAuthenticatedState = function (signedAuthToken) { - this.signedAuthToken = signedAuthToken; - this.authToken = this._extractAuthTokenData(signedAuthToken); - - if (this.authState != this.AUTHENTICATED) { - var oldState = this.authState; - this.authState = this.AUTHENTICATED; - var stateChangeData = { - oldState: oldState, - newState: this.authState, - signedAuthToken: signedAuthToken, - authToken: this.authToken - }; - if (!this.preparingPendingSubscriptions) { - this.processPendingSubscriptions(); - } - - Emitter.prototype.emit.call(this, 'authStateChange', stateChangeData); - } - Emitter.prototype.emit.call(this, 'authenticate', signedAuthToken); -}; - -SCClientSocket.prototype.decodeBase64 = function (encodedString) { - var decodedString; - if (typeof Buffer == 'undefined') { - if (__webpack_require__.g.atob) { - decodedString = __webpack_require__.g.atob(encodedString); - } else { - decodedString = base64.decode(encodedString); - } - } else { - var buffer = new Buffer(encodedString, 'base64'); - decodedString = buffer.toString('utf8'); - } - return decodedString; -}; - -SCClientSocket.prototype.encodeBase64 = function (decodedString) { - var encodedString; - if (typeof Buffer == 'undefined') { - if (__webpack_require__.g.btoa) { - encodedString = __webpack_require__.g.btoa(decodedString); - } else { - encodedString = base64.encode(decodedString); - } - } else { - var buffer = new Buffer(decodedString, 'utf8'); - encodedString = buffer.toString('base64'); - } - return encodedString; -}; - -SCClientSocket.prototype._extractAuthTokenData = function (signedAuthToken) { - var tokenParts = (signedAuthToken || '').split('.'); - var encodedTokenData = tokenParts[1]; - if (encodedTokenData != null) { - var tokenData = encodedTokenData; - try { - tokenData = this.decodeBase64(tokenData); - return JSON.parse(tokenData); - } catch (e) { - return tokenData; - } - } - return null; -}; - -SCClientSocket.prototype.getAuthToken = function () { - return this.authToken; -}; - -SCClientSocket.prototype.getSignedAuthToken = function () { - return this.signedAuthToken; -}; - -// Perform client-initiated authentication by providing an encrypted token string. -SCClientSocket.prototype.authenticate = function (signedAuthToken, callback) { - var self = this; - - this.emit('#authenticate', signedAuthToken, function (err, authStatus) { - if (authStatus && authStatus.isAuthenticated != null) { - // If authStatus is correctly formatted (has an isAuthenticated property), - // then we will rehydrate the authError. - if (authStatus.authError) { - authStatus.authError = scErrors.hydrateError(authStatus.authError); - } - } else { - // Some errors like BadConnectionError and TimeoutError will not pass a valid - // authStatus object to the current function, so we need to create it ourselves. - authStatus = { - isAuthenticated: self.authState, - authError: null - }; - } - if (err) { - if (err.name != 'BadConnectionError' && err.name != 'TimeoutError') { - // In case of a bad/closed connection or a timeout, we maintain the last - // known auth state since those errors don't mean that the token is invalid. - - self._changeToUnauthenticatedStateAndClearTokens(); - } - callback && callback(err, authStatus); - } else { - self.auth.saveToken(self.authTokenName, signedAuthToken, {}, function (err) { - if (err) { - self._onSCError(err); - } - if (authStatus.isAuthenticated) { - self._changeToAuthenticatedState(signedAuthToken); - } else { - self._changeToUnauthenticatedStateAndClearTokens(); - } - callback && callback(err, authStatus); - }); - } - }); -}; - -SCClientSocket.prototype._tryReconnect = function (initialDelay) { - var self = this; - - var exponent = this.connectAttempts++; - var reconnectOptions = this.options.autoReconnectOptions; - var timeout; - - if (initialDelay == null || exponent > 0) { - var initialTimeout = Math.round(reconnectOptions.initialDelay + (reconnectOptions.randomness || 0) * Math.random()); - - timeout = Math.round(initialTimeout * Math.pow(reconnectOptions.multiplier, exponent)); - } else { - timeout = initialDelay; - } - - if (timeout > reconnectOptions.maxDelay) { - timeout = reconnectOptions.maxDelay; - } - - clearTimeout(this._reconnectTimeoutRef); - - this.pendingReconnect = true; - this.pendingReconnectTimeout = timeout; - this._reconnectTimeoutRef = setTimeout(function () { - self.connect(); - }, timeout); -}; - -SCClientSocket.prototype._onSCOpen = function (status) { - var self = this; - - this.preparingPendingSubscriptions = true; - - if (status) { - this.id = status.id; - this.pingTimeout = status.pingTimeout; - this.transport.pingTimeout = this.pingTimeout; - if (status.isAuthenticated) { - this._changeToAuthenticatedState(status.authToken); - } else { - this._changeToUnauthenticatedStateAndClearTokens(); - } - } else { - // This can happen if auth.loadToken (in sctransport.js) fails with - // an error - This means that the signedAuthToken cannot be loaded by - // the auth engine and therefore, we need to unauthenticate the client. - this._changeToUnauthenticatedStateAndClearTokens(); - } - - this.connectAttempts = 0; - - if (this.options.autoSubscribeOnConnect) { - this.processPendingSubscriptions(); - } - - // If the user invokes the callback while in autoSubscribeOnConnect mode, it - // won't break anything. - Emitter.prototype.emit.call(this, 'connect', status, function () { - self.processPendingSubscriptions(); - }); - - if (this.state == this.OPEN) { - this._flushEmitBuffer(); - } -}; - -SCClientSocket.prototype._onSCError = function (err) { - var self = this; - - // Throw error in different stack frame so that error handling - // cannot interfere with a reconnect action. - setTimeout(function () { - if (self.listeners('error').length < 1) { - throw err; - } else { - Emitter.prototype.emit.call(self, 'error', err); - } - }, 0); -}; - -SCClientSocket.prototype._suspendSubscriptions = function () { - var channel, newState; - for (var channelName in this.channels) { - if (this.channels.hasOwnProperty(channelName)) { - channel = this.channels[channelName]; - if (channel.state == channel.SUBSCRIBED || - channel.state == channel.PENDING) { - - newState = channel.PENDING; - } else { - newState = channel.UNSUBSCRIBED; - } - - this._triggerChannelUnsubscribe(channel, newState); - } - } -}; - -SCClientSocket.prototype._abortAllPendingEventsDueToBadConnection = function (failureType) { - var currentNode = this._emitBuffer.head; - var nextNode; - - while (currentNode) { - nextNode = currentNode.next; - var eventObject = currentNode.data; - clearTimeout(eventObject.timeout); - delete eventObject.timeout; - currentNode.detach(); - currentNode = nextNode; - - var callback = eventObject.callback; - if (callback) { - delete eventObject.callback; - var errorMessage = "Event '" + eventObject.event + - "' was aborted due to a bad connection"; - var error = new BadConnectionError(errorMessage, failureType); - callback.call(eventObject, error, eventObject); - } - // Cleanup any pending response callback in the transport layer too. - if (eventObject.cid) { - this.transport.cancelPendingResponse(eventObject.cid); - } - } -}; - -SCClientSocket.prototype._onSCClose = function (code, data, openAbort) { - var self = this; - - this.id = null; - - if (this.transport) { - this.transport.off(); - } - this.pendingReconnect = false; - this.pendingReconnectTimeout = null; - clearTimeout(this._reconnectTimeoutRef); - - this._suspendSubscriptions(); - this._abortAllPendingEventsDueToBadConnection(openAbort ? 'connectAbort' : 'disconnect'); - - // Try to reconnect - // on server ping timeout (4000) - // or on client pong timeout (4001) - // or on close without status (1005) - // or on handshake failure (4003) - // or on handshake rejection (4008) - // or on socket hung up (1006) - if (this.options.autoReconnect) { - if (code == 4000 || code == 4001 || code == 1005) { - // If there is a ping or pong timeout or socket closes without - // status, don't wait before trying to reconnect - These could happen - // if the client wakes up after a period of inactivity and in this case we - // want to re-establish the connection as soon as possible. - this._tryReconnect(0); - - // Codes 4500 and above will be treated as permanent disconnects. - // Socket will not try to auto-reconnect. - } else if (code != 1000 && code < 4500) { - this._tryReconnect(); - } - } - - if (openAbort) { - Emitter.prototype.emit.call(self, 'connectAbort', code, data); - } else { - Emitter.prototype.emit.call(self, 'disconnect', code, data); - } - Emitter.prototype.emit.call(self, 'close', code, data); - - if (!SCClientSocket.ignoreStatuses[code]) { - var closeMessage; - if (data) { - closeMessage = 'Socket connection closed with status code ' + code + ' and reason: ' + data; - } else { - closeMessage = 'Socket connection closed with status code ' + code; - } - var err = new SocketProtocolError(SCClientSocket.errorStatuses[code] || closeMessage, code); - this._onSCError(err); - } -}; - -SCClientSocket.prototype._onSCEvent = function (event, data, res) { - var handler = this._privateEventHandlerMap[event]; - if (handler) { - handler.call(this, data, res); - } else { - Emitter.prototype.emit.call(this, event, data, function () { - res && res.callback.apply(res, arguments); - }); - } -}; - -SCClientSocket.prototype.decode = function (message) { - return this.transport.decode(message); -}; - -SCClientSocket.prototype.encode = function (object) { - return this.transport.encode(object); -}; - -SCClientSocket.prototype._flushEmitBuffer = function () { - var currentNode = this._emitBuffer.head; - var nextNode; - - while (currentNode) { - nextNode = currentNode.next; - var eventObject = currentNode.data; - currentNode.detach(); - this.transport.emitObject(eventObject); - currentNode = nextNode; - } -}; - -SCClientSocket.prototype._handleEventAckTimeout = function (eventObject, eventNode) { - if (eventNode) { - eventNode.detach(); - } - delete eventObject.timeout; - - var callback = eventObject.callback; - if (callback) { - delete eventObject.callback; - var error = new TimeoutError("Event response for '" + eventObject.event + "' timed out"); - callback.call(eventObject, error, eventObject); - } - // Cleanup any pending response callback in the transport layer too. - if (eventObject.cid) { - this.transport.cancelPendingResponse(eventObject.cid); - } -}; - -SCClientSocket.prototype._emit = function (event, data, callback) { - var self = this; - - if (this.state == this.CLOSED) { - this.connect(); - } - var eventObject = { - event: event, - callback: callback - }; - - var eventNode = new LinkedList.Item(); - - if (this.options.cloneData) { - eventObject.data = clone(data); - } else { - eventObject.data = data; - } - eventNode.data = eventObject; - - eventObject.timeout = setTimeout(function () { - self._handleEventAckTimeout(eventObject, eventNode); - }, this.ackTimeout); - - this._emitBuffer.append(eventNode); - if (this.state == this.OPEN) { - this._flushEmitBuffer(); - } -}; - -SCClientSocket.prototype.send = function (data) { - this.transport.send(data); -}; - -SCClientSocket.prototype.emit = function (event, data, callback) { - if (this._localEvents[event] == null) { - this._emit(event, data, callback); - } else if (event == 'error') { - Emitter.prototype.emit.call(this, event, data); - } else { - var error = new InvalidActionError('The "' + event + '" event is reserved and cannot be emitted on a client socket'); - this._onSCError(error); - } -}; - -SCClientSocket.prototype.publish = function (channelName, data, callback) { - var pubData = { - channel: this._decorateChannelName(channelName), - data: data - }; - this.emit('#publish', pubData, callback); -}; - -SCClientSocket.prototype._triggerChannelSubscribe = function (channel, subscriptionOptions) { - var channelName = channel.name; - - if (channel.state != channel.SUBSCRIBED) { - var oldState = channel.state; - channel.state = channel.SUBSCRIBED; - - var stateChangeData = { - channel: channelName, - oldState: oldState, - newState: channel.state, - subscriptionOptions: subscriptionOptions - }; - channel.emit('subscribeStateChange', stateChangeData); - channel.emit('subscribe', channelName, subscriptionOptions); - Emitter.prototype.emit.call(this, 'subscribeStateChange', stateChangeData); - Emitter.prototype.emit.call(this, 'subscribe', channelName, subscriptionOptions); - } -}; - -SCClientSocket.prototype._triggerChannelSubscribeFail = function (err, channel, subscriptionOptions) { - var channelName = channel.name; - var meetsAuthRequirements = !channel.waitForAuth || this.authState == this.AUTHENTICATED; - - if (channel.state != channel.UNSUBSCRIBED && meetsAuthRequirements) { - channel.state = channel.UNSUBSCRIBED; - - channel.emit('subscribeFail', err, channelName, subscriptionOptions); - Emitter.prototype.emit.call(this, 'subscribeFail', err, channelName, subscriptionOptions); - } -}; - -// Cancel any pending subscribe callback -SCClientSocket.prototype._cancelPendingSubscribeCallback = function (channel) { - if (channel._pendingSubscriptionCid != null) { - this.transport.cancelPendingResponse(channel._pendingSubscriptionCid); - delete channel._pendingSubscriptionCid; - } -}; - -SCClientSocket.prototype._decorateChannelName = function (channelName) { - if (this.channelPrefix) { - channelName = this.channelPrefix + channelName; - } - return channelName; -}; - -SCClientSocket.prototype._undecorateChannelName = function (decoratedChannelName) { - if (this.channelPrefix && decoratedChannelName.indexOf(this.channelPrefix) == 0) { - return decoratedChannelName.replace(this.channelPrefix, ''); - } - return decoratedChannelName; -}; - -SCClientSocket.prototype._trySubscribe = function (channel) { - var self = this; - - var meetsAuthRequirements = !channel.waitForAuth || this.authState == this.AUTHENTICATED; - - // We can only ever have one pending subscribe action at any given time on a channel - if (this.state == this.OPEN && !this.preparingPendingSubscriptions && - channel._pendingSubscriptionCid == null && meetsAuthRequirements) { - - var options = { - noTimeout: true - }; - - var subscriptionOptions = { - channel: this._decorateChannelName(channel.name) - }; - if (channel.waitForAuth) { - options.waitForAuth = true; - subscriptionOptions.waitForAuth = options.waitForAuth; - } - if (channel.data) { - subscriptionOptions.data = channel.data; - } - if (channel.batch) { - options.batch = true; - subscriptionOptions.batch = true; - } - - channel._pendingSubscriptionCid = this.transport.emit( - '#subscribe', subscriptionOptions, options, - function (err) { - delete channel._pendingSubscriptionCid; - if (err) { - self._triggerChannelSubscribeFail(err, channel, subscriptionOptions); - } else { - self._triggerChannelSubscribe(channel, subscriptionOptions); - } - } - ); - Emitter.prototype.emit.call(this, 'subscribeRequest', channel.name, subscriptionOptions); - } -}; - -SCClientSocket.prototype.subscribe = function (channelName, options) { - var channel = this.channels[channelName]; - - if (!channel) { - channel = new SCChannel(channelName, this, options); - this.channels[channelName] = channel; - } else if (options) { - channel.setOptions(options); - } - - if (channel.state == channel.UNSUBSCRIBED) { - channel.state = channel.PENDING; - this._trySubscribe(channel); - } - - return channel; -}; - -SCClientSocket.prototype._triggerChannelUnsubscribe = function (channel, newState) { - var channelName = channel.name; - var oldState = channel.state; - - if (newState) { - channel.state = newState; - } else { - channel.state = channel.UNSUBSCRIBED; - } - this._cancelPendingSubscribeCallback(channel); - - if (oldState == channel.SUBSCRIBED) { - var stateChangeData = { - channel: channelName, - oldState: oldState, - newState: channel.state - }; - channel.emit('subscribeStateChange', stateChangeData); - channel.emit('unsubscribe', channelName); - Emitter.prototype.emit.call(this, 'subscribeStateChange', stateChangeData); - Emitter.prototype.emit.call(this, 'unsubscribe', channelName); - } -}; - -SCClientSocket.prototype._tryUnsubscribe = function (channel) { - var self = this; - - if (this.state == this.OPEN) { - var options = { - noTimeout: true - }; - if (channel.batch) { - options.batch = true; - } - // If there is a pending subscribe action, cancel the callback - this._cancelPendingSubscribeCallback(channel); - - // This operation cannot fail because the TCP protocol guarantees delivery - // so long as the connection remains open. If the connection closes, - // the server will automatically unsubscribe the client and thus complete - // the operation on the server side. - var decoratedChannelName = this._decorateChannelName(channel.name); - this.transport.emit('#unsubscribe', decoratedChannelName, options); - } -}; - -SCClientSocket.prototype.unsubscribe = function (channelName) { - var channel = this.channels[channelName]; - - if (channel) { - if (channel.state != channel.UNSUBSCRIBED) { - - this._triggerChannelUnsubscribe(channel); - this._tryUnsubscribe(channel); - } - } -}; - -SCClientSocket.prototype.channel = function (channelName, options) { - var currentChannel = this.channels[channelName]; - - if (!currentChannel) { - currentChannel = new SCChannel(channelName, this, options); - this.channels[channelName] = currentChannel; - } - return currentChannel; -}; - -SCClientSocket.prototype.destroyChannel = function (channelName) { - var channel = this.channels[channelName]; - - if (channel) { - channel.unwatch(); - channel.unsubscribe(); - delete this.channels[channelName]; - } -}; - -SCClientSocket.prototype.subscriptions = function (includePending) { - var subs = []; - var channel, includeChannel; - for (var channelName in this.channels) { - if (this.channels.hasOwnProperty(channelName)) { - channel = this.channels[channelName]; - - if (includePending) { - includeChannel = channel && (channel.state == channel.SUBSCRIBED || - channel.state == channel.PENDING); - } else { - includeChannel = channel && channel.state == channel.SUBSCRIBED; - } - - if (includeChannel) { - subs.push(channelName); - } - } - } - return subs; -}; - -SCClientSocket.prototype.isSubscribed = function (channelName, includePending) { - var channel = this.channels[channelName]; - if (includePending) { - return !!channel && (channel.state == channel.SUBSCRIBED || - channel.state == channel.PENDING); - } - return !!channel && channel.state == channel.SUBSCRIBED; -}; - -SCClientSocket.prototype.processPendingSubscriptions = function () { - var self = this; - - this.preparingPendingSubscriptions = false; - - var pendingChannels = []; - - for (var i in this.channels) { - if (this.channels.hasOwnProperty(i)) { - var channel = this.channels[i]; - if (channel.state == channel.PENDING) { - pendingChannels.push(channel); - } - } - } - - pendingChannels.sort(function (a, b) { - var ap = a.priority || 0; - var bp = b.priority || 0; - if (ap > bp) { - return -1; - } - if (ap < bp) { - return 1; - } - return 0; - }); - - pendingChannels.forEach(function (channel) { - self._trySubscribe(channel); - }); -}; - -SCClientSocket.prototype.watch = function (channelName, handler) { - if (typeof handler != 'function') { - throw new InvalidArgumentsError('No handler function was provided'); - } - this._channelEmitter.on(channelName, handler); -}; - -SCClientSocket.prototype.unwatch = function (channelName, handler) { - if (handler) { - this._channelEmitter.removeListener(channelName, handler); - } else { - this._channelEmitter.removeAllListeners(channelName); - } -}; - -SCClientSocket.prototype.watchers = function (channelName) { - return this._channelEmitter.listeners(channelName); -}; - -module.exports = SCClientSocket; - - -/***/ }), - -/***/ 9781: -/*!******************************************************************!*\ - !*** ../../node_modules/socketcluster-client/lib/sctransport.js ***! - \******************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var Emitter = __webpack_require__(/*! component-emitter */ 317); -var Response = __webpack_require__(/*! ./response */ 907)/* .Response */ .H; -var querystring = __webpack_require__(/*! querystring */ 3329); -var WebSocket; -var createWebSocket; - -if (__webpack_require__.g.WebSocket) { - WebSocket = __webpack_require__.g.WebSocket; - createWebSocket = function (uri, options) { - return new WebSocket(uri); - }; -} else { - WebSocket = __webpack_require__(/*! ws */ 4500); - createWebSocket = function (uri, options) { - return new WebSocket(uri, null, options); - }; -} - -var scErrors = __webpack_require__(/*! sc-errors */ 6299); -var TimeoutError = scErrors.TimeoutError; -var BadConnectionError = scErrors.BadConnectionError; - - -var SCTransport = function (authEngine, codecEngine, options) { - var self = this; - - this.state = this.CLOSED; - this.auth = authEngine; - this.codec = codecEngine; - this.options = options; - this.connectTimeout = options.connectTimeout; - this.pingTimeout = options.ackTimeout; - this.pingTimeoutDisabled = !!options.pingTimeoutDisabled; - this.callIdGenerator = options.callIdGenerator; - this.authTokenName = options.authTokenName; - - this._pingTimeoutTicker = null; - this._callbackMap = {}; - this._batchSendList = []; - - // Open the connection. - - this.state = this.CONNECTING; - var uri = this.uri(); - - var wsSocket = createWebSocket(uri, this.options); - wsSocket.binaryType = this.options.binaryType; - - this.socket = wsSocket; - - wsSocket.onopen = function () { - self._onOpen(); - }; - - wsSocket.onclose = function (event) { - var code; - if (event.code == null) { - // This is to handle an edge case in React Native whereby - // event.code is undefined when the mobile device is locked. - // TODO: This is not perfect since this condition could also apply to - // an abnormal close (no close control frame) which would be a 1006. - code = 1005; - } else { - code = event.code; - } - self._onClose(code, event.reason); - }; - - wsSocket.onmessage = function (message, flags) { - self._onMessage(message.data); - }; - - wsSocket.onerror = function (error) { - // The onclose event will be called automatically after the onerror event - // if the socket is connected - Otherwise, if it's in the middle of - // connecting, we want to close it manually with a 1006 - This is necessary - // to prevent inconsistent behavior when running the client in Node.js - // vs in a browser. - - if (self.state === self.CONNECTING) { - self._onClose(1006); - } - }; - - this._connectTimeoutRef = setTimeout(function () { - self._onClose(4007); - self.socket.close(4007); - }, this.connectTimeout); -}; - -SCTransport.prototype = Object.create(Emitter.prototype); - -SCTransport.CONNECTING = SCTransport.prototype.CONNECTING = 'connecting'; -SCTransport.OPEN = SCTransport.prototype.OPEN = 'open'; -SCTransport.CLOSED = SCTransport.prototype.CLOSED = 'closed'; - -SCTransport.prototype.uri = function () { - var query = this.options.query || {}; - var schema = this.options.secure ? 'wss' : 'ws'; - - if (this.options.timestampRequests) { - query[this.options.timestampParam] = (new Date()).getTime(); - } - - query = querystring.encode(query); - - if (query.length) { - query = '?' + query; - } - - var host; - if (this.options.host) { - host = this.options.host; - } else { - var port = ''; - - if (this.options.port && ((schema == 'wss' && this.options.port != 443) - || (schema == 'ws' && this.options.port != 80))) { - port = ':' + this.options.port; - } - host = this.options.hostname + port; - } - - return schema + '://' + host + this.options.path + query; -}; - -SCTransport.prototype._onOpen = function () { - var self = this; - - clearTimeout(this._connectTimeoutRef); - this._resetPingTimeout(); - - this._handshake(function (err, status) { - if (err) { - var statusCode; - if (status && status.code) { - statusCode = status.code; - } else { - statusCode = 4003; - } - self._onError(err); - self._onClose(statusCode, err.toString()); - self.socket.close(statusCode); - } else { - self.state = self.OPEN; - Emitter.prototype.emit.call(self, 'open', status); - self._resetPingTimeout(); - } - }); -}; - -SCTransport.prototype._handshake = function (callback) { - var self = this; - this.auth.loadToken(this.authTokenName, function (err, token) { - if (err) { - callback(err); - } else { - // Don't wait for this.state to be 'open'. - // The underlying WebSocket (this.socket) is already open. - var options = { - force: true - }; - self.emit('#handshake', { - authToken: token - }, options, function (err, status) { - if (status) { - // Add the token which was used as part of authentication attempt - // to the status object. - status.authToken = token; - if (status.authError) { - status.authError = scErrors.hydrateError(status.authError); - } - } - callback(err, status); - }); - } - }); -}; - -SCTransport.prototype._abortAllPendingEventsDueToBadConnection = function (failureType) { - for (var i in this._callbackMap) { - if (this._callbackMap.hasOwnProperty(i)) { - var eventObject = this._callbackMap[i]; - delete this._callbackMap[i]; - - clearTimeout(eventObject.timeout); - delete eventObject.timeout; - - var errorMessage = "Event '" + eventObject.event + - "' was aborted due to a bad connection"; - var badConnectionError = new BadConnectionError(errorMessage, failureType); - - var callback = eventObject.callback; - delete eventObject.callback; - callback.call(eventObject, badConnectionError, eventObject); - } - } -}; - -SCTransport.prototype._onClose = function (code, data) { - delete this.socket.onopen; - delete this.socket.onclose; - delete this.socket.onmessage; - delete this.socket.onerror; - - clearTimeout(this._connectTimeoutRef); - clearTimeout(this._pingTimeoutTicker); - clearTimeout(this._batchTimeout); - - if (this.state == this.OPEN) { - this.state = this.CLOSED; - Emitter.prototype.emit.call(this, 'close', code, data); - this._abortAllPendingEventsDueToBadConnection('disconnect'); - - } else if (this.state == this.CONNECTING) { - this.state = this.CLOSED; - Emitter.prototype.emit.call(this, 'openAbort', code, data); - this._abortAllPendingEventsDueToBadConnection('connectAbort'); - } -}; - -SCTransport.prototype._handleEventObject = function (obj, message) { - if (obj && obj.event != null) { - var response = new Response(this, obj.cid); - Emitter.prototype.emit.call(this, 'event', obj.event, obj.data, response); - } else if (obj && obj.rid != null) { - var eventObject = this._callbackMap[obj.rid]; - if (eventObject) { - clearTimeout(eventObject.timeout); - delete eventObject.timeout; - delete this._callbackMap[obj.rid]; - - if (eventObject.callback) { - var rehydratedError = scErrors.hydrateError(obj.error); - eventObject.callback(rehydratedError, obj.data); - } - } - } else { - Emitter.prototype.emit.call(this, 'event', 'raw', message); - } -}; - -SCTransport.prototype._onMessage = function (message) { - Emitter.prototype.emit.call(this, 'event', 'message', message); - - var obj = this.decode(message); - - // If ping - if (obj == '#1') { - this._resetPingTimeout(); - if (this.socket.readyState == this.socket.OPEN) { - this.sendObject('#2'); - } - } else { - if (Array.isArray(obj)) { - var len = obj.length; - for (var i = 0; i < len; i++) { - this._handleEventObject(obj[i], message); - } - } else { - this._handleEventObject(obj, message); - } - } -}; - -SCTransport.prototype._onError = function (err) { - Emitter.prototype.emit.call(this, 'error', err); -}; - -SCTransport.prototype._resetPingTimeout = function () { - if (this.pingTimeoutDisabled) { - return; - } - var self = this; - - var now = (new Date()).getTime(); - clearTimeout(this._pingTimeoutTicker); - - this._pingTimeoutTicker = setTimeout(function () { - self._onClose(4000); - self.socket.close(4000); - }, this.pingTimeout); -}; - -SCTransport.prototype.getBytesReceived = function () { - return this.socket.bytesReceived; -}; - -SCTransport.prototype.close = function (code, data) { - code = code || 1000; - - if (this.state == this.OPEN) { - var packet = { - code: code, - data: data - }; - this.emit('#disconnect', packet); - - this._onClose(code, data); - this.socket.close(code); - - } else if (this.state == this.CONNECTING) { - this._onClose(code, data); - this.socket.close(code); - } -}; - -SCTransport.prototype.emitObject = function (eventObject, options) { - var simpleEventObject = { - event: eventObject.event, - data: eventObject.data - }; - - if (eventObject.callback) { - simpleEventObject.cid = eventObject.cid = this.callIdGenerator(); - this._callbackMap[eventObject.cid] = eventObject; - } - - this.sendObject(simpleEventObject, options); - - return eventObject.cid || null; -}; - -SCTransport.prototype._handleEventAckTimeout = function (eventObject) { - if (eventObject.cid) { - delete this._callbackMap[eventObject.cid]; - } - delete eventObject.timeout; - - var callback = eventObject.callback; - if (callback) { - delete eventObject.callback; - var error = new TimeoutError("Event response for '" + eventObject.event + "' timed out"); - callback.call(eventObject, error, eventObject); - } -}; - -// The last two optional arguments (a and b) can be options and/or callback -SCTransport.prototype.emit = function (event, data, a, b) { - var self = this; - - var callback, options; - - if (b) { - options = a; - callback = b; - } else { - if (a instanceof Function) { - options = {}; - callback = a; - } else { - options = a; - } - } - - var eventObject = { - event: event, - data: data, - callback: callback - }; - - if (callback && !options.noTimeout) { - eventObject.timeout = setTimeout(function () { - self._handleEventAckTimeout(eventObject); - }, this.options.ackTimeout); - } - - var cid = null; - if (this.state == this.OPEN || options.force) { - cid = this.emitObject(eventObject, options); - } - return cid; -}; - -SCTransport.prototype.cancelPendingResponse = function (cid) { - delete this._callbackMap[cid]; -}; - -SCTransport.prototype.decode = function (message) { - return this.codec.decode(message); -}; - -SCTransport.prototype.encode = function (object) { - return this.codec.encode(object); -}; - -SCTransport.prototype.send = function (data) { - if (this.socket.readyState != this.socket.OPEN) { - this._onClose(1005); - } else { - this.socket.send(data); - } -}; - -SCTransport.prototype.serializeObject = function (object) { - var str, formatError; - try { - str = this.encode(object); - } catch (err) { - formatError = err; - this._onError(formatError); - } - if (!formatError) { - return str; - } - return null; -}; - -SCTransport.prototype.sendObjectBatch = function (object) { - var self = this; - - this._batchSendList.push(object); - if (this._batchTimeout) { - return; - } - - this._batchTimeout = setTimeout(function () { - delete self._batchTimeout; - if (self._batchSendList.length) { - var str = self.serializeObject(self._batchSendList); - if (str != null) { - self.send(str); - } - self._batchSendList = []; - } - }, this.options.pubSubBatchDuration || 0); -}; - -SCTransport.prototype.sendObjectSingle = function (object) { - var str = this.serializeObject(object); - if (str != null) { - this.send(str); - } -}; - -SCTransport.prototype.sendObject = function (object, options) { - if (options && options.batch) { - this.sendObjectBatch(object); - } else { - this.sendObjectSingle(object); - } -}; - -module.exports.U = SCTransport; - - -/***/ }), - -/***/ 4500: -/*!*****************************************************************!*\ - !*** ../../node_modules/socketcluster-client/lib/ws-browser.js ***! - \*****************************************************************/ -/***/ ((module) => { - -var global; -if (typeof WorkerGlobalScope !== 'undefined') { - global = self; -} else { - global = typeof window != 'undefined' && window || (function() { return this; })(); -} - -var WebSocket = global.WebSocket || global.MozWebSocket; - -/** - * WebSocket constructor. - * - * The third `opts` options object gets ignored in web browsers, since it's - * non-standard, and throws a TypeError if passed to the constructor. - * See: https://github.com/einaros/ws/issues/227 - * - * @param {String} uri - * @param {Array} protocols (optional) - * @param {Object} opts (optional) - * @api public - */ - -function ws(uri, protocols, opts) { - var instance; - if (protocols) { - instance = new WebSocket(uri, protocols); - } else { - instance = new WebSocket(uri); - } - return instance; -} - -if (WebSocket) ws.prototype = WebSocket.prototype; - -module.exports = WebSocket ? ws : null; - - -/***/ }), - -/***/ 317: -/*!***************************************************************************************!*\ - !*** ../../node_modules/socketcluster-client/node_modules/component-emitter/index.js ***! - \***************************************************************************************/ -/***/ ((module) => { - - -/** - * Expose `Emitter`. - */ - -if (true) { - module.exports = Emitter; -} - -/** - * Initialize a new `Emitter`. - * - * @api public - */ - -function Emitter(obj) { - if (obj) return mixin(obj); -}; - -/** - * Mixin the emitter properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -function mixin(obj) { - for (var key in Emitter.prototype) { - obj[key] = Emitter.prototype[key]; - } - return obj; -} - -/** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.on = -Emitter.prototype.addEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - (this._callbacks['$' + event] = this._callbacks['$' + event] || []) - .push(fn); - return this; -}; - -/** - * Adds an `event` listener that will be invoked a single - * time then automatically removed. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.once = function(event, fn){ - function on() { - this.off(event, on); - fn.apply(this, arguments); - } - - on.fn = fn; - this.on(event, on); - return this; -}; - -/** - * Remove the given callback for `event` or all - * registered callbacks. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - -Emitter.prototype.off = -Emitter.prototype.removeListener = -Emitter.prototype.removeAllListeners = -Emitter.prototype.removeEventListener = function(event, fn){ - this._callbacks = this._callbacks || {}; - - // all - if (0 == arguments.length) { - this._callbacks = {}; - return this; - } - - // specific event - var callbacks = this._callbacks['$' + event]; - if (!callbacks) return this; - - // remove all handlers - if (1 == arguments.length) { - delete this._callbacks['$' + event]; - return this; - } - - // remove specific handler - var cb; - for (var i = 0; i < callbacks.length; i++) { - cb = callbacks[i]; - if (cb === fn || cb.fn === fn) { - callbacks.splice(i, 1); - break; - } - } - return this; -}; - -/** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} - */ - -Emitter.prototype.emit = function(event){ - this._callbacks = this._callbacks || {}; - var args = [].slice.call(arguments, 1) - , callbacks = this._callbacks['$' + event]; - - if (callbacks) { - callbacks = callbacks.slice(0); - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args); - } - } - - return this; -}; - -/** - * Return array of callbacks for `event`. - * - * @param {String} event - * @return {Array} - * @api public - */ - -Emitter.prototype.listeners = function(event){ - this._callbacks = this._callbacks || {}; - return this._callbacks['$' + event] || []; -}; - -/** - * Check if this emitter has `event` handlers. - * - * @param {String} event - * @return {Boolean} - * @api public - */ - -Emitter.prototype.hasListeners = function(event){ - return !! this.listeners(event).length; -}; - - -/***/ }), - -/***/ 6434: -/*!**************************************************************************!*\ - !*** ../../node_modules/socketcluster-client/node_modules/uuid/index.js ***! - \**************************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var v1 = __webpack_require__(/*! ./v1 */ 711); -var v4 = __webpack_require__(/*! ./v4 */ 4754); - -var uuid = v4; -uuid.v1 = v1; -uuid.v4 = v4; - -module.exports = uuid; - - -/***/ }), - -/***/ 399: -/*!************************************************************************************!*\ - !*** ../../node_modules/socketcluster-client/node_modules/uuid/lib/bytesToUuid.js ***! - \************************************************************************************/ -/***/ ((module) => { - -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -var byteToHex = []; -for (var i = 0; i < 256; ++i) { - byteToHex[i] = (i + 0x100).toString(16).substr(1); -} - -function bytesToUuid(buf, offset) { - var i = offset || 0; - var bth = byteToHex; - return bth[buf[i++]] + bth[buf[i++]] + - bth[buf[i++]] + bth[buf[i++]] + '-' + - bth[buf[i++]] + bth[buf[i++]] + '-' + - bth[buf[i++]] + bth[buf[i++]] + '-' + - bth[buf[i++]] + bth[buf[i++]] + '-' + - bth[buf[i++]] + bth[buf[i++]] + - bth[buf[i++]] + bth[buf[i++]] + - bth[buf[i++]] + bth[buf[i++]]; -} - -module.exports = bytesToUuid; - - -/***/ }), - -/***/ 6641: -/*!************************************************************************************!*\ - !*** ../../node_modules/socketcluster-client/node_modules/uuid/lib/rng-browser.js ***! - \************************************************************************************/ -/***/ ((module) => { - -// Unique ID creation requires a high quality random # generator. In the -// browser this is a little complicated due to unknown quality of Math.random() -// and inconsistent support for the `crypto` API. We do the best we can via -// feature-detection - -// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. -var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues.bind(crypto)) || - (typeof(msCrypto) != 'undefined' && msCrypto.getRandomValues.bind(msCrypto)); -if (getRandomValues) { - // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto - var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef - - module.exports = function whatwgRNG() { - getRandomValues(rnds8); - return rnds8; - }; -} else { - // Math.random()-based (RNG) - // - // If all else fails, use Math.random(). It's fast, but is of unspecified - // quality. - var rnds = new Array(16); - - module.exports = function mathRNG() { - for (var i = 0, r; i < 16; i++) { - if ((i & 0x03) === 0) r = Math.random() * 0x100000000; - rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; - } - - return rnds; - }; -} - - -/***/ }), - -/***/ 711: -/*!***********************************************************************!*\ - !*** ../../node_modules/socketcluster-client/node_modules/uuid/v1.js ***! - \***********************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var rng = __webpack_require__(/*! ./lib/rng */ 6641); -var bytesToUuid = __webpack_require__(/*! ./lib/bytesToUuid */ 399); - -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html - -var _nodeId; -var _clockseq; - -// Previous uuid creation time -var _lastMSecs = 0; -var _lastNSecs = 0; - -// See https://github.com/broofa/node-uuid for API details -function v1(options, buf, offset) { - var i = buf && offset || 0; - var b = buf || []; - - options = options || {}; - var node = options.node || _nodeId; - var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; - - // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 - if (node == null || clockseq == null) { - var seedBytes = rng(); - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [ - seedBytes[0] | 0x01, - seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5] - ]; - } - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - } - } - - // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); - - // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; - - // Time since last uuid creation (in msecs) - var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; - - // Per 4.2.1.2, Bump clockseq on clock regression - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } - - // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } - - // Per 4.2.1.2 Throw error if too many uuids are requested - if (nsecs >= 10000) { - throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); - } - - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; - - // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - msecs += 12219292800000; - - // `time_low` - var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; - - // `time_mid` - var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; - - // `time_high_and_version` - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - b[i++] = tmh >>> 16 & 0xff; - - // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - b[i++] = clockseq >>> 8 | 0x80; - - // `clock_seq_low` - b[i++] = clockseq & 0xff; - - // `node` - for (var n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } - - return buf ? buf : bytesToUuid(b); -} - -module.exports = v1; - - -/***/ }), - -/***/ 4754: -/*!***********************************************************************!*\ - !*** ../../node_modules/socketcluster-client/node_modules/uuid/v4.js ***! - \***********************************************************************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { - -var rng = __webpack_require__(/*! ./lib/rng */ 6641); -var bytesToUuid = __webpack_require__(/*! ./lib/bytesToUuid */ 399); - -function v4(options, buf, offset) { - var i = buf && offset || 0; - - if (typeof(options) == 'string') { - buf = options === 'binary' ? new Array(16) : null; - options = null; - } - options = options || {}; - - var rnds = options.random || (options.rng || rng)(); - - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = (rnds[6] & 0x0f) | 0x40; - rnds[8] = (rnds[8] & 0x3f) | 0x80; - - // Copy bytes to buffer, if provided - if (buf) { - for (var ii = 0; ii < 16; ++ii) { - buf[i + ii] = rnds[ii]; - } - } - - return buf || bytesToUuid(rnds); -} - -module.exports = v4; - - -/***/ }), - -/***/ 933: -/*!*************************************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/contentScriptBergamotApiClientPortListener.ts ***! - \*************************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.contentScriptBergamotApiClientPortListener = void 0; -const BergamotWasmApiClient_1 = __webpack_require__(/*! ./translation-api-clients/BergamotWasmApiClient */ 7423); -const BergamotRestApiClient_1 = __webpack_require__(/*! ./translation-api-clients/BergamotRestApiClient */ 8240); -const config_1 = __webpack_require__(/*! ../../config */ 7843); -// Currently it is possible build variants of the extension that uses the REST API - eg for performance testing / research -const bergamotApiClient = config_1.config.useBergamotRestApi - ? new BergamotRestApiClient_1.BergamotRestApiClient() - : new BergamotWasmApiClient_1.BergamotWasmApiClient(); -const contentScriptBergamotApiClientPortListener = (port) => { - if (port.name !== "port-from-content-script-bergamot-api-client") { - return; - } - port.onMessage.addListener(function (m) { - return __awaiter(this, void 0, void 0, function* () { - // console.debug("Message from content-script-bergamot-api-client:", {m}); - const { texts, from, to, requestId } = m; - try { - const results = yield bergamotApiClient.sendTranslationRequest(texts, from, to, (translationRequestProgress) => { - const translationRequestUpdate = { - translationRequestProgress, - requestId, - }; - port.postMessage({ - translationRequestUpdate, - }); - }); - // console.log({ results }); - const translationRequestUpdate = { - results, - requestId, - }; - port.postMessage({ - translationRequestUpdate, - }); - } - catch (err) { - if (err.message === "Attempt to postMessage on disconnected port") { - console.warn("Attempt to postMessage on disconnected port, but it is ok", err); - } - else { - console.info(`Caught exception/error in content script bergamot api client port listener:`, err); - // Make possibly unserializable errors serializable by only sending name, message and stack - let communicatedError; - if (err instanceof Error) { - const { name, message, stack } = err; - communicatedError = { name, message, stack }; - } - else { - communicatedError = err; - } - const translationRequestUpdate = { - error: communicatedError, - requestId, - }; - port.postMessage({ - translationRequestUpdate, - }); - } - } - }); - }); -}; -exports.contentScriptBergamotApiClientPortListener = contentScriptBergamotApiClientPortListener; - - -/***/ }), - -/***/ 800: -/*!*****************************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/contentScriptFrameInfoPortListener.ts ***! - \*****************************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.contentScriptFrameInfoPortListener = void 0; -const contentScriptFrameInfoPortListener = (port) => { - if (port.name !== "port-from-content-script-frame-info") { - return; - } - port.onMessage.addListener(function (m, senderPort) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - // console.debug("Message from port-from-content-script-frame-info:", {m}); - const { requestId } = m; - const frameInfo = { - windowId: (_a = senderPort.sender.tab) === null || _a === void 0 ? void 0 : _a.windowId, - tabId: (_b = senderPort.sender.tab) === null || _b === void 0 ? void 0 : _b.id, - frameId: senderPort.sender.frameId, - }; - try { - port.postMessage({ - requestId, - frameInfo, - }); - } - catch (err) { - if (err.message === "Attempt to postMessage on disconnected port") { - console.warn("Attempt to postMessage on disconnected port, but it is ok", err); - } - else { - throw err; - } - } - }); - }); -}; -exports.contentScriptFrameInfoPortListener = contentScriptFrameInfoPortListener; - - -/***/ }), - -/***/ 4958: -/*!*****************************************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/contentScriptLanguageDetectorProxyPortListener.ts ***! - \*****************************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.contentScriptLanguageDetectorProxyPortListener = void 0; -const LanguageDetector_1 = __webpack_require__(/*! ./lib/LanguageDetector */ 6621); -const contentScriptLanguageDetectorProxyPortListener = (port) => { - if (port.name !== "port-from-content-script-language-detector-proxy") { - return; - } - port.onMessage.addListener(function (m) { - return __awaiter(this, void 0, void 0, function* () { - // console.debug("Message from content-script-language-detector-proxy:", { m }); - const { str, requestId } = m; - const results = yield LanguageDetector_1.LanguageDetector.detectLanguage({ text: str }); - // console.debug({ results }); - try { - port.postMessage({ - languageDetectorResults: { - results, - requestId, - }, - }); - } - catch (err) { - if (err.message === "Attempt to postMessage on disconnected port") { - console.warn("Attempt to postMessage on disconnected port, but it is ok", err); - } - else { - throw err; - } - } - }); - }); -}; -exports.contentScriptLanguageDetectorProxyPortListener = contentScriptLanguageDetectorProxyPortListener; - - -/***/ }), - -/***/ 3797: -/*!********************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/lib/BergamotTranslatorAPI.ts ***! - \********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ - -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BergamotTranslatorAPI = exports.BergamotTranslatorAPIModelDownloadError = exports.BergamotTranslatorAPIModelLoadError = exports.BergamotTranslatorAPITranslationError = void 0; -const webextension_polyfill_ts_1 = __webpack_require__(/*! webextension-polyfill-ts */ 5006); -const nanoid_1 = __webpack_require__(/*! nanoid */ 3608); -const config_1 = __webpack_require__(/*! ../../../config */ 7843); -// Since Emscripten can handle heap growth, but not heap shrinkage, we -// need to refresh the worker after we've loaded/processed large models/translations -// in order to prevent unnecessary resident memory growth. -// -// These values define the cut-off estimated heap growth size and the idle -// timeout (in milliseconds) before destroying a worker. Once the heap growth -// is estimated to have exceeded a certain size, the worker is marked for -// destruction, and is terminated as soon as it has been idle for the -// given timeout. -// -// TODO: Update to reflect relevant checks for translation-related heap growth -// const FOO_LIMIT = X * 1024 * 1024; -const IDLE_TIMEOUT = 10 * 1000; -const WORKER_URL = webextension_polyfill_ts_1.browser.runtime.getURL(`translation-worker.js`); -class BergamotTranslatorAPITranslationError extends Error { - constructor() { - super(...arguments); - this.name = "BergamotTranslatorAPITranslationError"; - } -} -exports.BergamotTranslatorAPITranslationError = BergamotTranslatorAPITranslationError; -class BergamotTranslatorAPIModelLoadError extends Error { - constructor() { - super(...arguments); - this.name = "BergamotTranslatorAPIModelLoadError"; - } -} -exports.BergamotTranslatorAPIModelLoadError = BergamotTranslatorAPIModelLoadError; -class BergamotTranslatorAPIModelDownloadError extends Error { - constructor() { - super(...arguments); - this.name = "BergamotTranslatorAPIModelDownloadError"; - } -} -exports.BergamotTranslatorAPIModelDownloadError = BergamotTranslatorAPIModelDownloadError; -/** - * Class responsible for instantiating and communicating between this script - * and the translation worker process. - */ -class WorkerManager { - constructor() { - this.pendingRequests = new Map(); - // Holds the ID of the current pending idle cleanup setTimeout. - this._idleTimeout = null; - } - // private estimatedHeapGrowth: number; - loadModel(loadModelRequestWorkerMessage, onModelDownloadProgress) { - return __awaiter(this, void 0, void 0, function* () { - const worker = yield this.workerReady; - const loadModelResults = yield new Promise((resolve, reject) => { - const { requestId } = loadModelRequestWorkerMessage; - this.pendingRequests.set(requestId, { - resolve, - reject, - onModelDownloadProgress, - }); - worker.postMessage(loadModelRequestWorkerMessage); - }); - // TODO: Update estimatedHeapGrowth - this.checkEstimatedHeapGrowth(); - return loadModelResults; - }); - } - translate(translateRequestWorkerMessage) { - return __awaiter(this, void 0, void 0, function* () { - const worker = yield this.workerReady; - const translationResults = yield new Promise((resolve, reject) => { - const { requestId } = translateRequestWorkerMessage; - this.pendingRequests.set(requestId, { resolve, reject }); - worker.postMessage(translateRequestWorkerMessage); - }); - // TODO: Update estimatedHeapGrowth - this.checkEstimatedHeapGrowth(); - return translationResults; - }); - } - /** - * Triggers after we have our asynchronous result from the worker. - */ - checkEstimatedHeapGrowth() { - /* - // Determine if our input was large enough to trigger heap growth, - // or if we're already waiting to destroy the worker when it's - // idle. If so, schedule termination after the idle timeout. - if (this.estimatedHeapGrowth >= FOO_LIMIT || this._idleTimeout !== null) { - this.flushWorker(); - } - */ - } - onLoadModelResults(loadModelResultsWorkerMessage) { - const { requestId, loadModelResults } = loadModelResultsWorkerMessage; - this.pendingRequests.get(requestId).resolve(loadModelResults); - } - onTranslateWorkerResult(translationResultsWorkerMessage) { - const { requestId, translationResults } = translationResultsWorkerMessage; - this.pendingRequests.get(requestId).resolve(translationResults); - } - onModelDownloadProgress(modelDownloadProgressWorkerMessage) { - const { requestId, modelDownloadProgress, } = modelDownloadProgressWorkerMessage; - this.pendingRequests - .get(requestId) - .onModelDownloadProgress(modelDownloadProgress); - } - onError(errorWorkerMessage) { - const { requestId, message, errorSource } = errorWorkerMessage; - const apiErrorMessage = `Error event occurred during ${errorSource} in worker (requestId=${requestId}): ${message}`; - let error; - if (errorSource === "loadModel") { - error = new BergamotTranslatorAPIModelLoadError(apiErrorMessage); - } - else if (errorSource === "downloadModel") { - error = new BergamotTranslatorAPIModelDownloadError(apiErrorMessage); - } - else if (errorSource === "translate") { - error = new BergamotTranslatorAPITranslationError(apiErrorMessage); - } - else { - error = new Error(apiErrorMessage); - } - this.pendingRequests.get(requestId).reject(error); - } - get workerReady() { - if (!this._workerReadyPromise) { - this._workerReadyPromise = new Promise((resolve, reject) => { - const worker = new Worker(WORKER_URL); - worker.onerror = err => { - console.warn("Worker onerror callback fired", err); - reject(err); - }; - worker.onmessage = (msg) => { - // console.debug("Incoming message from worker", { msg }); - if (msg.data === "ready") { - resolve(worker); - } - else if (msg.data.type === "loadModelResults") { - this.onLoadModelResults(msg.data); - } - else if (msg.data.type === "translationResults") { - this.onTranslateWorkerResult(msg.data); - } - else if (msg.data.type === "modelDownloadProgress") { - this.onModelDownloadProgress(msg.data); - } - else if (msg.data.type === "log") { - console.log(`Relayed log message from worker: ${msg.data.message}`); - } - else if (msg.data.type === "error") { - this.onError(msg.data); - } - else { - throw new Error("Unknown worker message payload"); - } - }; - this._worker = worker; - }); - } - return this._workerReadyPromise; - } - // Schedule the current worker to be terminated after the idle timeout. - flushWorker() { - if (this._idleTimeout !== null) { - clearTimeout(this._idleTimeout); - } - this._idleTimeout = setTimeout(this._flushWorker.bind(this), IDLE_TIMEOUT); - } - // Immediately terminate the worker, as long as there no pending - // results. Otherwise, reschedule termination until after the next - // idle timeout. - _flushWorker() { - if (this.pendingRequests.size) { - this.flushWorker(); - } - else { - if (this._worker) { - this._worker.terminate(); - } - this._worker = null; - this._workerReadyPromise = null; - this._idleTimeout = null; - } - } -} -const workerManager = new WorkerManager(); -const translationPerformanceStats = (texts, translationWallTimeMs) => { - const seconds = translationWallTimeMs / 1000; - const textCount = texts.length; - const wordCount = texts - .map(text => text - .trim() - .split(" ") - .filter(word => word.trim() !== "").length) - .reduce((a, b) => a + b, 0); - const characterCount = texts - .map(text => text.trim().length) - .reduce((a, b) => a + b, 0); - const wordsPerSecond = Math.round(wordCount / seconds); - const charactersPerSecond = Math.round(characterCount / seconds); - return { - seconds, - textCount, - wordCount, - characterCount, - wordsPerSecond, - charactersPerSecond, - }; -}; -/** - * Class responsible for sending translations requests to the translation worker process - * in a compatible and somewhat efficient order. - * Emits events that can be used to track translation progress at a low level. - */ -class TranslationRequestDispatcher extends EventTarget { - constructor() { - super(...arguments); - this.queuedRequests = []; - this.queuedRequestsByRequestId = new Map(); - } - processQueue() { - return __awaiter(this, void 0, void 0, function* () { - if (this.processing) { - return; - } - this.processing = true; - while (this.queuedRequests.length) { - console.info(`Processing translation request queue of ${this.queuedRequests.length} requests`); - yield this.processNextItemInQueue(); - } - this.processing = false; - }); - } - processNextItemInQueue() { - return __awaiter(this, void 0, void 0, function* () { - // Shift the next request off the queue - const translateRequestWorkerMessage = this.queuedRequests.shift(); - const { translateParams, requestId } = translateRequestWorkerMessage; - try { - const { loadModelParams } = translateParams; - const { from, to } = loadModelParams; - const languagePair = `${from}${to}`; - // First check if we need to load a model - if (!this.loadedLanguagePair || - this.loadedLanguagePair !== languagePair) { - const modelWillLoadEventData = { - requestId, - loadModelParams, - }; - this.dispatchEvent(new CustomEvent("modelWillLoad", { - detail: modelWillLoadEventData, - })); - const loadModelRequestWorkerMessage = { - type: "loadModel", - requestId, - loadModelParams, - }; - const loadModelResults = yield workerManager.loadModel(loadModelRequestWorkerMessage, (modelDownloadProgress) => { - const modelDownloadProgressEventData = { - requestId, - modelDownloadProgress, - }; - this.dispatchEvent(new CustomEvent("modelDownloadProgress", { - detail: modelDownloadProgressEventData, - })); - }); - this.loadedLanguagePair = languagePair; - const modelLoadedEventData = { - requestId, - loadModelParams, - loadModelResults, - }; - this.dispatchEvent(new CustomEvent("modelLoaded", { - detail: modelLoadedEventData, - })); - } - // Send the translation request - const start = performance.now(); - const translationResults = yield workerManager.translate(translateRequestWorkerMessage); - // Summarize performance stats - const end = performance.now(); - const translationWallTimeMs = end - start; - const originalTextsTranslationPerformanceStats = translationPerformanceStats(translationResults.originalTexts, translationWallTimeMs); - const translationFinishedEventData = { - requestId, - translationWallTimeMs, - originalTextsTranslationPerformanceStats, - }; - this.dispatchEvent(new CustomEvent("translationFinished", { - detail: translationFinishedEventData, - })); - // Resolve the translation request - this.queuedRequestsByRequestId.get(requestId).resolve(translationResults); - } - catch (error) { - // Reject the translation request - this.queuedRequestsByRequestId.get(requestId).reject(error); - } - }); - } - translate(requestId, texts, from, to) { - const loadModelParams = { - from, - to, - bergamotModelsBaseUrl: config_1.config.bergamotModelsBaseUrl, - }; - const translateParams = { - texts, - loadModelParams, - }; - const translateRequestWorkerMessage = { - type: "translate", - requestId, - translateParams, - }; - this.queuedRequests.push(translateRequestWorkerMessage); - const queueLength = this.queuedRequests.length + (this.processing ? 1 : 0); - const translationRequestQueuedEventData = { - requestId, - queueLength, - }; - this.dispatchEvent(new CustomEvent("translationRequestQueued", { - detail: translationRequestQueuedEventData, - })); - const requestPromise = new Promise((resolve, reject) => { - this.queuedRequestsByRequestId.set(requestId, { resolve, reject }); - }); - // Kick off queue processing async - /* eslint-disable no-unused-vars */ - this.processQueue().then(_r => void 0); - /* eslint-enable no-unused-vars */ - // Return the promise that resolves when the in-scope translation request resolves - return requestPromise; - } -} -const translationRequestDispatcher = new TranslationRequestDispatcher(); -/** - * Provide a simpler public interface (compared to above) - */ -exports.BergamotTranslatorAPI = { - translate(texts, from, to, onTranslationRequestQueued, onModelWillLoad, onModelDownloadProgress, onModelLoaded, onTranslationFinished) { - return __awaiter(this, void 0, void 0, function* () { - const requestId = nanoid_1.nanoid(); - const translationRequestQueuedListener = (e) => { - // console.debug('Listener received "translationRequestQueued".', e.detail); - if (e.detail.requestId !== requestId) { - return; - } - translationRequestDispatcher.removeEventListener("translationRequestQueued", translationRequestQueuedListener); - if (e.detail.queueLength > 1) { - console.info(`BergamotTranslatorAPI[${requestId}]: Queued translation request to be processed after ${e - .detail.queueLength - 1} already queued requests`); - } - else { - console.info(`BergamotTranslatorAPI[${requestId}]: Queued translation request for immediate execution`); - } - onTranslationRequestQueued(e.detail); - }; - const modelWillLoadListener = (e) => { - // console.debug('Listener received "modelWillLoad".', e.detail); - if (e.detail.requestId !== requestId) { - return; - } - translationRequestDispatcher.removeEventListener("modelWillLoad", modelWillLoadListener); - const languagePair = `${from}${to}`; - console.info(`BergamotTranslatorAPI[${requestId}]: Model ${languagePair} will load`); - onModelWillLoad(e.detail); - }; - const modelDownloadProgressListener = (e) => { - // console.debug('Listener received "modelDownloadProgress".', e.detail); - if (e.detail.requestId !== requestId) { - return; - } - const languagePair = `${from}${to}`; - const { modelDownloadProgress } = e.detail; - console.info(`BergamotTranslatorAPI[${requestId}]: Model ${languagePair} download progress: `, `${languagePair}: onDownloadProgressUpdate - ${Math.round((modelDownloadProgress.bytesDownloaded / - modelDownloadProgress.bytesToDownload) * - 100)}% out of ${Math.round((modelDownloadProgress.bytesToDownload / 1024 / 1024) * 10) / 10} mb downloaded`, { modelDownloadProgress }); - onModelDownloadProgress(e.detail); - }; - const modelLoadedListener = (e) => { - // console.debug('Listener received "modelLoaded".', e.detail); - if (e.detail.requestId !== requestId) { - return; - } - translationRequestDispatcher.removeEventListener("modelLoaded", modelLoadedListener); - const { loadModelResults } = e.detail; - const languagePair = `${from}${to}`; - const { modelLoadWallTimeMs } = loadModelResults; - console.info(`BergamotTranslatorAPI[${requestId}]: Model ${languagePair} loaded in ${modelLoadWallTimeMs / - 1000} secs`); - onModelLoaded(e.detail); - }; - const translationFinishedListener = (e) => { - // console.debug('Listener received "translationFinished".', e.detail); - if (e.detail.requestId !== requestId) { - return; - } - translationRequestDispatcher.removeEventListener("translationFinished", translationFinishedListener); - const { originalTextsTranslationPerformanceStats } = e.detail; - const { wordCount, seconds, wordsPerSecond, } = originalTextsTranslationPerformanceStats; - console.info(`BergamotTranslatorAPI[${requestId}]: Translation of ${texts.length} texts (wordCount ${wordCount}) took ${seconds} secs (${wordsPerSecond} words per second)`); - onTranslationFinished(e.detail); - }; - try { - // console.debug(`Adding listeners for request id ${requestId}`); - translationRequestDispatcher.addEventListener("translationRequestQueued", translationRequestQueuedListener); - translationRequestDispatcher.addEventListener("modelWillLoad", modelWillLoadListener); - translationRequestDispatcher.addEventListener("modelDownloadProgress", modelDownloadProgressListener); - translationRequestDispatcher.addEventListener("modelLoaded", modelLoadedListener); - translationRequestDispatcher.addEventListener("translationFinished", translationFinishedListener); - const requestPromise = translationRequestDispatcher.translate(requestId, texts, from, to); - const [translationResults] = yield Promise.all([ - requestPromise, - ]); - return translationResults; - } - finally { - translationRequestDispatcher.removeEventListener("translationRequestQueued", translationRequestQueuedListener); - translationRequestDispatcher.removeEventListener("modelWillLoad", modelWillLoadListener); - translationRequestDispatcher.removeEventListener("modelDownloadProgress", modelDownloadProgressListener); - translationRequestDispatcher.removeEventListener("modelLoaded", modelLoadedListener); - translationRequestDispatcher.removeEventListener("translationFinished", translationFinishedListener); - } - }); - }, -}; - - -/***/ }), - -/***/ 6621: -/*!***************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/lib/LanguageDetector.ts ***! - \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.LanguageDetector = void 0; -const webextension_polyfill_ts_1 = __webpack_require__(/*! webextension-polyfill-ts */ 5006); -const browserWithExperimentAPIs_1 = __webpack_require__(/*! firefox-infobar-ui/ts/background-scripts/background.js/browserWithExperimentAPIs */ 2975); -// Since Emscripten can handle heap growth, but not heap shrinkage, we -// need to refresh the worker after we've processed a particularly large -// string in order to prevent unnecessary resident memory growth. -// -// These values define the cut-off string length and the idle timeout -// (in milliseconds) before destroying a worker. Once a string of the -// maximum size has been processed, the worker is marked for -// destruction, and is terminated as soon as it has been idle for the -// given timeout. -// -// 1.5MB. This is the approximate string length that forces heap growth -// for a 2MB heap. -const LARGE_STRING = 1.5 * 1024 * 1024; -const IDLE_TIMEOUT = 10 * 1000; -const WORKER_URL = webextension_polyfill_ts_1.browser.runtime.getURL(`wasm/cld-worker.js`); -const workerManager = { - // TODO: Make into a map instead to avoid the implicit assumption that the order of requests and results are the same - detectionQueue: [], - detectLanguage(params) { - return __awaiter(this, void 0, void 0, function* () { - const worker = yield this.workerReady; - const result = yield new Promise(resolve => { - this.detectionQueue.push({ resolve }); - worker.postMessage(params); - }); - // We have our asynchronous result from the worker. - // - // Determine if our input was large enough to trigger heap growth, - // or if we're already waiting to destroy the worker when it's - // idle. If so, schedule termination after the idle timeout. - if (params.text.length >= LARGE_STRING || this._idleTimeout !== null) { - this.flushWorker(); - } - return result; - }); - }, - onDetectLanguageWorkerResult(detectedLanguageResults) { - this.detectionQueue.shift().resolve(detectedLanguageResults); - }, - _worker: null, - _workerReadyPromise: null, - get workerReady() { - if (!this._workerReadyPromise) { - this._workerReadyPromise = new Promise(resolve => { - const worker = new Worker(WORKER_URL); - worker.onmessage = msg => { - if (msg.data === "ready") { - resolve(worker); - } - else { - this.onDetectLanguageWorkerResult(msg.data); - } - }; - this._worker = worker; - }); - } - return this._workerReadyPromise; - }, - // Holds the ID of the current pending idle cleanup setTimeout. - _idleTimeout: null, - // Schedule the current worker to be terminated after the idle timeout. - flushWorker() { - if (this._idleTimeout !== null) { - clearTimeout(this._idleTimeout); - } - this._idleTimeout = setTimeout(this._flushWorker.bind(this), IDLE_TIMEOUT); - }, - // Immediately terminate the worker, as long as there no pending - // results. Otherwise, reschedule termination until after the next - // idle timeout. - _flushWorker() { - if (this.detectionQueue.length) { - this.flushWorker(); - } - else { - if (this._worker) { - this._worker.terminate(); - } - this._worker = null; - this._workerReadyPromise = null; - this._idleTimeout = null; - } - }, -}; -exports.LanguageDetector = { - /** - * Detect the language of a given string. - * - * The argument may be either a string containing the text to analyze, - * or an object with the following properties: - * - * - 'text' The text to analyze. - * - * - 'isHTML' (optional) A boolean, indicating whether the text - * should be analyzed as HTML rather than plain text. - * - * - 'language' (optional) A string indicating the expected language. - * For text extracted from HTTP documents, this is expected to - * come from the Content-Language header. - * - * - 'tld' (optional) A string indicating the top-level domain of the - * document the text was extracted from. - * - * - 'encoding' (optional) A string describing the encoding of the - * document the string was extracted from. Note that, regardless - * of the value of this property, the 'text' property must be a - * UTF-16 JavaScript string. - * - * @returns {Promise} - * @resolves When detection is finished, with a object containing - * these fields: - * - 'language' (string with a language code) - * - 'confident' (boolean) Whether the detector is confident of the - * result. - * - 'languages' (array) An array of up to three elements, containing - * the most prevalent languages detected. It contains a - * 'languageCode' property, containing the ISO language code of - * the language, and a 'percent' property, describing the - * approximate percentage of the input which is in that language. - * For text of an unknown language, the result may contain an - * entry with the language code 'un', indicating the percent of - * the text which is unknown. - */ - detectLanguage(params) { - return __awaiter(this, void 0, void 0, function* () { - if (typeof params === "string") { - params = { text: params }; - } - // Either use the Firefox experimental web extension API or the bundled WASM-based language detection - if (true) { - return browserWithExperimentAPIs_1.browserWithExperimentAPIs.experiments.languageDetector.detectLanguage(params); - } - return workerManager.detectLanguage(params); - }); - }, -}; - - -/***/ }), - -/***/ 5733: -/*!**********************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/lib/translateAllFramesInTab.ts ***! - \**********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.translateAllFramesInTab = void 0; -const mobx_1 = __webpack_require__(/*! mobx */ 5412); -const BaseTranslationState_1 = __webpack_require__(/*! ../../../shared-resources/models/BaseTranslationState */ 9359); -const mobx_keystone_1 = __webpack_require__(/*! mobx-keystone */ 4380); -const Telemetry_1 = __webpack_require__(/*! ../telemetry/Telemetry */ 1114); -const translateAllFramesInTab = (tabId, from, to, extensionState) => __awaiter(void 0, void 0, void 0, function* () { - // Start timing - const start = performance.now(); - // Request translation of all frames in a specific tab - extensionState.requestTranslationOfAllFramesInTab(tabId, from, to); - // Wait for translation in all frames in tab to complete - yield mobx_1.when(() => { - const { tabTranslationStates } = extensionState; - const currentTabTranslationState = tabTranslationStates.get(tabId); - return (currentTabTranslationState && - [BaseTranslationState_1.TranslationStatus.TRANSLATED, BaseTranslationState_1.TranslationStatus.ERROR].includes(currentTabTranslationState.translationStatus)); - }); - // End timing - const end = performance.now(); - const timeToFullPageTranslatedMs = end - start; - const { tabTranslationStates } = extensionState; - const currentTabTranslationState = mobx_keystone_1.getSnapshot(tabTranslationStates.get(tabId)); - const { totalModelLoadWallTimeMs, totalTranslationEngineRequestCount, totalTranslationWallTimeMs, wordCount, wordCountVisibleInViewport, translationStatus, modelDownloadProgress, } = currentTabTranslationState; - if (translationStatus === BaseTranslationState_1.TranslationStatus.TRANSLATED) { - // Record "translation attempt concluded" telemetry - const timeToFullPageTranslatedSeconds = timeToFullPageTranslatedMs / 1000; - const timeToFullPageTranslatedWordsPerSecond = Math.round(wordCount / timeToFullPageTranslatedSeconds); - const translationEngineTimeMs = totalTranslationWallTimeMs; - const translationEngineWordsPerSecond = Math.round(wordCount / (translationEngineTimeMs / 1000)); - const modelDownloadTimeMs = modelDownloadProgress.durationMs || 0; - const modelLoadTimeMs = totalModelLoadWallTimeMs; - const unaccountedTranslationTimeMs = timeToFullPageTranslatedMs - - modelDownloadTimeMs - - modelLoadTimeMs - - translationEngineTimeMs; - console.info(`Translation of the full page in tab with id ${tabId} (${wordCount} words) took ${timeToFullPageTranslatedSeconds} secs (perceived as ${timeToFullPageTranslatedWordsPerSecond} words per second) across ${totalTranslationEngineRequestCount} translation engine requests (which took ${totalTranslationWallTimeMs / - 1000} seconds, operating at ${translationEngineWordsPerSecond} words per second). Model loading took ${modelLoadTimeMs / - 1000} seconds, after spending ${modelDownloadTimeMs / 1000} seconds ${modelDownloadProgress.bytesToDownload === 0 - ? "hydrating" - : "downloading and persisting"} model files. The remaining ${unaccountedTranslationTimeMs / - 1000} seconds where spent elsewhere.`); - Telemetry_1.telemetry.onTranslationFinished(tabId, from, to, timeToFullPageTranslatedMs, timeToFullPageTranslatedWordsPerSecond, modelDownloadTimeMs, modelLoadTimeMs, translationEngineTimeMs, translationEngineWordsPerSecond, wordCount, wordCountVisibleInViewport); - } - else { - // TODO: Record error telemetry - } -}); -exports.translateAllFramesInTab = translateAllFramesInTab; - - -/***/ }), - -/***/ 1119: -/*!*********************************************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/state-management/MobxKeystoneBackgroundContextHost.ts ***! - \*********************************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MobxKeystoneBackgroundContextHost = void 0; -const webextension_polyfill_ts_1 = __webpack_require__(/*! webextension-polyfill-ts */ 5006); -const mobx_keystone_1 = __webpack_require__(/*! mobx-keystone */ 4380); -const ErrorReporting_1 = __webpack_require__(/*! ../../../shared-resources/ErrorReporting */ 9009); -const DocumentTranslationState_1 = __webpack_require__(/*! ../../../shared-resources/models/DocumentTranslationState */ 1120); -const TranslateOwnTextTranslationState_1 = __webpack_require__(/*! ../../../shared-resources/models/TranslateOwnTextTranslationState */ 6745); -// If we don't import and use all relevant models here, we can't reference models in this build -// Ref: https://github.com/xaviergonz/mobx-keystone/issues/183 -DocumentTranslationState_1.DocumentTranslationState; -TranslateOwnTextTranslationState_1.TranslateOwnTextTranslationState; -// disable runtime data checking (we rely on TypeScript at compile time so that our model definitions can be cleaner) -mobx_keystone_1.setGlobalConfig({ - modelAutoTypeChecking: mobx_keystone_1.ModelAutoTypeCheckingMode.AlwaysOff, -}); -class MobxKeystoneBackgroundContextHost { - constructor() { - this.connectedPorts = []; - } - init(backgroundContextRootStore) { - let actionIsBeingAppliedForPropagationToContentScripts = false; - // Set up a connection / listener for the mobx-keystone-proxy - // allowing state changes to be sent from content scripts - this.mobxKeystoneProxyPortListener = port => { - if (port.name !== "port-from-mobx-keystone-proxy") { - return; - } - this.connectedPorts.push(port); - port.onMessage.addListener((m) => __awaiter(this, void 0, void 0, function* () { - // console.debug("Message from mobx-keystone-proxy:", { m }); - const { requestInitialState, actionCall, requestId } = m; - if (requestInitialState) { - const initialState = mobx_keystone_1.getSnapshot(backgroundContextRootStore); - // console.debug({ initialState }); - port.postMessage({ - initialState, - requestId, - }); - return; - } - if (actionCall) { - const _ = actionIsBeingAppliedForPropagationToContentScripts; - actionIsBeingAppliedForPropagationToContentScripts = true; - this.handleLocallyCancelledActionCall(actionCall, backgroundContextRootStore); - actionIsBeingAppliedForPropagationToContentScripts = _; - return; - } - ErrorReporting_1.captureExceptionWithExtras(new Error("Unexpected message"), { m }); - console.error("Unexpected message", { m }); - })); - port.onDisconnect.addListener(($port) => { - const existingPortIndex = this.connectedPorts.findIndex(p => p === $port); - this.connectedPorts.splice(existingPortIndex, 1); - }); - }; - webextension_polyfill_ts_1.browser.runtime.onConnect.addListener(this.mobxKeystoneProxyPortListener); - // Set up a listener for local (background context) actions to be replicated to content scripts - // in the same way that actions stemming from content scripts do - mobx_keystone_1.onActionMiddleware(backgroundContextRootStore, { - onStart: (actionCall, ctx) => { - if (!actionIsBeingAppliedForPropagationToContentScripts) { - // if the action comes from the background context cancel it silently - // and send resubmit it in the same way that content script actions are treated - // it will then be replicated by the server (background context) and properly executed everywhere - const serializedActionCall = mobx_keystone_1.serializeActionCall(actionCall, backgroundContextRootStore); - this.handleLocallyCancelledActionCall(serializedActionCall, backgroundContextRootStore); - ctx.data.cancelled = true; // just for logging purposes - // "cancel" the action by returning undefined - return { - result: mobx_keystone_1.ActionTrackingResult.Return, - value: undefined, - }; - } - // run actions that are being applied for propagation to content scripts unmodified - /* eslint-disable consistent-return */ - return undefined; - /* eslint-enable consistent-return */ - }, - }); - } - handleLocallyCancelledActionCall(serializedActionCall, backgroundContextRootStore) { - // apply the action over the server root store - // sometimes applying actions might fail (for example on invalid operations - // such as when one client asks to delete a model from an array and other asks to mutate it) - // so we try / catch it - let serializedActionCallToReplicate; - try { - // apply the action on the background context side and keep track of new model IDs being - // generated, so the clients will have the chance to keep those in sync - const applyActionResult = mobx_keystone_1.applySerializedActionAndTrackNewModelIds(backgroundContextRootStore, serializedActionCall); - serializedActionCallToReplicate = applyActionResult.serializedActionCall; - } - catch (err) { - console.error("Error applying action to server:", err); - } - if (serializedActionCallToReplicate) { - this.propagateActionToContentScripts(serializedActionCallToReplicate); - } - } - propagateActionToContentScripts(serializedActionCallToReplicate) { - // and distribute message, which includes new model IDs to keep them in sync - this.connectedPorts.forEach($port => { - try { - $port.postMessage({ - serializedActionCallToReplicate, - }); - } - catch (err) { - if (err.message === "Attempt to postMessage on disconnected port") { - console.warn("Attempt to postMessage on disconnected port, but it is ok", err); - } - else { - throw err; - } - } - }); - } -} -exports.MobxKeystoneBackgroundContextHost = MobxKeystoneBackgroundContextHost; - - -/***/ }), - -/***/ 823: -/*!*****************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/state-management/Store.ts ***! - \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Store = void 0; -const nanoid_1 = __webpack_require__(/*! nanoid */ 3608); -const webextension_polyfill_ts_1 = __webpack_require__(/*! webextension-polyfill-ts */ 5006); -class Store { - constructor(localStorageWrapper) { - this.get = (_keys) => __awaiter(this, void 0, void 0, function* () { return ({}); }); - this.set = (_items) => __awaiter(this, void 0, void 0, function* () { }); - this.initialExtensionPreferences = () => __awaiter(this, void 0, void 0, function* () { - return { - enableErrorReporting: false, - hidePrivacySummaryBanner: false, - extensionInstallationErrorReportingId: "", - extensionInstallationId: "", - extensionVersion: "", - }; - }); - /** - * Returns a persistent unique identifier of the extension installation - * sent with each report. Not related to the Firefox client id - */ - this.extensionInstallationId = () => __awaiter(this, void 0, void 0, function* () { - const { extensionInstallationId } = yield this.get("extensionInstallationId"); - if (extensionInstallationId) { - return extensionInstallationId; - } - const generatedId = nanoid_1.nanoid(); - yield this.set({ extensionInstallationId: generatedId }); - return generatedId; - }); - /** - * Returns a persistent unique identifier of the extension installation - * sent with each error report. Not related to the Firefox client id - * nor the extension installation id that identifies shared data. - */ - this.extensionInstallationErrorReportingId = () => __awaiter(this, void 0, void 0, function* () { - const { extensionInstallationErrorReportingId } = yield this.get("extensionInstallationErrorReportingId"); - if (extensionInstallationErrorReportingId) { - return extensionInstallationErrorReportingId; - } - const generatedId = nanoid_1.nanoid(); - yield this.set({ extensionInstallationErrorReportingId: generatedId }); - return generatedId; - }); - this.getExtensionPreferences = () => __awaiter(this, void 0, void 0, function* () { - const { extensionPreferences } = yield this.get("extensionPreferences"); - return Object.assign(Object.assign(Object.assign({}, (yield this.initialExtensionPreferences())), extensionPreferences), { - // The following are not editable extension preferences, but attributes - // that we want to display on the extension preferences dialog and/or - // add as context in error reports - extensionInstallationErrorReportingId: yield this.extensionInstallationErrorReportingId(), - extensionInstallationId: yield this.extensionInstallationId(), - extensionVersion: webextension_polyfill_ts_1.browser.runtime.getManifest().version, - }); - }); - this.setExtensionPreferences = (extensionPreferences) => __awaiter(this, void 0, void 0, function* () { - yield this.set({ extensionPreferences }); - }); - this.get = localStorageWrapper.get; - this.set = localStorageWrapper.set; - } -} -exports.Store = Store; - - -/***/ }), - -/***/ 7225: -/*!**************************************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/state-management/connectRootStoreToDevTools.ts ***! - \**************************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.connectRootStoreToDevTools = void 0; -const mobx_keystone_1 = __webpack_require__(/*! mobx-keystone */ 4380); -function connectRootStoreToDevTools(rootStore) { - return __awaiter(this, void 0, void 0, function* () { - // connect the store to the redux dev tools - // (different ports for different build variants developed simultaneously) - const { default: remotedev } = yield Promise.resolve().then(() => __importStar(__webpack_require__(/*! remotedev */ 8690))); - const port = process.env.REMOTE_DEV_SERVER_PORT; - console.info(`Connecting the background store to the Redux dev tools on port ${port}`); - const connection = remotedev.connectViaExtension({ - name: `Background Context (Port ${port})`, - realtime: true, - port, - }); - mobx_keystone_1.connectReduxDevTools(remotedev, connection, rootStore); - }); -} -exports.connectRootStoreToDevTools = connectRootStoreToDevTools; - - -/***/ }), - -/***/ 5660: -/*!********************************************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/state-management/createBackgroundContextRootStore.ts ***! - \********************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.createBackgroundContextRootStore = void 0; -const mobx_keystone_1 = __webpack_require__(/*! mobx-keystone */ 4380); -const ExtensionState_1 = __webpack_require__(/*! ../../../shared-resources/models/ExtensionState */ 7516); -// enable runtime data checking even in production mode -mobx_keystone_1.setGlobalConfig({ - modelAutoTypeChecking: mobx_keystone_1.ModelAutoTypeCheckingMode.AlwaysOn, -}); -function createBackgroundContextRootStore() { - // the parameter is the initial data for the model - const rootStore = new ExtensionState_1.ExtensionState({}); - // recommended by mobx-keystone (allows the model hook `onAttachedToRootStore` to work and other goodies) - mobx_keystone_1.registerRootStore(rootStore); - return rootStore; -} -exports.createBackgroundContextRootStore = createBackgroundContextRootStore; - - -/***/ }), - -/***/ 7404: -/*!*******************************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/state-management/localStorageWrapper.ts ***! - \*******************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.localStorageWrapper = void 0; -const webextension_polyfill_ts_1 = __webpack_require__(/*! webextension-polyfill-ts */ 5006); -exports.localStorageWrapper = { - get: webextension_polyfill_ts_1.browser.storage.local.get, - set: webextension_polyfill_ts_1.browser.storage.local.set, -}; - - -/***/ }), - -/***/ 1114: -/*!**************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/telemetry/Telemetry.ts ***! - \**************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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 __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.telemetry = exports.Telemetry = void 0; -const webext_1 = __importDefault(__webpack_require__(/*! @mozilla/glean/webext */ 5122)); -const pings_1 = __webpack_require__(/*! ./generated/pings */ 2609); -const config_1 = __webpack_require__(/*! ../../../config */ 7843); -const performance_1 = __webpack_require__(/*! ./generated/performance */ 7171); -const metadata_1 = __webpack_require__(/*! ./generated/metadata */ 6667); -const infobar_1 = __webpack_require__(/*! ./generated/infobar */ 2943); -const service_1 = __webpack_require__(/*! ./generated/service */ 2324); -const errors_1 = __webpack_require__(/*! ./generated/errors */ 1418); -const webextension_polyfill_ts_1 = __webpack_require__(/*! webextension-polyfill-ts */ 5006); -const bergamot_translator_version_1 = __webpack_require__(/*! ../../../web-worker-scripts/translation-worker.js/bergamot-translator-version */ 7531); -/** - * This class contains general telemetry initialization and helper code and synchronous telemetry-recording functions. - * - * Synchronous methods here is important, since it is the only way to guarantee that multiple Glean API calls are - * executed sequentially and not interleaved with other asynchronous Telemetry recording. - * For more information, see: https://github.com/mozilla-extensions/firefox-translations/pull/76#discussion_r602128568 - * - * Glean.js guarantees zero exceptions, but our glue code or specific way of invoking Glean.js may result in exceptions. - * For this reason we surround all code invoking Glean.js in try/catch blocks. - * - * Pings are grouped by tab id and submitted on specific triggers (see below), or after 1 minute of inactivity. - * - * The "1 minute" period can be overridden to facilitate testing by setting - * the telemetryInactivityThresholdInSecondsOverride string argument at initialization. - * - * Submit triggers: - * 1. Regular translation: infobar displayed -> translated pressed -> translation finished or error -> submit - * 2. Switch language: infobar displayed -> switch source or target lang -> submit (further actions will be submitted in translation scenario) - * 3. Reject: infobar displayed -> press never, not now or close -> submit - * 4. No action: infobar displayed -> no action -> submit on timer after a period of inactivity. - * 5. Language pair unsupported -> submit - */ -class Telemetry { - constructor() { - this.queuedRecordingsByTabId = {}; - this.inactivityDispatchTimersByTabId = {}; - /** - * Submits all collected metrics in a custom ping. - */ - this.queueRecording = (telemetryRecordingFunction, tabId) => { - if (!this.initialized) { - console.warn("Telemetry: ignoring ping that was submitted before Telemetry was initialized"); - return; - } - const tabIdString = String(tabId); - if (!this.queuedRecordingsByTabId[tabIdString]) { - this.queuedRecordingsByTabId[tabIdString] = []; - } - this.queuedRecordingsByTabId[tabIdString].push(telemetryRecordingFunction); - console.info(`Telemetry: Queued a recording in tab ${tabId}`); - }; - this.updateInactivityTimerForTab = (tabId) => { - const tabIdString = String(tabId); - this.clearInactivityTimerForTab(tabId); - // Submit queued recordings after a period of inactivity - this.inactivityDispatchTimersByTabId[tabIdString] = setTimeout(() => { - this.submitQueuedRecordings(tabIdString); - }, this.telemetryInactivityThresholdInSeconds * 1000); - // console.debug(`Telemetry: Inactivity timer ${this.inactivityDispatchTimersByTabId[tabIdString]} for tab ${tabId} set to fire in ${this.telemetryInactivityThresholdInSeconds} seconds.`, new Error()) - }; - this.updateInactivityTimerForAllTabs = () => { - Object.keys(this.queuedRecordingsByTabId).forEach((tabId) => { - this.updateInactivityTimerForTab(tabId); - }); - }; - this.clearInactivityTimerForTab = (tabId) => { - const tabIdString = String(tabId); - if (this.inactivityDispatchTimersByTabId[tabIdString]) { - // console.debug(`Telemetry: Inactivity timer ${this.inactivityDispatchTimersByTabId[tabIdString]} for tab ${tabId} cleared.`) - clearTimeout(this.inactivityDispatchTimersByTabId[tabIdString]); - delete this.inactivityDispatchTimersByTabId[tabIdString]; - } - }; - } - initialize(uploadEnabled, $firefoxClientId, telemetryInactivityThresholdInSecondsOverride) { - const appId = config_1.config.telemetryAppId; - this.setFirefoxClientId($firefoxClientId); - const manifest = webextension_polyfill_ts_1.browser.runtime.getManifest(); - this.extensionVersion = manifest.version; - try { - webext_1.default.initialize(appId, uploadEnabled, { - debug: { logPings: config_1.config.telemetryDebugMode }, - }); - this.telemetryInactivityThresholdInSeconds = telemetryInactivityThresholdInSecondsOverride - ? telemetryInactivityThresholdInSecondsOverride - : 60; - console.info(`Telemetry: initialization completed with application ID ${appId}. Inactivity threshold is set to ${this.telemetryInactivityThresholdInSeconds} seconds.`); - this.initialized = true; - } - catch (err) { - console.error(`Telemetry initialization error`, err); - } - } - uploadEnabledPreferenceUpdated(uploadEnabled) { - console.log("Telemetry: communicating updated uploadEnabled preference to Glean.js", { uploadEnabled }); - webext_1.default.setUploadEnabled(uploadEnabled); - } - setFirefoxClientId($firefoxClientId) { - this.firefoxClientId = $firefoxClientId; - } - setTranslationRelevantFxTelemetryMetrics(translationRelevantFxTelemetryMetrics) { - this.translationRelevantFxTelemetryMetrics = translationRelevantFxTelemetryMetrics; - } - recordCommonMetadata(from, to) { - metadata_1.fromLang.set(from); - metadata_1.toLang.set(to); - metadata_1.firefoxClientId.set(this.firefoxClientId); - metadata_1.extensionVersion.set(this.extensionVersion); - metadata_1.extensionBuildId.set(config_1.config.extensionBuildId.substring(0, 100)); - metadata_1.bergamotTranslatorVersion.set(bergamot_translator_version_1.BERGAMOT_VERSION_FULL); - if (this.translationRelevantFxTelemetryMetrics) { - const { systemMemoryMb, systemCpuCount, systemCpuCores, systemCpuVendor, systemCpuFamily, systemCpuModel, systemCpuStepping, systemCpuL2cacheKB, systemCpuL3cacheKB, systemCpuSpeedMhz, systemCpuExtensions, } = this.translationRelevantFxTelemetryMetrics; - metadata_1.systemMemory.set(systemMemoryMb); - metadata_1.cpuCount.set(systemCpuCount); - metadata_1.cpuCoresCount.set(systemCpuCores); - metadata_1.cpuVendor.set(systemCpuVendor); - metadata_1.cpuFamily.set(systemCpuFamily); - metadata_1.cpuModel.set(systemCpuModel); - metadata_1.cpuStepping.set(systemCpuStepping); - metadata_1.cpuL2Cache.set(systemCpuL2cacheKB); - metadata_1.cpuL3Cache.set(systemCpuL3cacheKB); - metadata_1.cpuSpeed.set(systemCpuSpeedMhz); - metadata_1.cpuExtensions.set(systemCpuExtensions.join(",")); - } - } - onInfoBarDisplayed(tabId, from, to) { - this.queueRecording(() => { - infobar_1.displayed.record(); - this.recordCommonMetadata(from, to); - }, tabId); - this.updateInactivityTimerForAllTabs(); - } - onSelectTranslateFrom(tabId, newFrom, to) { - this.queueRecording(() => { - infobar_1.changeLang.record(); - this.recordCommonMetadata(newFrom, to); - }, tabId); - this.submitQueuedRecordings(tabId); - } - onSelectTranslateTo(tabId, from, newTo) { - this.queueRecording(() => { - infobar_1.changeLang.record(); - this.recordCommonMetadata(from, newTo); - }, tabId); - this.submitQueuedRecordings(tabId); - } - onInfoBarClosed(tabId, from, to) { - this.queueRecording(() => { - infobar_1.closed.record(); - this.recordCommonMetadata(from, to); - }, tabId); - this.submitQueuedRecordings(tabId); - } - onNeverTranslateSelectedLanguage(tabId, from, to) { - this.queueRecording(() => { - infobar_1.neverTranslateLang.record(); - this.recordCommonMetadata(from, to); - }, tabId); - this.updateInactivityTimerForAllTabs(); - } - onNeverTranslateThisSite(tabId, from, to) { - this.queueRecording(() => { - infobar_1.neverTranslateSite.record(); - this.recordCommonMetadata(from, to); - }, tabId); - this.updateInactivityTimerForAllTabs(); - } - onShowOriginalButtonPressed(tabId, _from, _to) { - this.updateInactivityTimerForAllTabs(); - // TODO? - } - onShowTranslatedButtonPressed(tabId, _from, _to) { - this.updateInactivityTimerForAllTabs(); - // TODO? - } - onTranslateButtonPressed(tabId, from, to) { - this.queueRecording(() => { - infobar_1.translate.record(); - this.recordCommonMetadata(from, to); - }, tabId); - this.updateInactivityTimerForAllTabs(); - } - onNotNowButtonPressed(tabId, from, to) { - this.queueRecording(() => { - infobar_1.notNow.record(); - this.recordCommonMetadata(from, to); - }, tabId); - this.updateInactivityTimerForAllTabs(); - } - /** - * A translation attempt starts when a translation is requested in a - * specific tab and ends when all translations in that tab has completed - */ - onTranslationFinished(tabId, from, to, timeToFullPageTranslatedMs, timeToFullPageTranslatedWordsPerSecond, modelDownloadTimeMs, modelLoadTimeMs, translationEngineTimeMs, translationEngineWordsPerSecond, $wordCount, $wordCountVisibleInViewport) { - this.queueRecording(() => { - performance_1.fullPageTranslatedTime.setRawNanos(timeToFullPageTranslatedMs * 1000000); - performance_1.fullPageTranslatedWps.set(timeToFullPageTranslatedWordsPerSecond); - performance_1.modelDownloadTimeNum.setRawNanos(modelDownloadTimeMs * 1000000); - performance_1.modelLoadTimeNum.setRawNanos(modelLoadTimeMs * 1000000); - performance_1.translationEngineTime.setRawNanos(translationEngineTimeMs * 1000000); - performance_1.translationEngineWps.set(translationEngineWordsPerSecond); - performance_1.wordCount.set($wordCount); - performance_1.wordCountVisibleInViewport.set($wordCountVisibleInViewport); - this.recordCommonMetadata(from, to); - }, tabId); - this.submitQueuedRecordings(tabId); - } - onTranslationStatusOffer(tabId, from, to) { - this.queueRecording(() => { - service_1.langMismatch.add(1); - this.recordCommonMetadata(from, to); - }, tabId); - this.updateInactivityTimerForAllTabs(); - } - onTranslationStatusTranslationUnsupported(tabId, from, to) { - this.queueRecording(() => { - service_1.notSupported.add(1); - this.recordCommonMetadata(from, to); - }, tabId); - this.submitQueuedRecordings(tabId); - } - onModelLoadErrorOccurred(tabId, from, to) { - this.submitQueuedRecordings(tabId); - // TODO? - } - onModelDownloadErrorOccurred(tabId, from, to) { - this.queueRecording(() => { - errors_1.modelDownload.add(1); - this.recordCommonMetadata(from, to); - }, tabId); - this.submitQueuedRecordings(tabId); - } - onTranslationErrorOccurred(tabId, from, to) { - this.queueRecording(() => { - errors_1.translation.add(1); - this.recordCommonMetadata(from, to); - }, tabId); - this.submitQueuedRecordings(tabId); - } - onOtherErrorOccurred(tabId, from, to) { - this.submitQueuedRecordings(tabId); - // TODO? - } - submitQueuedRecordings(tabId) { - const tabIdString = String(tabId); - const recordings = this - .queuedRecordingsByTabId[tabIdString]; - if (recordings.length === 0) { - // console.debug(`Telemetry: Submit of 0 recordings from tab ${tabId} requested. Ignoring.`) - return; - } - delete this.queuedRecordingsByTabId[tabIdString]; - this.queuedRecordingsByTabId[tabIdString] = []; - this.clearInactivityTimerForTab(tabId); - try { - recordings.forEach(telemetryRecordingFunction => { - telemetryRecordingFunction(); - }); - pings_1.custom.submit(); - console.info(`Telemetry: A ping based on ${recordings.length} recordings for tab ${tabId} have been dispatched to Glean.js`); - } - catch (err) { - console.error(`Telemetry dispatch error`, err); - } - } - cleanup() { - return __awaiter(this, void 0, void 0, function* () { - // Cancel ongoing timers - Object.keys(this.inactivityDispatchTimersByTabId).forEach((tabId) => { - this.clearInactivityTimerForTab(tabId); - }); - // Make sure to send buffered telemetry events - Object.keys(this.queuedRecordingsByTabId).forEach((tabId) => { - this.submitQueuedRecordings(tabId); - }); - }); - } -} -exports.Telemetry = Telemetry; -// Expose singleton instances -exports.telemetry = new Telemetry(); - - -/***/ }), - -/***/ 1418: -/*!*********************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/telemetry/generated/errors.ts ***! - \*********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.modelDownload = exports.memory = exports.marian = exports.translation = void 0; -// AUTOGENERATED BY glean_parser. DO NOT EDIT. DO NOT COMMIT. -const counter_1 = __importDefault(__webpack_require__(/*! @mozilla/glean/webext/private/metrics/counter */ 499)); -/** - * The translation procedure has failed. - * - * Generated from `errors.translation`. - */ -exports.translation = new counter_1.default({ - category: "errors", - name: "translation", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Marian code related error. - * - * Generated from `errors.marian`. - */ -exports.marian = new counter_1.default({ - category: "errors", - name: "marian", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Memory allocation error. - * - * Generated from `errors.memory`. - */ -exports.memory = new counter_1.default({ - category: "errors", - name: "memory", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Failed to download a model for a supported language pair. - * - * Generated from `errors.model_download`. - */ -exports.modelDownload = new counter_1.default({ - category: "errors", - name: "model_download", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); - - -/***/ }), - -/***/ 2943: -/*!**********************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/telemetry/generated/infobar.ts ***! - \**********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.changeLang = exports.notNow = exports.neverTranslateSite = exports.neverTranslateLang = exports.translate = exports.closed = exports.displayed = void 0; -// AUTOGENERATED BY glean_parser. DO NOT EDIT. DO NOT COMMIT. -const event_1 = __importDefault(__webpack_require__(/*! @mozilla/glean/webext/private/metrics/event */ 2178)); -/** - * The translation infobar was automatically displayed in a browser. - * - * Generated from `infobar.displayed`. - */ -exports.displayed = new event_1.default({ - category: "infobar", - name: "displayed", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}, []); -/** - * The translation infobar was closed. - * - * Generated from `infobar.closed`. - */ -exports.closed = new event_1.default({ - category: "infobar", - name: "closed", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}, []); -/** - * The "Translate" button was pressed on translation infobar. - * - * Generated from `infobar.translate`. - */ -exports.translate = new event_1.default({ - category: "infobar", - name: "translate", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}, []); -/** - * "Never translate language" button in the infobar options was pressed. - * - * Generated from `infobar.never_translate_lang`. - */ -exports.neverTranslateLang = new event_1.default({ - category: "infobar", - name: "never_translate_lang", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}, []); -/** - * "Never translate site" button in the infobar options was pressed. - * - * Generated from `infobar.never_translate_site`. - */ -exports.neverTranslateSite = new event_1.default({ - category: "infobar", - name: "never_translate_site", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}, []); -/** - * "Not now" button on the infobar was pressed. - * - * Generated from `infobar.not_now`. - */ -exports.notNow = new event_1.default({ - category: "infobar", - name: "not_now", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}, []); -/** - * "This page is in" language was changed manually. - * - * Generated from `infobar.change_lang`. - */ -exports.changeLang = new event_1.default({ - category: "infobar", - name: "change_lang", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}, []); - - -/***/ }), - -/***/ 6667: -/*!***********************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/telemetry/generated/metadata.ts ***! - \***********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.cpuExtensions = exports.cpuSpeed = exports.cpuL3Cache = exports.cpuL2Cache = exports.cpuStepping = exports.cpuModel = exports.cpuFamily = exports.cpuVendor = exports.cpuCoresCount = exports.cpuCount = exports.systemMemory = exports.bergamotTranslatorVersion = exports.extensionBuildId = exports.extensionVersion = exports.firefoxClientId = exports.toLang = exports.fromLang = void 0; -// AUTOGENERATED BY glean_parser. DO NOT EDIT. DO NOT COMMIT. -const string_1 = __importDefault(__webpack_require__(/*! @mozilla/glean/webext/private/metrics/string */ 4245)); -const quantity_1 = __importDefault(__webpack_require__(/*! @mozilla/glean/webext/private/metrics/quantity */ 4717)); -/** - * Translation source language. - * - * Generated from `metadata.from_lang`. - */ -exports.fromLang = new string_1.default({ - category: "metadata", - name: "from_lang", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Translation target language. - * - * Generated from `metadata.to_lang`. - */ -exports.toLang = new string_1.default({ - category: "metadata", - name: "to_lang", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Firefox Telemetry client id. - * - * Generated from `metadata.firefox_client_id`. - */ -exports.firefoxClientId = new string_1.default({ - category: "metadata", - name: "firefox_client_id", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Extension version - * - * Generated from `metadata.extension_version`. - */ -exports.extensionVersion = new string_1.default({ - category: "metadata", - name: "extension_version", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Extension build id, indicating which git revision - * and build config was used to produce this build - * - * Generated from `metadata.extension_build_id`. - */ -exports.extensionBuildId = new string_1.default({ - category: "metadata", - name: "extension_build_id", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Bergamot translator engine version - * - * Generated from `metadata.bergamot_translator_version`. - */ -exports.bergamotTranslatorVersion = new string_1.default({ - category: "metadata", - name: "bergamot_translator_version", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Telemetry Environment `system.memoryMB` metric - * - * Generated from `metadata.system_memory`. - */ -exports.systemMemory = new quantity_1.default({ - category: "metadata", - name: "system_memory", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Telemetry Environment `system.cpu.count` metric - * - * Generated from `metadata.cpu_count`. - */ -exports.cpuCount = new quantity_1.default({ - category: "metadata", - name: "cpu_count", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Telemetry Environment `system.cpu.cores` metric - * - * Generated from `metadata.cpu_cores_count`. - */ -exports.cpuCoresCount = new quantity_1.default({ - category: "metadata", - name: "cpu_cores_count", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Telemetry Environment `system.cpu.vendor` metric - * - * Generated from `metadata.cpu_vendor`. - */ -exports.cpuVendor = new string_1.default({ - category: "metadata", - name: "cpu_vendor", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Telemetry Environment `system.cpu.family` metric - * - * Generated from `metadata.cpu_family`. - */ -exports.cpuFamily = new quantity_1.default({ - category: "metadata", - name: "cpu_family", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Telemetry Environment `system.cpu.model` metric - * - * Generated from `metadata.cpu_model`. - */ -exports.cpuModel = new quantity_1.default({ - category: "metadata", - name: "cpu_model", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Telemetry Environment `system.cpu.stepping` metric - * - * Generated from `metadata.cpu_stepping`. - */ -exports.cpuStepping = new quantity_1.default({ - category: "metadata", - name: "cpu_stepping", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Telemetry Environment `system.cpu.l2cacheKB` metric - * - * Generated from `metadata.cpu_l2_cache`. - */ -exports.cpuL2Cache = new quantity_1.default({ - category: "metadata", - name: "cpu_l2_cache", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Telemetry Environment `system.cpu.l3cacheKB` metric - * - * Generated from `metadata.cpu_l3_cache`. - */ -exports.cpuL3Cache = new quantity_1.default({ - category: "metadata", - name: "cpu_l3_cache", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Telemetry Environment `system.cpu.speedMHz` metric - * - * Generated from `metadata.cpu_speed`. - */ -exports.cpuSpeed = new quantity_1.default({ - category: "metadata", - name: "cpu_speed", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Telemetry Environment `system.cpu.extensions` metric - * - * Generated from `metadata.cpu_extensions`. - */ -exports.cpuExtensions = new string_1.default({ - category: "metadata", - name: "cpu_extensions", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); - - -/***/ }), - -/***/ 7171: -/*!**************************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/telemetry/generated/performance.ts ***! - \**************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.translationQuality = exports.wordCountVisibleInViewport = exports.wordCount = exports.translationEngineWps = exports.translationEngineTime = exports.modelLoadTimeNum = exports.modelDownloadTimeNum = exports.fullPageTranslatedWps = exports.fullPageTranslatedTime = void 0; -// AUTOGENERATED BY glean_parser. DO NOT EDIT. DO NOT COMMIT. -const string_1 = __importDefault(__webpack_require__(/*! @mozilla/glean/webext/private/metrics/string */ 4245)); -const timespan_1 = __importDefault(__webpack_require__(/*! @mozilla/glean/webext/private/metrics/timespan */ 2939)); -const quantity_1 = __importDefault(__webpack_require__(/*! @mozilla/glean/webext/private/metrics/quantity */ 4717)); -/** - * Timing from "translation button pressed" - * to "full page is translated". - * - * Generated from `performance.full_page_translated_time`. - */ -exports.fullPageTranslatedTime = new timespan_1.default({ - category: "performance", - name: "full_page_translated_time", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}, "millisecond"); -/** - * Speed of the translation from "translation button - * pressed" to "full page is translated". - * - * Generated from `performance.full_page_translated_wps`. - */ -exports.fullPageTranslatedWps = new quantity_1.default({ - category: "performance", - name: "full_page_translated_wps", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Time spent on downloading a translation model for a language pair. - * (Renamed from model_download_time to model_download_time_num as part of - * changing type from string to quantity) - * - * Generated from `performance.model_download_time_num`. - */ -exports.modelDownloadTimeNum = new timespan_1.default({ - category: "performance", - name: "model_download_time_num", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}, "millisecond"); -/** - * Time spent on loading a model into memory to start translation. - * (Renamed from model_load_time to model_load_time_num as part of - * changing type from string to quantity) - * - * Generated from `performance.model_load_time_num`. - */ -exports.modelLoadTimeNum = new timespan_1.default({ - category: "performance", - name: "model_load_time_num", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}, "millisecond"); -/** - * Time spent on translation by the translation engine. - * - * Generated from `performance.translation_engine_time`. - */ -exports.translationEngineTime = new timespan_1.default({ - category: "performance", - name: "translation_engine_time", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}, "millisecond"); -/** - * Speed of translation as measured by the translation engine. - * - * Generated from `performance.translation_engine_wps`. - */ -exports.translationEngineWps = new quantity_1.default({ - category: "performance", - name: "translation_engine_wps", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Total number of words on the original web page. - * - * Generated from `performance.word_count`. - */ -exports.wordCount = new quantity_1.default({ - category: "performance", - name: "word_count", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Total number of visible words on the original web page that - * were visible in the viewport at the time of "translation button pressed". - * - * Generated from `performance.word_count_visible_in_viewport`. - */ -exports.wordCountVisibleInViewport = new quantity_1.default({ - category: "performance", - name: "word_count_visible_in_viewport", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * Quality estimation of translation. - * - * Generated from `performance.translation_quality`. - */ -exports.translationQuality = new string_1.default({ - category: "performance", - name: "translation_quality", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); - - -/***/ }), - -/***/ 2609: -/*!********************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/telemetry/generated/pings.ts ***! - \********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.custom = void 0; -// AUTOGENERATED BY glean_parser. DO NOT EDIT. DO NOT COMMIT. -const ping_1 = __importDefault(__webpack_require__(/*! @mozilla/glean/webext/private/ping */ 8410)); -/** - * A custom ping, sending time is fully controlled by the application. - * - * Generated from `custom`. - */ -exports.custom = new ping_1.default({ - includeClientId: true, - sendIfEmpty: false, - name: "custom", - reasonCodes: [], -}); - - -/***/ }), - -/***/ 2324: -/*!**********************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/telemetry/generated/service.ts ***! - \**********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.langMismatch = exports.notSupported = void 0; -// AUTOGENERATED BY glean_parser. DO NOT EDIT. DO NOT COMMIT. -const counter_1 = __importDefault(__webpack_require__(/*! @mozilla/glean/webext/private/metrics/counter */ 499)); -/** - * Language pair of user and website languages is not supported. - * - * Generated from `service.not_supported`. - */ -exports.notSupported = new counter_1.default({ - category: "service", - name: "not_supported", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); -/** - * The user and website languages do not match. - * - * Generated from `service.lang_mismatch`. - */ -exports.langMismatch = new counter_1.default({ - category: "service", - name: "lang_mismatch", - sendInPings: ["custom"], - lifetime: "ping", - disabled: false, -}); - - -/***/ }), - -/***/ 8240: -/*!****************************************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/translation-api-clients/BergamotRestApiClient.ts ***! - \****************************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BergamotRestApiClient = void 0; -const config_1 = __webpack_require__(/*! ../../../config */ 7843); -const MS_IN_A_MINUTE = 60 * 1000; -// https://stackoverflow.com/a/57888548/682317 -const fetchWithTimeout = (url, ms, options = {}) => { - const controller = new AbortController(); - const promise = fetch(url, Object.assign({ signal: controller.signal }, options)); - const timeout = setTimeout(() => controller.abort(), ms); - return promise.finally(() => clearTimeout(timeout)); -}; -class BergamotRestApiClient { - constructor(requestTimeoutMs = null) { - /** - * Timeout after which we consider a ping submission failed. - */ - this.requestTimeoutMs = 1.5 * MS_IN_A_MINUTE; - /** - * See https://github.com/browsermt/mts/wiki/BergamotAPI - */ - this.composeSubmitRequestPath = () => { - return `/api/bergamot/v1`; - }; - this.composeUrl = () => { - return `${config_1.config.bergamotRestApiUrl}${this.composeSubmitRequestPath()}`; - }; - this.sendTranslationRequest = (texts, _from, _to, _translationRequestProgressCallback) => __awaiter(this, void 0, void 0, function* () { - const payload = { - text: texts, - options: { - // "inputFormat": "wrappedText", - // "returnWordAlignment": true, - returnSentenceScore: true, - // "returnSoftAlignment": true, - // "returnQualityEstimate": true, - // "returnWordScores": true, - // "returnTokenization": true, - // "returnOriginal": true, - }, - }; - const dataResponse = yield fetchWithTimeout(this.composeUrl(), this.requestTimeoutMs, { - method: "POST", - headers: { - Accept: "application/json", - "Content-Type": "application/json; charset=UTF-8", - }, - body: JSON.stringify(payload), - }).catch((error) => __awaiter(this, void 0, void 0, function* () { - return Promise.reject(error); - })); - if (!dataResponse.ok) { - throw new Error("Data response failed"); - } - const parsedResponse = yield dataResponse.json(); - // console.log({ parsedResponse }); - const originalTexts = texts; - const translatedTexts = []; - const qeAnnotatedTranslatedTexts = []; - parsedResponse.text.map((paragraph) => { - const translationObjects = getBestTranslationObjectsOfEachSentenceInBergamotRestApiParagraph(paragraph); - // TODO: Currently the rest server doesn't retain the leading/trailing - // whitespace information of sentences. It is a bug on rest server side. - // Once it is fixed there, we need to stop appending whitespaces. - const separator = " "; - // Join sentence translations - const translatedPlainTextString = translationObjects - .map(({ translation }) => translation) - .join(separator); - translatedTexts.push(translatedPlainTextString); - // Generate QE Annotated HTML for each sentence - const qeAnnotatedSentenceHTMLs = translationObjects.map(({ translation, sentenceScore }) => generateQEAnnotatedHTML(translation, sentenceScore)); - const qeAnnotatedTranslatedMarkup = qeAnnotatedSentenceHTMLs.join(separator); - qeAnnotatedTranslatedTexts.push(qeAnnotatedTranslatedMarkup); - }); - return { - originalTexts, - translatedTexts, - qeAnnotatedTranslatedTexts, - }; - }); - if (requestTimeoutMs) { - this.requestTimeoutMs = requestTimeoutMs; - } - } -} -exports.BergamotRestApiClient = BergamotRestApiClient; -/** - * This function parses 'Paragraph' entity of the response for the - * the best translations and returns them - */ -function getBestTranslationObjectsOfEachSentenceInBergamotRestApiParagraph(paragraph) { - const bestTranslations = []; - paragraph[0].forEach(sentenceTranslationList => { - // Depending on the request, there might be multiple 'best translations'. - // We are fetching the best one (present in 'translation' field). - const bestTranslation = sentenceTranslationList.nBest[0]; - bestTranslations.push(bestTranslation); - }); - return bestTranslations; -} -/** - * This function generates the Quality Estimation annotated HTML of a string - * based on its score. - * - * @param translation input string - * @param score score of the input string - * @returns string QE annotated HTML of input string - */ -function generateQEAnnotatedHTML(translation, score) { - // Color choices and thresholds below are chosen based on intuitiveness. - // They will be changed according to the UI design of Translator once it - // is fixed. - let color; - if (score >= -0.2) { - color = "green"; - } - else if (score >= -0.5 && score < -0.2) { - color = "black"; - } - else if (score >= -0.8 && score < -0.5) { - color = "mediumvioletred"; - } - else { - color = "red"; - } - return ` ${translation}`; -} - - -/***/ }), - -/***/ 7423: -/*!****************************************************************************************************!*\ - !*** ../core/ts/background-scripts/background.js/translation-api-clients/BergamotWasmApiClient.ts ***! - \****************************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BergamotWasmApiClient = void 0; -const BergamotTranslatorAPI_1 = __webpack_require__(/*! ../lib/BergamotTranslatorAPI */ 3797); -class BergamotWasmApiClient { - constructor() { - this.sendTranslationRequest = (texts, from, to, translationRequestProgressCallback) => __awaiter(this, void 0, void 0, function* () { - if (typeof texts === "string") { - texts = [texts]; - } - const translationRequestProgress = { - requestId: undefined, - initiationTimestamp: Date.now(), - queued: false, - modelLoadNecessary: undefined, - modelDownloadNecessary: undefined, - modelDownloading: false, - modelDownloadProgress: undefined, - modelLoading: false, - modelLoaded: undefined, - modelLoadWallTimeMs: undefined, - translationFinished: false, - translationWallTimeMs: undefined, - errorOccurred: false, - }; - try { - const translationResults = yield BergamotTranslatorAPI_1.BergamotTranslatorAPI.translate(texts, from, to, (translationRequestQueuedEventData) => { - translationRequestProgress.requestId = - translationRequestQueuedEventData.requestId; - translationRequestProgress.queued = true; - translationRequestProgressCallback(Object.assign({}, translationRequestProgress)); - }, (_modelWillLoadEventData) => { - translationRequestProgress.modelLoadNecessary = true; - translationRequestProgress.modelLoading = true; - translationRequestProgressCallback(Object.assign({}, translationRequestProgress)); - }, (modelDownloadProgressEventData) => { - translationRequestProgress.modelDownloadNecessary = true; - translationRequestProgress.modelDownloading = - modelDownloadProgressEventData.modelDownloadProgress - .bytesDownloaded < - modelDownloadProgressEventData.modelDownloadProgress - .bytesToDownload; - translationRequestProgress.modelDownloadProgress = - modelDownloadProgressEventData.modelDownloadProgress; - translationRequestProgressCallback(Object.assign({}, translationRequestProgress)); - }, (modelLoadedEventData) => { - translationRequestProgress.modelLoading = false; - translationRequestProgress.modelDownloading = false; - translationRequestProgress.modelLoaded = true; - translationRequestProgress.modelLoadWallTimeMs = - modelLoadedEventData.loadModelResults.modelLoadWallTimeMs; - translationRequestProgressCallback(Object.assign({}, translationRequestProgress)); - }, (translationFinishedEventData) => { - translationRequestProgress.queued = false; - translationRequestProgress.translationFinished = true; - translationRequestProgress.translationWallTimeMs = - translationFinishedEventData.translationWallTimeMs; - translationRequestProgressCallback(Object.assign({}, translationRequestProgress)); - }); - console.log({ translationResults }); - return translationResults; - } - catch (error) { - translationRequestProgress.queued = false; - translationRequestProgress.translationFinished = false; - translationRequestProgress.errorOccurred = true; - translationRequestProgressCallback(Object.assign({}, translationRequestProgress)); - throw error; - } - }); - } -} -exports.BergamotWasmApiClient = BergamotWasmApiClient; - - -/***/ }), - -/***/ 7531: -/*!******************************************************************************************!*\ - !*** ../core/ts/web-worker-scripts/translation-worker.js/bergamot-translator-version.ts ***! - \******************************************************************************************/ -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BERGAMOT_VERSION_FULL = void 0; -exports.BERGAMOT_VERSION_FULL = "v0.3.1+d264450"; - - -/***/ }), - -/***/ 4120: -/*!************************************************************************!*\ - !*** ./ts/background-scripts/background.js/NativeTranslateUiBroker.ts ***! - \************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.NativeTranslateUiBroker = exports.NativeTranslateUiStateInfobarState = void 0; -const LanguageSupport_1 = __webpack_require__(/*! ../../../../core/ts/shared-resources/LanguageSupport */ 3872); -const BaseTranslationState_1 = __webpack_require__(/*! ../../../../core/ts/shared-resources/models/BaseTranslationState */ 9359); -const Telemetry_1 = __webpack_require__(/*! ../../../../core/ts/background-scripts/background.js/telemetry/Telemetry */ 1114); -const mobx_keystone_1 = __webpack_require__(/*! mobx-keystone */ 4380); -const mobx_1 = __webpack_require__(/*! mobx */ 5412); -const translateAllFramesInTab_1 = __webpack_require__(/*! ../../../../core/ts/background-scripts/background.js/lib/translateAllFramesInTab */ 5733); -const browserWithExperimentAPIs_1 = __webpack_require__(/*! ./browserWithExperimentAPIs */ 2975); -/* eslint-disable no-unused-vars, no-shadow */ -// TODO: update typescript-eslint when support for this kind of declaration is supported -var NativeTranslateUiStateInfobarState; -(function (NativeTranslateUiStateInfobarState) { - NativeTranslateUiStateInfobarState[NativeTranslateUiStateInfobarState["STATE_OFFER"] = 0] = "STATE_OFFER"; - NativeTranslateUiStateInfobarState[NativeTranslateUiStateInfobarState["STATE_TRANSLATING"] = 1] = "STATE_TRANSLATING"; - NativeTranslateUiStateInfobarState[NativeTranslateUiStateInfobarState["STATE_TRANSLATED"] = 2] = "STATE_TRANSLATED"; - NativeTranslateUiStateInfobarState[NativeTranslateUiStateInfobarState["STATE_ERROR"] = 3] = "STATE_ERROR"; - NativeTranslateUiStateInfobarState[NativeTranslateUiStateInfobarState["STATE_UNAVAILABLE"] = 4] = "STATE_UNAVAILABLE"; -})(NativeTranslateUiStateInfobarState = exports.NativeTranslateUiStateInfobarState || (exports.NativeTranslateUiStateInfobarState = {})); -class NativeTranslateUiBroker { - constructor(extensionState) { - this.extensionState = extensionState; - this.telemetryPreferencesEventsToObserve = [ - "onUploadEnabledPrefChange", - "onCachedClientIDPrefChange", - ]; - this.translateUiEventsToObserve = [ - "onInfoBarDisplayed", - "onSelectTranslateTo", - "onSelectTranslateFrom", - "onInfoBarClosed", - "onNeverTranslateSelectedLanguage", - "onNeverTranslateThisSite", - "onShowOriginalButtonPressed", - "onShowTranslatedButtonPressed", - "onTranslateButtonPressed", - "onNotNowButtonPressed", - ]; - } - start() { - return __awaiter(this, void 0, void 0, function* () { - // Current value of Telemetry preferences - const uploadEnabled = yield browserWithExperimentAPIs_1.browserWithExperimentAPIs.experiments.telemetryPreferences.getUploadEnabledPref(); - const cachedClientID = yield browserWithExperimentAPIs_1.browserWithExperimentAPIs.experiments.telemetryPreferences.getCachedClientIDPref(); - // Initialize telemetry - const telemetryInactivityThresholdInSecondsOverride = yield browserWithExperimentAPIs_1.browserWithExperimentAPIs.experiments.extensionPreferences.getTelemetryInactivityThresholdInSecondsOverridePref(); - Telemetry_1.telemetry.initialize(uploadEnabled, cachedClientID, telemetryInactivityThresholdInSecondsOverride); - // The translationRelevantFxTelemetryMetrics gets available first once the telemetry environment has initialized - browserWithExperimentAPIs_1.browserWithExperimentAPIs.experiments.telemetryEnvironment - .getTranslationRelevantFxTelemetryMetrics() - .then((translationRelevantFxTelemetryMetrics) => { - Telemetry_1.telemetry.setTranslationRelevantFxTelemetryMetrics(translationRelevantFxTelemetryMetrics); - }); - // Hook up experiment API events with listeners in this class - this.telemetryPreferencesEventsToObserve.map((eventRef) => { - browserWithExperimentAPIs_1.browserWithExperimentAPIs.experiments.telemetryPreferences[eventRef].addListener(this[eventRef].bind(this)); - }); - this.translateUiEventsToObserve.map((eventRef) => { - browserWithExperimentAPIs_1.browserWithExperimentAPIs.experiments.translateUi[eventRef].addListener(this[eventRef].bind(this)); - }); - yield browserWithExperimentAPIs_1.browserWithExperimentAPIs.experiments.translateUi.start(); - const { summarizeLanguageSupport } = new LanguageSupport_1.LanguageSupport(); - // Boils down extension state to the subset relevant for the native translate ui - const nativeTranslateUiStateFromTabTranslationState = (tts) => __awaiter(this, void 0, void 0, function* () { - const infobarState = nativeTranslateUiStateInfobarStateFromTranslationStatus(tts.translationStatus); - const detectedLanguageResults = tts.detectedLanguageResults; - const { acceptedTargetLanguages, - // defaultSourceLanguage, - defaultTargetLanguage, supportedSourceLanguages, - // supportedTargetLanguagesGivenDefaultSourceLanguage, - allPossiblySupportedTargetLanguages, } = yield summarizeLanguageSupport(detectedLanguageResults); - const translationDurationMs = Date.now() - tts.translationInitiationTimestamp; - // Localized translation progress text - const { modelLoading, queuedTranslationEngineRequestCount, modelDownloading, modelDownloadProgress, } = tts; - let localizedTranslationProgressText; - if (modelDownloading) { - const showDetailedProgress = modelDownloadProgress && modelDownloadProgress.bytesDownloaded > 0; - const percentDownloaded = Math.round((modelDownloadProgress.bytesDownloaded / - modelDownloadProgress.bytesToDownload) * - 100); - const mbToDownload = Math.round((modelDownloadProgress.bytesToDownload / 1024 / 1024) * 10) / 10; - const localizedDetailedDownloadProgressText = browser.i18n.getMessage("detailedDownloadProgress", [percentDownloaded, mbToDownload]); - localizedTranslationProgressText = `(${browser.i18n.getMessage("currentlyDownloadingLanguageModel")}...${showDetailedProgress - ? ` ${localizedDetailedDownloadProgressText}` - : ``})`; - } - else if (modelLoading) { - localizedTranslationProgressText = `(${browser.i18n.getMessage("currentlyLoadingLanguageModel")}...)`; - } - else if (queuedTranslationEngineRequestCount > 0) { - // Using neutral plural form since there is no support for plural form in browser.i18n - localizedTranslationProgressText = `(${browser.i18n.getMessage("loadedLanguageModel")}. ${browser.i18n.getMessage("partsLeftToTranslate", queuedTranslationEngineRequestCount)})`; - } - else { - localizedTranslationProgressText = ""; - } - return { - acceptedTargetLanguages, - detectedLanguageResults, - // defaultSourceLanguage, - defaultTargetLanguage, - infobarState, - translatedFrom: tts.translateFrom, - translatedTo: tts.translateTo, - originalShown: tts.showOriginal, - // Additionally, since supported source and target languages are only supported in specific pairs, keep these dynamic: - supportedSourceLanguages, - supportedTargetLanguages: allPossiblySupportedTargetLanguages, - // Translation progress - modelDownloading, - translationDurationMs, - localizedTranslationProgressText, - }; - }); - const nativeTranslateUiStateInfobarStateFromTranslationStatus = (translationStatus) => { - switch (translationStatus) { - case BaseTranslationState_1.TranslationStatus.UNKNOWN: - return NativeTranslateUiStateInfobarState.STATE_UNAVAILABLE; - case BaseTranslationState_1.TranslationStatus.UNAVAILABLE: - return NativeTranslateUiStateInfobarState.STATE_UNAVAILABLE; - case BaseTranslationState_1.TranslationStatus.DETECTING_LANGUAGE: - return NativeTranslateUiStateInfobarState.STATE_UNAVAILABLE; - case BaseTranslationState_1.TranslationStatus.LANGUAGE_NOT_DETECTED: - return NativeTranslateUiStateInfobarState.STATE_OFFER; - case BaseTranslationState_1.TranslationStatus.SOURCE_LANGUAGE_UNDERSTOOD: - return NativeTranslateUiStateInfobarState.STATE_UNAVAILABLE; - case BaseTranslationState_1.TranslationStatus.TRANSLATION_UNSUPPORTED: - return NativeTranslateUiStateInfobarState.STATE_UNAVAILABLE; - case BaseTranslationState_1.TranslationStatus.OFFER: - return NativeTranslateUiStateInfobarState.STATE_OFFER; - case BaseTranslationState_1.TranslationStatus.TRANSLATING: - return NativeTranslateUiStateInfobarState.STATE_TRANSLATING; - case BaseTranslationState_1.TranslationStatus.TRANSLATED: - return NativeTranslateUiStateInfobarState.STATE_TRANSLATED; - case BaseTranslationState_1.TranslationStatus.ERROR: - return NativeTranslateUiStateInfobarState.STATE_ERROR; - } - throw Error(`No corresponding NativeTranslateUiStateInfobarState available for translationStatus "${translationStatus}"`); - }; - // React to tab translation state changes - mobx_1.reaction(() => this.extensionState.tabTranslationStates, (tabTranslationStates, _previousTabTranslationStates) => __awaiter(this, void 0, void 0, function* () { - tabTranslationStates.forEach((tts, tabId) => __awaiter(this, void 0, void 0, function* () { - const uiState = yield nativeTranslateUiStateFromTabTranslationState(mobx_keystone_1.getSnapshot(tts)); - browserWithExperimentAPIs_1.browserWithExperimentAPIs.experiments.translateUi.setUiState(tabId, uiState); - // Send telemetry on some translation status changes - const hasChanged = property => { - const previousTabTranslationState = _previousTabTranslationStates.get(tabId); - return (!previousTabTranslationState || - tts[property] !== previousTabTranslationState[property]); - }; - if (hasChanged("translationStatus")) { - if (tts.translationStatus === BaseTranslationState_1.TranslationStatus.OFFER) { - Telemetry_1.telemetry.onTranslationStatusOffer(tabId, tts.effectiveTranslateFrom, tts.effectiveTranslateTo); - } - if (tts.translationStatus === - BaseTranslationState_1.TranslationStatus.TRANSLATION_UNSUPPORTED) { - Telemetry_1.telemetry.onTranslationStatusTranslationUnsupported(tabId, tts.effectiveTranslateFrom, tts.effectiveTranslateTo); - } - } - if (hasChanged("modelLoadErrorOccurred")) { - if (tts.modelLoadErrorOccurred) { - Telemetry_1.telemetry.onModelLoadErrorOccurred(tabId, tts.effectiveTranslateFrom, tts.effectiveTranslateTo); - } - } - if (hasChanged("modelDownloadErrorOccurred")) { - if (tts.modelDownloadErrorOccurred) { - Telemetry_1.telemetry.onModelDownloadErrorOccurred(tabId, tts.effectiveTranslateFrom, tts.effectiveTranslateTo); - } - } - if (hasChanged("translationErrorOccurred")) { - if (tts.translationErrorOccurred) { - Telemetry_1.telemetry.onTranslationErrorOccurred(tabId, tts.effectiveTranslateFrom, tts.effectiveTranslateTo); - } - } - if (hasChanged("otherErrorOccurred")) { - if (tts.otherErrorOccurred) { - Telemetry_1.telemetry.onOtherErrorOccurred(tabId, tts.effectiveTranslateFrom, tts.effectiveTranslateTo); - } - } - if (hasChanged("modelDownloadProgress")) { - if (tts.modelDownloadProgress) { - Telemetry_1.telemetry.updateInactivityTimerForAllTabs(); - } - } - })); - // TODO: check _previousTabTranslationStates for those that had something and now should be inactive - })); - }); - } - onUploadEnabledPrefChange() { - return __awaiter(this, void 0, void 0, function* () { - const uploadEnabled = yield browserWithExperimentAPIs_1.browserWithExperimentAPIs.experiments.telemetryPreferences.getUploadEnabledPref(); - // console.debug("onUploadEnabledPrefChange", { uploadEnabled }); - Telemetry_1.telemetry.uploadEnabledPreferenceUpdated(uploadEnabled); - }); - } - onCachedClientIDPrefChange() { - return __awaiter(this, void 0, void 0, function* () { - const cachedClientID = yield browserWithExperimentAPIs_1.browserWithExperimentAPIs.experiments.telemetryPreferences.getCachedClientIDPref(); - // console.debug("onCachedClientIDPrefChange", { cachedClientID }); - Telemetry_1.telemetry.setFirefoxClientId(cachedClientID); - }); - } - onInfoBarDisplayed(tabId, from, to) { - console.debug("onInfoBarDisplayed", { tabId, from, to }); - Telemetry_1.telemetry.onInfoBarDisplayed(tabId, from, to); - } - onSelectTranslateFrom(tabId, newFrom, to) { - console.debug("onSelectTranslateFrom", { tabId, newFrom, to }); - Telemetry_1.telemetry.onSelectTranslateFrom(tabId, newFrom, to); - } - onSelectTranslateTo(tabId, from, newTo) { - console.debug("onSelectTranslateTo", { tabId, from, newTo }); - Telemetry_1.telemetry.onSelectTranslateFrom(tabId, from, newTo); - } - onInfoBarClosed(tabId, from, to) { - console.debug("onInfoBarClosed", { tabId, from, to }); - Telemetry_1.telemetry.onInfoBarClosed(tabId, from, to); - } - onNeverTranslateSelectedLanguage(tabId, from, to) { - console.debug("onNeverTranslateSelectedLanguage", { tabId, from, to }); - Telemetry_1.telemetry.onNeverTranslateSelectedLanguage(tabId, from, to); - } - onNeverTranslateThisSite(tabId, from, to) { - console.debug("onNeverTranslateThisSite", { tabId, from, to }); - Telemetry_1.telemetry.onNeverTranslateThisSite(tabId, from, to); - } - onShowOriginalButtonPressed(tabId, from, to) { - console.debug("onShowOriginalButtonPressed", { tabId, from, to }); - Telemetry_1.telemetry.onShowOriginalButtonPressed(tabId, from, to); - this.extensionState.showOriginalInTab(tabId); - } - onShowTranslatedButtonPressed(tabId, from, to) { - console.debug("onShowTranslatedButtonPressed", { tabId, from, to }); - Telemetry_1.telemetry.onShowTranslatedButtonPressed(tabId, from, to); - this.extensionState.hideOriginalInTab(tabId); - } - onTranslateButtonPressed(tabId, from, to) { - console.debug("onTranslateButtonPressed", { tabId, from, to }); - Telemetry_1.telemetry.onTranslateButtonPressed(tabId, from, to); - translateAllFramesInTab_1.translateAllFramesInTab(tabId, from, to, this.extensionState); - } - onNotNowButtonPressed(tabId, from, to) { - console.debug("onNotNowButtonPressed", { tabId, from, to }); - Telemetry_1.telemetry.onNotNowButtonPressed(tabId, from, to); - } - stop() { - return __awaiter(this, void 0, void 0, function* () { - yield browserWithExperimentAPIs_1.browserWithExperimentAPIs.experiments.translateUi.stop(); - this.telemetryPreferencesEventsToObserve.map(eventRef => { - browserWithExperimentAPIs_1.browserWithExperimentAPIs.experiments.telemetryPreferences[eventRef].removeListener(this[eventRef]); - }); - this.translateUiEventsToObserve.map(eventRef => { - browserWithExperimentAPIs_1.browserWithExperimentAPIs.experiments.translateUi[eventRef].removeListener(this[eventRef]); - }); - yield Telemetry_1.telemetry.cleanup(); - }); - } -} -exports.NativeTranslateUiBroker = NativeTranslateUiBroker; - - -/***/ }), - -/***/ 2975: -/*!**************************************************************************!*\ - !*** ./ts/background-scripts/background.js/browserWithExperimentAPIs.ts ***! - \**************************************************************************/ -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.browserWithExperimentAPIs = void 0; -exports.browserWithExperimentAPIs = browser; - - -/***/ }), - -/***/ 7227: -/*!******************************************************!*\ - !*** ./ts/background-scripts/background.js/index.ts ***! - \******************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "(extensionGlue)" }]*/ -const ErrorReporting_1 = __webpack_require__(/*! ../../../../core/ts/shared-resources/ErrorReporting */ 9009); -const webextension_polyfill_ts_1 = __webpack_require__(/*! webextension-polyfill-ts */ 5006); -const localStorageWrapper_1 = __webpack_require__(/*! ../../../../core/ts/background-scripts/background.js/state-management/localStorageWrapper */ 7404); -const contentScriptFrameInfoPortListener_1 = __webpack_require__(/*! ../../../../core/ts/background-scripts/background.js/contentScriptFrameInfoPortListener */ 800); -const createBackgroundContextRootStore_1 = __webpack_require__(/*! ../../../../core/ts/background-scripts/background.js/state-management/createBackgroundContextRootStore */ 5660); -const contentScriptLanguageDetectorProxyPortListener_1 = __webpack_require__(/*! ../../../../core/ts/background-scripts/background.js/contentScriptLanguageDetectorProxyPortListener */ 4958); -const Store_1 = __webpack_require__(/*! ../../../../core/ts/background-scripts/background.js/state-management/Store */ 823); -const connectRootStoreToDevTools_1 = __webpack_require__(/*! ../../../../core/ts/background-scripts/background.js/state-management/connectRootStoreToDevTools */ 7225); -const MobxKeystoneBackgroundContextHost_1 = __webpack_require__(/*! ../../../../core/ts/background-scripts/background.js/state-management/MobxKeystoneBackgroundContextHost */ 1119); -const NativeTranslateUiBroker_1 = __webpack_require__(/*! ./NativeTranslateUiBroker */ 4120); -const contentScriptBergamotApiClientPortListener_1 = __webpack_require__(/*! ../../../../core/ts/background-scripts/background.js/contentScriptBergamotApiClientPortListener */ 933); -const bergamot_translator_version_1 = __webpack_require__(/*! ../../../../core/ts/web-worker-scripts/translation-worker.js/bergamot-translator-version */ 7531); -const config_1 = __webpack_require__(/*! ../../../../core/ts/config */ 7843); -const store = new Store_1.Store(localStorageWrapper_1.localStorageWrapper); -/* eslint-enable no-unused-vars */ -/** - * Ties together overall execution logic and allows content scripts - * to access persistent storage and background-context API:s via cross-process messaging - */ -class ExtensionGlue { - constructor() { - this.extensionState = createBackgroundContextRootStore_1.createBackgroundContextRootStore(); - } - init() { - return __awaiter(this, void 0, void 0, function* () { - // Add version to extension log output to facilitate general troubleshooting - const manifest = webextension_polyfill_ts_1.browser.runtime.getManifest(); - console.info(`Extension ${manifest.name} version ${manifest.version} [build id "${config_1.config.extensionBuildId}"] (with bergamot-translator ${bergamot_translator_version_1.BERGAMOT_VERSION_FULL}) initializing.`); - // Initiate the root extension state store - this.extensionState = createBackgroundContextRootStore_1.createBackgroundContextRootStore(); - // Allow for easy introspection of extension state in development mode - if (false) {} - // Make the root extension state store available to content script contexts - const mobxKeystoneBackgroundContextHost = new MobxKeystoneBackgroundContextHost_1.MobxKeystoneBackgroundContextHost(); - mobxKeystoneBackgroundContextHost.init(this.extensionState); - // Enable error reporting if not opted out - this.extensionPreferencesPortListener = yield ErrorReporting_1.initErrorReportingInBackgroundScript(store, [ - "port-from-options-ui:index", - "port-from-options-ui:form", - "port-from-main-interface:index", - "port-from-get-started:index", - "port-from-get-started:component", - "port-from-dom-translation-content-script:index", - ]); - }); - } - start() { - return __awaiter(this, void 0, void 0, function* () { - // Set up native translate ui - this.nativeTranslateUiBroker = new NativeTranslateUiBroker_1.NativeTranslateUiBroker(this.extensionState); - yield this.nativeTranslateUiBroker.start(); - // Set up content script port listeners - this.contentScriptLanguageDetectorProxyPortListener = contentScriptLanguageDetectorProxyPortListener_1.contentScriptLanguageDetectorProxyPortListener; - this.contentScriptBergamotApiClientPortListener = contentScriptBergamotApiClientPortListener_1.contentScriptBergamotApiClientPortListener; - this.contentScriptFrameInfoPortListener = contentScriptFrameInfoPortListener_1.contentScriptFrameInfoPortListener; - [ - "contentScriptLanguageDetectorProxyPortListener", - "contentScriptBergamotApiClientPortListener", - "contentScriptFrameInfoPortListener", - ].forEach(listenerName => { - webextension_polyfill_ts_1.browser.runtime.onConnect.addListener(this[listenerName]); - }); - }); - } - // TODO: Run this cleanup-method when relevant - cleanup() { - return __awaiter(this, void 0, void 0, function* () { - yield this.nativeTranslateUiBroker.stop(); - // Tear down content script port listeners - [ - this.extensionPreferencesPortListener, - this.contentScriptLanguageDetectorProxyPortListener, - this.contentScriptBergamotApiClientPortListener, - this.contentScriptFrameInfoPortListener, - ].forEach((listener) => { - try { - webextension_polyfill_ts_1.browser.runtime.onConnect.removeListener(listener); - } - catch (err) { - console.warn(`Port listener removal error`, err); - } - }); - }); - } -} -// make an instance of the ExtensionGlue class available to the extension background context -const extensionGlue = (window.extensionGlue = new ExtensionGlue()); -// migrations -const runMigrations = () => __awaiter(void 0, void 0, void 0, function* () { - console.info("Running relevant migrations"); -}); -// init the extension glue on every extension load -function onEveryExtensionLoad() { - return __awaiter(this, void 0, void 0, function* () { - yield extensionGlue.init(); - yield runMigrations(); - yield extensionGlue.start(); - }); -} -onEveryExtensionLoad().then(); -// Open and keep the test-runner open after each extension reload when in development mode -if (false) {} - - -/***/ }) - -/******/ }); -/************************************************************************/ -/******/ // The module cache -/******/ var __webpack_module_cache__ = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ // Check if module is in cache -/******/ if(__webpack_module_cache__[moduleId]) { -/******/ return __webpack_module_cache__[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = __webpack_module_cache__[moduleId] = { -/******/ id: moduleId, -/******/ loaded: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.loaded = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = __webpack_modules__; -/******/ -/******/ // the startup function -/******/ // It's empty as some runtime module handles the default behavior -/******/ __webpack_require__.x = x => {}; -/************************************************************************/ -/******/ /* webpack/runtime/compat get default export */ -/******/ (() => { -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = (module) => { -/******/ var getter = module && module.__esModule ? -/******/ () => (module['default']) : -/******/ () => (module); -/******/ __webpack_require__.d(getter, { a: getter }); -/******/ return getter; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/define property getters */ -/******/ (() => { -/******/ // define getter functions for harmony exports -/******/ __webpack_require__.d = (exports, definition) => { -/******/ for(var key in definition) { -/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { -/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); -/******/ } -/******/ } -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/global */ -/******/ (() => { -/******/ __webpack_require__.g = (function() { -/******/ if (typeof globalThis === 'object') return globalThis; -/******/ try { -/******/ return this || new Function('return this')(); -/******/ } catch (e) { -/******/ if (typeof window === 'object') return window; -/******/ } -/******/ })(); -/******/ })(); -/******/ -/******/ /* webpack/runtime/harmony module decorator */ -/******/ (() => { -/******/ __webpack_require__.hmd = (module) => { -/******/ module = Object.create(module); -/******/ if (!module.children) module.children = []; -/******/ Object.defineProperty(module, 'exports', { -/******/ enumerable: true, -/******/ set: () => { -/******/ throw new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id); -/******/ } -/******/ }); -/******/ return module; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/hasOwnProperty shorthand */ -/******/ (() => { -/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -/******/ })(); -/******/ -/******/ /* webpack/runtime/make namespace object */ -/******/ (() => { -/******/ // define __esModule on exports -/******/ __webpack_require__.r = (exports) => { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/node module decorator */ -/******/ (() => { -/******/ __webpack_require__.nmd = (module) => { -/******/ module.paths = []; -/******/ if (!module.children) module.children = []; -/******/ return module; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/jsonp chunk loading */ -/******/ (() => { -/******/ // no baseURI -/******/ -/******/ // object to store loaded and loading chunks -/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched -/******/ // Promise = chunk loading, 0 = chunk loaded -/******/ var installedChunks = { -/******/ 352: 0 -/******/ }; -/******/ -/******/ var deferredModules = [ -/******/ [7227,351] -/******/ ]; -/******/ // no chunk on demand loading -/******/ -/******/ // no prefetching -/******/ -/******/ // no preloaded -/******/ -/******/ // no HMR -/******/ -/******/ // no HMR manifest -/******/ -/******/ var checkDeferredModules = x => {}; -/******/ -/******/ // install a JSONP callback for chunk loading -/******/ var webpackJsonpCallback = (parentChunkLoadingFunction, data) => { -/******/ var [chunkIds, moreModules, runtime, executeModules] = data; -/******/ // add "moreModules" to the modules object, -/******/ // then flag all "chunkIds" as loaded and fire callback -/******/ var moduleId, chunkId, i = 0, resolves = []; -/******/ for(;i < chunkIds.length; i++) { -/******/ chunkId = chunkIds[i]; -/******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) { -/******/ resolves.push(installedChunks[chunkId][0]); -/******/ } -/******/ installedChunks[chunkId] = 0; -/******/ } -/******/ for(moduleId in moreModules) { -/******/ if(__webpack_require__.o(moreModules, moduleId)) { -/******/ __webpack_require__.m[moduleId] = moreModules[moduleId]; -/******/ } -/******/ } -/******/ if(runtime) runtime(__webpack_require__); -/******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data); -/******/ while(resolves.length) { -/******/ resolves.shift()(); -/******/ } -/******/ -/******/ // add entry modules from loaded chunk to deferred list -/******/ if(executeModules) deferredModules.push.apply(deferredModules, executeModules); -/******/ -/******/ // run deferred modules when all chunks ready -/******/ return checkDeferredModules(); -/******/ } -/******/ -/******/ var chunkLoadingGlobal = self["webpackChunkfirefox_infobar_ui"] = self["webpackChunkfirefox_infobar_ui"] || []; -/******/ chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0)); -/******/ chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal)); -/******/ -/******/ function checkDeferredModulesImpl() { -/******/ var result; -/******/ for(var i = 0; i < deferredModules.length; i++) { -/******/ var deferredModule = deferredModules[i]; -/******/ var fulfilled = true; -/******/ for(var j = 1; j < deferredModule.length; j++) { -/******/ var depId = deferredModule[j]; -/******/ if(installedChunks[depId] !== 0) fulfilled = false; -/******/ } -/******/ if(fulfilled) { -/******/ deferredModules.splice(i--, 1); -/******/ result = __webpack_require__(__webpack_require__.s = deferredModule[0]); -/******/ } -/******/ } -/******/ if(deferredModules.length === 0) { -/******/ __webpack_require__.x(); -/******/ __webpack_require__.x = x => {}; -/******/ } -/******/ return result; -/******/ } -/******/ var startup = __webpack_require__.x; -/******/ __webpack_require__.x = () => { -/******/ // reset startup function so it can be called again when more startup code is added -/******/ __webpack_require__.x = startup || (x => {}); -/******/ return (checkDeferredModules = checkDeferredModulesImpl)(); -/******/ }; -/******/ })(); -/******/ -/************************************************************************/ -/******/ -/******/ // run startup -/******/ var __webpack_exports__ = __webpack_require__.x(); -/******/ -/******/ })() -; -//# sourceMappingURL=background.js.map \ No newline at end of file diff --git a/browser/extensions/translations/extension/commons.js b/browser/extensions/translations/extension/commons.js deleted file mode 100644 index 75da09d64fac..000000000000 --- a/browser/extensions/translations/extension/commons.js +++ /dev/null @@ -1,26403 +0,0 @@ -(self["webpackChunkfirefox_infobar_ui"] = self["webpackChunkfirefox_infobar_ui"] || []).push([[351],{ - -/***/ 1346: -/*!********************************************************************!*\ - !*** ../../node_modules/@sentry/browser/esm/index.js + 51 modules ***! - \********************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -// ESM COMPAT FLAG -__webpack_require__.r(__webpack_exports__); - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "BrowserClient": () => (/* reexport */ BrowserClient), - "Hub": () => (/* reexport */ Hub), - "Integrations": () => (/* binding */ INTEGRATIONS), - "SDK_NAME": () => (/* reexport */ SDK_NAME), - "SDK_VERSION": () => (/* reexport */ SDK_VERSION), - "Scope": () => (/* reexport */ Scope), - "Severity": () => (/* reexport */ Severity), - "Status": () => (/* reexport */ Status), - "Transports": () => (/* reexport */ transports_namespaceObject), - "addBreadcrumb": () => (/* reexport */ addBreadcrumb), - "addGlobalEventProcessor": () => (/* reexport */ addGlobalEventProcessor), - "captureEvent": () => (/* reexport */ captureEvent), - "captureException": () => (/* reexport */ captureException), - "captureMessage": () => (/* reexport */ captureMessage), - "close": () => (/* reexport */ sdk_close), - "configureScope": () => (/* reexport */ configureScope), - "defaultIntegrations": () => (/* reexport */ defaultIntegrations), - "eventFromException": () => (/* reexport */ eventFromException), - "eventFromMessage": () => (/* reexport */ eventFromMessage), - "flush": () => (/* reexport */ flush), - "forceLoad": () => (/* reexport */ forceLoad), - "getCurrentHub": () => (/* reexport */ getCurrentHub), - "getHubFromCarrier": () => (/* reexport */ getHubFromCarrier), - "init": () => (/* reexport */ init), - "injectReportDialog": () => (/* reexport */ injectReportDialog), - "lastEventId": () => (/* reexport */ lastEventId), - "makeMain": () => (/* reexport */ makeMain), - "onLoad": () => (/* reexport */ onLoad), - "setContext": () => (/* reexport */ setContext), - "setExtra": () => (/* reexport */ setExtra), - "setExtras": () => (/* reexport */ setExtras), - "setTag": () => (/* reexport */ setTag), - "setTags": () => (/* reexport */ setTags), - "setUser": () => (/* reexport */ setUser), - "showReportDialog": () => (/* reexport */ showReportDialog), - "startTransaction": () => (/* reexport */ startTransaction), - "withScope": () => (/* reexport */ withScope), - "wrap": () => (/* reexport */ sdk_wrap) -}); - -// NAMESPACE OBJECT: ../../node_modules/@sentry/core/esm/integrations/index.js -var integrations_namespaceObject = {}; -__webpack_require__.r(integrations_namespaceObject); -__webpack_require__.d(integrations_namespaceObject, { - "FunctionToString": () => (FunctionToString), - "InboundFilters": () => (InboundFilters) -}); - -// NAMESPACE OBJECT: ../../node_modules/@sentry/browser/esm/integrations/index.js -var esm_integrations_namespaceObject = {}; -__webpack_require__.r(esm_integrations_namespaceObject); -__webpack_require__.d(esm_integrations_namespaceObject, { - "Breadcrumbs": () => (Breadcrumbs), - "GlobalHandlers": () => (GlobalHandlers), - "LinkedErrors": () => (LinkedErrors), - "TryCatch": () => (TryCatch), - "UserAgent": () => (UserAgent) -}); - -// NAMESPACE OBJECT: ../../node_modules/@sentry/browser/esm/transports/index.js -var transports_namespaceObject = {}; -__webpack_require__.r(transports_namespaceObject); -__webpack_require__.d(transports_namespaceObject, { - "BaseTransport": () => (BaseTransport), - "FetchTransport": () => (FetchTransport), - "XHRTransport": () => (XHRTransport) -}); - -;// CONCATENATED MODULE: ../../node_modules/tslib/tslib.es6.js -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -var __assign = function() { - __assign = Object.assign || function __assign(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); -} - -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -} - -function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} - -function __param(paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } -} - -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} - -function __awaiter(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()); - }); -} - -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -function __createBinding(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -} - -function __exportStar(m, exports) { - for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p]; -} - -function __values(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."); -} - -function __read(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; -} - -function tslib_es6_spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} - -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -}; - -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} - -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -} - -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } -} - -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -} - -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; -}; - -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result.default = mod; - return result; -} - -function __importDefault(mod) { - return (mod && mod.__esModule) ? mod : { default: mod }; -} - -function __classPrivateFieldGet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); -} - -function __classPrivateFieldSet(receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/types/esm/severity.js -/** JSDoc */ -// eslint-disable-next-line import/export -var Severity; -(function (Severity) { - /** JSDoc */ - Severity["Fatal"] = "fatal"; - /** JSDoc */ - Severity["Error"] = "error"; - /** JSDoc */ - Severity["Warning"] = "warning"; - /** JSDoc */ - Severity["Log"] = "log"; - /** JSDoc */ - Severity["Info"] = "info"; - /** JSDoc */ - Severity["Debug"] = "debug"; - /** JSDoc */ - Severity["Critical"] = "critical"; -})(Severity || (Severity = {})); -// eslint-disable-next-line @typescript-eslint/no-namespace, import/export -(function (Severity) { - /** - * Converts a string-based level into a {@link Severity}. - * - * @param level string representation of Severity - * @returns Severity - */ - function fromString(level) { - switch (level) { - case 'debug': - return Severity.Debug; - case 'info': - return Severity.Info; - case 'warn': - case 'warning': - return Severity.Warning; - case 'error': - return Severity.Error; - case 'fatal': - return Severity.Fatal; - case 'critical': - return Severity.Critical; - case 'log': - default: - return Severity.Log; - } - } - Severity.fromString = fromString; -})(Severity || (Severity = {})); - -;// CONCATENATED MODULE: ../../node_modules/@sentry/types/esm/status.js -/** The status of an event. */ -// eslint-disable-next-line import/export -var Status; -(function (Status) { - /** The status could not be determined. */ - Status["Unknown"] = "unknown"; - /** The event was skipped due to configuration or callbacks. */ - Status["Skipped"] = "skipped"; - /** The event was sent to Sentry successfully. */ - Status["Success"] = "success"; - /** The client is currently rate limited and will try again later. */ - Status["RateLimit"] = "rate_limit"; - /** The event could not be processed. */ - Status["Invalid"] = "invalid"; - /** A server-side error ocurred during submission. */ - Status["Failed"] = "failed"; -})(Status || (Status = {})); -// eslint-disable-next-line @typescript-eslint/no-namespace, import/export -(function (Status) { - /** - * Converts a HTTP status code into a {@link Status}. - * - * @param code The HTTP response status code. - * @returns The send status or {@link Status.Unknown}. - */ - function fromHttpCode(code) { - if (code >= 200 && code < 300) { - return Status.Success; - } - if (code === 429) { - return Status.RateLimit; - } - if (code >= 400 && code < 500) { - return Status.Invalid; - } - if (code >= 500) { - return Status.Failed; - } - return Status.Unknown; - } - Status.fromHttpCode = fromHttpCode; -})(Status || (Status = {})); - -;// CONCATENATED MODULE: ../../node_modules/@sentry/utils/esm/is.js -/* eslint-disable @typescript-eslint/no-explicit-any */ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -/** - * Checks whether given value's type is one of a few Error or Error-like - * {@link isError}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isError(wat) { - switch (Object.prototype.toString.call(wat)) { - case '[object Error]': - return true; - case '[object Exception]': - return true; - case '[object DOMException]': - return true; - default: - return isInstanceOf(wat, Error); - } -} -/** - * Checks whether given value's type is ErrorEvent - * {@link isErrorEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isErrorEvent(wat) { - return Object.prototype.toString.call(wat) === '[object ErrorEvent]'; -} -/** - * Checks whether given value's type is DOMError - * {@link isDOMError}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isDOMError(wat) { - return Object.prototype.toString.call(wat) === '[object DOMError]'; -} -/** - * Checks whether given value's type is DOMException - * {@link isDOMException}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isDOMException(wat) { - return Object.prototype.toString.call(wat) === '[object DOMException]'; -} -/** - * Checks whether given value's type is a string - * {@link isString}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isString(wat) { - return Object.prototype.toString.call(wat) === '[object String]'; -} -/** - * Checks whether given value's is a primitive (undefined, null, number, boolean, string) - * {@link isPrimitive}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isPrimitive(wat) { - return wat === null || (typeof wat !== 'object' && typeof wat !== 'function'); -} -/** - * Checks whether given value's type is an object literal - * {@link isPlainObject}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isPlainObject(wat) { - return Object.prototype.toString.call(wat) === '[object Object]'; -} -/** - * Checks whether given value's type is an Event instance - * {@link isEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isEvent(wat) { - return typeof Event !== 'undefined' && isInstanceOf(wat, Event); -} -/** - * Checks whether given value's type is an Element instance - * {@link isElement}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isElement(wat) { - return typeof Element !== 'undefined' && isInstanceOf(wat, Element); -} -/** - * Checks whether given value's type is an regexp - * {@link isRegExp}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isRegExp(wat) { - return Object.prototype.toString.call(wat) === '[object RegExp]'; -} -/** - * Checks whether given value has a then function. - * @param wat A value to be checked. - */ -function isThenable(wat) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return Boolean(wat && wat.then && typeof wat.then === 'function'); -} -/** - * Checks whether given value's type is a SyntheticEvent - * {@link isSyntheticEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isSyntheticEvent(wat) { - return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat; -} -/** - * Checks whether given value's type is an instance of provided constructor. - * {@link isInstanceOf}. - * - * @param wat A value to be checked. - * @param base A constructor to be used in a check. - * @returns A boolean representing the result. - */ -function isInstanceOf(wat, base) { - try { - return wat instanceof base; - } - catch (_e) { - return false; - } -} - -// EXTERNAL MODULE: ../../node_modules/@sentry/utils/esm/time.js -var time = __webpack_require__(5870); -;// CONCATENATED MODULE: ../../node_modules/@sentry/utils/esm/syncpromise.js -/* eslint-disable @typescript-eslint/explicit-function-return-type */ -/* eslint-disable @typescript-eslint/typedef */ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -/* eslint-disable @typescript-eslint/no-explicit-any */ - -/** SyncPromise internal states */ -var States; -(function (States) { - /** Pending */ - States["PENDING"] = "PENDING"; - /** Resolved / OK */ - States["RESOLVED"] = "RESOLVED"; - /** Rejected / Error */ - States["REJECTED"] = "REJECTED"; -})(States || (States = {})); -/** - * Thenable class that behaves like a Promise and follows it's interface - * but is not async internally - */ -var SyncPromise = /** @class */ (function () { - function SyncPromise(executor) { - var _this = this; - this._state = States.PENDING; - this._handlers = []; - /** JSDoc */ - this._resolve = function (value) { - _this._setResult(States.RESOLVED, value); - }; - /** JSDoc */ - this._reject = function (reason) { - _this._setResult(States.REJECTED, reason); - }; - /** JSDoc */ - this._setResult = function (state, value) { - if (_this._state !== States.PENDING) { - return; - } - if (isThenable(value)) { - value.then(_this._resolve, _this._reject); - return; - } - _this._state = state; - _this._value = value; - _this._executeHandlers(); - }; - // TODO: FIXME - /** JSDoc */ - this._attachHandler = function (handler) { - _this._handlers = _this._handlers.concat(handler); - _this._executeHandlers(); - }; - /** JSDoc */ - this._executeHandlers = function () { - if (_this._state === States.PENDING) { - return; - } - var cachedHandlers = _this._handlers.slice(); - _this._handlers = []; - cachedHandlers.forEach(function (handler) { - if (handler.done) { - return; - } - if (_this._state === States.RESOLVED) { - if (handler.onfulfilled) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - handler.onfulfilled(_this._value); - } - } - if (_this._state === States.REJECTED) { - if (handler.onrejected) { - handler.onrejected(_this._value); - } - } - handler.done = true; - }); - }; - try { - executor(this._resolve, this._reject); - } - catch (e) { - this._reject(e); - } - } - /** JSDoc */ - SyncPromise.resolve = function (value) { - return new SyncPromise(function (resolve) { - resolve(value); - }); - }; - /** JSDoc */ - SyncPromise.reject = function (reason) { - return new SyncPromise(function (_, reject) { - reject(reason); - }); - }; - /** JSDoc */ - SyncPromise.all = function (collection) { - return new SyncPromise(function (resolve, reject) { - if (!Array.isArray(collection)) { - reject(new TypeError("Promise.all requires an array as input.")); - return; - } - if (collection.length === 0) { - resolve([]); - return; - } - var counter = collection.length; - var resolvedCollection = []; - collection.forEach(function (item, index) { - SyncPromise.resolve(item) - .then(function (value) { - resolvedCollection[index] = value; - counter -= 1; - if (counter !== 0) { - return; - } - resolve(resolvedCollection); - }) - .then(null, reject); - }); - }); - }; - /** JSDoc */ - SyncPromise.prototype.then = function (onfulfilled, onrejected) { - var _this = this; - return new SyncPromise(function (resolve, reject) { - _this._attachHandler({ - done: false, - onfulfilled: function (result) { - if (!onfulfilled) { - // TODO: ¯\_(ツ)_/¯ - // TODO: FIXME - resolve(result); - return; - } - try { - resolve(onfulfilled(result)); - return; - } - catch (e) { - reject(e); - return; - } - }, - onrejected: function (reason) { - if (!onrejected) { - reject(reason); - return; - } - try { - resolve(onrejected(reason)); - return; - } - catch (e) { - reject(e); - return; - } - }, - }); - }); - }; - /** JSDoc */ - SyncPromise.prototype.catch = function (onrejected) { - return this.then(function (val) { return val; }, onrejected); - }; - /** JSDoc */ - SyncPromise.prototype.finally = function (onfinally) { - var _this = this; - return new SyncPromise(function (resolve, reject) { - var val; - var isRejected; - return _this.then(function (value) { - isRejected = false; - val = value; - if (onfinally) { - onfinally(); - } - }, function (reason) { - isRejected = true; - val = reason; - if (onfinally) { - onfinally(); - } - }).then(function () { - if (isRejected) { - reject(val); - return; - } - resolve(val); - }); - }); - }; - /** JSDoc */ - SyncPromise.prototype.toString = function () { - return '[object SyncPromise]'; - }; - return SyncPromise; -}()); - - -// EXTERNAL MODULE: ../../node_modules/@sentry/utils/esm/misc.js -var misc = __webpack_require__(637); -;// CONCATENATED MODULE: ../../node_modules/@sentry/hub/esm/scope.js - - -/** - * Holds additional event information. {@link Scope.applyToEvent} will be - * called by the client before an event will be sent. - */ -var Scope = /** @class */ (function () { - function Scope() { - /** Flag if notifiying is happening. */ - this._notifyingListeners = false; - /** Callback for client to receive scope changes. */ - this._scopeListeners = []; - /** Callback list that will be called after {@link applyToEvent}. */ - this._eventProcessors = []; - /** Array of breadcrumbs. */ - this._breadcrumbs = []; - /** User */ - this._user = {}; - /** Tags */ - this._tags = {}; - /** Extra */ - this._extra = {}; - /** Contexts */ - this._contexts = {}; - } - /** - * Inherit values from the parent scope. - * @param scope to clone. - */ - Scope.clone = function (scope) { - var newScope = new Scope(); - if (scope) { - newScope._breadcrumbs = tslib_es6_spread(scope._breadcrumbs); - newScope._tags = __assign({}, scope._tags); - newScope._extra = __assign({}, scope._extra); - newScope._contexts = __assign({}, scope._contexts); - newScope._user = scope._user; - newScope._level = scope._level; - newScope._span = scope._span; - newScope._session = scope._session; - newScope._transactionName = scope._transactionName; - newScope._fingerprint = scope._fingerprint; - newScope._eventProcessors = tslib_es6_spread(scope._eventProcessors); - } - return newScope; - }; - /** - * Add internal on change listener. Used for sub SDKs that need to store the scope. - * @hidden - */ - Scope.prototype.addScopeListener = function (callback) { - this._scopeListeners.push(callback); - }; - /** - * @inheritDoc - */ - Scope.prototype.addEventProcessor = function (callback) { - this._eventProcessors.push(callback); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setUser = function (user) { - this._user = user || {}; - if (this._session) { - this._session.update({ user: user }); - } - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.getUser = function () { - return this._user; - }; - /** - * @inheritDoc - */ - Scope.prototype.setTags = function (tags) { - this._tags = __assign(__assign({}, this._tags), tags); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setTag = function (key, value) { - var _a; - this._tags = __assign(__assign({}, this._tags), (_a = {}, _a[key] = value, _a)); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setExtras = function (extras) { - this._extra = __assign(__assign({}, this._extra), extras); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setExtra = function (key, extra) { - var _a; - this._extra = __assign(__assign({}, this._extra), (_a = {}, _a[key] = extra, _a)); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setFingerprint = function (fingerprint) { - this._fingerprint = fingerprint; - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setLevel = function (level) { - this._level = level; - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setTransactionName = function (name) { - this._transactionName = name; - this._notifyScopeListeners(); - return this; - }; - /** - * Can be removed in major version. - * @deprecated in favor of {@link this.setTransactionName} - */ - Scope.prototype.setTransaction = function (name) { - return this.setTransactionName(name); - }; - /** - * @inheritDoc - */ - Scope.prototype.setContext = function (key, context) { - var _a; - if (context === null) { - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete this._contexts[key]; - } - else { - this._contexts = __assign(__assign({}, this._contexts), (_a = {}, _a[key] = context, _a)); - } - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setSpan = function (span) { - this._span = span; - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.getSpan = function () { - return this._span; - }; - /** - * @inheritDoc - */ - Scope.prototype.getTransaction = function () { - var _a, _b, _c, _d; - // often, this span will be a transaction, but it's not guaranteed to be - var span = this.getSpan(); - // try it the new way first - if ((_a = span) === null || _a === void 0 ? void 0 : _a.transaction) { - return (_b = span) === null || _b === void 0 ? void 0 : _b.transaction; - } - // fallback to the old way (known bug: this only finds transactions with sampled = true) - if ((_d = (_c = span) === null || _c === void 0 ? void 0 : _c.spanRecorder) === null || _d === void 0 ? void 0 : _d.spans[0]) { - return span.spanRecorder.spans[0]; - } - // neither way found a transaction - return undefined; - }; - /** - * @inheritDoc - */ - Scope.prototype.setSession = function (session) { - if (!session) { - delete this._session; - } - else { - this._session = session; - } - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.getSession = function () { - return this._session; - }; - /** - * @inheritDoc - */ - Scope.prototype.update = function (captureContext) { - if (!captureContext) { - return this; - } - if (typeof captureContext === 'function') { - var updatedScope = captureContext(this); - return updatedScope instanceof Scope ? updatedScope : this; - } - if (captureContext instanceof Scope) { - this._tags = __assign(__assign({}, this._tags), captureContext._tags); - this._extra = __assign(__assign({}, this._extra), captureContext._extra); - this._contexts = __assign(__assign({}, this._contexts), captureContext._contexts); - if (captureContext._user && Object.keys(captureContext._user).length) { - this._user = captureContext._user; - } - if (captureContext._level) { - this._level = captureContext._level; - } - if (captureContext._fingerprint) { - this._fingerprint = captureContext._fingerprint; - } - } - else if (isPlainObject(captureContext)) { - // eslint-disable-next-line no-param-reassign - captureContext = captureContext; - this._tags = __assign(__assign({}, this._tags), captureContext.tags); - this._extra = __assign(__assign({}, this._extra), captureContext.extra); - this._contexts = __assign(__assign({}, this._contexts), captureContext.contexts); - if (captureContext.user) { - this._user = captureContext.user; - } - if (captureContext.level) { - this._level = captureContext.level; - } - if (captureContext.fingerprint) { - this._fingerprint = captureContext.fingerprint; - } - } - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.clear = function () { - this._breadcrumbs = []; - this._tags = {}; - this._extra = {}; - this._user = {}; - this._contexts = {}; - this._level = undefined; - this._transactionName = undefined; - this._fingerprint = undefined; - this._span = undefined; - this._session = undefined; - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.addBreadcrumb = function (breadcrumb, maxBreadcrumbs) { - var mergedBreadcrumb = __assign({ timestamp: (0,time/* dateTimestampInSeconds */.yW)() }, breadcrumb); - this._breadcrumbs = - maxBreadcrumbs !== undefined && maxBreadcrumbs >= 0 - ? tslib_es6_spread(this._breadcrumbs, [mergedBreadcrumb]).slice(-maxBreadcrumbs) - : tslib_es6_spread(this._breadcrumbs, [mergedBreadcrumb]); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.clearBreadcrumbs = function () { - this._breadcrumbs = []; - this._notifyScopeListeners(); - return this; - }; - /** - * Applies the current context and fingerprint to the event. - * Note that breadcrumbs will be added by the client. - * Also if the event has already breadcrumbs on it, we do not merge them. - * @param event Event - * @param hint May contain additional informartion about the original exception. - * @hidden - */ - Scope.prototype.applyToEvent = function (event, hint) { - if (this._extra && Object.keys(this._extra).length) { - event.extra = __assign(__assign({}, this._extra), event.extra); - } - if (this._tags && Object.keys(this._tags).length) { - event.tags = __assign(__assign({}, this._tags), event.tags); - } - if (this._user && Object.keys(this._user).length) { - event.user = __assign(__assign({}, this._user), event.user); - } - if (this._contexts && Object.keys(this._contexts).length) { - event.contexts = __assign(__assign({}, this._contexts), event.contexts); - } - if (this._level) { - event.level = this._level; - } - if (this._transactionName) { - event.transaction = this._transactionName; - } - // We want to set the trace context for normal events only if there isn't already - // a trace context on the event. There is a product feature in place where we link - // errors with transaction and it relys on that. - if (this._span) { - event.contexts = __assign({ trace: this._span.getTraceContext() }, event.contexts); - } - this._applyFingerprint(event); - event.breadcrumbs = tslib_es6_spread((event.breadcrumbs || []), this._breadcrumbs); - event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined; - return this._notifyEventProcessors(tslib_es6_spread(getGlobalEventProcessors(), this._eventProcessors), event, hint); - }; - /** - * This will be called after {@link applyToEvent} is finished. - */ - Scope.prototype._notifyEventProcessors = function (processors, event, hint, index) { - var _this = this; - if (index === void 0) { index = 0; } - return new SyncPromise(function (resolve, reject) { - var processor = processors[index]; - if (event === null || typeof processor !== 'function') { - resolve(event); - } - else { - var result = processor(__assign({}, event), hint); - if (isThenable(result)) { - result - .then(function (final) { return _this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve); }) - .then(null, reject); - } - else { - _this._notifyEventProcessors(processors, result, hint, index + 1) - .then(resolve) - .then(null, reject); - } - } - }); - }; - /** - * This will be called on every set call. - */ - Scope.prototype._notifyScopeListeners = function () { - var _this = this; - if (!this._notifyingListeners) { - this._notifyingListeners = true; - setTimeout(function () { - _this._scopeListeners.forEach(function (callback) { - callback(_this); - }); - _this._notifyingListeners = false; - }); - } - }; - /** - * Applies fingerprint from the scope to the event if there's one, - * uses message if there's one instead or get rid of empty fingerprint - */ - Scope.prototype._applyFingerprint = function (event) { - // Make sure it's an array first and we actually have something in place - event.fingerprint = event.fingerprint - ? Array.isArray(event.fingerprint) - ? event.fingerprint - : [event.fingerprint] - : []; - // If we have something on the scope, then merge it with event - if (this._fingerprint) { - event.fingerprint = event.fingerprint.concat(this._fingerprint); - } - // If we have no data at all, remove empty array default - if (event.fingerprint && !event.fingerprint.length) { - delete event.fingerprint; - } - }; - return Scope; -}()); - -/** - * Retruns the global event processors. - */ -function getGlobalEventProcessors() { - var global = (0,misc/* getGlobalObject */.Rf)(); - global.__SENTRY__ = global.__SENTRY__ || {}; - global.__SENTRY__.globalEventProcessors = global.__SENTRY__.globalEventProcessors || []; - return global.__SENTRY__.globalEventProcessors; -} -/** - * Add a EventProcessor to be kept globally. - * @param callback EventProcessor to add - */ -function addGlobalEventProcessor(callback) { - getGlobalEventProcessors().push(callback); -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/utils/esm/logger.js -/* eslint-disable @typescript-eslint/no-explicit-any */ - -// TODO: Implement different loggers for different environments -var global = (0,misc/* getGlobalObject */.Rf)(); -/** Prefix for logging strings */ -var PREFIX = 'Sentry Logger '; -/** JSDoc */ -var Logger = /** @class */ (function () { - /** JSDoc */ - function Logger() { - this._enabled = false; - } - /** JSDoc */ - Logger.prototype.disable = function () { - this._enabled = false; - }; - /** JSDoc */ - Logger.prototype.enable = function () { - this._enabled = true; - }; - /** JSDoc */ - Logger.prototype.log = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - if (!this._enabled) { - return; - } - (0,misc/* consoleSandbox */.Cf)(function () { - global.console.log(PREFIX + "[Log]: " + args.join(' ')); - }); - }; - /** JSDoc */ - Logger.prototype.warn = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - if (!this._enabled) { - return; - } - (0,misc/* consoleSandbox */.Cf)(function () { - global.console.warn(PREFIX + "[Warn]: " + args.join(' ')); - }); - }; - /** JSDoc */ - Logger.prototype.error = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - if (!this._enabled) { - return; - } - (0,misc/* consoleSandbox */.Cf)(function () { - global.console.error(PREFIX + "[Error]: " + args.join(' ')); - }); - }; - return Logger; -}()); -// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used -global.__SENTRY__ = global.__SENTRY__ || {}; -var logger = global.__SENTRY__.logger || (global.__SENTRY__.logger = new Logger()); - - -// EXTERNAL MODULE: ../../node_modules/@sentry/utils/esm/node.js -var node = __webpack_require__(4833); -;// CONCATENATED MODULE: ../../node_modules/@sentry/types/esm/session.js -/** - * Session Status - */ -var SessionStatus; -(function (SessionStatus) { - /** JSDoc */ - SessionStatus["Ok"] = "ok"; - /** JSDoc */ - SessionStatus["Exited"] = "exited"; - /** JSDoc */ - SessionStatus["Crashed"] = "crashed"; - /** JSDoc */ - SessionStatus["Abnormal"] = "abnormal"; -})(SessionStatus || (SessionStatus = {})); - -;// CONCATENATED MODULE: ../../node_modules/@sentry/utils/esm/browser.js - -/** - * Given a child DOM element, returns a query-selector statement describing that - * and its ancestors - * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] - * @returns generated DOM path - */ -function htmlTreeAsString(elem) { - // try/catch both: - // - accessing event.target (see getsentry/raven-js#838, #768) - // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly - // - can throw an exception in some circumstances. - try { - var currentElem = elem; - var MAX_TRAVERSE_HEIGHT = 5; - var MAX_OUTPUT_LEN = 80; - var out = []; - var height = 0; - var len = 0; - var separator = ' > '; - var sepLength = separator.length; - var nextStr = void 0; - // eslint-disable-next-line no-plusplus - while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { - nextStr = _htmlElementAsString(currentElem); - // bail out if - // - nextStr is the 'html' element - // - the length of the string that would be created exceeds MAX_OUTPUT_LEN - // (ignore this limit if we are on the first iteration) - if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) { - break; - } - out.push(nextStr); - len += nextStr.length; - currentElem = currentElem.parentNode; - } - return out.reverse().join(separator); - } - catch (_oO) { - return ''; - } -} -/** - * Returns a simple, query-selector representation of a DOM element - * e.g. [HTMLElement] => input#foo.btn[name=baz] - * @returns generated DOM path - */ -function _htmlElementAsString(el) { - var elem = el; - var out = []; - var className; - var classes; - var key; - var attr; - var i; - if (!elem || !elem.tagName) { - return ''; - } - out.push(elem.tagName.toLowerCase()); - if (elem.id) { - out.push("#" + elem.id); - } - // eslint-disable-next-line prefer-const - className = elem.className; - if (className && isString(className)) { - classes = className.split(/\s+/); - for (i = 0; i < classes.length; i++) { - out.push("." + classes[i]); - } - } - var allowedAttrs = ['type', 'name', 'title', 'alt']; - for (i = 0; i < allowedAttrs.length; i++) { - key = allowedAttrs[i]; - attr = elem.getAttribute(key); - if (attr) { - out.push("[" + key + "=\"" + attr + "\"]"); - } - } - return out.join(''); -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/utils/esm/memo.js -/* eslint-disable @typescript-eslint/no-unsafe-member-access */ -/* eslint-disable @typescript-eslint/no-explicit-any */ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -/** - * Memo class used for decycle json objects. Uses WeakSet if available otherwise array. - */ -var Memo = /** @class */ (function () { - function Memo() { - this._hasWeakSet = typeof WeakSet === 'function'; - this._inner = this._hasWeakSet ? new WeakSet() : []; - } - /** - * Sets obj to remember. - * @param obj Object to remember - */ - Memo.prototype.memoize = function (obj) { - if (this._hasWeakSet) { - if (this._inner.has(obj)) { - return true; - } - this._inner.add(obj); - return false; - } - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (var i = 0; i < this._inner.length; i++) { - var value = this._inner[i]; - if (value === obj) { - return true; - } - } - this._inner.push(obj); - return false; - }; - /** - * Removes object from internal storage. - * @param obj Object to forget - */ - Memo.prototype.unmemoize = function (obj) { - if (this._hasWeakSet) { - this._inner.delete(obj); - } - else { - for (var i = 0; i < this._inner.length; i++) { - if (this._inner[i] === obj) { - this._inner.splice(i, 1); - break; - } - } - } - }; - return Memo; -}()); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/utils/esm/stacktrace.js -var defaultFunctionName = ''; -/** - * Safely extract function name from itself - */ -function getFunctionName(fn) { - try { - if (!fn || typeof fn !== 'function') { - return defaultFunctionName; - } - return fn.name || defaultFunctionName; - } - catch (e) { - // Just accessing custom props in some Selenium environments - // can cause a "Permission denied" exception (see raven-js#495). - return defaultFunctionName; - } -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/utils/esm/string.js - -/** - * Truncates given string to the maximum characters count - * - * @param str An object that contains serializable values - * @param max Maximum number of characters in truncated string - * @returns string Encoded - */ -function truncate(str, max) { - if (max === void 0) { max = 0; } - if (typeof str !== 'string' || max === 0) { - return str; - } - return str.length <= max ? str : str.substr(0, max) + "..."; -} -/** - * This is basically just `trim_line` from - * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67 - * - * @param str An object that contains serializable values - * @param max Maximum number of characters in truncated string - * @returns string Encoded - */ -function snipLine(line, colno) { - var newLine = line; - var ll = newLine.length; - if (ll <= 150) { - return newLine; - } - if (colno > ll) { - // eslint-disable-next-line no-param-reassign - colno = ll; - } - var start = Math.max(colno - 60, 0); - if (start < 5) { - start = 0; - } - var end = Math.min(start + 140, ll); - if (end > ll - 5) { - end = ll; - } - if (end === ll) { - start = Math.max(end - 140, 0); - } - newLine = newLine.slice(start, end); - if (start > 0) { - newLine = "'{snip} " + newLine; - } - if (end < ll) { - newLine += ' {snip}'; - } - return newLine; -} -/** - * Join values in array - * @param input array of values to be joined together - * @param delimiter string to be placed in-between values - * @returns Joined values - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function safeJoin(input, delimiter) { - if (!Array.isArray(input)) { - return ''; - } - var output = []; - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (var i = 0; i < input.length; i++) { - var value = input[i]; - try { - output.push(String(value)); - } - catch (e) { - output.push('[value cannot be serialized]'); - } - } - return output.join(delimiter); -} -/** - * Checks if the value matches a regex or includes the string - * @param value The string value to be checked against - * @param pattern Either a regex or a string that must be contained in value - */ -function isMatchingPattern(value, pattern) { - if (!isString(value)) { - return false; - } - if (isRegExp(pattern)) { - return pattern.test(value); - } - if (typeof pattern === 'string') { - return value.indexOf(pattern) !== -1; - } - return false; -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/utils/esm/object.js - - - - - - -/** - * Wrap a given object method with a higher-order function - * - * @param source An object that contains a method to be wrapped. - * @param name A name of method to be wrapped. - * @param replacement A function that should be used to wrap a given method. - * @returns void - */ -function fill(source, name, replacement) { - if (!(name in source)) { - return; - } - var original = source[name]; - var wrapped = replacement(original); - // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work - // otherwise it'll throw "TypeError: Object.defineProperties called on non-object" - if (typeof wrapped === 'function') { - try { - wrapped.prototype = wrapped.prototype || {}; - Object.defineProperties(wrapped, { - __sentry_original__: { - enumerable: false, - value: original, - }, - }); - } - catch (_Oo) { - // This can throw if multiple fill happens on a global object like XMLHttpRequest - // Fixes https://github.com/getsentry/sentry-javascript/issues/2043 - } - } - source[name] = wrapped; -} -/** - * Encodes given object into url-friendly format - * - * @param object An object that contains serializable values - * @returns string Encoded - */ -function urlEncode(object) { - return Object.keys(object) - .map(function (key) { return encodeURIComponent(key) + "=" + encodeURIComponent(object[key]); }) - .join('&'); -} -/** - * Transforms any object into an object literal with all it's attributes - * attached to it. - * - * @param value Initial source that we have to transform in order to be usable by the serializer - */ -function getWalkSource(value) { - if (isError(value)) { - var error = value; - var err = { - message: error.message, - name: error.name, - stack: error.stack, - }; - for (var i in error) { - if (Object.prototype.hasOwnProperty.call(error, i)) { - err[i] = error[i]; - } - } - return err; - } - if (isEvent(value)) { - var event_1 = value; - var source = {}; - source.type = event_1.type; - // Accessing event.target can throw (see getsentry/raven-js#838, #768) - try { - source.target = isElement(event_1.target) - ? htmlTreeAsString(event_1.target) - : Object.prototype.toString.call(event_1.target); - } - catch (_oO) { - source.target = ''; - } - try { - source.currentTarget = isElement(event_1.currentTarget) - ? htmlTreeAsString(event_1.currentTarget) - : Object.prototype.toString.call(event_1.currentTarget); - } - catch (_oO) { - source.currentTarget = ''; - } - if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) { - source.detail = event_1.detail; - } - for (var i in event_1) { - if (Object.prototype.hasOwnProperty.call(event_1, i)) { - source[i] = event_1; - } - } - return source; - } - return value; -} -/** Calculates bytes size of input string */ -function utf8Length(value) { - // eslint-disable-next-line no-bitwise - return ~-encodeURI(value).split(/%..|./).length; -} -/** Calculates bytes size of input object */ -function jsonSize(value) { - return utf8Length(JSON.stringify(value)); -} -/** JSDoc */ -function normalizeToSize(object, -// Default Node.js REPL depth -depth, -// 100kB, as 200kB is max payload size, so half sounds reasonable -maxSize) { - if (depth === void 0) { depth = 3; } - if (maxSize === void 0) { maxSize = 100 * 1024; } - var serialized = normalize(object, depth); - if (jsonSize(serialized) > maxSize) { - return normalizeToSize(object, depth - 1, maxSize); - } - return serialized; -} -/** Transforms any input value into a string form, either primitive value or a type of the input */ -function serializeValue(value) { - var type = Object.prototype.toString.call(value); - // Node.js REPL notation - if (typeof value === 'string') { - return value; - } - if (type === '[object Object]') { - return '[Object]'; - } - if (type === '[object Array]') { - return '[Array]'; - } - var normalized = normalizeValue(value); - return isPrimitive(normalized) ? normalized : type; -} -/** - * normalizeValue() - * - * Takes unserializable input and make it serializable friendly - * - * - translates undefined/NaN values to "[undefined]"/"[NaN]" respectively, - * - serializes Error objects - * - filter global objects - */ -function normalizeValue(value, key) { - if (key === 'domain' && value && typeof value === 'object' && value._events) { - return '[Domain]'; - } - if (key === 'domainEmitter') { - return '[DomainEmitter]'; - } - if (typeof __webpack_require__.g !== 'undefined' && value === __webpack_require__.g) { - return '[Global]'; - } - if (typeof window !== 'undefined' && value === window) { - return '[Window]'; - } - if (typeof document !== 'undefined' && value === document) { - return '[Document]'; - } - // React's SyntheticEvent thingy - if (isSyntheticEvent(value)) { - return '[SyntheticEvent]'; - } - if (typeof value === 'number' && value !== value) { - return '[NaN]'; - } - if (value === void 0) { - return '[undefined]'; - } - if (typeof value === 'function') { - return "[Function: " + getFunctionName(value) + "]"; - } - return value; -} -/** - * Walks an object to perform a normalization on it - * - * @param key of object that's walked in current iteration - * @param value object to be walked - * @param depth Optional number indicating how deep should walking be performed - * @param memo Optional Memo class handling decycling - */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -function walk(key, value, depth, memo) { - if (depth === void 0) { depth = +Infinity; } - if (memo === void 0) { memo = new Memo(); } - // If we reach the maximum depth, serialize whatever has left - if (depth === 0) { - return serializeValue(value); - } - /* eslint-disable @typescript-eslint/no-unsafe-member-access */ - // If value implements `toJSON` method, call it and return early - if (value !== null && value !== undefined && typeof value.toJSON === 'function') { - return value.toJSON(); - } - /* eslint-enable @typescript-eslint/no-unsafe-member-access */ - // If normalized value is a primitive, there are no branches left to walk, so we can just bail out, as theres no point in going down that branch any further - var normalized = normalizeValue(value, key); - if (isPrimitive(normalized)) { - return normalized; - } - // Create source that we will use for next itterations, either objectified error object (Error type with extracted keys:value pairs) or the input itself - var source = getWalkSource(value); - // Create an accumulator that will act as a parent for all future itterations of that branch - var acc = Array.isArray(value) ? [] : {}; - // If we already walked that branch, bail out, as it's circular reference - if (memo.memoize(value)) { - return '[Circular ~]'; - } - // Walk all keys of the source - for (var innerKey in source) { - // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration. - if (!Object.prototype.hasOwnProperty.call(source, innerKey)) { - continue; - } - // Recursively walk through all the child nodes - acc[innerKey] = walk(innerKey, source[innerKey], depth - 1, memo); - } - // Once walked through all the branches, remove the parent from memo storage - memo.unmemoize(value); - // Return accumulated values - return acc; -} -/** - * normalize() - * - * - Creates a copy to prevent original input mutation - * - Skip non-enumerablers - * - Calls `toJSON` if implemented - * - Removes circular references - * - Translates non-serializeable values (undefined/NaN/Functions) to serializable format - * - Translates known global objects/Classes to a string representations - * - Takes care of Error objects serialization - * - Optionally limit depth of final output - */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -function normalize(input, depth) { - try { - return JSON.parse(JSON.stringify(input, function (key, value) { return walk(key, value, depth); })); - } - catch (_oO) { - return '**non-serializable**'; - } -} -/** - * Given any captured exception, extract its keys and create a sorted - * and truncated list that will be used inside the event message. - * eg. `Non-error exception captured with keys: foo, bar, baz` - */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -function extractExceptionKeysForMessage(exception, maxLength) { - if (maxLength === void 0) { maxLength = 40; } - var keys = Object.keys(getWalkSource(exception)); - keys.sort(); - if (!keys.length) { - return '[object has no keys]'; - } - if (keys[0].length >= maxLength) { - return truncate(keys[0], maxLength); - } - for (var includedKeys = keys.length; includedKeys > 0; includedKeys--) { - var serialized = keys.slice(0, includedKeys).join(', '); - if (serialized.length > maxLength) { - continue; - } - if (includedKeys === keys.length) { - return serialized; - } - return truncate(serialized, maxLength); - } - return ''; -} -/** - * Given any object, return the new object with removed keys that value was `undefined`. - * Works recursively on objects and arrays. - */ -function dropUndefinedKeys(val) { - var e_1, _a; - if (isPlainObject(val)) { - var obj = val; - var rv = {}; - try { - for (var _b = __values(Object.keys(obj)), _c = _b.next(); !_c.done; _c = _b.next()) { - var key = _c.value; - if (typeof obj[key] !== 'undefined') { - rv[key] = dropUndefinedKeys(obj[key]); - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } - finally { if (e_1) throw e_1.error; } - } - return rv; - } - if (Array.isArray(val)) { - return val.map(dropUndefinedKeys); - } - return val; -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/hub/esm/session.js - - -/** - * @inheritdoc - */ -var Session = /** @class */ (function () { - function Session(context) { - this.errors = 0; - this.sid = (0,misc/* uuid4 */.DM)(); - this.timestamp = Date.now(); - this.started = Date.now(); - this.duration = 0; - this.status = SessionStatus.Ok; - if (context) { - this.update(context); - } - } - /** JSDoc */ - // eslint-disable-next-line complexity - Session.prototype.update = function (context) { - if (context === void 0) { context = {}; } - if (context.user) { - if (context.user.ip_address) { - this.ipAddress = context.user.ip_address; - } - if (!context.did) { - this.did = context.user.id || context.user.email || context.user.username; - } - } - this.timestamp = context.timestamp || Date.now(); - if (context.sid) { - // Good enough uuid validation. — Kamil - this.sid = context.sid.length === 32 ? context.sid : (0,misc/* uuid4 */.DM)(); - } - if (context.did) { - this.did = "" + context.did; - } - if (typeof context.started === 'number') { - this.started = context.started; - } - if (typeof context.duration === 'number') { - this.duration = context.duration; - } - else { - this.duration = this.timestamp - this.started; - } - if (context.release) { - this.release = context.release; - } - if (context.environment) { - this.environment = context.environment; - } - if (context.ipAddress) { - this.ipAddress = context.ipAddress; - } - if (context.userAgent) { - this.userAgent = context.userAgent; - } - if (typeof context.errors === 'number') { - this.errors = context.errors; - } - if (context.status) { - this.status = context.status; - } - }; - /** JSDoc */ - Session.prototype.close = function (status) { - if (status) { - this.update({ status: status }); - } - else if (this.status === SessionStatus.Ok) { - this.update({ status: SessionStatus.Exited }); - } - else { - this.update(); - } - }; - /** JSDoc */ - Session.prototype.toJSON = function () { - return dropUndefinedKeys({ - sid: "" + this.sid, - init: true, - started: new Date(this.started).toISOString(), - timestamp: new Date(this.timestamp).toISOString(), - status: this.status, - errors: this.errors, - did: typeof this.did === 'number' || typeof this.did === 'string' ? "" + this.did : undefined, - duration: this.duration, - attrs: dropUndefinedKeys({ - release: this.release, - environment: this.environment, - ip_address: this.ipAddress, - user_agent: this.userAgent, - }), - }); - }; - return Session; -}()); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/hub/esm/hub.js - - - - -/** - * API compatibility version of this hub. - * - * WARNING: This number should only be increased when the global interface - * changes and new methods are introduced. - * - * @hidden - */ -var API_VERSION = 3; -/** - * Default maximum number of breadcrumbs added to an event. Can be overwritten - * with {@link Options.maxBreadcrumbs}. - */ -var DEFAULT_BREADCRUMBS = 100; -/** - * Absolute maximum number of breadcrumbs added to an event. The - * `maxBreadcrumbs` option cannot be higher than this value. - */ -var MAX_BREADCRUMBS = 100; -/** - * @inheritDoc - */ -var Hub = /** @class */ (function () { - /** - * Creates a new instance of the hub, will push one {@link Layer} into the - * internal stack on creation. - * - * @param client bound to the hub. - * @param scope bound to the hub. - * @param version number, higher number means higher priority. - */ - function Hub(client, scope, _version) { - if (scope === void 0) { scope = new Scope(); } - if (_version === void 0) { _version = API_VERSION; } - this._version = _version; - /** Is a {@link Layer}[] containing the client and scope */ - this._stack = [{}]; - this.getStackTop().scope = scope; - this.bindClient(client); - } - /** - * @inheritDoc - */ - Hub.prototype.isOlderThan = function (version) { - return this._version < version; - }; - /** - * @inheritDoc - */ - Hub.prototype.bindClient = function (client) { - var top = this.getStackTop(); - top.client = client; - if (client && client.setupIntegrations) { - client.setupIntegrations(); - } - }; - /** - * @inheritDoc - */ - Hub.prototype.pushScope = function () { - // We want to clone the content of prev scope - var scope = Scope.clone(this.getScope()); - this.getStack().push({ - client: this.getClient(), - scope: scope, - }); - return scope; - }; - /** - * @inheritDoc - */ - Hub.prototype.popScope = function () { - if (this.getStack().length <= 1) - return false; - return !!this.getStack().pop(); - }; - /** - * @inheritDoc - */ - Hub.prototype.withScope = function (callback) { - var scope = this.pushScope(); - try { - callback(scope); - } - finally { - this.popScope(); - } - }; - /** - * @inheritDoc - */ - Hub.prototype.getClient = function () { - return this.getStackTop().client; - }; - /** Returns the scope of the top stack. */ - Hub.prototype.getScope = function () { - return this.getStackTop().scope; - }; - /** Returns the scope stack for domains or the process. */ - Hub.prototype.getStack = function () { - return this._stack; - }; - /** Returns the topmost scope layer in the order domain > local > process. */ - Hub.prototype.getStackTop = function () { - return this._stack[this._stack.length - 1]; - }; - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - Hub.prototype.captureException = function (exception, hint) { - var eventId = (this._lastEventId = (0,misc/* uuid4 */.DM)()); - var finalHint = hint; - // If there's no explicit hint provided, mimick the same thing that would happen - // in the minimal itself to create a consistent behavior. - // We don't do this in the client, as it's the lowest level API, and doing this, - // would prevent user from having full control over direct calls. - if (!hint) { - var syntheticException = void 0; - try { - throw new Error('Sentry syntheticException'); - } - catch (exception) { - syntheticException = exception; - } - finalHint = { - originalException: exception, - syntheticException: syntheticException, - }; - } - this._invokeClient('captureException', exception, __assign(__assign({}, finalHint), { event_id: eventId })); - return eventId; - }; - /** - * @inheritDoc - */ - Hub.prototype.captureMessage = function (message, level, hint) { - var eventId = (this._lastEventId = (0,misc/* uuid4 */.DM)()); - var finalHint = hint; - // If there's no explicit hint provided, mimick the same thing that would happen - // in the minimal itself to create a consistent behavior. - // We don't do this in the client, as it's the lowest level API, and doing this, - // would prevent user from having full control over direct calls. - if (!hint) { - var syntheticException = void 0; - try { - throw new Error(message); - } - catch (exception) { - syntheticException = exception; - } - finalHint = { - originalException: message, - syntheticException: syntheticException, - }; - } - this._invokeClient('captureMessage', message, level, __assign(__assign({}, finalHint), { event_id: eventId })); - return eventId; - }; - /** - * @inheritDoc - */ - Hub.prototype.captureEvent = function (event, hint) { - var eventId = (this._lastEventId = (0,misc/* uuid4 */.DM)()); - this._invokeClient('captureEvent', event, __assign(__assign({}, hint), { event_id: eventId })); - return eventId; - }; - /** - * @inheritDoc - */ - Hub.prototype.lastEventId = function () { - return this._lastEventId; - }; - /** - * @inheritDoc - */ - Hub.prototype.addBreadcrumb = function (breadcrumb, hint) { - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - if (!scope || !client) - return; - // eslint-disable-next-line @typescript-eslint/unbound-method - var _b = (client.getOptions && client.getOptions()) || {}, _c = _b.beforeBreadcrumb, beforeBreadcrumb = _c === void 0 ? null : _c, _d = _b.maxBreadcrumbs, maxBreadcrumbs = _d === void 0 ? DEFAULT_BREADCRUMBS : _d; - if (maxBreadcrumbs <= 0) - return; - var timestamp = (0,time/* dateTimestampInSeconds */.yW)(); - var mergedBreadcrumb = __assign({ timestamp: timestamp }, breadcrumb); - var finalBreadcrumb = beforeBreadcrumb - ? (0,misc/* consoleSandbox */.Cf)(function () { return beforeBreadcrumb(mergedBreadcrumb, hint); }) - : mergedBreadcrumb; - if (finalBreadcrumb === null) - return; - scope.addBreadcrumb(finalBreadcrumb, Math.min(maxBreadcrumbs, MAX_BREADCRUMBS)); - }; - /** - * @inheritDoc - */ - Hub.prototype.setUser = function (user) { - var scope = this.getScope(); - if (scope) - scope.setUser(user); - }; - /** - * @inheritDoc - */ - Hub.prototype.setTags = function (tags) { - var scope = this.getScope(); - if (scope) - scope.setTags(tags); - }; - /** - * @inheritDoc - */ - Hub.prototype.setExtras = function (extras) { - var scope = this.getScope(); - if (scope) - scope.setExtras(extras); - }; - /** - * @inheritDoc - */ - Hub.prototype.setTag = function (key, value) { - var scope = this.getScope(); - if (scope) - scope.setTag(key, value); - }; - /** - * @inheritDoc - */ - Hub.prototype.setExtra = function (key, extra) { - var scope = this.getScope(); - if (scope) - scope.setExtra(key, extra); - }; - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Hub.prototype.setContext = function (name, context) { - var scope = this.getScope(); - if (scope) - scope.setContext(name, context); - }; - /** - * @inheritDoc - */ - Hub.prototype.configureScope = function (callback) { - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - if (scope && client) { - callback(scope); - } - }; - /** - * @inheritDoc - */ - Hub.prototype.run = function (callback) { - var oldHub = makeMain(this); - try { - callback(this); - } - finally { - makeMain(oldHub); - } - }; - /** - * @inheritDoc - */ - Hub.prototype.getIntegration = function (integration) { - var client = this.getClient(); - if (!client) - return null; - try { - return client.getIntegration(integration); - } - catch (_oO) { - logger.warn("Cannot retrieve integration " + integration.id + " from the current Hub"); - return null; - } - }; - /** - * @inheritDoc - */ - Hub.prototype.startSpan = function (context) { - return this._callExtensionMethod('startSpan', context); - }; - /** - * @inheritDoc - */ - Hub.prototype.startTransaction = function (context, customSamplingContext) { - return this._callExtensionMethod('startTransaction', context, customSamplingContext); - }; - /** - * @inheritDoc - */ - Hub.prototype.traceHeaders = function () { - return this._callExtensionMethod('traceHeaders'); - }; - /** - * @inheritDoc - */ - Hub.prototype.startSession = function (context) { - // End existing session if there's one - this.endSession(); - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - var _b = (client && client.getOptions()) || {}, release = _b.release, environment = _b.environment; - var session = new Session(__assign(__assign({ release: release, - environment: environment }, (scope && { user: scope.getUser() })), context)); - if (scope) { - scope.setSession(session); - } - return session; - }; - /** - * @inheritDoc - */ - Hub.prototype.endSession = function () { - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - if (!scope) - return; - var session = scope.getSession(); - if (session) { - session.close(); - if (client && client.captureSession) { - client.captureSession(session); - } - scope.setSession(); - } - }; - /** - * Internal helper function to call a method on the top client if it exists. - * - * @param method The method to call on the client. - * @param args Arguments to pass to the client function. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Hub.prototype._invokeClient = function (method) { - var _a; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var _b = this.getStackTop(), scope = _b.scope, client = _b.client; - if (client && client[method]) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - (_a = client)[method].apply(_a, tslib_es6_spread(args, [scope])); - } - }; - /** - * Calls global extension method and binding current instance to the function call - */ - // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366) - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Hub.prototype._callExtensionMethod = function (method) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var carrier = getMainCarrier(); - var sentry = carrier.__SENTRY__; - if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') { - return sentry.extensions[method].apply(this, args); - } - logger.warn("Extension method " + method + " couldn't be found, doing nothing."); - }; - return Hub; -}()); - -/** Returns the global shim registry. */ -function getMainCarrier() { - var carrier = (0,misc/* getGlobalObject */.Rf)(); - carrier.__SENTRY__ = carrier.__SENTRY__ || { - extensions: {}, - hub: undefined, - }; - return carrier; -} -/** - * Replaces the current main hub with the passed one on the global object - * - * @returns The old replaced hub - */ -function makeMain(hub) { - var registry = getMainCarrier(); - var oldHub = getHubFromCarrier(registry); - setHubOnCarrier(registry, hub); - return oldHub; -} -/** - * Returns the default hub instance. - * - * If a hub is already registered in the global carrier but this module - * contains a more recent version, it replaces the registered version. - * Otherwise, the currently registered hub will be returned. - */ -function getCurrentHub() { - // Get main carrier (global for every environment) - var registry = getMainCarrier(); - // If there's no hub, or its an old API, assign a new one - if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) { - setHubOnCarrier(registry, new Hub()); - } - // Prefer domains over global if they are there (applicable only to Node environment) - if ((0,node/* isNodeEnv */.KV)()) { - return getHubFromActiveDomain(registry); - } - // Return hub that lives on a global object - return getHubFromCarrier(registry); -} -/** - * Returns the active domain, if one exists - * - * @returns The domain, or undefined if there is no active domain - */ -function getActiveDomain() { - var sentry = getMainCarrier().__SENTRY__; - return sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active; -} -/** - * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist - * @returns discovered hub - */ -function getHubFromActiveDomain(registry) { - try { - var activeDomain = getActiveDomain(); - // If there's no active domain, just return global hub - if (!activeDomain) { - return getHubFromCarrier(registry); - } - // If there's no hub on current domain, or it's an old API, assign a new one - if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(API_VERSION)) { - var registryHubTopStack = getHubFromCarrier(registry).getStackTop(); - setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, Scope.clone(registryHubTopStack.scope))); - } - // Return hub that lives on a domain - return getHubFromCarrier(activeDomain); - } - catch (_Oo) { - // Return hub that lives on a global object - return getHubFromCarrier(registry); - } -} -/** - * This will tell whether a carrier has a hub on it or not - * @param carrier object - */ -function hasHubOnCarrier(carrier) { - return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub); -} -/** - * This will create a new {@link Hub} and add to the passed object on - * __SENTRY__.hub. - * @param carrier object - * @hidden - */ -function getHubFromCarrier(carrier) { - if (carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub) - return carrier.__SENTRY__.hub; - carrier.__SENTRY__ = carrier.__SENTRY__ || {}; - carrier.__SENTRY__.hub = new Hub(); - return carrier.__SENTRY__.hub; -} -/** - * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute - * @param carrier object - * @param hub Hub - */ -function setHubOnCarrier(carrier, hub) { - if (!carrier) - return false; - carrier.__SENTRY__ = carrier.__SENTRY__ || {}; - carrier.__SENTRY__.hub = hub; - return true; -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/minimal/esm/index.js - - -/** - * This calls a function on the current hub. - * @param method function to call on hub. - * @param args to pass to function. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function callOnHub(method) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var hub = getCurrentHub(); - if (hub && hub[method]) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return hub[method].apply(hub, tslib_es6_spread(args)); - } - throw new Error("No hub defined or " + method + " was not found on the hub, please open a bug report."); -} -/** - * Captures an exception event and sends it to Sentry. - * - * @param exception An exception-like object. - * @returns The generated eventId. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types -function captureException(exception, captureContext) { - var syntheticException; - try { - throw new Error('Sentry syntheticException'); - } - catch (exception) { - syntheticException = exception; - } - return callOnHub('captureException', exception, { - captureContext: captureContext, - originalException: exception, - syntheticException: syntheticException, - }); -} -/** - * Captures a message event and sends it to Sentry. - * - * @param message The message to send to Sentry. - * @param level Define the level of the message. - * @returns The generated eventId. - */ -function captureMessage(message, captureContext) { - var syntheticException; - try { - throw new Error(message); - } - catch (exception) { - syntheticException = exception; - } - // This is necessary to provide explicit scopes upgrade, without changing the original - // arity of the `captureMessage(message, level)` method. - var level = typeof captureContext === 'string' ? captureContext : undefined; - var context = typeof captureContext !== 'string' ? { captureContext: captureContext } : undefined; - return callOnHub('captureMessage', message, level, __assign({ originalException: message, syntheticException: syntheticException }, context)); -} -/** - * Captures a manually created event and sends it to Sentry. - * - * @param event The event to send to Sentry. - * @returns The generated eventId. - */ -function captureEvent(event) { - return callOnHub('captureEvent', event); -} -/** - * Callback to set context information onto the scope. - * @param callback Callback function that receives Scope. - */ -function configureScope(callback) { - callOnHub('configureScope', callback); -} -/** - * Records a new breadcrumb which will be attached to future events. - * - * Breadcrumbs will be added to subsequent events to provide more context on - * user's actions prior to an error or crash. - * - * @param breadcrumb The breadcrumb to record. - */ -function addBreadcrumb(breadcrumb) { - callOnHub('addBreadcrumb', breadcrumb); -} -/** - * Sets context data with the given name. - * @param name of the context - * @param context Any kind of data. This data will be normalized. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setContext(name, context) { - callOnHub('setContext', name, context); -} -/** - * Set an object that will be merged sent as extra data with the event. - * @param extras Extras object to merge into current context. - */ -function setExtras(extras) { - callOnHub('setExtras', extras); -} -/** - * Set an object that will be merged sent as tags data with the event. - * @param tags Tags context object to merge into current context. - */ -function setTags(tags) { - callOnHub('setTags', tags); -} -/** - * Set key:value that will be sent as extra data with the event. - * @param key String of extra - * @param extra Any kind of data. This data will be normalized. - */ -function setExtra(key, extra) { - callOnHub('setExtra', key, extra); -} -/** - * Set key:value that will be sent as tags data with the event. - * @param key String key of tag - * @param value String value of tag - */ -function setTag(key, value) { - callOnHub('setTag', key, value); -} -/** - * Updates user context information for future events. - * - * @param user User context object to be set in the current context. Pass `null` to unset the user. - */ -function setUser(user) { - callOnHub('setUser', user); -} -/** - * Creates a new scope with and executes the given operation within. - * The scope is automatically removed once the operation - * finishes or throws. - * - * This is essentially a convenience function for: - * - * pushScope(); - * callback(); - * popScope(); - * - * @param callback that will be enclosed into push/popScope. - */ -function withScope(callback) { - callOnHub('withScope', callback); -} -/** - * Calls a function on the latest client. Use this with caution, it's meant as - * in "internal" helper so we don't need to expose every possible function in - * the shim. It is not guaranteed that the client actually implements the - * function. - * - * @param method The method to call on the client/client. - * @param args Arguments to pass to the client/fontend. - * @hidden - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function _callOnClient(method) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - callOnHub.apply(void 0, __spread(['_invokeClient', method], args)); -} -/** - * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation. - * - * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a - * new child span within the transaction or any span, call the respective `.startChild()` method. - * - * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded. - * - * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its - * finished child spans will be sent to Sentry. - * - * @param context Properties of the new `Transaction`. - * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent - * default values). See {@link Options.tracesSampler}. - * - * @returns The transaction which was just started - */ -function startTransaction(context, customSamplingContext) { - return callOnHub('startTransaction', __assign({}, context), customSamplingContext); -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/utils/esm/polyfill.js -var setPrototypeOf = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties); -/** - * setPrototypeOf polyfill using __proto__ - */ -// eslint-disable-next-line @typescript-eslint/ban-types -function setProtoOf(obj, proto) { - // @ts-ignore __proto__ does not exist on obj - obj.__proto__ = proto; - return obj; -} -/** - * setPrototypeOf polyfill using mixin - */ -// eslint-disable-next-line @typescript-eslint/ban-types -function mixinProperties(obj, proto) { - for (var prop in proto) { - // eslint-disable-next-line no-prototype-builtins - if (!obj.hasOwnProperty(prop)) { - // @ts-ignore typescript complains about indexing so we remove - obj[prop] = proto[prop]; - } - } - return obj; -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/utils/esm/error.js - - -/** An error emitted by Sentry SDKs and related utilities. */ -var SentryError = /** @class */ (function (_super) { - __extends(SentryError, _super); - function SentryError(message) { - var _newTarget = this.constructor; - var _this = _super.call(this, message) || this; - _this.message = message; - _this.name = _newTarget.prototype.constructor.name; - setPrototypeOf(_this, _newTarget.prototype); - return _this; - } - return SentryError; -}(Error)); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/utils/esm/dsn.js - - -/** Regular expression used to parse a Dsn. */ -var DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+))?@)([\w.-]+)(?::(\d+))?\/(.+)/; -/** Error message */ -var ERROR_MESSAGE = 'Invalid Dsn'; -/** The Sentry Dsn, identifying a Sentry instance and project. */ -var Dsn = /** @class */ (function () { - /** Creates a new Dsn component */ - function Dsn(from) { - if (typeof from === 'string') { - this._fromString(from); - } - else { - this._fromComponents(from); - } - this._validate(); - } - /** - * Renders the string representation of this Dsn. - * - * By default, this will render the public representation without the password - * component. To get the deprecated private representation, set `withPassword` - * to true. - * - * @param withPassword When set to true, the password will be included. - */ - Dsn.prototype.toString = function (withPassword) { - if (withPassword === void 0) { withPassword = false; } - var _a = this, host = _a.host, path = _a.path, pass = _a.pass, port = _a.port, projectId = _a.projectId, protocol = _a.protocol, user = _a.user; - return (protocol + "://" + user + (withPassword && pass ? ":" + pass : '') + - ("@" + host + (port ? ":" + port : '') + "/" + (path ? path + "/" : path) + projectId)); - }; - /** Parses a string into this Dsn. */ - Dsn.prototype._fromString = function (str) { - var match = DSN_REGEX.exec(str); - if (!match) { - throw new SentryError(ERROR_MESSAGE); - } - var _a = __read(match.slice(1), 6), protocol = _a[0], user = _a[1], _b = _a[2], pass = _b === void 0 ? '' : _b, host = _a[3], _c = _a[4], port = _c === void 0 ? '' : _c, lastPath = _a[5]; - var path = ''; - var projectId = lastPath; - var split = projectId.split('/'); - if (split.length > 1) { - path = split.slice(0, -1).join('/'); - projectId = split.pop(); - } - if (projectId) { - var projectMatch = projectId.match(/^\d+/); - if (projectMatch) { - projectId = projectMatch[0]; - } - } - this._fromComponents({ host: host, pass: pass, path: path, projectId: projectId, port: port, protocol: protocol, user: user }); - }; - /** Maps Dsn components into this instance. */ - Dsn.prototype._fromComponents = function (components) { - this.protocol = components.protocol; - this.user = components.user; - this.pass = components.pass || ''; - this.host = components.host; - this.port = components.port || ''; - this.path = components.path || ''; - this.projectId = components.projectId; - }; - /** Validates this Dsn and throws on error. */ - Dsn.prototype._validate = function () { - var _this = this; - ['protocol', 'user', 'host', 'projectId'].forEach(function (component) { - if (!_this[component]) { - throw new SentryError(ERROR_MESSAGE + ": " + component + " missing"); - } - }); - if (!this.projectId.match(/^\d+$/)) { - throw new SentryError(ERROR_MESSAGE + ": Invalid projectId " + this.projectId); - } - if (this.protocol !== 'http' && this.protocol !== 'https') { - throw new SentryError(ERROR_MESSAGE + ": Invalid protocol " + this.protocol); - } - if (this.port && isNaN(parseInt(this.port, 10))) { - throw new SentryError(ERROR_MESSAGE + ": Invalid port " + this.port); - } - }; - return Dsn; -}()); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/core/esm/integration.js - - - -var installedIntegrations = []; -/** Gets integration to install */ -function getIntegrationsToSetup(options) { - var defaultIntegrations = (options.defaultIntegrations && tslib_es6_spread(options.defaultIntegrations)) || []; - var userIntegrations = options.integrations; - var integrations = []; - if (Array.isArray(userIntegrations)) { - var userIntegrationsNames_1 = userIntegrations.map(function (i) { return i.name; }); - var pickedIntegrationsNames_1 = []; - // Leave only unique default integrations, that were not overridden with provided user integrations - defaultIntegrations.forEach(function (defaultIntegration) { - if (userIntegrationsNames_1.indexOf(defaultIntegration.name) === -1 && - pickedIntegrationsNames_1.indexOf(defaultIntegration.name) === -1) { - integrations.push(defaultIntegration); - pickedIntegrationsNames_1.push(defaultIntegration.name); - } - }); - // Don't add same user integration twice - userIntegrations.forEach(function (userIntegration) { - if (pickedIntegrationsNames_1.indexOf(userIntegration.name) === -1) { - integrations.push(userIntegration); - pickedIntegrationsNames_1.push(userIntegration.name); - } - }); - } - else if (typeof userIntegrations === 'function') { - integrations = userIntegrations(defaultIntegrations); - integrations = Array.isArray(integrations) ? integrations : [integrations]; - } - else { - integrations = tslib_es6_spread(defaultIntegrations); - } - // Make sure that if present, `Debug` integration will always run last - var integrationsNames = integrations.map(function (i) { return i.name; }); - var alwaysLastToRun = 'Debug'; - if (integrationsNames.indexOf(alwaysLastToRun) !== -1) { - integrations.push.apply(integrations, tslib_es6_spread(integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1))); - } - return integrations; -} -/** Setup given integration */ -function setupIntegration(integration) { - if (installedIntegrations.indexOf(integration.name) !== -1) { - return; - } - integration.setupOnce(addGlobalEventProcessor, getCurrentHub); - installedIntegrations.push(integration.name); - logger.log("Integration installed: " + integration.name); -} -/** - * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default - * integrations are added unless they were already provided before. - * @param integrations array of integration instances - * @param withDefault should enable default integrations - */ -function setupIntegrations(options) { - var integrations = {}; - getIntegrationsToSetup(options).forEach(function (integration) { - integrations[integration.name] = integration; - setupIntegration(integration); - }); - return integrations; -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/core/esm/baseclient.js - -/* eslint-disable max-lines */ - - - - -/** - * Base implementation for all JavaScript SDK clients. - * - * Call the constructor with the corresponding backend constructor and options - * specific to the client subclass. To access these options later, use - * {@link Client.getOptions}. Also, the Backend instance is available via - * {@link Client.getBackend}. - * - * If a Dsn is specified in the options, it will be parsed and stored. Use - * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is - * invalid, the constructor will throw a {@link SentryException}. Note that - * without a valid Dsn, the SDK will not send any events to Sentry. - * - * Before sending an event via the backend, it is passed through - * {@link BaseClient.prepareEvent} to add SDK information and scope data - * (breadcrumbs and context). To add more custom information, override this - * method and extend the resulting prepared event. - * - * To issue automatically created events (e.g. via instrumentation), use - * {@link Client.captureEvent}. It will prepare the event and pass it through - * the callback lifecycle. To issue auto-breadcrumbs, use - * {@link Client.addBreadcrumb}. - * - * @example - * class NodeClient extends BaseClient { - * public constructor(options: NodeOptions) { - * super(NodeBackend, options); - * } - * - * // ... - * } - */ -var BaseClient = /** @class */ (function () { - /** - * Initializes this client instance. - * - * @param backendClass A constructor function to create the backend. - * @param options Options for the client. - */ - function BaseClient(backendClass, options) { - /** Array of used integrations. */ - this._integrations = {}; - /** Number of call being processed */ - this._processing = 0; - this._backend = new backendClass(options); - this._options = options; - if (options.dsn) { - this._dsn = new Dsn(options.dsn); - } - } - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - BaseClient.prototype.captureException = function (exception, hint, scope) { - var _this = this; - var eventId = hint && hint.event_id; - this._process(this._getBackend() - .eventFromException(exception, hint) - .then(function (event) { return _this._captureEvent(event, hint, scope); }) - .then(function (result) { - eventId = result; - })); - return eventId; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.captureMessage = function (message, level, hint, scope) { - var _this = this; - var eventId = hint && hint.event_id; - var promisedEvent = isPrimitive(message) - ? this._getBackend().eventFromMessage("" + message, level, hint) - : this._getBackend().eventFromException(message, hint); - this._process(promisedEvent - .then(function (event) { return _this._captureEvent(event, hint, scope); }) - .then(function (result) { - eventId = result; - })); - return eventId; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.captureEvent = function (event, hint, scope) { - var eventId = hint && hint.event_id; - this._process(this._captureEvent(event, hint, scope).then(function (result) { - eventId = result; - })); - return eventId; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.captureSession = function (session) { - if (!session.release) { - logger.warn('Discarded session because of missing release'); - } - else { - this._sendSession(session); - } - }; - /** - * @inheritDoc - */ - BaseClient.prototype.getDsn = function () { - return this._dsn; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.getOptions = function () { - return this._options; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.flush = function (timeout) { - var _this = this; - return this._isClientProcessing(timeout).then(function (ready) { - return _this._getBackend() - .getTransport() - .close(timeout) - .then(function (transportFlushed) { return ready && transportFlushed; }); - }); - }; - /** - * @inheritDoc - */ - BaseClient.prototype.close = function (timeout) { - var _this = this; - return this.flush(timeout).then(function (result) { - _this.getOptions().enabled = false; - return result; - }); - }; - /** - * Sets up the integrations - */ - BaseClient.prototype.setupIntegrations = function () { - if (this._isEnabled()) { - this._integrations = setupIntegrations(this._options); - } - }; - /** - * @inheritDoc - */ - BaseClient.prototype.getIntegration = function (integration) { - try { - return this._integrations[integration.id] || null; - } - catch (_oO) { - logger.warn("Cannot retrieve integration " + integration.id + " from the current Client"); - return null; - } - }; - /** Updates existing session based on the provided event */ - BaseClient.prototype._updateSessionFromEvent = function (session, event) { - var e_1, _a; - var crashed = false; - var errored = false; - var userAgent; - var exceptions = event.exception && event.exception.values; - if (exceptions) { - errored = true; - try { - for (var exceptions_1 = __values(exceptions), exceptions_1_1 = exceptions_1.next(); !exceptions_1_1.done; exceptions_1_1 = exceptions_1.next()) { - var ex = exceptions_1_1.value; - var mechanism = ex.mechanism; - if (mechanism && mechanism.handled === false) { - crashed = true; - break; - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (exceptions_1_1 && !exceptions_1_1.done && (_a = exceptions_1.return)) _a.call(exceptions_1); - } - finally { if (e_1) throw e_1.error; } - } - } - var user = event.user; - if (!session.userAgent) { - var headers = event.request ? event.request.headers : {}; - for (var key in headers) { - if (key.toLowerCase() === 'user-agent') { - userAgent = headers[key]; - break; - } - } - } - session.update(__assign(__assign({}, (crashed && { status: SessionStatus.Crashed })), { user: user, - userAgent: userAgent, errors: session.errors + Number(errored || crashed) })); - }; - /** Deliver captured session to Sentry */ - BaseClient.prototype._sendSession = function (session) { - this._getBackend().sendSession(session); - }; - /** Waits for the client to be done with processing. */ - BaseClient.prototype._isClientProcessing = function (timeout) { - var _this = this; - return new SyncPromise(function (resolve) { - var ticked = 0; - var tick = 1; - var interval = setInterval(function () { - if (_this._processing == 0) { - clearInterval(interval); - resolve(true); - } - else { - ticked += tick; - if (timeout && ticked >= timeout) { - clearInterval(interval); - resolve(false); - } - } - }, tick); - }); - }; - /** Returns the current backend. */ - BaseClient.prototype._getBackend = function () { - return this._backend; - }; - /** Determines whether this SDK is enabled and a valid Dsn is present. */ - BaseClient.prototype._isEnabled = function () { - return this.getOptions().enabled !== false && this._dsn !== undefined; - }; - /** - * Adds common information to events. - * - * The information includes release and environment from `options`, - * breadcrumbs and context (extra, tags and user) from the scope. - * - * Information that is already present in the event is never overwritten. For - * nested objects, such as the context, keys are merged. - * - * @param event The original event. - * @param hint May contain additional information about the original exception. - * @param scope A scope containing event metadata. - * @returns A new event with more information. - */ - BaseClient.prototype._prepareEvent = function (event, scope, hint) { - var _this = this; - var _a = this.getOptions().normalizeDepth, normalizeDepth = _a === void 0 ? 3 : _a; - var prepared = __assign(__assign({}, event), { event_id: event.event_id || (hint && hint.event_id ? hint.event_id : (0,misc/* uuid4 */.DM)()), timestamp: event.timestamp || (0,time/* dateTimestampInSeconds */.yW)() }); - this._applyClientOptions(prepared); - this._applyIntegrationsMetadata(prepared); - // If we have scope given to us, use it as the base for further modifications. - // This allows us to prevent unnecessary copying of data if `captureContext` is not provided. - var finalScope = scope; - if (hint && hint.captureContext) { - finalScope = Scope.clone(finalScope).update(hint.captureContext); - } - // We prepare the result here with a resolved Event. - var result = SyncPromise.resolve(prepared); - // This should be the last thing called, since we want that - // {@link Hub.addEventProcessor} gets the finished prepared event. - if (finalScope) { - // In case we have a hub we reassign it. - result = finalScope.applyToEvent(prepared, hint); - } - return result.then(function (evt) { - if (typeof normalizeDepth === 'number' && normalizeDepth > 0) { - return _this._normalizeEvent(evt, normalizeDepth); - } - return evt; - }); - }; - /** - * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization. - * Normalized keys: - * - `breadcrumbs.data` - * - `user` - * - `contexts` - * - `extra` - * @param event Event - * @returns Normalized event - */ - BaseClient.prototype._normalizeEvent = function (event, depth) { - if (!event) { - return null; - } - var normalized = __assign(__assign(__assign(__assign(__assign({}, event), (event.breadcrumbs && { - breadcrumbs: event.breadcrumbs.map(function (b) { return (__assign(__assign({}, b), (b.data && { - data: normalize(b.data, depth), - }))); }), - })), (event.user && { - user: normalize(event.user, depth), - })), (event.contexts && { - contexts: normalize(event.contexts, depth), - })), (event.extra && { - extra: normalize(event.extra, depth), - })); - // event.contexts.trace stores information about a Transaction. Similarly, - // event.spans[] stores information about child Spans. Given that a - // Transaction is conceptually a Span, normalization should apply to both - // Transactions and Spans consistently. - // For now the decision is to skip normalization of Transactions and Spans, - // so this block overwrites the normalized event to add back the original - // Transaction information prior to normalization. - if (event.contexts && event.contexts.trace) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - normalized.contexts.trace = event.contexts.trace; - } - return normalized; - }; - /** - * Enhances event using the client configuration. - * It takes care of all "static" values like environment, release and `dist`, - * as well as truncating overly long values. - * @param event event instance to be enhanced - */ - BaseClient.prototype._applyClientOptions = function (event) { - var options = this.getOptions(); - var environment = options.environment, release = options.release, dist = options.dist, _a = options.maxValueLength, maxValueLength = _a === void 0 ? 250 : _a; - if (!('environment' in event)) { - event.environment = 'environment' in options ? environment : 'production'; - } - if (event.release === undefined && release !== undefined) { - event.release = release; - } - if (event.dist === undefined && dist !== undefined) { - event.dist = dist; - } - if (event.message) { - event.message = truncate(event.message, maxValueLength); - } - var exception = event.exception && event.exception.values && event.exception.values[0]; - if (exception && exception.value) { - exception.value = truncate(exception.value, maxValueLength); - } - var request = event.request; - if (request && request.url) { - request.url = truncate(request.url, maxValueLength); - } - }; - /** - * This function adds all used integrations to the SDK info in the event. - * @param sdkInfo The sdkInfo of the event that will be filled with all integrations. - */ - BaseClient.prototype._applyIntegrationsMetadata = function (event) { - var sdkInfo = event.sdk; - var integrationsArray = Object.keys(this._integrations); - if (sdkInfo && integrationsArray.length > 0) { - sdkInfo.integrations = integrationsArray; - } - }; - /** - * Tells the backend to send this event - * @param event The Sentry event to send - */ - BaseClient.prototype._sendEvent = function (event) { - this._getBackend().sendEvent(event); - }; - /** - * Processes the event and logs an error in case of rejection - * @param event - * @param hint - * @param scope - */ - BaseClient.prototype._captureEvent = function (event, hint, scope) { - return this._processEvent(event, hint, scope).then(function (finalEvent) { - return finalEvent.event_id; - }, function (reason) { - logger.error(reason); - return undefined; - }); - }; - /** - * Processes an event (either error or message) and sends it to Sentry. - * - * This also adds breadcrumbs and context information to the event. However, - * platform specific meta data (such as the User's IP address) must be added - * by the SDK implementor. - * - * - * @param event The event to send to Sentry. - * @param hint May contain additional information about the original exception. - * @param scope A scope containing event metadata. - * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send. - */ - BaseClient.prototype._processEvent = function (event, hint, scope) { - var _this = this; - // eslint-disable-next-line @typescript-eslint/unbound-method - var _a = this.getOptions(), beforeSend = _a.beforeSend, sampleRate = _a.sampleRate; - if (!this._isEnabled()) { - return SyncPromise.reject(new SentryError('SDK not enabled, will not send event.')); - } - var isTransaction = event.type === 'transaction'; - // 1.0 === 100% events are sent - // 0.0 === 0% events are sent - // Sampling for transaction happens somewhere else - if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) { - return SyncPromise.reject(new SentryError('This event has been sampled, will not send event.')); - } - return this._prepareEvent(event, scope, hint) - .then(function (prepared) { - if (prepared === null) { - throw new SentryError('An event processor returned null, will not send event.'); - } - var isInternalException = hint && hint.data && hint.data.__sentry__ === true; - if (isInternalException || isTransaction || !beforeSend) { - return prepared; - } - var beforeSendResult = beforeSend(prepared, hint); - if (typeof beforeSendResult === 'undefined') { - throw new SentryError('`beforeSend` method has to return `null` or a valid event.'); - } - else if (isThenable(beforeSendResult)) { - return beforeSendResult.then(function (event) { return event; }, function (e) { - throw new SentryError("beforeSend rejected with " + e); - }); - } - return beforeSendResult; - }) - .then(function (processedEvent) { - if (processedEvent === null) { - throw new SentryError('`beforeSend` returned `null`, will not send event.'); - } - var session = scope && scope.getSession(); - if (!isTransaction && session) { - _this._updateSessionFromEvent(session, processedEvent); - } - _this._sendEvent(processedEvent); - return processedEvent; - }) - .then(null, function (reason) { - if (reason instanceof SentryError) { - throw reason; - } - _this.captureException(reason, { - data: { - __sentry__: true, - }, - originalException: reason, - }); - throw new SentryError("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: " + reason); - }); - }; - /** - * Occupies the client with processing and event - */ - BaseClient.prototype._process = function (promise) { - var _this = this; - this._processing += 1; - promise.then(function (value) { - _this._processing -= 1; - return value; - }, function (reason) { - _this._processing -= 1; - return reason; - }); - }; - return BaseClient; -}()); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/core/esm/transports/noop.js - - -/** Noop transport */ -var NoopTransport = /** @class */ (function () { - function NoopTransport() { - } - /** - * @inheritDoc - */ - NoopTransport.prototype.sendEvent = function (_) { - return SyncPromise.resolve({ - reason: "NoopTransport: Event has been skipped because no Dsn is configured.", - status: Status.Skipped, - }); - }; - /** - * @inheritDoc - */ - NoopTransport.prototype.close = function (_) { - return SyncPromise.resolve(true); - }; - return NoopTransport; -}()); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/core/esm/basebackend.js - - -/** - * This is the base implemention of a Backend. - * @hidden - */ -var BaseBackend = /** @class */ (function () { - /** Creates a new backend instance. */ - function BaseBackend(options) { - this._options = options; - if (!this._options.dsn) { - logger.warn('No DSN provided, backend will not do anything.'); - } - this._transport = this._setupTransport(); - } - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - BaseBackend.prototype.eventFromException = function (_exception, _hint) { - throw new SentryError('Backend has to implement `eventFromException` method'); - }; - /** - * @inheritDoc - */ - BaseBackend.prototype.eventFromMessage = function (_message, _level, _hint) { - throw new SentryError('Backend has to implement `eventFromMessage` method'); - }; - /** - * @inheritDoc - */ - BaseBackend.prototype.sendEvent = function (event) { - this._transport.sendEvent(event).then(null, function (reason) { - logger.error("Error while sending event: " + reason); - }); - }; - /** - * @inheritDoc - */ - BaseBackend.prototype.sendSession = function (session) { - if (!this._transport.sendSession) { - logger.warn("Dropping session because custom transport doesn't implement sendSession"); - return; - } - this._transport.sendSession(session).then(null, function (reason) { - logger.error("Error while sending session: " + reason); - }); - }; - /** - * @inheritDoc - */ - BaseBackend.prototype.getTransport = function () { - return this._transport; - }; - /** - * Sets up the transport so it can be used later to send requests. - */ - BaseBackend.prototype._setupTransport = function () { - return new NoopTransport(); - }; - return BaseBackend; -}()); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/utils/esm/supports.js - - -/** - * Tells whether current environment supports ErrorEvent objects - * {@link supportsErrorEvent}. - * - * @returns Answer to the given question. - */ -function supportsErrorEvent() { - try { - new ErrorEvent(''); - return true; - } - catch (e) { - return false; - } -} -/** - * Tells whether current environment supports DOMError objects - * {@link supportsDOMError}. - * - * @returns Answer to the given question. - */ -function supportsDOMError() { - try { - // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError': - // 1 argument required, but only 0 present. - // @ts-ignore It really needs 1 argument, not 0. - new DOMError(''); - return true; - } - catch (e) { - return false; - } -} -/** - * Tells whether current environment supports DOMException objects - * {@link supportsDOMException}. - * - * @returns Answer to the given question. - */ -function supportsDOMException() { - try { - new DOMException(''); - return true; - } - catch (e) { - return false; - } -} -/** - * Tells whether current environment supports Fetch API - * {@link supportsFetch}. - * - * @returns Answer to the given question. - */ -function supportsFetch() { - if (!('fetch' in (0,misc/* getGlobalObject */.Rf)())) { - return false; - } - try { - new Headers(); - new Request(''); - new Response(); - return true; - } - catch (e) { - return false; - } -} -/** - * isNativeFetch checks if the given function is a native implementation of fetch() - */ -// eslint-disable-next-line @typescript-eslint/ban-types -function isNativeFetch(func) { - return func && /^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString()); -} -/** - * Tells whether current environment supports Fetch API natively - * {@link supportsNativeFetch}. - * - * @returns true if `window.fetch` is natively implemented, false otherwise - */ -function supportsNativeFetch() { - if (!supportsFetch()) { - return false; - } - var global = (0,misc/* getGlobalObject */.Rf)(); - // Fast path to avoid DOM I/O - // eslint-disable-next-line @typescript-eslint/unbound-method - if (isNativeFetch(global.fetch)) { - return true; - } - // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension) - // so create a "pure" iframe to see if that has native fetch - var result = false; - var doc = global.document; - // eslint-disable-next-line deprecation/deprecation - if (doc && typeof doc.createElement === "function") { - try { - var sandbox = doc.createElement('iframe'); - sandbox.hidden = true; - doc.head.appendChild(sandbox); - if (sandbox.contentWindow && sandbox.contentWindow.fetch) { - // eslint-disable-next-line @typescript-eslint/unbound-method - result = isNativeFetch(sandbox.contentWindow.fetch); - } - doc.head.removeChild(sandbox); - } - catch (err) { - logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err); - } - } - return result; -} -/** - * Tells whether current environment supports ReportingObserver API - * {@link supportsReportingObserver}. - * - * @returns Answer to the given question. - */ -function supportsReportingObserver() { - return 'ReportingObserver' in getGlobalObject(); -} -/** - * Tells whether current environment supports Referrer Policy API - * {@link supportsReferrerPolicy}. - * - * @returns Answer to the given question. - */ -function supportsReferrerPolicy() { - // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default - // https://caniuse.com/#feat=referrer-policy - // It doesn't. And it throw exception instead of ignoring this parameter... - // REF: https://github.com/getsentry/raven-js/issues/1233 - if (!supportsFetch()) { - return false; - } - try { - new Request('_', { - referrerPolicy: 'origin', - }); - return true; - } - catch (e) { - return false; - } -} -/** - * Tells whether current environment supports History API - * {@link supportsHistory}. - * - * @returns Answer to the given question. - */ -function supportsHistory() { - // NOTE: in Chrome App environment, touching history.pushState, *even inside - // a try/catch block*, will cause Chrome to output an error to console.error - // borrowed from: https://github.com/angular/angular.js/pull/13945/files - var global = (0,misc/* getGlobalObject */.Rf)(); - /* eslint-disable @typescript-eslint/no-unsafe-member-access */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var chrome = global.chrome; - var isChromePackagedApp = chrome && chrome.app && chrome.app.runtime; - /* eslint-enable @typescript-eslint/no-unsafe-member-access */ - var hasHistoryApi = 'history' in global && !!global.history.pushState && !!global.history.replaceState; - return !isChromePackagedApp && hasHistoryApi; -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/tracekit.js -/** - * This was originally forked from https://github.com/occ/TraceKit, but has since been - * largely modified and is now maintained as part of Sentry JS SDK. - */ - -// global reference to slice -var UNKNOWN_FUNCTION = '?'; -// Chromium based browsers: Chrome, Brave, new Opera, new Edge -var chrome = /^\s*at (?:(.*?) ?\()?((?:file|https?|blob|chrome-extension|address|native|eval|webpack||[-a-z]+:|.*bundle|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i; -// gecko regex: `(?:bundle|\d+\.js)`: `bundle` is for react native, `\d+\.js` also but specifically for ram bundles because it -// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js -// We need this specific case for now because we want no other regex to match. -var gecko = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:file|https?|blob|chrome|webpack|resource|moz-extension|capacitor).*?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js))(?::(\d+))?(?::(\d+))?\s*$/i; -var winjs = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i; -var geckoEval = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i; -var chromeEval = /\((\S*)(?::(\d+))(?::(\d+))\)/; -// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108 -var reactMinifiedRegexp = /Minified React error #\d+;/i; -/** JSDoc */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types -function computeStackTrace(ex) { - var stack = null; - var popSize = 0; - if (ex) { - if (typeof ex.framesToPop === 'number') { - popSize = ex.framesToPop; - } - else if (reactMinifiedRegexp.test(ex.message)) { - popSize = 1; - } - } - try { - // This must be tried first because Opera 10 *destroys* - // its stacktrace property if you try to access the stack - // property first!! - stack = computeStackTraceFromStacktraceProp(ex); - if (stack) { - return popFrames(stack, popSize); - } - } - catch (e) { - // no-empty - } - try { - stack = computeStackTraceFromStackProp(ex); - if (stack) { - return popFrames(stack, popSize); - } - } - catch (e) { - // no-empty - } - return { - message: extractMessage(ex), - name: ex && ex.name, - stack: [], - failed: true, - }; -} -/** JSDoc */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any, complexity -function computeStackTraceFromStackProp(ex) { - if (!ex || !ex.stack) { - return null; - } - var stack = []; - var lines = ex.stack.split('\n'); - var isEval; - var submatch; - var parts; - var element; - for (var i = 0; i < lines.length; ++i) { - if ((parts = chrome.exec(lines[i]))) { - var isNative = parts[2] && parts[2].indexOf('native') === 0; // start of line - isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line - if (isEval && (submatch = chromeEval.exec(parts[2]))) { - // throw out eval line/column and use top-most line/column number - parts[2] = submatch[1]; // url - parts[3] = submatch[2]; // line - parts[4] = submatch[3]; // column - } - element = { - // working with the regexp above is super painful. it is quite a hack, but just stripping the `address at ` - // prefix here seems like the quickest solution for now. - url: parts[2] && parts[2].indexOf('address at ') === 0 ? parts[2].substr('address at '.length) : parts[2], - func: parts[1] || UNKNOWN_FUNCTION, - args: isNative ? [parts[2]] : [], - line: parts[3] ? +parts[3] : null, - column: parts[4] ? +parts[4] : null, - }; - } - else if ((parts = winjs.exec(lines[i]))) { - element = { - url: parts[2], - func: parts[1] || UNKNOWN_FUNCTION, - args: [], - line: +parts[3], - column: parts[4] ? +parts[4] : null, - }; - } - else if ((parts = gecko.exec(lines[i]))) { - isEval = parts[3] && parts[3].indexOf(' > eval') > -1; - if (isEval && (submatch = geckoEval.exec(parts[3]))) { - // throw out eval line/column and use top-most line number - parts[1] = parts[1] || "eval"; - parts[3] = submatch[1]; - parts[4] = submatch[2]; - parts[5] = ''; // no column when eval - } - else if (i === 0 && !parts[5] && ex.columnNumber !== void 0) { - // FireFox uses this awesome columnNumber property for its top frame - // Also note, Firefox's column number is 0-based and everything else expects 1-based, - // so adding 1 - // NOTE: this hack doesn't work if top-most frame is eval - stack[0].column = ex.columnNumber + 1; - } - element = { - url: parts[3], - func: parts[1] || UNKNOWN_FUNCTION, - args: parts[2] ? parts[2].split(',') : [], - line: parts[4] ? +parts[4] : null, - column: parts[5] ? +parts[5] : null, - }; - } - else { - continue; - } - if (!element.func && element.line) { - element.func = UNKNOWN_FUNCTION; - } - stack.push(element); - } - if (!stack.length) { - return null; - } - return { - message: extractMessage(ex), - name: ex.name, - stack: stack, - }; -} -/** JSDoc */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function computeStackTraceFromStacktraceProp(ex) { - if (!ex || !ex.stacktrace) { - return null; - } - // Access and store the stacktrace property before doing ANYTHING - // else to it because Opera is not very good at providing it - // reliably in other circumstances. - var stacktrace = ex.stacktrace; - var opera10Regex = / line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i; - var opera11Regex = / line (\d+), column (\d+)\s*(?:in (?:]+)>|([^)]+))\((.*)\))? in (.*):\s*$/i; - var lines = stacktrace.split('\n'); - var stack = []; - var parts; - for (var line = 0; line < lines.length; line += 2) { - var element = null; - if ((parts = opera10Regex.exec(lines[line]))) { - element = { - url: parts[2], - func: parts[3], - args: [], - line: +parts[1], - column: null, - }; - } - else if ((parts = opera11Regex.exec(lines[line]))) { - element = { - url: parts[6], - func: parts[3] || parts[4], - args: parts[5] ? parts[5].split(',') : [], - line: +parts[1], - column: +parts[2], - }; - } - if (element) { - if (!element.func && element.line) { - element.func = UNKNOWN_FUNCTION; - } - stack.push(element); - } - } - if (!stack.length) { - return null; - } - return { - message: extractMessage(ex), - name: ex.name, - stack: stack, - }; -} -/** Remove N number of frames from the stack */ -function popFrames(stacktrace, popSize) { - try { - return __assign(__assign({}, stacktrace), { stack: stacktrace.stack.slice(popSize) }); - } - catch (e) { - return stacktrace; - } -} -/** - * There are cases where stacktrace.message is an Event object - * https://github.com/getsentry/sentry-javascript/issues/1949 - * In this specific case we try to extract stacktrace.message.error.message - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function extractMessage(ex) { - var message = ex && ex.message; - if (!message) { - return 'No error message'; - } - if (message.error && typeof message.error.message === 'string') { - return message.error.message; - } - return message; -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/parsers.js - - -var STACKTRACE_LIMIT = 50; -/** - * This function creates an exception from an TraceKitStackTrace - * @param stacktrace TraceKitStackTrace that will be converted to an exception - * @hidden - */ -function exceptionFromStacktrace(stacktrace) { - var frames = prepareFramesForEvent(stacktrace.stack); - var exception = { - type: stacktrace.name, - value: stacktrace.message, - }; - if (frames && frames.length) { - exception.stacktrace = { frames: frames }; - } - if (exception.type === undefined && exception.value === '') { - exception.value = 'Unrecoverable error caught'; - } - return exception; -} -/** - * @hidden - */ -function eventFromPlainObject(exception, syntheticException, rejection) { - var event = { - exception: { - values: [ - { - type: isEvent(exception) ? exception.constructor.name : rejection ? 'UnhandledRejection' : 'Error', - value: "Non-Error " + (rejection ? 'promise rejection' : 'exception') + " captured with keys: " + extractExceptionKeysForMessage(exception), - }, - ], - }, - extra: { - __serialized__: normalizeToSize(exception), - }, - }; - if (syntheticException) { - var stacktrace = computeStackTrace(syntheticException); - var frames_1 = prepareFramesForEvent(stacktrace.stack); - event.stacktrace = { - frames: frames_1, - }; - } - return event; -} -/** - * @hidden - */ -function eventFromStacktrace(stacktrace) { - var exception = exceptionFromStacktrace(stacktrace); - return { - exception: { - values: [exception], - }, - }; -} -/** - * @hidden - */ -function prepareFramesForEvent(stack) { - if (!stack || !stack.length) { - return []; - } - var localStack = stack; - var firstFrameFunction = localStack[0].func || ''; - var lastFrameFunction = localStack[localStack.length - 1].func || ''; - // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call) - if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) { - localStack = localStack.slice(1); - } - // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call) - if (lastFrameFunction.indexOf('sentryWrapped') !== -1) { - localStack = localStack.slice(0, -1); - } - // The frame where the crash happened, should be the last entry in the array - return localStack - .slice(0, STACKTRACE_LIMIT) - .map(function (frame) { return ({ - colno: frame.column === null ? undefined : frame.column, - filename: frame.url || localStack[0].url, - function: frame.func || '?', - in_app: true, - lineno: frame.line === null ? undefined : frame.line, - }); }) - .reverse(); -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/eventbuilder.js - - - - -/** - * Builds and Event from a Exception - * @hidden - */ -function eventFromException(options, exception, hint) { - var syntheticException = (hint && hint.syntheticException) || undefined; - var event = eventFromUnknownInput(exception, syntheticException, { - attachStacktrace: options.attachStacktrace, - }); - (0,misc/* addExceptionMechanism */.EG)(event, { - handled: true, - type: 'generic', - }); - event.level = Severity.Error; - if (hint && hint.event_id) { - event.event_id = hint.event_id; - } - return SyncPromise.resolve(event); -} -/** - * Builds and Event from a Message - * @hidden - */ -function eventFromMessage(options, message, level, hint) { - if (level === void 0) { level = Severity.Info; } - var syntheticException = (hint && hint.syntheticException) || undefined; - var event = eventFromString(message, syntheticException, { - attachStacktrace: options.attachStacktrace, - }); - event.level = level; - if (hint && hint.event_id) { - event.event_id = hint.event_id; - } - return SyncPromise.resolve(event); -} -/** - * @hidden - */ -function eventFromUnknownInput(exception, syntheticException, options) { - if (options === void 0) { options = {}; } - var event; - if (isErrorEvent(exception) && exception.error) { - // If it is an ErrorEvent with `error` property, extract it to get actual Error - var errorEvent = exception; - // eslint-disable-next-line no-param-reassign - exception = errorEvent.error; - event = eventFromStacktrace(computeStackTrace(exception)); - return event; - } - if (isDOMError(exception) || isDOMException(exception)) { - // If it is a DOMError or DOMException (which are legacy APIs, but still supported in some browsers) - // then we just extract the name and message, as they don't provide anything else - // https://developer.mozilla.org/en-US/docs/Web/API/DOMError - // https://developer.mozilla.org/en-US/docs/Web/API/DOMException - var domException = exception; - var name_1 = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException'); - var message = domException.message ? name_1 + ": " + domException.message : name_1; - event = eventFromString(message, syntheticException, options); - (0,misc/* addExceptionTypeValue */.Db)(event, message); - return event; - } - if (isError(exception)) { - // we have a real Error object, do nothing - event = eventFromStacktrace(computeStackTrace(exception)); - return event; - } - if (isPlainObject(exception) || isEvent(exception)) { - // If it is plain Object or Event, serialize it manually and extract options - // This will allow us to group events based on top-level keys - // which is much better than creating new group when any key/value change - var objectException = exception; - event = eventFromPlainObject(objectException, syntheticException, options.rejection); - (0,misc/* addExceptionMechanism */.EG)(event, { - synthetic: true, - }); - return event; - } - // If none of previous checks were valid, then it means that it's not: - // - an instance of DOMError - // - an instance of DOMException - // - an instance of Event - // - an instance of Error - // - a valid ErrorEvent (one with an error property) - // - a plain Object - // - // So bail out and capture it as a simple message: - event = eventFromString(exception, syntheticException, options); - (0,misc/* addExceptionTypeValue */.Db)(event, "" + exception, undefined); - (0,misc/* addExceptionMechanism */.EG)(event, { - synthetic: true, - }); - return event; -} -/** - * @hidden - */ -function eventFromString(input, syntheticException, options) { - if (options === void 0) { options = {}; } - var event = { - message: input, - }; - if (options.attachStacktrace && syntheticException) { - var stacktrace = computeStackTrace(syntheticException); - var frames_1 = prepareFramesForEvent(stacktrace.stack); - event.stacktrace = { - frames: frames_1, - }; - } - return event; -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/core/esm/request.js -/** Creates a SentryRequest from an event. */ -function sessionToSentryRequest(session, api) { - var envelopeHeaders = JSON.stringify({ - sent_at: new Date().toISOString(), - }); - var itemHeaders = JSON.stringify({ - type: 'session', - }); - return { - body: envelopeHeaders + "\n" + itemHeaders + "\n" + JSON.stringify(session), - type: 'session', - url: api.getEnvelopeEndpointWithUrlEncodedAuth(), - }; -} -/** Creates a SentryRequest from an event. */ -function eventToSentryRequest(event, api) { - var useEnvelope = event.type === 'transaction'; - var req = { - body: JSON.stringify(event), - type: event.type || 'event', - url: useEnvelope ? api.getEnvelopeEndpointWithUrlEncodedAuth() : api.getStoreEndpointWithUrlEncodedAuth(), - }; - // https://develop.sentry.dev/sdk/envelopes/ - // Since we don't need to manipulate envelopes nor store them, there is no - // exported concept of an Envelope with operations including serialization and - // deserialization. Instead, we only implement a minimal subset of the spec to - // serialize events inline here. - if (useEnvelope) { - var envelopeHeaders = JSON.stringify({ - event_id: event.event_id, - // We need to add * 1000 since we divide it by 1000 by default but JS works with ms precision - // The reason we use timestampWithMs here is that all clocks across the SDK use the same clock - sent_at: new Date().toISOString(), - }); - var itemHeaders = JSON.stringify({ - type: event.type, - }); - // The trailing newline is optional. We intentionally don't send it to avoid - // sending unnecessary bytes. - // - // const envelope = `${envelopeHeaders}\n${itemHeaders}\n${req.body}\n`; - var envelope = envelopeHeaders + "\n" + itemHeaders + "\n" + req.body; - req.body = envelope; - } - return req; -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/core/esm/api.js - -var SENTRY_API_VERSION = '7'; -/** Helper class to provide urls to different Sentry endpoints. */ -var API = /** @class */ (function () { - /** Create a new instance of API */ - function API(dsn) { - this.dsn = dsn; - this._dsnObject = new Dsn(dsn); - } - /** Returns the Dsn object. */ - API.prototype.getDsn = function () { - return this._dsnObject; - }; - /** Returns the prefix to construct Sentry ingestion API endpoints. */ - API.prototype.getBaseApiEndpoint = function () { - var dsn = this._dsnObject; - var protocol = dsn.protocol ? dsn.protocol + ":" : ''; - var port = dsn.port ? ":" + dsn.port : ''; - return protocol + "//" + dsn.host + port + (dsn.path ? "/" + dsn.path : '') + "/api/"; - }; - /** Returns the store endpoint URL. */ - API.prototype.getStoreEndpoint = function () { - return this._getIngestEndpoint('store'); - }; - /** - * Returns the store endpoint URL with auth in the query string. - * - * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. - */ - API.prototype.getStoreEndpointWithUrlEncodedAuth = function () { - return this.getStoreEndpoint() + "?" + this._encodedAuth(); - }; - /** - * Returns the envelope endpoint URL with auth in the query string. - * - * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. - */ - API.prototype.getEnvelopeEndpointWithUrlEncodedAuth = function () { - return this._getEnvelopeEndpoint() + "?" + this._encodedAuth(); - }; - /** Returns only the path component for the store endpoint. */ - API.prototype.getStoreEndpointPath = function () { - var dsn = this._dsnObject; - return (dsn.path ? "/" + dsn.path : '') + "/api/" + dsn.projectId + "/store/"; - }; - /** - * Returns an object that can be used in request headers. - * This is needed for node and the old /store endpoint in sentry - */ - API.prototype.getRequestHeaders = function (clientName, clientVersion) { - var dsn = this._dsnObject; - var header = ["Sentry sentry_version=" + SENTRY_API_VERSION]; - header.push("sentry_client=" + clientName + "/" + clientVersion); - header.push("sentry_key=" + dsn.user); - if (dsn.pass) { - header.push("sentry_secret=" + dsn.pass); - } - return { - 'Content-Type': 'application/json', - 'X-Sentry-Auth': header.join(', '), - }; - }; - /** Returns the url to the report dialog endpoint. */ - API.prototype.getReportDialogEndpoint = function (dialogOptions) { - if (dialogOptions === void 0) { dialogOptions = {}; } - var dsn = this._dsnObject; - var endpoint = this.getBaseApiEndpoint() + "embed/error-page/"; - var encodedOptions = []; - encodedOptions.push("dsn=" + dsn.toString()); - for (var key in dialogOptions) { - if (key === 'user') { - if (!dialogOptions.user) { - continue; - } - if (dialogOptions.user.name) { - encodedOptions.push("name=" + encodeURIComponent(dialogOptions.user.name)); - } - if (dialogOptions.user.email) { - encodedOptions.push("email=" + encodeURIComponent(dialogOptions.user.email)); - } - } - else { - encodedOptions.push(encodeURIComponent(key) + "=" + encodeURIComponent(dialogOptions[key])); - } - } - if (encodedOptions.length) { - return endpoint + "?" + encodedOptions.join('&'); - } - return endpoint; - }; - /** Returns the envelope endpoint URL. */ - API.prototype._getEnvelopeEndpoint = function () { - return this._getIngestEndpoint('envelope'); - }; - /** Returns the ingest API endpoint for target. */ - API.prototype._getIngestEndpoint = function (target) { - var base = this.getBaseApiEndpoint(); - var dsn = this._dsnObject; - return "" + base + dsn.projectId + "/" + target + "/"; - }; - /** Returns a URL-encoded string with auth config suitable for a query string. */ - API.prototype._encodedAuth = function () { - var dsn = this._dsnObject; - var auth = { - // We send only the minimum set of required information. See - // https://github.com/getsentry/sentry-javascript/issues/2572. - sentry_key: dsn.user, - sentry_version: SENTRY_API_VERSION, - }; - return urlEncode(auth); - }; - return API; -}()); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/utils/esm/promisebuffer.js - - -/** A simple queue that holds promises. */ -var PromiseBuffer = /** @class */ (function () { - function PromiseBuffer(_limit) { - this._limit = _limit; - /** Internal set of queued Promises */ - this._buffer = []; - } - /** - * Says if the buffer is ready to take more requests - */ - PromiseBuffer.prototype.isReady = function () { - return this._limit === undefined || this.length() < this._limit; - }; - /** - * Add a promise to the queue. - * - * @param task Can be any PromiseLike - * @returns The original promise. - */ - PromiseBuffer.prototype.add = function (task) { - var _this = this; - if (!this.isReady()) { - return SyncPromise.reject(new SentryError('Not adding Promise due to buffer limit reached.')); - } - if (this._buffer.indexOf(task) === -1) { - this._buffer.push(task); - } - task - .then(function () { return _this.remove(task); }) - .then(null, function () { - return _this.remove(task).then(null, function () { - // We have to add this catch here otherwise we have an unhandledPromiseRejection - // because it's a new Promise chain. - }); - }); - return task; - }; - /** - * Remove a promise to the queue. - * - * @param task Can be any PromiseLike - * @returns Removed promise. - */ - PromiseBuffer.prototype.remove = function (task) { - var removedTask = this._buffer.splice(this._buffer.indexOf(task), 1)[0]; - return removedTask; - }; - /** - * This function returns the number of unresolved promises in the queue. - */ - PromiseBuffer.prototype.length = function () { - return this._buffer.length; - }; - /** - * This will drain the whole queue, returns true if queue is empty or drained. - * If timeout is provided and the queue takes longer to drain, the promise still resolves but with false. - * - * @param timeout Number in ms to wait until it resolves with false. - */ - PromiseBuffer.prototype.drain = function (timeout) { - var _this = this; - return new SyncPromise(function (resolve) { - var capturedSetTimeout = setTimeout(function () { - if (timeout && timeout > 0) { - resolve(false); - } - }, timeout); - SyncPromise.all(_this._buffer) - .then(function () { - clearTimeout(capturedSetTimeout); - resolve(true); - }) - .then(null, function () { - resolve(true); - }); - }); - }; - return PromiseBuffer; -}()); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/transports/base.js - - - - -/** Base Transport class implementation */ -var BaseTransport = /** @class */ (function () { - function BaseTransport(options) { - this.options = options; - /** A simple buffer holding all requests. */ - this._buffer = new PromiseBuffer(30); - /** Locks transport after receiving rate limits in a response */ - this._rateLimits = {}; - this._api = new API(this.options.dsn); - // eslint-disable-next-line deprecation/deprecation - this.url = this._api.getStoreEndpointWithUrlEncodedAuth(); - } - /** - * @inheritDoc - */ - BaseTransport.prototype.sendEvent = function (_) { - throw new SentryError('Transport Class has to implement `sendEvent` method'); - }; - /** - * @inheritDoc - */ - BaseTransport.prototype.close = function (timeout) { - return this._buffer.drain(timeout); - }; - /** - * Handle Sentry repsonse for promise-based transports. - */ - BaseTransport.prototype._handleResponse = function (_a) { - var requestType = _a.requestType, response = _a.response, headers = _a.headers, resolve = _a.resolve, reject = _a.reject; - var status = Status.fromHttpCode(response.status); - /** - * "The name is case-insensitive." - * https://developer.mozilla.org/en-US/docs/Web/API/Headers/get - */ - var limited = this._handleRateLimit(headers); - if (limited) - logger.warn("Too many requests, backing off till: " + this._disabledUntil(requestType)); - if (status === Status.Success) { - resolve({ status: status }); - return; - } - reject(response); - }; - /** - * Gets the time that given category is disabled until for rate limiting - */ - BaseTransport.prototype._disabledUntil = function (category) { - return this._rateLimits[category] || this._rateLimits.all; - }; - /** - * Checks if a category is rate limited - */ - BaseTransport.prototype._isRateLimited = function (category) { - return this._disabledUntil(category) > new Date(Date.now()); - }; - /** - * Sets internal _rateLimits from incoming headers. Returns true if headers contains a non-empty rate limiting header. - */ - BaseTransport.prototype._handleRateLimit = function (headers) { - var e_1, _a, e_2, _b; - var now = Date.now(); - var rlHeader = headers['x-sentry-rate-limits']; - var raHeader = headers['retry-after']; - if (rlHeader) { - try { - for (var _c = __values(rlHeader.trim().split(',')), _d = _c.next(); !_d.done; _d = _c.next()) { - var limit = _d.value; - var parameters = limit.split(':', 2); - var headerDelay = parseInt(parameters[0], 10); - var delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default - try { - for (var _e = (e_2 = void 0, __values(parameters[1].split(';'))), _f = _e.next(); !_f.done; _f = _e.next()) { - var category = _f.value; - this._rateLimits[category || 'all'] = new Date(now + delay); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (_f && !_f.done && (_b = _e.return)) _b.call(_e); - } - finally { if (e_2) throw e_2.error; } - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_d && !_d.done && (_a = _c.return)) _a.call(_c); - } - finally { if (e_1) throw e_1.error; } - } - return true; - } - else if (raHeader) { - this._rateLimits.all = new Date(now + (0,misc/* parseRetryAfterHeader */.JY)(now, raHeader)); - return true; - } - return false; - }; - return BaseTransport; -}()); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/transports/fetch.js - - - - -var fetch_global = (0,misc/* getGlobalObject */.Rf)(); -/** `fetch` based transport */ -var FetchTransport = /** @class */ (function (_super) { - __extends(FetchTransport, _super); - function FetchTransport() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * @inheritDoc - */ - FetchTransport.prototype.sendEvent = function (event) { - return this._sendRequest(eventToSentryRequest(event, this._api), event); - }; - /** - * @inheritDoc - */ - FetchTransport.prototype.sendSession = function (session) { - return this._sendRequest(sessionToSentryRequest(session, this._api), session); - }; - /** - * @param sentryRequest Prepared SentryRequest to be delivered - * @param originalPayload Original payload used to create SentryRequest - */ - FetchTransport.prototype._sendRequest = function (sentryRequest, originalPayload) { - var _this = this; - if (this._isRateLimited(sentryRequest.type)) { - return Promise.reject({ - event: originalPayload, - type: sentryRequest.type, - reason: "Transport locked till " + this._disabledUntil(sentryRequest.type) + " due to too many requests.", - status: 429, - }); - } - var options = { - body: sentryRequest.body, - method: 'POST', - // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default - // https://caniuse.com/#feat=referrer-policy - // It doesn't. And it throw exception instead of ignoring this parameter... - // REF: https://github.com/getsentry/raven-js/issues/1233 - referrerPolicy: (supportsReferrerPolicy() ? 'origin' : ''), - }; - if (this.options.fetchParameters !== undefined) { - Object.assign(options, this.options.fetchParameters); - } - if (this.options.headers !== undefined) { - options.headers = this.options.headers; - } - return this._buffer.add(new SyncPromise(function (resolve, reject) { - fetch_global - .fetch(sentryRequest.url, options) - .then(function (response) { - var headers = { - 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'), - 'retry-after': response.headers.get('Retry-After'), - }; - _this._handleResponse({ requestType: sentryRequest.type, response: response, headers: headers, resolve: resolve, reject: reject }); - }) - .catch(reject); - })); - }; - return FetchTransport; -}(BaseTransport)); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/transports/xhr.js - - - - -/** `XHR` based transport */ -var XHRTransport = /** @class */ (function (_super) { - __extends(XHRTransport, _super); - function XHRTransport() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * @inheritDoc - */ - XHRTransport.prototype.sendEvent = function (event) { - return this._sendRequest(eventToSentryRequest(event, this._api), event); - }; - /** - * @inheritDoc - */ - XHRTransport.prototype.sendSession = function (session) { - return this._sendRequest(sessionToSentryRequest(session, this._api), session); - }; - /** - * @param sentryRequest Prepared SentryRequest to be delivered - * @param originalPayload Original payload used to create SentryRequest - */ - XHRTransport.prototype._sendRequest = function (sentryRequest, originalPayload) { - var _this = this; - if (this._isRateLimited(sentryRequest.type)) { - return Promise.reject({ - event: originalPayload, - type: sentryRequest.type, - reason: "Transport locked till " + this._disabledUntil(sentryRequest.type) + " due to too many requests.", - status: 429, - }); - } - return this._buffer.add(new SyncPromise(function (resolve, reject) { - var request = new XMLHttpRequest(); - request.onreadystatechange = function () { - if (request.readyState === 4) { - var headers = { - 'x-sentry-rate-limits': request.getResponseHeader('X-Sentry-Rate-Limits'), - 'retry-after': request.getResponseHeader('Retry-After'), - }; - _this._handleResponse({ requestType: sentryRequest.type, response: request, headers: headers, resolve: resolve, reject: reject }); - } - }; - request.open('POST', sentryRequest.url); - for (var header in _this.options.headers) { - if (_this.options.headers.hasOwnProperty(header)) { - request.setRequestHeader(header, _this.options.headers[header]); - } - } - request.send(sentryRequest.body); - })); - }; - return XHRTransport; -}(BaseTransport)); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/backend.js - - - - - - -/** - * The Sentry Browser SDK Backend. - * @hidden - */ -var BrowserBackend = /** @class */ (function (_super) { - __extends(BrowserBackend, _super); - function BrowserBackend() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * @inheritDoc - */ - BrowserBackend.prototype.eventFromException = function (exception, hint) { - return eventFromException(this._options, exception, hint); - }; - /** - * @inheritDoc - */ - BrowserBackend.prototype.eventFromMessage = function (message, level, hint) { - if (level === void 0) { level = Severity.Info; } - return eventFromMessage(this._options, message, level, hint); - }; - /** - * @inheritDoc - */ - BrowserBackend.prototype._setupTransport = function () { - if (!this._options.dsn) { - // We return the noop transport here in case there is no Dsn. - return _super.prototype._setupTransport.call(this); - } - var transportOptions = __assign(__assign({}, this._options.transportOptions), { dsn: this._options.dsn }); - if (this._options.transport) { - return new this._options.transport(transportOptions); - } - if (supportsFetch()) { - return new FetchTransport(transportOptions); - } - return new XHRTransport(transportOptions); - }; - return BrowserBackend; -}(BaseBackend)); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/helpers.js - - - -var ignoreOnError = 0; -/** - * @hidden - */ -function shouldIgnoreOnError() { - return ignoreOnError > 0; -} -/** - * @hidden - */ -function ignoreNextOnError() { - // onerror should trigger before setTimeout - ignoreOnError += 1; - setTimeout(function () { - ignoreOnError -= 1; - }); -} -/** - * Instruments the given function and sends an event to Sentry every time the - * function throws an exception. - * - * @param fn A function to wrap. - * @returns The wrapped function. - * @hidden - */ -function wrap(fn, options, before) { - if (options === void 0) { options = {}; } - if (typeof fn !== 'function') { - return fn; - } - try { - // We don't wanna wrap it twice - if (fn.__sentry__) { - return fn; - } - // If this has already been wrapped in the past, return that wrapped function - if (fn.__sentry_wrapped__) { - return fn.__sentry_wrapped__; - } - } - catch (e) { - // Just accessing custom props in some Selenium environments - // can cause a "Permission denied" exception (see raven-js#495). - // Bail on wrapping and return the function as-is (defers to window.onerror). - return fn; - } - /* eslint-disable prefer-rest-params */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var sentryWrapped = function () { - var args = Array.prototype.slice.call(arguments); - try { - if (before && typeof before === 'function') { - before.apply(this, arguments); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access - var wrappedArguments = args.map(function (arg) { return wrap(arg, options); }); - if (fn.handleEvent) { - // Attempt to invoke user-land function - // NOTE: If you are a Sentry user, and you are seeing this stack frame, it - // means the sentry.javascript SDK caught an error invoking your application code. This - // is expected behavior and NOT indicative of a bug with sentry.javascript. - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return fn.handleEvent.apply(this, wrappedArguments); - } - // Attempt to invoke user-land function - // NOTE: If you are a Sentry user, and you are seeing this stack frame, it - // means the sentry.javascript SDK caught an error invoking your application code. This - // is expected behavior and NOT indicative of a bug with sentry.javascript. - return fn.apply(this, wrappedArguments); - } - catch (ex) { - ignoreNextOnError(); - withScope(function (scope) { - scope.addEventProcessor(function (event) { - var processedEvent = __assign({}, event); - if (options.mechanism) { - (0,misc/* addExceptionTypeValue */.Db)(processedEvent, undefined, undefined); - (0,misc/* addExceptionMechanism */.EG)(processedEvent, options.mechanism); - } - processedEvent.extra = __assign(__assign({}, processedEvent.extra), { arguments: args }); - return processedEvent; - }); - captureException(ex); - }); - throw ex; - } - }; - /* eslint-enable prefer-rest-params */ - // Accessing some objects may throw - // ref: https://github.com/getsentry/sentry-javascript/issues/1168 - try { - for (var property in fn) { - if (Object.prototype.hasOwnProperty.call(fn, property)) { - sentryWrapped[property] = fn[property]; - } - } - } - catch (_oO) { } // eslint-disable-line no-empty - fn.prototype = fn.prototype || {}; - sentryWrapped.prototype = fn.prototype; - Object.defineProperty(fn, '__sentry_wrapped__', { - enumerable: false, - value: sentryWrapped, - }); - // Signal that this function has been wrapped/filled already - // for both debugging and to prevent it to being wrapped/filled twice - Object.defineProperties(sentryWrapped, { - __sentry__: { - enumerable: false, - value: true, - }, - __sentry_original__: { - enumerable: false, - value: fn, - }, - }); - // Restore original function name (not all browsers allow that) - try { - var descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name'); - if (descriptor.configurable) { - Object.defineProperty(sentryWrapped, 'name', { - get: function () { - return fn.name; - }, - }); - } - // eslint-disable-next-line no-empty - } - catch (_oO) { } - return sentryWrapped; -} -/** - * Injects the Report Dialog script - * @hidden - */ -function injectReportDialog(options) { - if (options === void 0) { options = {}; } - if (!options.eventId) { - logger.error("Missing eventId option in showReportDialog call"); - return; - } - if (!options.dsn) { - logger.error("Missing dsn option in showReportDialog call"); - return; - } - var script = document.createElement('script'); - script.async = true; - script.src = new API(options.dsn).getReportDialogEndpoint(options); - if (options.onLoad) { - // eslint-disable-next-line @typescript-eslint/unbound-method - script.onload = options.onLoad; - } - (document.head || document.body).appendChild(script); -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/utils/esm/instrument.js - - - - - - - -var instrument_global = (0,misc/* getGlobalObject */.Rf)(); -/** - * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc. - * - Console API - * - Fetch API - * - XHR API - * - History API - * - DOM API (click/typing) - * - Error API - * - UnhandledRejection API - */ -var handlers = {}; -var instrumented = {}; -/** Instruments given API */ -function instrument(type) { - if (instrumented[type]) { - return; - } - instrumented[type] = true; - switch (type) { - case 'console': - instrumentConsole(); - break; - case 'dom': - instrumentDOM(); - break; - case 'xhr': - instrumentXHR(); - break; - case 'fetch': - instrumentFetch(); - break; - case 'history': - instrumentHistory(); - break; - case 'error': - instrumentError(); - break; - case 'unhandledrejection': - instrumentUnhandledRejection(); - break; - default: - logger.warn('unknown instrumentation type:', type); - } -} -/** - * Add handler that will be called when given type of instrumentation triggers. - * Use at your own risk, this might break without changelog notice, only used internally. - * @hidden - */ -function addInstrumentationHandler(handler) { - if (!handler || typeof handler.type !== 'string' || typeof handler.callback !== 'function') { - return; - } - handlers[handler.type] = handlers[handler.type] || []; - handlers[handler.type].push(handler.callback); - instrument(handler.type); -} -/** JSDoc */ -function triggerHandlers(type, data) { - var e_1, _a; - if (!type || !handlers[type]) { - return; - } - try { - for (var _b = __values(handlers[type] || []), _c = _b.next(); !_c.done; _c = _b.next()) { - var handler = _c.value; - try { - handler(data); - } - catch (e) { - logger.error("Error while triggering instrumentation handler.\nType: " + type + "\nName: " + getFunctionName(handler) + "\nError: " + e); - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } - finally { if (e_1) throw e_1.error; } - } -} -/** JSDoc */ -function instrumentConsole() { - if (!('console' in instrument_global)) { - return; - } - ['debug', 'info', 'warn', 'error', 'log', 'assert'].forEach(function (level) { - if (!(level in instrument_global.console)) { - return; - } - fill(instrument_global.console, level, function (originalConsoleLevel) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - triggerHandlers('console', { args: args, level: level }); - // this fails for some browsers. :( - if (originalConsoleLevel) { - Function.prototype.apply.call(originalConsoleLevel, instrument_global.console, args); - } - }; - }); - }); -} -/** JSDoc */ -function instrumentFetch() { - if (!supportsNativeFetch()) { - return; - } - fill(instrument_global, 'fetch', function (originalFetch) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var handlerData = { - args: args, - fetchData: { - method: getFetchMethod(args), - url: getFetchUrl(args), - }, - startTimestamp: Date.now(), - }; - triggerHandlers('fetch', __assign({}, handlerData)); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return originalFetch.apply(instrument_global, args).then(function (response) { - triggerHandlers('fetch', __assign(__assign({}, handlerData), { endTimestamp: Date.now(), response: response })); - return response; - }, function (error) { - triggerHandlers('fetch', __assign(__assign({}, handlerData), { endTimestamp: Date.now(), error: error })); - // NOTE: If you are a Sentry user, and you are seeing this stack frame, - // it means the sentry.javascript SDK caught an error invoking your application code. - // This is expected behavior and NOT indicative of a bug with sentry.javascript. - throw error; - }); - }; - }); -} -/* eslint-disable @typescript-eslint/no-unsafe-member-access */ -/** Extract `method` from fetch call arguments */ -function getFetchMethod(fetchArgs) { - if (fetchArgs === void 0) { fetchArgs = []; } - if ('Request' in instrument_global && isInstanceOf(fetchArgs[0], Request) && fetchArgs[0].method) { - return String(fetchArgs[0].method).toUpperCase(); - } - if (fetchArgs[1] && fetchArgs[1].method) { - return String(fetchArgs[1].method).toUpperCase(); - } - return 'GET'; -} -/** Extract `url` from fetch call arguments */ -function getFetchUrl(fetchArgs) { - if (fetchArgs === void 0) { fetchArgs = []; } - if (typeof fetchArgs[0] === 'string') { - return fetchArgs[0]; - } - if ('Request' in instrument_global && isInstanceOf(fetchArgs[0], Request)) { - return fetchArgs[0].url; - } - return String(fetchArgs[0]); -} -/* eslint-enable @typescript-eslint/no-unsafe-member-access */ -/** JSDoc */ -function instrumentXHR() { - if (!('XMLHttpRequest' in instrument_global)) { - return; - } - // Poor man's implementation of ES6 `Map`, tracking and keeping in sync key and value separately. - var requestKeys = []; - var requestValues = []; - var xhrproto = XMLHttpRequest.prototype; - fill(xhrproto, 'open', function (originalOpen) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - // eslint-disable-next-line @typescript-eslint/no-this-alias - var xhr = this; - var url = args[1]; - xhr.__sentry_xhr__ = { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - method: isString(args[0]) ? args[0].toUpperCase() : args[0], - url: args[1], - }; - // if Sentry key appears in URL, don't capture it as a request - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (isString(url) && xhr.__sentry_xhr__.method === 'POST' && url.match(/sentry_key/)) { - xhr.__sentry_own_request__ = true; - } - var onreadystatechangeHandler = function () { - if (xhr.readyState === 4) { - try { - // touching statusCode in some platforms throws - // an exception - if (xhr.__sentry_xhr__) { - xhr.__sentry_xhr__.status_code = xhr.status; - } - } - catch (e) { - /* do nothing */ - } - try { - var requestPos = requestKeys.indexOf(xhr); - if (requestPos !== -1) { - // Make sure to pop both key and value to keep it in sync. - requestKeys.splice(requestPos); - var args_1 = requestValues.splice(requestPos)[0]; - if (xhr.__sentry_xhr__ && args_1[0] !== undefined) { - xhr.__sentry_xhr__.body = args_1[0]; - } - } - } - catch (e) { - /* do nothing */ - } - triggerHandlers('xhr', { - args: args, - endTimestamp: Date.now(), - startTimestamp: Date.now(), - xhr: xhr, - }); - } - }; - if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') { - fill(xhr, 'onreadystatechange', function (original) { - return function () { - var readyStateArgs = []; - for (var _i = 0; _i < arguments.length; _i++) { - readyStateArgs[_i] = arguments[_i]; - } - onreadystatechangeHandler(); - return original.apply(xhr, readyStateArgs); - }; - }); - } - else { - xhr.addEventListener('readystatechange', onreadystatechangeHandler); - } - return originalOpen.apply(xhr, args); - }; - }); - fill(xhrproto, 'send', function (originalSend) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - requestKeys.push(this); - requestValues.push(args); - triggerHandlers('xhr', { - args: args, - startTimestamp: Date.now(), - xhr: this, - }); - return originalSend.apply(this, args); - }; - }); -} -var lastHref; -/** JSDoc */ -function instrumentHistory() { - if (!supportsHistory()) { - return; - } - var oldOnPopState = instrument_global.onpopstate; - instrument_global.onpopstate = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var to = instrument_global.location.href; - // keep track of the current URL state, as we always receive only the updated state - var from = lastHref; - lastHref = to; - triggerHandlers('history', { - from: from, - to: to, - }); - if (oldOnPopState) { - return oldOnPopState.apply(this, args); - } - }; - /** @hidden */ - function historyReplacementFunction(originalHistoryFunction) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var url = args.length > 2 ? args[2] : undefined; - if (url) { - // coerce to string (this is what pushState does) - var from = lastHref; - var to = String(url); - // keep track of the current URL state, as we always receive only the updated state - lastHref = to; - triggerHandlers('history', { - from: from, - to: to, - }); - } - return originalHistoryFunction.apply(this, args); - }; - } - fill(instrument_global.history, 'pushState', historyReplacementFunction); - fill(instrument_global.history, 'replaceState', historyReplacementFunction); -} -/** JSDoc */ -function instrumentDOM() { - if (!('document' in instrument_global)) { - return; - } - // Capture breadcrumbs from any click that is unhandled / bubbled up all the way - // to the document. Do this before we instrument addEventListener. - instrument_global.document.addEventListener('click', domEventHandler('click', triggerHandlers.bind(null, 'dom')), false); - instrument_global.document.addEventListener('keypress', keypressEventHandler(triggerHandlers.bind(null, 'dom')), false); - // After hooking into document bubbled up click and keypresses events, we also hook into user handled click & keypresses. - ['EventTarget', 'Node'].forEach(function (target) { - /* eslint-disable @typescript-eslint/no-unsafe-member-access */ - var proto = instrument_global[target] && instrument_global[target].prototype; - // eslint-disable-next-line no-prototype-builtins - if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) { - return; - } - /* eslint-enable @typescript-eslint/no-unsafe-member-access */ - fill(proto, 'addEventListener', function (original) { - return function (eventName, fn, options) { - if (fn && fn.handleEvent) { - if (eventName === 'click') { - fill(fn, 'handleEvent', function (innerOriginal) { - return function (event) { - domEventHandler('click', triggerHandlers.bind(null, 'dom'))(event); - return innerOriginal.call(this, event); - }; - }); - } - if (eventName === 'keypress') { - fill(fn, 'handleEvent', function (innerOriginal) { - return function (event) { - keypressEventHandler(triggerHandlers.bind(null, 'dom'))(event); - return innerOriginal.call(this, event); - }; - }); - } - } - else { - if (eventName === 'click') { - domEventHandler('click', triggerHandlers.bind(null, 'dom'), true)(this); - } - if (eventName === 'keypress') { - keypressEventHandler(triggerHandlers.bind(null, 'dom'))(this); - } - } - return original.call(this, eventName, fn, options); - }; - }); - fill(proto, 'removeEventListener', function (original) { - return function (eventName, fn, options) { - try { - original.call(this, eventName, fn.__sentry_wrapped__, options); - } - catch (e) { - // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments - } - return original.call(this, eventName, fn, options); - }; - }); - }); -} -var debounceDuration = 1000; -var debounceTimer = 0; -var keypressTimeout; -var lastCapturedEvent; -/** - * Wraps addEventListener to capture UI breadcrumbs - * @param name the event name (e.g. "click") - * @param handler function that will be triggered - * @param debounce decides whether it should wait till another event loop - * @returns wrapped breadcrumb events handler - * @hidden - */ -function domEventHandler(name, handler, debounce) { - if (debounce === void 0) { debounce = false; } - return function (event) { - // reset keypress timeout; e.g. triggering a 'click' after - // a 'keypress' will reset the keypress debounce so that a new - // set of keypresses can be recorded - keypressTimeout = undefined; - // It's possible this handler might trigger multiple times for the same - // event (e.g. event propagation through node ancestors). Ignore if we've - // already captured the event. - if (!event || lastCapturedEvent === event) { - return; - } - lastCapturedEvent = event; - if (debounceTimer) { - clearTimeout(debounceTimer); - } - if (debounce) { - debounceTimer = setTimeout(function () { - handler({ event: event, name: name }); - }); - } - else { - handler({ event: event, name: name }); - } - }; -} -/** - * Wraps addEventListener to capture keypress UI events - * @param handler function that will be triggered - * @returns wrapped keypress events handler - * @hidden - */ -function keypressEventHandler(handler) { - // TODO: if somehow user switches keypress target before - // debounce timeout is triggered, we will only capture - // a single breadcrumb from the FIRST target (acceptable?) - return function (event) { - var target; - try { - target = event.target; - } - catch (e) { - // just accessing event properties can throw an exception in some rare circumstances - // see: https://github.com/getsentry/raven-js/issues/838 - return; - } - var tagName = target && target.tagName; - // only consider keypress events on actual input elements - // this will disregard keypresses targeting body (e.g. tabbing - // through elements, hotkeys, etc) - if (!tagName || (tagName !== 'INPUT' && tagName !== 'TEXTAREA' && !target.isContentEditable)) { - return; - } - // record first keypress in a series, but ignore subsequent - // keypresses until debounce clears - if (!keypressTimeout) { - domEventHandler('input', handler)(event); - } - clearTimeout(keypressTimeout); - keypressTimeout = setTimeout(function () { - keypressTimeout = undefined; - }, debounceDuration); - }; -} -var _oldOnErrorHandler = null; -/** JSDoc */ -function instrumentError() { - _oldOnErrorHandler = instrument_global.onerror; - instrument_global.onerror = function (msg, url, line, column, error) { - triggerHandlers('error', { - column: column, - error: error, - line: line, - msg: msg, - url: url, - }); - if (_oldOnErrorHandler) { - // eslint-disable-next-line prefer-rest-params - return _oldOnErrorHandler.apply(this, arguments); - } - return false; - }; -} -var _oldOnUnhandledRejectionHandler = null; -/** JSDoc */ -function instrumentUnhandledRejection() { - _oldOnUnhandledRejectionHandler = instrument_global.onunhandledrejection; - instrument_global.onunhandledrejection = function (e) { - triggerHandlers('unhandledrejection', e); - if (_oldOnUnhandledRejectionHandler) { - // eslint-disable-next-line prefer-rest-params - return _oldOnUnhandledRejectionHandler.apply(this, arguments); - } - return true; - }; -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/integrations/breadcrumbs.js - -/* eslint-disable @typescript-eslint/no-unsafe-member-access */ -/* eslint-disable max-lines */ - - - -/** - * Default Breadcrumbs instrumentations - * TODO: Deprecated - with v6, this will be renamed to `Instrument` - */ -var Breadcrumbs = /** @class */ (function () { - /** - * @inheritDoc - */ - function Breadcrumbs(options) { - /** - * @inheritDoc - */ - this.name = Breadcrumbs.id; - this._options = __assign({ console: true, dom: true, fetch: true, history: true, sentry: true, xhr: true }, options); - } - /** - * Create a breadcrumb of `sentry` from the events themselves - */ - Breadcrumbs.prototype.addSentryBreadcrumb = function (event) { - if (!this._options.sentry) { - return; - } - getCurrentHub().addBreadcrumb({ - category: "sentry." + (event.type === 'transaction' ? 'transaction' : 'event'), - event_id: event.event_id, - level: event.level, - message: (0,misc/* getEventDescription */.jH)(event), - }, { - event: event, - }); - }; - /** - * Instrument browser built-ins w/ breadcrumb capturing - * - Console API - * - DOM API (click/typing) - * - XMLHttpRequest API - * - Fetch API - * - History API - */ - Breadcrumbs.prototype.setupOnce = function () { - var _this = this; - if (this._options.console) { - addInstrumentationHandler({ - callback: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - _this._consoleBreadcrumb.apply(_this, tslib_es6_spread(args)); - }, - type: 'console', - }); - } - if (this._options.dom) { - addInstrumentationHandler({ - callback: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - _this._domBreadcrumb.apply(_this, tslib_es6_spread(args)); - }, - type: 'dom', - }); - } - if (this._options.xhr) { - addInstrumentationHandler({ - callback: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - _this._xhrBreadcrumb.apply(_this, tslib_es6_spread(args)); - }, - type: 'xhr', - }); - } - if (this._options.fetch) { - addInstrumentationHandler({ - callback: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - _this._fetchBreadcrumb.apply(_this, tslib_es6_spread(args)); - }, - type: 'fetch', - }); - } - if (this._options.history) { - addInstrumentationHandler({ - callback: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - _this._historyBreadcrumb.apply(_this, tslib_es6_spread(args)); - }, - type: 'history', - }); - } - }; - /** - * Creates breadcrumbs from console API calls - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Breadcrumbs.prototype._consoleBreadcrumb = function (handlerData) { - var breadcrumb = { - category: 'console', - data: { - arguments: handlerData.args, - logger: 'console', - }, - level: Severity.fromString(handlerData.level), - message: safeJoin(handlerData.args, ' '), - }; - if (handlerData.level === 'assert') { - if (handlerData.args[0] === false) { - breadcrumb.message = "Assertion failed: " + (safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'); - breadcrumb.data.arguments = handlerData.args.slice(1); - } - else { - // Don't capture a breadcrumb for passed assertions - return; - } - } - getCurrentHub().addBreadcrumb(breadcrumb, { - input: handlerData.args, - level: handlerData.level, - }); - }; - /** - * Creates breadcrumbs from DOM API calls - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Breadcrumbs.prototype._domBreadcrumb = function (handlerData) { - var target; - // Accessing event.target can throw (see getsentry/raven-js#838, #768) - try { - target = handlerData.event.target - ? htmlTreeAsString(handlerData.event.target) - : htmlTreeAsString(handlerData.event); - } - catch (e) { - target = ''; - } - if (target.length === 0) { - return; - } - getCurrentHub().addBreadcrumb({ - category: "ui." + handlerData.name, - message: target, - }, { - event: handlerData.event, - name: handlerData.name, - }); - }; - /** - * Creates breadcrumbs from XHR API calls - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Breadcrumbs.prototype._xhrBreadcrumb = function (handlerData) { - if (handlerData.endTimestamp) { - // We only capture complete, non-sentry requests - if (handlerData.xhr.__sentry_own_request__) { - return; - } - var _a = handlerData.xhr.__sentry_xhr__ || {}, method = _a.method, url = _a.url, status_code = _a.status_code, body = _a.body; - getCurrentHub().addBreadcrumb({ - category: 'xhr', - data: { - method: method, - url: url, - status_code: status_code, - }, - type: 'http', - }, { - xhr: handlerData.xhr, - input: body, - }); - return; - } - }; - /** - * Creates breadcrumbs from fetch API calls - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Breadcrumbs.prototype._fetchBreadcrumb = function (handlerData) { - // We only capture complete fetch requests - if (!handlerData.endTimestamp) { - return; - } - if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') { - // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests) - return; - } - if (handlerData.error) { - getCurrentHub().addBreadcrumb({ - category: 'fetch', - data: handlerData.fetchData, - level: Severity.Error, - type: 'http', - }, { - data: handlerData.error, - input: handlerData.args, - }); - } - else { - getCurrentHub().addBreadcrumb({ - category: 'fetch', - data: __assign(__assign({}, handlerData.fetchData), { status_code: handlerData.response.status }), - type: 'http', - }, { - input: handlerData.args, - response: handlerData.response, - }); - } - }; - /** - * Creates breadcrumbs from history API calls - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Breadcrumbs.prototype._historyBreadcrumb = function (handlerData) { - var global = (0,misc/* getGlobalObject */.Rf)(); - var from = handlerData.from; - var to = handlerData.to; - var parsedLoc = (0,misc/* parseUrl */.en)(global.location.href); - var parsedFrom = (0,misc/* parseUrl */.en)(from); - var parsedTo = (0,misc/* parseUrl */.en)(to); - // Initial pushState doesn't provide `from` information - if (!parsedFrom.path) { - parsedFrom = parsedLoc; - } - // Use only the path component of the URL if the URL matches the current - // document (almost all the time when using pushState) - if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) { - to = parsedTo.relative; - } - if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) { - from = parsedFrom.relative; - } - getCurrentHub().addBreadcrumb({ - category: 'navigation', - data: { - from: from, - to: to, - }, - }); - }; - /** - * @inheritDoc - */ - Breadcrumbs.id = 'Breadcrumbs'; - return Breadcrumbs; -}()); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/version.js -var SDK_NAME = 'sentry.javascript.browser'; -var SDK_VERSION = '5.27.2'; - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/client.js - - - - - - - -/** - * The Sentry Browser SDK Client. - * - * @see BrowserOptions for documentation on configuration options. - * @see SentryClient for usage documentation. - */ -var BrowserClient = /** @class */ (function (_super) { - __extends(BrowserClient, _super); - /** - * Creates a new Browser SDK instance. - * - * @param options Configuration options for this SDK. - */ - function BrowserClient(options) { - if (options === void 0) { options = {}; } - return _super.call(this, BrowserBackend, options) || this; - } - /** - * Show a report dialog to the user to send feedback to a specific event. - * - * @param options Set individual options for the dialog - */ - BrowserClient.prototype.showReportDialog = function (options) { - if (options === void 0) { options = {}; } - // doesn't work without a document (React Native) - var document = (0,misc/* getGlobalObject */.Rf)().document; - if (!document) { - return; - } - if (!this._isEnabled()) { - logger.error('Trying to call showReportDialog with Sentry Client disabled'); - return; - } - injectReportDialog(__assign(__assign({}, options), { dsn: options.dsn || this.getDsn() })); - }; - /** - * @inheritDoc - */ - BrowserClient.prototype._prepareEvent = function (event, scope, hint) { - event.platform = event.platform || 'javascript'; - event.sdk = __assign(__assign({}, event.sdk), { name: SDK_NAME, packages: tslib_es6_spread(((event.sdk && event.sdk.packages) || []), [ - { - name: 'npm:@sentry/browser', - version: SDK_VERSION, - }, - ]), version: SDK_VERSION }); - return _super.prototype._prepareEvent.call(this, event, scope, hint); - }; - /** - * @inheritDoc - */ - BrowserClient.prototype._sendEvent = function (event) { - var integration = this.getIntegration(Breadcrumbs); - if (integration) { - integration.addSentryBreadcrumb(event); - } - _super.prototype._sendEvent.call(this, event); - }; - return BrowserClient; -}(BaseClient)); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/core/esm/sdk.js - - -/** - * Internal function to create a new SDK client instance. The client is - * installed and then bound to the current scope. - * - * @param clientClass The client class to instantiate. - * @param options Options to pass to the client. - */ -function initAndBind(clientClass, options) { - if (options.debug === true) { - logger.enable(); - } - var hub = getCurrentHub(); - var client = new clientClass(options); - hub.bindClient(client); -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/core/esm/integrations/inboundfilters.js - - - -// "Script error." is hard coded into browsers for errors that it can't read. -// this is the result of a script being pulled in from an external domain and CORS. -var DEFAULT_IGNORE_ERRORS = [/^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/]; -/** Inbound filters configurable by the user */ -var InboundFilters = /** @class */ (function () { - function InboundFilters(_options) { - if (_options === void 0) { _options = {}; } - this._options = _options; - /** - * @inheritDoc - */ - this.name = InboundFilters.id; - } - /** - * @inheritDoc - */ - InboundFilters.prototype.setupOnce = function () { - addGlobalEventProcessor(function (event) { - var hub = getCurrentHub(); - if (!hub) { - return event; - } - var self = hub.getIntegration(InboundFilters); - if (self) { - var client = hub.getClient(); - var clientOptions = client ? client.getOptions() : {}; - var options = self._mergeOptions(clientOptions); - if (self._shouldDropEvent(event, options)) { - return null; - } - } - return event; - }); - }; - /** JSDoc */ - InboundFilters.prototype._shouldDropEvent = function (event, options) { - if (this._isSentryError(event, options)) { - logger.warn("Event dropped due to being internal Sentry Error.\nEvent: " + (0,misc/* getEventDescription */.jH)(event)); - return true; - } - if (this._isIgnoredError(event, options)) { - logger.warn("Event dropped due to being matched by `ignoreErrors` option.\nEvent: " + (0,misc/* getEventDescription */.jH)(event)); - return true; - } - if (this._isDeniedUrl(event, options)) { - logger.warn("Event dropped due to being matched by `denyUrls` option.\nEvent: " + (0,misc/* getEventDescription */.jH)(event) + ".\nUrl: " + this._getEventFilterUrl(event)); - return true; - } - if (!this._isAllowedUrl(event, options)) { - logger.warn("Event dropped due to not being matched by `allowUrls` option.\nEvent: " + (0,misc/* getEventDescription */.jH)(event) + ".\nUrl: " + this._getEventFilterUrl(event)); - return true; - } - return false; - }; - /** JSDoc */ - InboundFilters.prototype._isSentryError = function (event, options) { - if (!options.ignoreInternal) { - return false; - } - try { - return ((event && - event.exception && - event.exception.values && - event.exception.values[0] && - event.exception.values[0].type === 'SentryError') || - false); - } - catch (_oO) { - return false; - } - }; - /** JSDoc */ - InboundFilters.prototype._isIgnoredError = function (event, options) { - if (!options.ignoreErrors || !options.ignoreErrors.length) { - return false; - } - return this._getPossibleEventMessages(event).some(function (message) { - // Not sure why TypeScript complains here... - return options.ignoreErrors.some(function (pattern) { return isMatchingPattern(message, pattern); }); - }); - }; - /** JSDoc */ - InboundFilters.prototype._isDeniedUrl = function (event, options) { - // TODO: Use Glob instead? - if (!options.denyUrls || !options.denyUrls.length) { - return false; - } - var url = this._getEventFilterUrl(event); - return !url ? false : options.denyUrls.some(function (pattern) { return isMatchingPattern(url, pattern); }); - }; - /** JSDoc */ - InboundFilters.prototype._isAllowedUrl = function (event, options) { - // TODO: Use Glob instead? - if (!options.allowUrls || !options.allowUrls.length) { - return true; - } - var url = this._getEventFilterUrl(event); - return !url ? true : options.allowUrls.some(function (pattern) { return isMatchingPattern(url, pattern); }); - }; - /** JSDoc */ - InboundFilters.prototype._mergeOptions = function (clientOptions) { - if (clientOptions === void 0) { clientOptions = {}; } - return { - allowUrls: tslib_es6_spread(([]), (this._options.allowUrls || []), ([]), (clientOptions.allowUrls || [])), - denyUrls: tslib_es6_spread(([]), (this._options.denyUrls || []), ([]), (clientOptions.denyUrls || [])), - ignoreErrors: tslib_es6_spread((this._options.ignoreErrors || []), (clientOptions.ignoreErrors || []), DEFAULT_IGNORE_ERRORS), - ignoreInternal: typeof this._options.ignoreInternal !== 'undefined' ? this._options.ignoreInternal : true, - }; - }; - /** JSDoc */ - InboundFilters.prototype._getPossibleEventMessages = function (event) { - if (event.message) { - return [event.message]; - } - if (event.exception) { - try { - var _a = (event.exception.values && event.exception.values[0]) || {}, _b = _a.type, type = _b === void 0 ? '' : _b, _c = _a.value, value = _c === void 0 ? '' : _c; - return ["" + value, type + ": " + value]; - } - catch (oO) { - logger.error("Cannot extract message for event " + (0,misc/* getEventDescription */.jH)(event)); - return []; - } - } - return []; - }; - /** JSDoc */ - InboundFilters.prototype._getEventFilterUrl = function (event) { - try { - if (event.stacktrace) { - var frames_1 = event.stacktrace.frames; - return (frames_1 && frames_1[frames_1.length - 1].filename) || null; - } - if (event.exception) { - var frames_2 = event.exception.values && event.exception.values[0].stacktrace && event.exception.values[0].stacktrace.frames; - return (frames_2 && frames_2[frames_2.length - 1].filename) || null; - } - return null; - } - catch (oO) { - logger.error("Cannot extract url for event " + (0,misc/* getEventDescription */.jH)(event)); - return null; - } - }; - /** - * @inheritDoc - */ - InboundFilters.id = 'InboundFilters'; - return InboundFilters; -}()); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/core/esm/integrations/functiontostring.js -var originalFunctionToString; -/** Patch toString calls to return proper name for wrapped functions */ -var FunctionToString = /** @class */ (function () { - function FunctionToString() { - /** - * @inheritDoc - */ - this.name = FunctionToString.id; - } - /** - * @inheritDoc - */ - FunctionToString.prototype.setupOnce = function () { - // eslint-disable-next-line @typescript-eslint/unbound-method - originalFunctionToString = Function.prototype.toString; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Function.prototype.toString = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var context = this.__sentry_original__ || this; - return originalFunctionToString.apply(context, args); - }; - }; - /** - * @inheritDoc - */ - FunctionToString.id = 'FunctionToString'; - return FunctionToString; -}()); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/integrations/trycatch.js - - - -var DEFAULT_EVENT_TARGET = [ - 'EventTarget', - 'Window', - 'Node', - 'ApplicationCache', - 'AudioTrackList', - 'ChannelMergerNode', - 'CryptoOperation', - 'EventSource', - 'FileReader', - 'HTMLUnknownElement', - 'IDBDatabase', - 'IDBRequest', - 'IDBTransaction', - 'KeyOperation', - 'MediaController', - 'MessagePort', - 'ModalWindow', - 'Notification', - 'SVGElementInstance', - 'Screen', - 'TextTrack', - 'TextTrackCue', - 'TextTrackList', - 'WebSocket', - 'WebSocketWorker', - 'Worker', - 'XMLHttpRequest', - 'XMLHttpRequestEventTarget', - 'XMLHttpRequestUpload', -]; -/** Wrap timer functions and event targets to catch errors and provide better meta data */ -var TryCatch = /** @class */ (function () { - /** - * @inheritDoc - */ - function TryCatch(options) { - /** - * @inheritDoc - */ - this.name = TryCatch.id; - this._options = __assign({ XMLHttpRequest: true, eventTarget: true, requestAnimationFrame: true, setInterval: true, setTimeout: true }, options); - } - /** - * Wrap timer functions and event targets to catch errors - * and provide better metadata. - */ - TryCatch.prototype.setupOnce = function () { - var global = (0,misc/* getGlobalObject */.Rf)(); - if (this._options.setTimeout) { - fill(global, 'setTimeout', this._wrapTimeFunction.bind(this)); - } - if (this._options.setInterval) { - fill(global, 'setInterval', this._wrapTimeFunction.bind(this)); - } - if (this._options.requestAnimationFrame) { - fill(global, 'requestAnimationFrame', this._wrapRAF.bind(this)); - } - if (this._options.XMLHttpRequest && 'XMLHttpRequest' in global) { - fill(XMLHttpRequest.prototype, 'send', this._wrapXHR.bind(this)); - } - if (this._options.eventTarget) { - var eventTarget = Array.isArray(this._options.eventTarget) ? this._options.eventTarget : DEFAULT_EVENT_TARGET; - eventTarget.forEach(this._wrapEventTarget.bind(this)); - } - }; - /** JSDoc */ - TryCatch.prototype._wrapTimeFunction = function (original) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var originalCallback = args[0]; - args[0] = wrap(originalCallback, { - mechanism: { - data: { function: getFunctionName(original) }, - handled: true, - type: 'instrument', - }, - }); - return original.apply(this, args); - }; - }; - /** JSDoc */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - TryCatch.prototype._wrapRAF = function (original) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return function (callback) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return original.call(this, wrap(callback, { - mechanism: { - data: { - function: 'requestAnimationFrame', - handler: getFunctionName(original), - }, - handled: true, - type: 'instrument', - }, - })); - }; - }; - /** JSDoc */ - TryCatch.prototype._wrapEventTarget = function (target) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var global = (0,misc/* getGlobalObject */.Rf)(); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - var proto = global[target] && global[target].prototype; - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) { - return; - } - fill(proto, 'addEventListener', function (original) { - return function (eventName, fn, options) { - try { - if (typeof fn.handleEvent === 'function') { - fn.handleEvent = wrap(fn.handleEvent.bind(fn), { - mechanism: { - data: { - function: 'handleEvent', - handler: getFunctionName(fn), - target: target, - }, - handled: true, - type: 'instrument', - }, - }); - } - } - catch (err) { - // can sometimes get 'Permission denied to access property "handle Event' - } - return original.call(this, eventName, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - wrap(fn, { - mechanism: { - data: { - function: 'addEventListener', - handler: getFunctionName(fn), - target: target, - }, - handled: true, - type: 'instrument', - }, - }), options); - }; - }); - fill(proto, 'removeEventListener', function (original) { - return function (eventName, fn, options) { - /** - * There are 2 possible scenarios here: - * - * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified - * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function - * as a pass-through, and call original `removeEventListener` with it. - * - * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using - * our wrapped version of `addEventListener`, which internally calls `wrap` helper. - * This helper "wraps" whole callback inside a try/catch statement, and attached appropriate metadata to it, - * in order for us to make a distinction between wrapped/non-wrapped functions possible. - * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler. - * - * When someone adds a handler prior to initialization, and then do it again, but after, - * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible - * to get rid of the initial handler and it'd stick there forever. - */ - try { - original.call(this, eventName, fn.__sentry_wrapped__, options); - } - catch (e) { - // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments - } - return original.call(this, eventName, fn, options); - }; - }); - }; - /** JSDoc */ - TryCatch.prototype._wrapXHR = function (originalSend) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - // eslint-disable-next-line @typescript-eslint/no-this-alias - var xhr = this; - var xmlHttpRequestProps = ['onload', 'onerror', 'onprogress', 'onreadystatechange']; - xmlHttpRequestProps.forEach(function (prop) { - if (prop in xhr && typeof xhr[prop] === 'function') { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - fill(xhr, prop, function (original) { - var wrapOptions = { - mechanism: { - data: { - function: prop, - handler: getFunctionName(original), - }, - handled: true, - type: 'instrument', - }, - }; - // If Instrument integration has been called before TryCatch, get the name of original function - if (original.__sentry_original__) { - wrapOptions.mechanism.data.handler = getFunctionName(original.__sentry_original__); - } - // Otherwise wrap directly - return wrap(original, wrapOptions); - }); - } - }); - return originalSend.apply(this, args); - }; - }; - /** - * @inheritDoc - */ - TryCatch.id = 'TryCatch'; - return TryCatch; -}()); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/integrations/globalhandlers.js - -/* eslint-disable @typescript-eslint/no-unsafe-member-access */ - - - - - -/** Global handlers */ -var GlobalHandlers = /** @class */ (function () { - /** JSDoc */ - function GlobalHandlers(options) { - /** - * @inheritDoc - */ - this.name = GlobalHandlers.id; - /** JSDoc */ - this._onErrorHandlerInstalled = false; - /** JSDoc */ - this._onUnhandledRejectionHandlerInstalled = false; - this._options = __assign({ onerror: true, onunhandledrejection: true }, options); - } - /** - * @inheritDoc - */ - GlobalHandlers.prototype.setupOnce = function () { - Error.stackTraceLimit = 50; - if (this._options.onerror) { - logger.log('Global Handler attached: onerror'); - this._installGlobalOnErrorHandler(); - } - if (this._options.onunhandledrejection) { - logger.log('Global Handler attached: onunhandledrejection'); - this._installGlobalOnUnhandledRejectionHandler(); - } - }; - /** JSDoc */ - GlobalHandlers.prototype._installGlobalOnErrorHandler = function () { - var _this = this; - if (this._onErrorHandlerInstalled) { - return; - } - addInstrumentationHandler({ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callback: function (data) { - var error = data.error; - var currentHub = getCurrentHub(); - var hasIntegration = currentHub.getIntegration(GlobalHandlers); - var isFailedOwnDelivery = error && error.__sentry_own_request__ === true; - if (!hasIntegration || shouldIgnoreOnError() || isFailedOwnDelivery) { - return; - } - var client = currentHub.getClient(); - var event = isPrimitive(error) - ? _this._eventFromIncompleteOnError(data.msg, data.url, data.line, data.column) - : _this._enhanceEventWithInitialFrame(eventFromUnknownInput(error, undefined, { - attachStacktrace: client && client.getOptions().attachStacktrace, - rejection: false, - }), data.url, data.line, data.column); - (0,misc/* addExceptionMechanism */.EG)(event, { - handled: false, - type: 'onerror', - }); - currentHub.captureEvent(event, { - originalException: error, - }); - }, - type: 'error', - }); - this._onErrorHandlerInstalled = true; - }; - /** JSDoc */ - GlobalHandlers.prototype._installGlobalOnUnhandledRejectionHandler = function () { - var _this = this; - if (this._onUnhandledRejectionHandlerInstalled) { - return; - } - addInstrumentationHandler({ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callback: function (e) { - var error = e; - // dig the object of the rejection out of known event types - try { - // PromiseRejectionEvents store the object of the rejection under 'reason' - // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent - if ('reason' in e) { - error = e.reason; - } - // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents - // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into - // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec - // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and - // https://github.com/getsentry/sentry-javascript/issues/2380 - else if ('detail' in e && 'reason' in e.detail) { - error = e.detail.reason; - } - } - catch (_oO) { - // no-empty - } - var currentHub = getCurrentHub(); - var hasIntegration = currentHub.getIntegration(GlobalHandlers); - var isFailedOwnDelivery = error && error.__sentry_own_request__ === true; - if (!hasIntegration || shouldIgnoreOnError() || isFailedOwnDelivery) { - return true; - } - var client = currentHub.getClient(); - var event = isPrimitive(error) - ? _this._eventFromIncompleteRejection(error) - : eventFromUnknownInput(error, undefined, { - attachStacktrace: client && client.getOptions().attachStacktrace, - rejection: true, - }); - event.level = Severity.Error; - (0,misc/* addExceptionMechanism */.EG)(event, { - handled: false, - type: 'onunhandledrejection', - }); - currentHub.captureEvent(event, { - originalException: error, - }); - return; - }, - type: 'unhandledrejection', - }); - this._onUnhandledRejectionHandlerInstalled = true; - }; - /** - * This function creates a stack from an old, error-less onerror handler. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - GlobalHandlers.prototype._eventFromIncompleteOnError = function (msg, url, line, column) { - var ERROR_TYPES_RE = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i; - // If 'message' is ErrorEvent, get real message from inside - var message = isErrorEvent(msg) ? msg.message : msg; - var name; - if (isString(message)) { - var groups = message.match(ERROR_TYPES_RE); - if (groups) { - name = groups[1]; - message = groups[2]; - } - } - var event = { - exception: { - values: [ - { - type: name || 'Error', - value: message, - }, - ], - }, - }; - return this._enhanceEventWithInitialFrame(event, url, line, column); - }; - /** - * This function creates an Event from an TraceKitStackTrace that has part of it missing. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - GlobalHandlers.prototype._eventFromIncompleteRejection = function (error) { - return { - exception: { - values: [ - { - type: 'UnhandledRejection', - value: "Non-Error promise rejection captured with value: " + error, - }, - ], - }, - }; - }; - /** JSDoc */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - GlobalHandlers.prototype._enhanceEventWithInitialFrame = function (event, url, line, column) { - event.exception = event.exception || {}; - event.exception.values = event.exception.values || []; - event.exception.values[0] = event.exception.values[0] || {}; - event.exception.values[0].stacktrace = event.exception.values[0].stacktrace || {}; - event.exception.values[0].stacktrace.frames = event.exception.values[0].stacktrace.frames || []; - var colno = isNaN(parseInt(column, 10)) ? undefined : column; - var lineno = isNaN(parseInt(line, 10)) ? undefined : line; - var filename = isString(url) && url.length > 0 ? url : (0,misc/* getLocationHref */.l4)(); - if (event.exception.values[0].stacktrace.frames.length === 0) { - event.exception.values[0].stacktrace.frames.push({ - colno: colno, - filename: filename, - function: '?', - in_app: true, - lineno: lineno, - }); - } - return event; - }; - /** - * @inheritDoc - */ - GlobalHandlers.id = 'GlobalHandlers'; - return GlobalHandlers; -}()); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/integrations/linkederrors.js - - - - - -var DEFAULT_KEY = 'cause'; -var DEFAULT_LIMIT = 5; -/** Adds SDK info to an event. */ -var LinkedErrors = /** @class */ (function () { - /** - * @inheritDoc - */ - function LinkedErrors(options) { - if (options === void 0) { options = {}; } - /** - * @inheritDoc - */ - this.name = LinkedErrors.id; - this._key = options.key || DEFAULT_KEY; - this._limit = options.limit || DEFAULT_LIMIT; - } - /** - * @inheritDoc - */ - LinkedErrors.prototype.setupOnce = function () { - addGlobalEventProcessor(function (event, hint) { - var self = getCurrentHub().getIntegration(LinkedErrors); - if (self) { - return self._handler(event, hint); - } - return event; - }); - }; - /** - * @inheritDoc - */ - LinkedErrors.prototype._handler = function (event, hint) { - if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) { - return event; - } - var linkedErrors = this._walkErrorTree(hint.originalException, this._key); - event.exception.values = tslib_es6_spread(linkedErrors, event.exception.values); - return event; - }; - /** - * @inheritDoc - */ - LinkedErrors.prototype._walkErrorTree = function (error, key, stack) { - if (stack === void 0) { stack = []; } - if (!isInstanceOf(error[key], Error) || stack.length + 1 >= this._limit) { - return stack; - } - var stacktrace = computeStackTrace(error[key]); - var exception = exceptionFromStacktrace(stacktrace); - return this._walkErrorTree(error[key], key, tslib_es6_spread([exception], stack)); - }; - /** - * @inheritDoc - */ - LinkedErrors.id = 'LinkedErrors'; - return LinkedErrors; -}()); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/integrations/useragent.js - - - -var useragent_global = (0,misc/* getGlobalObject */.Rf)(); -/** UserAgent */ -var UserAgent = /** @class */ (function () { - function UserAgent() { - /** - * @inheritDoc - */ - this.name = UserAgent.id; - } - /** - * @inheritDoc - */ - UserAgent.prototype.setupOnce = function () { - addGlobalEventProcessor(function (event) { - var _a, _b, _c; - if (getCurrentHub().getIntegration(UserAgent)) { - // if none of the information we want exists, don't bother - if (!useragent_global.navigator && !useragent_global.location && !useragent_global.document) { - return event; - } - // grab as much info as exists and add it to the event - var url = ((_a = event.request) === null || _a === void 0 ? void 0 : _a.url) || ((_b = useragent_global.location) === null || _b === void 0 ? void 0 : _b.href); - var referrer = (useragent_global.document || {}).referrer; - var userAgent = (useragent_global.navigator || {}).userAgent; - var headers = __assign(__assign(__assign({}, (_c = event.request) === null || _c === void 0 ? void 0 : _c.headers), (referrer && { Referer: referrer })), (userAgent && { 'User-Agent': userAgent })); - var request = __assign(__assign({}, (url && { url: url })), { headers: headers }); - return __assign(__assign({}, event), { request: request }); - } - return event; - }); - }; - /** - * @inheritDoc - */ - UserAgent.id = 'UserAgent'; - return UserAgent; -}()); - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/sdk.js - - - - - -var defaultIntegrations = [ - new InboundFilters(), - new FunctionToString(), - new TryCatch(), - new Breadcrumbs(), - new GlobalHandlers(), - new LinkedErrors(), - new UserAgent(), -]; -/** - * The Sentry Browser SDK Client. - * - * To use this SDK, call the {@link init} function as early as possible when - * loading the web page. To set context information or send manual events, use - * the provided methods. - * - * @example - * - * ``` - * - * import { init } from '@sentry/browser'; - * - * init({ - * dsn: '__DSN__', - * // ... - * }); - * ``` - * - * @example - * ``` - * - * import { configureScope } from '@sentry/browser'; - * configureScope((scope: Scope) => { - * scope.setExtra({ battery: 0.7 }); - * scope.setTag({ user_mode: 'admin' }); - * scope.setUser({ id: '4711' }); - * }); - * ``` - * - * @example - * ``` - * - * import { addBreadcrumb } from '@sentry/browser'; - * addBreadcrumb({ - * message: 'My Breadcrumb', - * // ... - * }); - * ``` - * - * @example - * - * ``` - * - * import * as Sentry from '@sentry/browser'; - * Sentry.captureMessage('Hello, world!'); - * Sentry.captureException(new Error('Good bye')); - * Sentry.captureEvent({ - * message: 'Manual', - * stacktrace: [ - * // ... - * ], - * }); - * ``` - * - * @see {@link BrowserOptions} for documentation on configuration options. - */ -function init(options) { - if (options === void 0) { options = {}; } - if (options.defaultIntegrations === undefined) { - options.defaultIntegrations = defaultIntegrations; - } - if (options.release === undefined) { - var window_1 = (0,misc/* getGlobalObject */.Rf)(); - // This supports the variable that sentry-webpack-plugin injects - if (window_1.SENTRY_RELEASE && window_1.SENTRY_RELEASE.id) { - options.release = window_1.SENTRY_RELEASE.id; - } - } - if (options.autoSessionTracking === undefined) { - options.autoSessionTracking = false; - } - initAndBind(BrowserClient, options); - if (options.autoSessionTracking) { - startSessionTracking(); - } -} -/** - * Present the user with a report dialog. - * - * @param options Everything is optional, we try to fetch all info need from the global scope. - */ -function showReportDialog(options) { - if (options === void 0) { options = {}; } - if (!options.eventId) { - options.eventId = getCurrentHub().lastEventId(); - } - var client = getCurrentHub().getClient(); - if (client) { - client.showReportDialog(options); - } -} -/** - * This is the getter for lastEventId. - * - * @returns The last event id of a captured event. - */ -function lastEventId() { - return getCurrentHub().lastEventId(); -} -/** - * This function is here to be API compatible with the loader. - * @hidden - */ -function forceLoad() { - // Noop -} -/** - * This function is here to be API compatible with the loader. - * @hidden - */ -function onLoad(callback) { - callback(); -} -/** - * A promise that resolves when all current events have been sent. - * If you provide a timeout and the queue takes longer to drain the promise returns false. - * - * @param timeout Maximum time in ms the client should wait. - */ -function flush(timeout) { - var client = getCurrentHub().getClient(); - if (client) { - return client.flush(timeout); - } - return SyncPromise.reject(false); -} -/** - * A promise that resolves when all current events have been sent. - * If you provide a timeout and the queue takes longer to drain the promise returns false. - * - * @param timeout Maximum time in ms the client should wait. - */ -function sdk_close(timeout) { - var client = getCurrentHub().getClient(); - if (client) { - return client.close(timeout); - } - return SyncPromise.reject(false); -} -/** - * Wrap code within a try/catch block so the SDK is able to capture errors. - * - * @param fn A function to wrap. - * - * @returns The result of wrapped function call. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function sdk_wrap(fn) { - return wrap(fn)(); -} -/** - * Enable automatic Session Tracking for the initial page load. - */ -function startSessionTracking() { - var window = (0,misc/* getGlobalObject */.Rf)(); - var hub = getCurrentHub(); - /** - * We should be using `Promise.all([windowLoaded, firstContentfulPaint])` here, - * but, as always, it's not available in the IE10-11. Thanks IE. - */ - var loadResolved = document.readyState === 'complete'; - var fcpResolved = false; - var possiblyEndSession = function () { - if (fcpResolved && loadResolved) { - hub.endSession(); - } - }; - var resolveWindowLoaded = function () { - loadResolved = true; - possiblyEndSession(); - window.removeEventListener('load', resolveWindowLoaded); - }; - hub.startSession(); - if (!loadResolved) { - // IE doesn't support `{ once: true }` for event listeners, so we have to manually - // attach and then detach it once completed. - window.addEventListener('load', resolveWindowLoaded); - } - try { - var po = new PerformanceObserver(function (entryList, po) { - entryList.getEntries().forEach(function (entry) { - if (entry.name === 'first-contentful-paint' && entry.startTime < firstHiddenTime_1) { - po.disconnect(); - fcpResolved = true; - possiblyEndSession(); - } - }); - }); - // There's no need to even attach this listener if `PerformanceObserver` constructor will fail, - // so we do it below here. - var firstHiddenTime_1 = document.visibilityState === 'hidden' ? 0 : Infinity; - document.addEventListener('visibilitychange', function (event) { - firstHiddenTime_1 = Math.min(firstHiddenTime_1, event.timeStamp); - }, { once: true }); - po.observe({ - type: 'paint', - buffered: true, - }); - } - catch (e) { - fcpResolved = true; - possiblyEndSession(); - } -} - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/exports.js - - - - - - - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/core/esm/integrations/index.js - - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/integrations/index.js - - - - - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/transports/index.js - - - - -;// CONCATENATED MODULE: ../../node_modules/@sentry/browser/esm/index.js - - - - - - -var windowIntegrations = {}; -// This block is needed to add compatibility with the integrations packages when used with a CDN -var _window = (0,misc/* getGlobalObject */.Rf)(); -if (_window.Sentry && _window.Sentry.Integrations) { - windowIntegrations = _window.Sentry.Integrations; -} -var INTEGRATIONS = __assign(__assign(__assign({}, windowIntegrations), integrations_namespaceObject), esm_integrations_namespaceObject); - - - -/***/ }), - -/***/ 637: -/*!****************************************************!*\ - !*** ../../node_modules/@sentry/utils/esm/misc.js ***! - \****************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Rf": () => (/* binding */ getGlobalObject), -/* harmony export */ "DM": () => (/* binding */ uuid4), -/* harmony export */ "en": () => (/* binding */ parseUrl), -/* harmony export */ "jH": () => (/* binding */ getEventDescription), -/* harmony export */ "Cf": () => (/* binding */ consoleSandbox), -/* harmony export */ "Db": () => (/* binding */ addExceptionTypeValue), -/* harmony export */ "EG": () => (/* binding */ addExceptionMechanism), -/* harmony export */ "l4": () => (/* binding */ getLocationHref), -/* harmony export */ "JY": () => (/* binding */ parseRetryAfterHeader) -/* harmony export */ }); -/* unused harmony exports parseSemver, addContextToFrame, stripUrlQueryAndFragment */ -/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node */ 4833); - - -var fallbackGlobalObject = {}; -/** - * Safely get global scope object - * - * @returns Global scope object - */ -function getGlobalObject() { - return ((0,_node__WEBPACK_IMPORTED_MODULE_0__/* .isNodeEnv */ .KV)() - ? __webpack_require__.g - : typeof window !== 'undefined' - ? window - : typeof self !== 'undefined' - ? self - : fallbackGlobalObject); -} -/** - * UUID4 generator - * - * @returns string Generated UUID4. - */ -function uuid4() { - var global = getGlobalObject(); - var crypto = global.crypto || global.msCrypto; - if (!(crypto === void 0) && crypto.getRandomValues) { - // Use window.crypto API if available - var arr = new Uint16Array(8); - crypto.getRandomValues(arr); - // set 4 in byte 7 - // eslint-disable-next-line no-bitwise - arr[3] = (arr[3] & 0xfff) | 0x4000; - // set 2 most significant bits of byte 9 to '10' - // eslint-disable-next-line no-bitwise - arr[4] = (arr[4] & 0x3fff) | 0x8000; - var pad = function (num) { - var v = num.toString(16); - while (v.length < 4) { - v = "0" + v; - } - return v; - }; - return (pad(arr[0]) + pad(arr[1]) + pad(arr[2]) + pad(arr[3]) + pad(arr[4]) + pad(arr[5]) + pad(arr[6]) + pad(arr[7])); - } - // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 - return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) { - // eslint-disable-next-line no-bitwise - var r = (Math.random() * 16) | 0; - // eslint-disable-next-line no-bitwise - var v = c === 'x' ? r : (r & 0x3) | 0x8; - return v.toString(16); - }); -} -/** - * Parses string form of URL into an object - * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B - * // intentionally using regex and not href parsing trick because React Native and other - * // environments where DOM might not be available - * @returns parsed URL object - */ -function parseUrl(url) { - if (!url) { - return {}; - } - var match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); - if (!match) { - return {}; - } - // coerce to undefined values to empty string so we don't get 'undefined' - var query = match[6] || ''; - var fragment = match[8] || ''; - return { - host: match[4], - path: match[5], - protocol: match[2], - relative: match[5] + query + fragment, - }; -} -/** - * Extracts either message or type+value from an event that can be used for user-facing logs - * @returns event's description - */ -function getEventDescription(event) { - if (event.message) { - return event.message; - } - if (event.exception && event.exception.values && event.exception.values[0]) { - var exception = event.exception.values[0]; - if (exception.type && exception.value) { - return exception.type + ": " + exception.value; - } - return exception.type || exception.value || event.event_id || ''; - } - return event.event_id || ''; -} -/** JSDoc */ -function consoleSandbox(callback) { - var global = getGlobalObject(); - var levels = ['debug', 'info', 'warn', 'error', 'log', 'assert']; - if (!('console' in global)) { - return callback(); - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - var originalConsole = global.console; - var wrappedLevels = {}; - // Restore all wrapped console methods - levels.forEach(function (level) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (level in global.console && originalConsole[level].__sentry_original__) { - wrappedLevels[level] = originalConsole[level]; - originalConsole[level] = originalConsole[level].__sentry_original__; - } - }); - // Perform callback manipulations - var result = callback(); - // Revert restoration to wrapped state - Object.keys(wrappedLevels).forEach(function (level) { - originalConsole[level] = wrappedLevels[level]; - }); - return result; -} -/** - * Adds exception values, type and value to an synthetic Exception. - * @param event The event to modify. - * @param value Value of the exception. - * @param type Type of the exception. - * @hidden - */ -function addExceptionTypeValue(event, value, type) { - event.exception = event.exception || {}; - event.exception.values = event.exception.values || []; - event.exception.values[0] = event.exception.values[0] || {}; - event.exception.values[0].value = event.exception.values[0].value || value || ''; - event.exception.values[0].type = event.exception.values[0].type || type || 'Error'; -} -/** - * Adds exception mechanism to a given event. - * @param event The event to modify. - * @param mechanism Mechanism of the mechanism. - * @hidden - */ -function addExceptionMechanism(event, mechanism) { - if (mechanism === void 0) { mechanism = {}; } - // TODO: Use real type with `keyof Mechanism` thingy and maybe make it better? - try { - // @ts-ignore Type 'Mechanism | {}' is not assignable to type 'Mechanism | undefined' - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - event.exception.values[0].mechanism = event.exception.values[0].mechanism || {}; - Object.keys(mechanism).forEach(function (key) { - // @ts-ignore Mechanism has no index signature - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - event.exception.values[0].mechanism[key] = mechanism[key]; - }); - } - catch (_oO) { - // no-empty - } -} -/** - * A safe form of location.href - */ -function getLocationHref() { - try { - return document.location.href; - } - catch (oO) { - return ''; - } -} -// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string -var SEMVER_REGEXP = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; -/** - * Parses input into a SemVer interface - * @param input string representation of a semver version - */ -function parseSemver(input) { - var match = input.match(SEMVER_REGEXP) || []; - var major = parseInt(match[1], 10); - var minor = parseInt(match[2], 10); - var patch = parseInt(match[3], 10); - return { - buildmetadata: match[5], - major: isNaN(major) ? undefined : major, - minor: isNaN(minor) ? undefined : minor, - patch: isNaN(patch) ? undefined : patch, - prerelease: match[4], - }; -} -var defaultRetryAfter = 60 * 1000; // 60 seconds -/** - * Extracts Retry-After value from the request header or returns default value - * @param now current unix timestamp - * @param header string representation of 'Retry-After' header - */ -function parseRetryAfterHeader(now, header) { - if (!header) { - return defaultRetryAfter; - } - var headerDelay = parseInt("" + header, 10); - if (!isNaN(headerDelay)) { - return headerDelay * 1000; - } - var headerDate = Date.parse("" + header); - if (!isNaN(headerDate)) { - return headerDate - now; - } - return defaultRetryAfter; -} -/** - * This function adds context (pre/post/line) lines to the provided frame - * - * @param lines string[] containing all lines - * @param frame StackFrame that will be mutated - * @param linesOfContext number of context lines we want to add pre/post - */ -function addContextToFrame(lines, frame, linesOfContext) { - if (linesOfContext === void 0) { linesOfContext = 5; } - var lineno = frame.lineno || 0; - var maxLines = lines.length; - var sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0); - frame.pre_context = lines - .slice(Math.max(0, sourceLine - linesOfContext), sourceLine) - .map(function (line) { return snipLine(line, 0); }); - frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0); - frame.post_context = lines - .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext) - .map(function (line) { return snipLine(line, 0); }); -} -/** - * Strip the query string and fragment off of a given URL or path (if present) - * - * @param urlPath Full URL or path, including possible query string and/or fragment - * @returns URL or path without query string or fragment - */ -function stripUrlQueryAndFragment(urlPath) { - // eslint-disable-next-line no-useless-escape - return urlPath.split(/[\?#]/, 1)[0]; -} - - -/***/ }), - -/***/ 4833: -/*!****************************************************!*\ - !*** ../../node_modules/@sentry/utils/esm/node.js ***! - \****************************************************/ -/***/ ((module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "KV": () => (/* binding */ isNodeEnv), -/* harmony export */ "l$": () => (/* binding */ dynamicRequire) -/* harmony export */ }); -/* unused harmony export extractNodeRequestData */ -/* module decorator */ module = __webpack_require__.hmd(module); - - -/** - * Checks whether we're in the Node.js or Browser environment - * - * @returns Answer to given question - */ -function isNodeEnv() { - return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; -} -/** - * Requires a module which is protected against bundler minification. - * - * @param request The module path to resolve - */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -function dynamicRequire(mod, request) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return mod.require(request); -} -/** Default request keys that'll be used to extract data from the request */ -var DEFAULT_REQUEST_KEYS = (/* unused pure expression or super */ null && (['cookies', 'data', 'headers', 'method', 'query_string', 'url'])); -/** - * Normalizes data from the request object, accounting for framework differences. - * - * @param req The request object from which to extract data - * @param keys An optional array of keys to include in the normalized data. Defaults to DEFAULT_REQUEST_KEYS if not - * provided. - * @returns An object containing normalized request data - */ -function extractNodeRequestData(req, keys) { - if (keys === void 0) { keys = DEFAULT_REQUEST_KEYS; } - // make sure we can safely use dynamicRequire below - if (!isNodeEnv()) { - throw new Error("Can't get node request data outside of a node environment"); - } - var requestData = {}; - // headers: - // node, express: req.headers - // koa: req.header - var headers = (req.headers || req.header || {}); - // method: - // node, express, koa: req.method - var method = req.method; - // host: - // express: req.hostname in > 4 and req.host in < 4 - // koa: req.host - // node: req.headers.host - var host = req.hostname || req.host || headers.host || ''; - // protocol: - // node: - // express, koa: req.protocol - var protocol = req.protocol === 'https' || req.secure || (req.socket || {}).encrypted - ? 'https' - : 'http'; - // url (including path and query string): - // node, express: req.originalUrl - // koa: req.url - var originalUrl = (req.originalUrl || req.url || ''); - // absolute url - var absoluteUrl = protocol + "://" + host + originalUrl; - keys.forEach(function (key) { - switch (key) { - case 'headers': - requestData.headers = headers; - break; - case 'method': - requestData.method = method; - break; - case 'url': - requestData.url = absoluteUrl; - break; - case 'cookies': - // cookies: - // node, express, koa: req.headers.cookie - // vercel, sails.js, express (w/ cookie middleware): req.cookies - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.cookies = req.cookies || dynamicRequire(module, 'cookie').parse(headers.cookie || ''); - break; - case 'query_string': - // query string: - // node: req.url (raw) - // express, koa: req.query - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.query_string = dynamicRequire(module, 'url').parse(originalUrl || '', false).query; - break; - case 'data': - if (method === 'GET' || method === 'HEAD') { - break; - } - // body data: - // node, express, koa: req.body - if (req.body !== undefined) { - requestData.data = isString(req.body) ? req.body : JSON.stringify(normalize(req.body)); - } - break; - default: - if ({}.hasOwnProperty.call(req, key)) { - requestData[key] = req[key]; - } - } - }); - return requestData; -} - - -/***/ }), - -/***/ 5870: -/*!****************************************************!*\ - !*** ../../node_modules/@sentry/utils/esm/time.js ***! - \****************************************************/ -/***/ ((module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "yW": () => (/* binding */ dateTimestampInSeconds) -/* harmony export */ }); -/* unused harmony exports timestampInSeconds, timestampWithMs, usingPerformanceAPI, browserPerformanceTimeOrigin */ -/* harmony import */ var _misc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./misc */ 637); -/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./node */ 4833); -/* module decorator */ module = __webpack_require__.hmd(module); - - -/** - * A TimestampSource implementation for environments that do not support the Performance Web API natively. - * - * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier - * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It - * is more obvious to explain "why does my span have negative duration" than "why my spans have zero duration". - */ -var dateTimestampSource = { - nowSeconds: function () { return Date.now() / 1000; }, -}; -/** - * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not - * support the API. - * - * Wrapping the native API works around differences in behavior from different browsers. - */ -function getBrowserPerformance() { - var performance = (0,_misc__WEBPACK_IMPORTED_MODULE_0__/* .getGlobalObject */ .Rf)().performance; - if (!performance || !performance.now) { - return undefined; - } - // Replace performance.timeOrigin with our own timeOrigin based on Date.now(). - // - // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin + - // performance.now() gives a date arbitrarily in the past. - // - // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is - // undefined. - // - // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to - // interact with data coming out of performance entries. - // - // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that - // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes - // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have - // observed skews that can be as long as days, weeks or months. - // - // See https://github.com/getsentry/sentry-javascript/issues/2590. - // - // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload - // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation - // transactions of long-lived web pages. - var timeOrigin = Date.now() - performance.now(); - return { - now: function () { return performance.now(); }, - timeOrigin: timeOrigin, - }; -} -/** - * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't - * implement the API. - */ -function getNodePerformance() { - try { - var perfHooks = (0,_node__WEBPACK_IMPORTED_MODULE_1__/* .dynamicRequire */ .l$)(module, 'perf_hooks'); - return perfHooks.performance; - } - catch (_) { - return undefined; - } -} -/** - * The Performance API implementation for the current platform, if available. - */ -var platformPerformance = (0,_node__WEBPACK_IMPORTED_MODULE_1__/* .isNodeEnv */ .KV)() ? getNodePerformance() : getBrowserPerformance(); -var timestampSource = platformPerformance === undefined - ? dateTimestampSource - : { - nowSeconds: function () { return (platformPerformance.timeOrigin + platformPerformance.now()) / 1000; }, - }; -/** - * Returns a timestamp in seconds since the UNIX epoch using the Date API. - */ -var dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource); -/** - * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the - * availability of the Performance API. - * - * See `usingPerformanceAPI` to test whether the Performance API is used. - * - * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is - * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The - * skew can grow to arbitrary amounts like days, weeks or months. - * See https://github.com/getsentry/sentry-javascript/issues/2590. - */ -var timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource); -// Re-exported with an old name for backwards-compatibility. -var timestampWithMs = (/* unused pure expression or super */ null && (timestampInSeconds)); -/** - * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps. - */ -var usingPerformanceAPI = platformPerformance !== undefined; -/** - * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the - * performance API is available. - */ -var browserPerformanceTimeOrigin = (function () { - var performance = (0,_misc__WEBPACK_IMPORTED_MODULE_0__/* .getGlobalObject */ .Rf)().performance; - if (!performance) { - return undefined; - } - if (performance.timeOrigin) { - return performance.timeOrigin; - } - // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin - // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing. - // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always - // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the - // Date API. - // eslint-disable-next-line deprecation/deprecation - return (performance.timing && performance.timing.navigationStart) || Date.now(); -})(); - - -/***/ }), - -/***/ 8122: -/*!*******************************************************!*\ - !*** ../../node_modules/fast-deep-equal/es6/index.js ***! - \*******************************************************/ -/***/ ((module) => { - -"use strict"; - - -// do not edit .js files directly - edit src/index.jst - - - var envHasBigInt64Array = typeof BigInt64Array !== 'undefined'; - - -module.exports = function equal(a, b) { - if (a === b) return true; - - if (a && b && typeof a == 'object' && typeof b == 'object') { - if (a.constructor !== b.constructor) return false; - - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) - if (!equal(a[i], b[i])) return false; - return true; - } - - - if ((a instanceof Map) && (b instanceof Map)) { - if (a.size !== b.size) return false; - for (i of a.entries()) - if (!b.has(i[0])) return false; - for (i of a.entries()) - if (!equal(i[1], b.get(i[0]))) return false; - return true; - } - - if ((a instanceof Set) && (b instanceof Set)) { - if (a.size !== b.size) return false; - for (i of a.entries()) - if (!b.has(i[0])) return false; - return true; - } - - if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) - if (a[i] !== b[i]) return false; - return true; - } - - - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - - for (i = length; i-- !== 0;) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - - for (i = length; i-- !== 0;) { - var key = keys[i]; - - if (!equal(a[key], b[key])) return false; - } - - return true; - } - - // true if both NaN, false otherwise - return a!==a && b!==b; -}; - - -/***/ }), - -/***/ 3229: -/*!****************************************!*\ - !*** ../../node_modules/flat/index.js ***! - \****************************************/ -/***/ ((module) => { - -module.exports = flatten -flatten.flatten = flatten -flatten.unflatten = unflatten - -function isBuffer (obj) { - return obj && - obj.constructor && - (typeof obj.constructor.isBuffer === 'function') && - obj.constructor.isBuffer(obj) -} - -function keyIdentity (key) { - return key -} - -function flatten (target, opts) { - opts = opts || {} - - const delimiter = opts.delimiter || '.' - const maxDepth = opts.maxDepth - const transformKey = opts.transformKey || keyIdentity - const output = {} - - function step (object, prev, currentDepth) { - currentDepth = currentDepth || 1 - Object.keys(object).forEach(function (key) { - const value = object[key] - const isarray = opts.safe && Array.isArray(value) - const type = Object.prototype.toString.call(value) - const isbuffer = isBuffer(value) - const isobject = ( - type === '[object Object]' || - type === '[object Array]' - ) - - const newKey = prev - ? prev + delimiter + transformKey(key) - : transformKey(key) - - if (!isarray && !isbuffer && isobject && Object.keys(value).length && - (!opts.maxDepth || currentDepth < maxDepth)) { - return step(value, newKey, currentDepth + 1) - } - - output[newKey] = value - }) - } - - step(target) - - return output -} - -function unflatten (target, opts) { - opts = opts || {} - - const delimiter = opts.delimiter || '.' - const overwrite = opts.overwrite || false - const transformKey = opts.transformKey || keyIdentity - const result = {} - - const isbuffer = isBuffer(target) - if (isbuffer || Object.prototype.toString.call(target) !== '[object Object]') { - return target - } - - // safely ensure that the key is - // an integer. - function getkey (key) { - const parsedKey = Number(key) - - return ( - isNaN(parsedKey) || - key.indexOf('.') !== -1 || - opts.object - ) ? key - : parsedKey - } - - function addKeys (keyPrefix, recipient, target) { - return Object.keys(target).reduce(function (result, key) { - result[keyPrefix + delimiter + key] = target[key] - - return result - }, recipient) - } - - function isEmpty (val) { - const type = Object.prototype.toString.call(val) - const isArray = type === '[object Array]' - const isObject = type === '[object Object]' - - if (!val) { - return true - } else if (isArray) { - return !val.length - } else if (isObject) { - return !Object.keys(val).length - } - } - - target = Object.keys(target).reduce(function (result, key) { - const type = Object.prototype.toString.call(target[key]) - const isObject = (type === '[object Object]' || type === '[object Array]') - if (!isObject || isEmpty(target[key])) { - result[key] = target[key] - return result - } else { - return addKeys( - key, - result, - flatten(target[key], opts) - ) - } - }, {}) - - Object.keys(target).forEach(function (key) { - const split = key.split(delimiter).map(transformKey) - let key1 = getkey(split.shift()) - let key2 = getkey(split[0]) - let recipient = result - - while (key2 !== undefined) { - if (key1 === '__proto__') { - return - } - - const type = Object.prototype.toString.call(recipient[key1]) - const isobject = ( - type === '[object Object]' || - type === '[object Array]' - ) - - // do not write over falsey, non-undefined values if overwrite is false - if (!overwrite && !isobject && typeof recipient[key1] !== 'undefined') { - return - } - - if ((overwrite && !isobject) || (!overwrite && recipient[key1] == null)) { - recipient[key1] = ( - typeof key2 === 'number' && - !opts.object ? [] : {} - ) - } - - recipient = recipient[key1] - if (split.length > 0) { - key1 = getkey(split.shift()) - key2 = getkey(split[0]) - } - } - - // unflatten again for 'messy objects' - recipient[key1] = unflatten(target[key], opts) - }) - - return result -} - - -/***/ }), - -/***/ 4380: -/*!*****************************************************************************!*\ - !*** ../../node_modules/mobx-keystone/dist/mobxkeystone.esm.js + 6 modules ***! - \*****************************************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -// ESM COMPAT FLAG -__webpack_require__.r(__webpack_exports__); - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "ActionContextActionType": () => (/* binding */ ActionContextActionType), - "ActionContextAsyncStepType": () => (/* binding */ ActionContextAsyncStepType), - "ActionTrackingResult": () => (/* binding */ ActionTrackingResult), - "ArraySet": () => (/* binding */ ArraySet), - "ArraySetTypeInfo": () => (/* binding */ ArraySetTypeInfo), - "ArrayTypeInfo": () => (/* binding */ ArrayTypeInfo), - "BaseModel": () => (/* binding */ BaseModel), - "BooleanTypeInfo": () => (/* binding */ BooleanTypeInfo), - "BuiltInAction": () => (/* binding */ BuiltInAction), - "Draft": () => (/* binding */ Draft), - "ExtendedModel": () => (/* binding */ ExtendedModel), - "Frozen": () => (/* binding */ Frozen), - "FrozenCheckMode": () => (/* binding */ FrozenCheckMode), - "FrozenTypeInfo": () => (/* binding */ FrozenTypeInfo), - "HookAction": () => (/* binding */ HookAction), - "InternalPatchRecorder": () => (/* binding */ InternalPatchRecorder), - "LiteralTypeInfo": () => (/* binding */ LiteralTypeInfo), - "MobxKeystoneError": () => (/* binding */ MobxKeystoneError), - "Model": () => (/* binding */ Model), - "ModelAutoTypeCheckingMode": () => (/* binding */ ModelAutoTypeCheckingMode), - "ModelTypeInfo": () => (/* binding */ ModelTypeInfo), - "NumberTypeInfo": () => (/* binding */ NumberTypeInfo), - "ObjectMap": () => (/* binding */ ObjectMap), - "ObjectMapTypeInfo": () => (/* binding */ ObjectMapTypeInfo), - "ObjectTypeInfo": () => (/* binding */ ObjectTypeInfo), - "OrTypeInfo": () => (/* binding */ OrTypeInfo), - "RecordTypeInfo": () => (/* binding */ RecordTypeInfo), - "Ref": () => (/* binding */ Ref), - "RefTypeInfo": () => (/* binding */ RefTypeInfo), - "RefinementTypeInfo": () => (/* binding */ RefinementTypeInfo), - "SandboxManager": () => (/* binding */ SandboxManager), - "StringTypeInfo": () => (/* binding */ StringTypeInfo), - "TupleTypeInfo": () => (/* binding */ TupleTypeInfo), - "TypeCheckError": () => (/* binding */ TypeCheckError), - "TypeInfo": () => (/* binding */ TypeInfo), - "UncheckedTypeInfo": () => (/* binding */ UncheckedTypeInfo), - "UndoManager": () => (/* binding */ UndoManager), - "UndoStore": () => (/* binding */ UndoStore), - "WalkTreeMode": () => (/* binding */ WalkTreeMode), - "_async": () => (/* binding */ _async), - "_await": () => (/* binding */ _await), - "abstractModelClass": () => (/* binding */ abstractModelClass), - "actionCallToReduxAction": () => (/* binding */ actionCallToReduxAction), - "actionTrackingMiddleware": () => (/* binding */ actionTrackingMiddleware), - "addActionMiddleware": () => (/* binding */ addActionMiddleware), - "addActionToFnModel": () => (/* binding */ addActionToFnModel), - "addHiddenProp": () => (/* binding */ addHiddenProp), - "addLateInitializationFunction": () => (/* binding */ addLateInitializationFunction), - "applyAction": () => (/* binding */ applyAction), - "applyDelete": () => (/* binding */ applyDelete), - "applyMethodCall": () => (/* binding */ applyMethodCall), - "applyPatches": () => (/* binding */ applyPatches), - "applySerializedActionAndSyncNewModelIds": () => (/* binding */ applySerializedActionAndSyncNewModelIds), - "applySerializedActionAndTrackNewModelIds": () => (/* binding */ applySerializedActionAndTrackNewModelIds), - "applySet": () => (/* binding */ applySet), - "applySnapshot": () => (/* binding */ applySnapshot), - "arraySet": () => (/* binding */ arraySet), - "asMap": () => (/* binding */ asMap), - "asReduxStore": () => (/* binding */ asReduxStore), - "asSet": () => (/* binding */ asSet), - "assertCanWrite": () => (/* binding */ assertCanWrite), - "assertFnModelKeyNotInUse": () => (/* binding */ assertFnModelKeyNotInUse), - "assertIsFunction": () => (/* binding */ assertIsFunction), - "assertIsMap": () => (/* binding */ assertIsMap), - "assertIsModel": () => (/* binding */ assertIsModel), - "assertIsModelClass": () => (/* binding */ assertIsModelClass), - "assertIsObject": () => (/* binding */ assertIsObject), - "assertIsObservableArray": () => (/* binding */ assertIsObservableArray), - "assertIsObservableObject": () => (/* binding */ assertIsObservableObject), - "assertIsPlainObject": () => (/* binding */ assertIsPlainObject), - "assertIsPrimitive": () => (/* binding */ assertIsPrimitive), - "assertIsSet": () => (/* binding */ assertIsSet), - "assertIsString": () => (/* binding */ assertIsString), - "assertIsTreeNode": () => (/* binding */ assertIsTreeNode), - "assertTweakedObject": () => (/* binding */ assertTweakedObject), - "baseModelPropNames": () => (/* binding */ baseModelPropNames), - "canWrite": () => (/* binding */ canWrite), - "cannotSerialize": () => (/* binding */ cannotSerialize), - "checkModelDecoratorArgs": () => (/* binding */ checkModelDecoratorArgs), - "clone": () => (/* binding */ clone), - "computedWalkTreeAggregate": () => (/* binding */ computedWalkTreeAggregate), - "connectReduxDevTools": () => (/* binding */ connectReduxDevTools), - "createContext": () => (/* binding */ createContext), - "customRef": () => (/* binding */ customRef), - "debugFreeze": () => (/* binding */ debugFreeze), - "decorateWrapMethodOrField": () => (/* binding */ decorateWrapMethodOrField), - "decoratedModel": () => (/* binding */ decoratedModel), - "deepEquals": () => (/* binding */ deepEquals), - "deleteFromArray": () => (/* binding */ deleteFromArray), - "deserializeActionCall": () => (/* binding */ deserializeActionCall), - "deserializeActionCallArgument": () => (/* binding */ deserializeActionCallArgument), - "detach": () => (/* binding */ detach), - "draft": () => (/* binding */ draft), - "extendFnModelActions": () => (/* binding */ extendFnModelActions), - "extendFnModelSetterActions": () => (/* binding */ extendFnModelSetterActions), - "extendFnModelViews": () => (/* binding */ extendFnModelViews), - "failure": () => (/* binding */ failure), - "fastGetParent": () => (/* binding */ fastGetParent), - "fastGetParentIncludingDataObjects": () => (/* binding */ fastGetParentIncludingDataObjects), - "fastGetParentPath": () => (/* binding */ fastGetParentPath), - "fastGetParentPathIncludingDataObjects": () => (/* binding */ fastGetParentPathIncludingDataObjects), - "fastGetRoot": () => (/* binding */ fastGetRoot), - "fastGetRootPath": () => (/* binding */ fastGetRootPath), - "fastGetRootStore": () => (/* binding */ fastGetRootStore), - "fastIsModelDataObject": () => (/* binding */ fastIsModelDataObject), - "fastIsRootStore": () => (/* binding */ fastIsRootStore), - "findParent": () => (/* binding */ findParent), - "findParentPath": () => (/* binding */ findParentPath), - "flow": () => (/* binding */ flow), - "fnArray": () => (/* binding */ fnArray), - "fnModel": () => (/* binding */ fnModel), - "fnObject": () => (/* binding */ fnObject), - "fromSnapshot": () => (/* binding */ fromSnapshot), - "frozen": () => (/* binding */ frozen), - "frozenKey": () => (/* binding */ frozenKey), - "getActionMiddlewares": () => (/* binding */ getActionMiddlewares), - "getActionProtection": () => (/* binding */ getActionProtection), - "getChildrenObjects": () => (/* binding */ getChildrenObjects), - "getCurrentActionContext": () => (/* binding */ getCurrentActionContext), - "getFnModelAction": () => (/* binding */ getFnModelAction), - "getGlobalConfig": () => (/* binding */ getGlobalConfig), - "getMobxVersion": () => (/* binding */ getMobxVersion), - "getModelDataType": () => (/* binding */ getModelDataType), - "getModelRefId": () => (/* binding */ getModelRefId), - "getNodeSandboxManager": () => (/* binding */ getNodeSandboxManager), - "getParent": () => (/* binding */ getParent), - "getParentPath": () => (/* binding */ getParentPath), - "getParentToChildPath": () => (/* binding */ getParentToChildPath), - "getRefsResolvingTo": () => (/* binding */ getRefsResolvingTo), - "getRoot": () => (/* binding */ getRoot), - "getRootPath": () => (/* binding */ getRootPath), - "getRootStore": () => (/* binding */ getRootStore), - "getSnapshot": () => (/* binding */ getSnapshot), - "getTypeInfo": () => (/* binding */ getTypeInfo), - "inDevMode": () => (/* binding */ inDevMode), - "instanceCreationDataTypeSymbol": () => (/* binding */ instanceCreationDataTypeSymbol), - "instanceDataTypeSymbol": () => (/* binding */ instanceDataTypeSymbol), - "internalApplyDelete": () => (/* binding */ internalApplyDelete), - "internalApplyMethodCall": () => (/* binding */ internalApplyMethodCall), - "internalApplyPatches": () => (/* binding */ internalApplyPatches), - "internalCustomRef": () => (/* binding */ internalCustomRef), - "internalPatchRecorder": () => (/* binding */ internalPatchRecorder), - "isArray": () => (/* binding */ isArray), - "isBuiltInAction": () => (/* binding */ isBuiltInAction), - "isChildOfParent": () => (/* binding */ isChildOfParent), - "isFrozenSnapshot": () => (/* binding */ isFrozenSnapshot), - "isHookAction": () => (/* binding */ isHookAction), - "isMap": () => (/* binding */ isMap), - "isModel": () => (/* binding */ isModel), - "isModelAction": () => (/* binding */ isModelAction), - "isModelAutoTypeCheckingEnabled": () => (/* binding */ isModelAutoTypeCheckingEnabled), - "isModelClass": () => (/* binding */ isModelClass), - "isModelDataObject": () => (/* binding */ isModelDataObject), - "isModelFlow": () => (/* binding */ isModelFlow), - "isModelSnapshot": () => (/* binding */ isModelSnapshot), - "isObject": () => (/* binding */ isObject), - "isParentOfChild": () => (/* binding */ isParentOfChild), - "isPlainObject": () => (/* binding */ isPlainObject), - "isPrimitive": () => (/* binding */ isPrimitive), - "isRefOfType": () => (/* binding */ isRefOfType), - "isReservedModelKey": () => (/* binding */ isReservedModelKey), - "isRoot": () => (/* binding */ isRoot), - "isRootStore": () => (/* binding */ isRootStore), - "isSandboxedNode": () => (/* binding */ isSandboxedNode), - "isSet": () => (/* binding */ isSet), - "isTreeNode": () => (/* binding */ isTreeNode), - "isTweakedObject": () => (/* binding */ isTweakedObject), - "jsonPatchToPatch": () => (/* binding */ jsonPatchToPatch), - "jsonPointerToPath": () => (/* binding */ jsonPointerToPath), - "lateVal": () => (/* binding */ lateVal), - "lazy": () => (/* binding */ lazy), - "logWarning": () => (/* binding */ logWarning), - "makePropReadonly": () => (/* binding */ makePropReadonly), - "mapToArray": () => (/* binding */ mapToArray), - "mapToObject": () => (/* binding */ mapToObject), - "model": () => (/* binding */ model), - "modelAction": () => (/* binding */ modelAction), - "modelClass": () => (/* binding */ modelClass), - "modelFlow": () => (/* binding */ modelFlow), - "modelIdKey": () => (/* binding */ modelIdKey), - "modelInitializedSymbol": () => (/* binding */ modelInitializedSymbol), - "modelSnapshotInWithMetadata": () => (/* binding */ modelSnapshotInWithMetadata), - "modelSnapshotOutWithMetadata": () => (/* binding */ modelSnapshotOutWithMetadata), - "modelTypeKey": () => (/* binding */ modelTypeKey), - "noDefaultValue": () => (/* binding */ noDefaultValue), - "objectMap": () => (/* binding */ objectMap), - "onActionMiddleware": () => (/* binding */ onActionMiddleware), - "onChildAttachedTo": () => (/* binding */ onChildAttachedTo), - "onGlobalPatches": () => (/* binding */ onGlobalPatches), - "onPatches": () => (/* binding */ onPatches), - "onSnapshot": () => (/* binding */ onSnapshot), - "patchRecorder": () => (/* binding */ patchRecorder), - "patchToJsonPatch": () => (/* binding */ patchToJsonPatch), - "pathToJsonPointer": () => (/* binding */ pathToJsonPointer), - "prop": () => (/* binding */ prop), - "propTransform": () => (/* binding */ propTransform), - "prop_dateString": () => (/* binding */ prop_dateString), - "prop_dateTimestamp": () => (/* binding */ prop_dateTimestamp), - "prop_mapArray": () => (/* binding */ prop_mapArray), - "prop_mapObject": () => (/* binding */ prop_mapObject), - "prop_setArray": () => (/* binding */ prop_setArray), - "propsCreationDataTypeSymbol": () => (/* binding */ propsCreationDataTypeSymbol), - "propsDataTypeSymbol": () => (/* binding */ propsDataTypeSymbol), - "readonlyMiddleware": () => (/* binding */ readonlyMiddleware), - "reduxActionType": () => (/* binding */ reduxActionType), - "registerActionCallArgumentSerializer": () => (/* binding */ registerActionCallArgumentSerializer), - "registerRootStore": () => (/* binding */ registerRootStore), - "resolvePath": () => (/* binding */ resolvePath), - "resolvePathCheckingIds": () => (/* binding */ resolvePathCheckingIds), - "rootRef": () => (/* binding */ rootRef), - "runLateInitializationFunctions": () => (/* binding */ runLateInitializationFunctions), - "runUnprotected": () => (/* binding */ runUnprotected), - "runWithoutSnapshotOrPatches": () => (/* binding */ runWithoutSnapshotOrPatches), - "runningWithoutSnapshotOrPatches": () => (/* binding */ runningWithoutSnapshotOrPatches), - "sandbox": () => (/* binding */ sandbox), - "serializeActionCall": () => (/* binding */ serializeActionCall), - "serializeActionCallArgument": () => (/* binding */ serializeActionCallArgument), - "setCurrentActionContext": () => (/* binding */ setCurrentActionContext), - "setGlobalConfig": () => (/* binding */ setGlobalConfig), - "setToArray": () => (/* binding */ setToArray), - "simplifyActionContext": () => (/* binding */ simplifyActionContext), - "skipIdChecking": () => (/* binding */ skipIdChecking), - "stringAsDate": () => (/* binding */ stringAsDate), - "tProp": () => (/* binding */ tProp), - "tProp_dateString": () => (/* binding */ tProp_dateString), - "tProp_dateTimestamp": () => (/* binding */ tProp_dateTimestamp), - "tProp_mapArray": () => (/* binding */ tProp_mapArray), - "tProp_mapObject": () => (/* binding */ tProp_mapObject), - "tProp_setArray": () => (/* binding */ tProp_setArray), - "tag": () => (/* binding */ tag), - "timestampAsDate": () => (/* binding */ timestampAsDate), - "toTreeNode": () => (/* binding */ toTreeNode), - "transaction": () => (/* binding */ transaction), - "transactionMiddleware": () => (/* binding */ transactionMiddleware), - "tryUntweak": () => (/* binding */ tryUntweak), - "tweak": () => (/* binding */ tweak), - "tweakedObjects": () => (/* binding */ tweakedObjects), - "typeCheck": () => (/* binding */ typeCheck), - "types": () => (/* binding */ types), - "undoMiddleware": () => (/* binding */ undoMiddleware), - "unregisterRootStore": () => (/* binding */ unregisterRootStore), - "walkTree": () => (/* binding */ walkTree), - "withoutUndo": () => (/* binding */ withoutUndo) -}); - -// EXTERNAL MODULE: ../../node_modules/mobx/dist/mobx.esm.js -var mobx_esm = __webpack_require__(5412); -;// CONCATENATED MODULE: ../../node_modules/mobx-keystone/node_modules/uuid/dist/esm-browser/rng.js -// Unique ID creation requires a high quality random # generator. In the browser we therefore -// require the crypto API and do not support built-in fallback to lower quality random number -// generators (like Math.random()). -// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, -// find the complete implementation of crypto (msCrypto) on IE11. -var getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto); -var rnds8 = new Uint8Array(16); -function rng() { - if (!getRandomValues) { - throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); - } - - return getRandomValues(rnds8); -} -;// CONCATENATED MODULE: ../../node_modules/mobx-keystone/node_modules/uuid/dist/esm-browser/regex.js -/* harmony default export */ const regex = (/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i); -;// CONCATENATED MODULE: ../../node_modules/mobx-keystone/node_modules/uuid/dist/esm-browser/validate.js - - -function validate(uuid) { - return typeof uuid === 'string' && regex.test(uuid); -} - -/* harmony default export */ const esm_browser_validate = (validate); -;// CONCATENATED MODULE: ../../node_modules/mobx-keystone/node_modules/uuid/dist/esm-browser/stringify.js - -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ - -var byteToHex = []; - -for (var i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).substr(1)); -} - -function stringify(arr) { - var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields - - if (!esm_browser_validate(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - - return uuid; -} - -/* harmony default export */ const esm_browser_stringify = (stringify); -;// CONCATENATED MODULE: ../../node_modules/mobx-keystone/node_modules/uuid/dist/esm-browser/v4.js - - - -function v4(options, buf, offset) { - options = options || {}; - var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided - - if (buf) { - offset = offset || 0; - - for (var i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } - - return buf; - } - - return esm_browser_stringify(rnds); -} - -/* harmony default export */ const esm_browser_v4 = (v4); -;// CONCATENATED MODULE: ../../node_modules/mobx-keystone/node_modules/tslib/tslib.es6.js -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -var __assign = function() { - __assign = Object.assign || function __assign(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); -} - -function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -} - -function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} - -function __param(paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } -} - -function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} - -function __awaiter(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()); - }); -} - -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -var __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -}); - -function __exportStar(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); -} - -function __values(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."); -} - -function __read(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; -} - -function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; -} - -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -}; - -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} - -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -} - -function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } -} - -function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } -} - -function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; -}; - -var __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}; - -function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -} - -function __importDefault(mod) { - return (mod && mod.__esModule) ? mod : { default: mod }; -} - -function __classPrivateFieldGet(receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); -} - -function __classPrivateFieldSet(receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; -} - -// EXTERNAL MODULE: ../../node_modules/fast-deep-equal/es6/index.js -var es6 = __webpack_require__(8122); -var es6_default = /*#__PURE__*/__webpack_require__.n(es6); -;// CONCATENATED MODULE: ../../node_modules/mobx-keystone/dist/mobxkeystone.esm.js - - - - - -/** - * Action type, sync or async. - */ -var ActionContextActionType; - -(function (ActionContextActionType) { - ActionContextActionType["Sync"] = "sync"; - ActionContextActionType["Async"] = "async"; -})(ActionContextActionType || (ActionContextActionType = {})); -/** - * An async step type. - */ - - -var ActionContextAsyncStepType; - -(function (ActionContextAsyncStepType) { - /** - * The flow is about to start. - */ - ActionContextAsyncStepType["Spawn"] = "spawn"; - /** - * The flow is about to return (finish). - */ - - ActionContextAsyncStepType["Return"] = "return"; - /** - * The flow is about to continue. - */ - - ActionContextAsyncStepType["Resume"] = "resume"; - /** - * The flow yield just threw, which might be recovered (caught) or not. - */ - - ActionContextAsyncStepType["ResumeError"] = "resumeError"; - /** - * The flow is about to throw an error to the flow caller. - */ - - ActionContextAsyncStepType["Throw"] = "throw"; -})(ActionContextAsyncStepType || (ActionContextAsyncStepType = {})); - -var currentActionContext; -/** - * Gets the currently running action context, or undefined if none. - * - * @returns - */ - -function getCurrentActionContext() { - return currentActionContext; -} -/** - * @ignore - * @internal - * - * Sets the current action context. - * - * @param ctx Current action context. - */ - -function setCurrentActionContext(ctx) { - currentActionContext = ctx; -} - -function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } -} - -function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; -} - -function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); -} - -function _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = superClass; -} - -function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); -} - -function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - - return _setPrototypeOf(o, p); -} - -function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - - try { - Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); - return true; - } catch (e) { - return false; - } -} - -function _construct(Parent, args, Class) { - if (_isNativeReflectConstruct()) { - _construct = Reflect.construct; - } else { - _construct = function _construct(Parent, args, Class) { - var a = [null]; - a.push.apply(a, args); - var Constructor = Function.bind.apply(Parent, a); - var instance = new Constructor(); - if (Class) _setPrototypeOf(instance, Class.prototype); - return instance; - }; - } - - return _construct.apply(null, arguments); -} - -function _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; -} - -function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); -} - -function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return self; -} - -function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); -} - -function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - - return arr2; -} - -function _createForOfIteratorHelperLoose(o, allowArrayLike) { - var it; - - if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { - if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { - if (it) o = it; - var i = 0; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); -} - -/** - * A mobx-keystone error. - */ - -var MobxKeystoneError = /*#__PURE__*/function (_Error) { - _inheritsLoose(MobxKeystoneError, _Error); - - function MobxKeystoneError(msg) { - var _this; - - _this = _Error.call(this, msg) || this; // Set the prototype explicitly. - - Object.setPrototypeOf(_assertThisInitialized(_this), MobxKeystoneError.prototype); - return _this; - } - - return MobxKeystoneError; -}( /*#__PURE__*/_wrapNativeSuper(Error)); -/** - * @ignore - * @internal - */ - -function failure(msg) { - return new MobxKeystoneError(msg); -} -var writableHiddenPropDescriptor = { - enumerable: false, - writable: true, - configurable: false, - value: undefined -}; -/** - * @ignore - * @internal - */ - -function addHiddenProp(object, propName, value, writable) { - if (writable === void 0) { - writable = true; - } - - if (writable) { - Object.defineProperty(object, propName, writableHiddenPropDescriptor); - object[propName] = value; - } else { - Object.defineProperty(object, propName, { - enumerable: false, - writable: writable, - configurable: true, - value: value - }); - } -} -/** - * @ignore - * @internal - */ - -function makePropReadonly(object, propName, enumerable) { - var propDesc = Object.getOwnPropertyDescriptor(object, propName); - - if (propDesc) { - propDesc.enumerable = enumerable; - - if (propDesc.get) { - delete propDesc.set; - } else { - propDesc.writable = false; - } - - Object.defineProperty(object, propName, propDesc); - } -} -/** - * @ignore - * @internal - */ - -function isPlainObject(value) { - if (!isObject(value)) return false; - var proto = Object.getPrototypeOf(value); - return proto === Object.prototype || proto === null; -} -/** - * @ignore - * @internal - */ - -function isObject(value) { - return value !== null && typeof value === "object"; -} -/** - * @ignore - * @internal - */ - -function isPrimitive(value) { - switch (typeof value) { - case "number": - case "string": - case "boolean": - case "undefined": - case "bigint": - return true; - } - - return value === null; -} -/** - * @ignore - * @internal - */ - -function debugFreeze(value) { - if (inDevMode()) { - Object.freeze(value); - } -} -/** - * @ignore - * @internal - */ - -function deleteFromArray(array, value) { - var index = array.indexOf(value); - - if (index >= 0) { - array.splice(index, 1); - return true; - } - - return false; -} -/** - * @ignore - * @internal - */ - -function isMap(val) { - return val instanceof Map || (0,mobx_esm.isObservableMap)(val); -} -/** - * @ignore - * @internal - */ - -function isSet(val) { - return val instanceof Set || (0,mobx_esm.isObservableSet)(val); -} -/** - * @ignore - * @internal - */ - -function isArray(val) { - return Array.isArray(val) || (0,mobx_esm.isObservableArray)(val); -} -/** - * @ignore - * @internal - */ - -function inDevMode() { - return "production" !== "production"; -} -/** - * @ignore - * @internal - */ - -function assertIsObject(value, argName) { - if (!isObject(value)) { - throw failure(argName + " must be an object"); - } -} -/** - * @ignore - * @internal - */ - -function assertIsPlainObject(value, argName) { - if (!isPlainObject(value)) { - throw failure(argName + " must be a plain object"); - } -} -/** - * @ignore - * @internal - */ - -function assertIsObservableObject(value, argName) { - if (!(0,mobx_esm.isObservableObject)(value)) { - throw failure(argName + " must be an observable object"); - } -} -/** - * @ignore - * @internal - */ - -function assertIsObservableArray(value, argName) { - if (!(0,mobx_esm.isObservableArray)(value)) { - throw failure(argName + " must be an observable array"); - } -} -/** - * @ignore - * @internal - */ - -function assertIsMap(value, argName) { - if (!isMap(value)) { - throw failure(argName + " must be a map"); - } -} -/** - * @ignore - * @internal - */ - -function assertIsSet(value, argName) { - if (!isSet(value)) { - throw failure(argName + " must be a set"); - } -} -/** - * @ignore - * @internal - */ - -function assertIsFunction(value, argName) { - if (typeof value !== "function") { - throw failure(argName + " must be a function"); - } -} -/** - * @ignore - * @internal - */ - -function assertIsPrimitive(value, argName) { - if (!isPrimitive(value)) { - throw failure(argName + " must be a primitive"); - } -} -/** - * @ignore - * @internal - */ - -function assertIsString(value, argName) { - if (typeof value !== "string") { - throw failure(argName + " must be a string"); - } -} -var decoratorsSymbol = /*#__PURE__*/Symbol("decorators"); -/** - * @ignore - * @internal - */ - -function addLateInitializationFunction(target, fn) { - var decoratorsArray = target[decoratorsSymbol]; - - if (!decoratorsArray) { - decoratorsArray = []; - addHiddenProp(target, decoratorsSymbol, decoratorsArray); - } - - decoratorsArray.push(fn); -} -/** - * @ignore - * @internal - */ - -function decorateWrapMethodOrField(decoratorName, data, wrap) { - var target = data.target, - propertyKey = data.propertyKey, - baseDescriptor = data.baseDescriptor; - - var addFieldDecorator = function addFieldDecorator() { - addLateInitializationFunction(target, function (instance) { - instance[propertyKey] = wrap(data, instance[propertyKey]); - }); - }; - - if (baseDescriptor) { - if (baseDescriptor.get !== undefined) { - throw failure("@" + decoratorName + " cannot be used with getters"); - } - - if (baseDescriptor.value) { - // babel / typescript - method decorator - // @action method() { } - return { - enumerable: false, - writable: true, - configurable: true, - value: wrap(data, baseDescriptor.value) - }; - } else { - // babel - field decorator: @action method = () => {} - addFieldDecorator(); - } - } else { - // typescript - field decorator - addFieldDecorator(); - } -} -/** - * @ignore - * @internal - */ - -function runLateInitializationFunctions(instance) { - var fns = instance[decoratorsSymbol]; - - if (fns) { - for (var _iterator = _createForOfIteratorHelperLoose(fns), _step; !(_step = _iterator()).done;) { - var fn = _step.value; - fn(instance); - } - } -} -var warningsAlreadyDisplayed = /*#__PURE__*/new Set(); -/** - * @ignore - * @internal - */ - -function logWarning(type, msg, uniqueKey) { - if (uniqueKey) { - if (warningsAlreadyDisplayed.has(uniqueKey)) { - return; - } - - warningsAlreadyDisplayed.add(uniqueKey); - } - - msg = "[mobx-keystone] " + msg; - - switch (type) { - case "warn": - console.warn(msg); - break; - - case "error": - console.error(msg); - break; - - default: - throw failure("unknown log type - " + type); - } -} -var notMemoized = /*#__PURE__*/Symbol("notMemoized"); -/** - * @ignore - * @internal - */ - -function lateVal(getter) { - var memoized = notMemoized; - - var fn = function fn() { - if (memoized === notMemoized) { - memoized = getter.apply(void 0, arguments); - } - - return memoized; - }; - - return fn; -} -/** - * @ignore - * @internal - */ - -function lazy(valueGen) { - var inited = false; - var val; - return function () { - if (!inited) { - val = valueGen(); - inited = true; - } - - return val; - }; -} -/** - * @ignore - * @internal - */ - -function getMobxVersion() { - if (mobx_esm.makeObservable) { - return 6; - } else { - return 5; - } -} - -var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; -function toBase64(input) { - if (typeof __webpack_require__.g === "object" && typeof __webpack_require__.g.Buffer === "function") { - // node - return Buffer.from(input).toString("base64"); - } - - if (typeof btoa === "function") { - // browser - return btoa(input); - } - - var str = String(input); - var output = ""; - - for ( // initialize result and counter - var block = 0, charCode, idx = 0, map = chars; // if the next str index does not exist: - // change the mapping table to "=" - // check if d has no fractional digits - str.charAt(idx | 0) || (map = "=", idx % 1); // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8 - output += map.charAt(63 & block >> 8 - idx % 1 * 8)) { - charCode = str.charCodeAt(idx += 3 / 4); - - if (charCode > 0xff) { - throw new Error("the string to be encoded contains characters outside of the Latin1 range."); - } - - block = block << 8 | charCode; - } - - return output; -} - -/** - * Model auto type-checking mode. - */ - -var ModelAutoTypeCheckingMode; - -(function (ModelAutoTypeCheckingMode) { - /** - * Auto type check models only in dev mode - */ - ModelAutoTypeCheckingMode["DevModeOnly"] = "devModeOnly"; - /** - * Auto type check models no matter the current environment - */ - - ModelAutoTypeCheckingMode["AlwaysOn"] = "alwaysOn"; - /** - * Do not auto type check models no matter the current environment - */ - - ModelAutoTypeCheckingMode["AlwaysOff"] = "alwaysOff"; -})(ModelAutoTypeCheckingMode || (ModelAutoTypeCheckingMode = {})); - -var localId = 0; -var localBaseId = /*#__PURE__*/shortenUuid( /*#__PURE__*/esm_browser_v4()); - -function defaultModelIdGenerator() { - // we use base 36 for local id since it is short and fast - var id = localId.toString(36) + "-" + localBaseId; - localId++; - return id; -} // defaults - - -var globalConfig = { - modelAutoTypeChecking: ModelAutoTypeCheckingMode.DevModeOnly, - modelIdGenerator: defaultModelIdGenerator, - allowUndefinedArrayElements: false -}; -/** - * Partially sets the current global config. - * - * @param config Partial object with the new configurations. Options not included in the object won't be changed. - */ - -function setGlobalConfig(config) { - globalConfig = Object.freeze(_extends({}, globalConfig, config)); -} -/** - * Returns the current global config object. - * - * @returns - */ - -function getGlobalConfig() { - return globalConfig; -} -/** - * @ignore - * @internal - * - * Returns if the auto type checking for models is enabled. - * - * @returns - */ - -function isModelAutoTypeCheckingEnabled() { - switch (getGlobalConfig().modelAutoTypeChecking) { - case ModelAutoTypeCheckingMode.DevModeOnly: - return inDevMode(); - - case ModelAutoTypeCheckingMode.AlwaysOff: - return false; - - case ModelAutoTypeCheckingMode.AlwaysOn: - return true; - - default: - throw failure("invalid 'modelAutoTypeChecking' config value - " + globalConfig.modelAutoTypeChecking); - } -} - -function shortenUuid(uuid) { - // remove non-hex chars - var hex = uuid.split("-").join(""); // convert to base64 - - var hexMatch = hex.match(/\w{2}/g); - var str = String.fromCharCode.apply(null, hexMatch.map(function (a) { - return parseInt(a, 16); - })); - return toBase64(str); -} - -/** - * @ignore - */ - -var noDefaultValue = /*#__PURE__*/Symbol("noDefaultValue"); -function prop(arg1, arg2) { - var def; - var opts = {}; - var hasDefaultValue = false; - - if (arguments.length >= 2) { - // default, options - def = arg1; - hasDefaultValue = true; - opts = _extends({}, arg2); - } else if (arguments.length === 1) { - // default | options - if (isObject(arg1)) { - // options - opts = _extends({}, arg1); - } else { - // default - def = arg1; - hasDefaultValue = true; - } - } - - var isDefFn = typeof def === "function"; - return { - $propValueType: null, - $propCreationValueType: null, - $isOptional: null, - $instanceValueType: null, - $instanceCreationValueType: null, - defaultFn: hasDefaultValue && isDefFn ? def : noDefaultValue, - defaultValue: hasDefaultValue && !isDefFn ? def : noDefaultValue, - typeChecker: undefined, - transform: undefined, - options: opts - }; -} - -/** - * Creates a prop transform, useful to transform property data into another kind of data. - * - * For example, to transform from a number timestamp into a date: - * ```ts - * const asDate = propTransform({ - * propToData(prop: number) { - * return new Date(prop) - * }, - * dataToProp(data: Date) { - * return +data - * } - * }) - * - * @model("myApp/MyModel") - * class MyModel extends Model({ - * timestamp: prop() - * }) { - * @asDate("timestamp") - * date!: Date - * } - * - * const date: Date = myModel.date - * // inside some model action - * myModel.date = new Date() - * ``` - * - * @typename TProp Property value type. - * @typename TData Data value type. - * @param transform Transform to apply. - * @returns A decorator that can be used to decorate model class fields. - */ - -function propTransform(transform) { - var parametrizedDecorator = function parametrizedDecorator(boundPropName) { - var decorator = function decorator(target, propertyKey) { - addLateInitializationFunction(target, function (instance) { - // make the field a getter setter - Object.defineProperty(instance, propertyKey, { - get: function get() { - var memoTransform = memoTransformCache.getOrCreateMemoTransform(this, propertyKey, transform); - return memoTransform.propToData(this.$[boundPropName]); - }, - set: function set(value) { - var memoTransform = memoTransformCache.getOrCreateMemoTransform(this, propertyKey, transform); - this.$[boundPropName] = memoTransform.dataToProp(value); - return true; - } - }); - }); - }; - - return decorator; - }; - - parametrizedDecorator.propToData = transform.propToData.bind(transform); - parametrizedDecorator.dataToProp = transform.dataToProp.bind(transform); - return parametrizedDecorator; -} - -var MemoTransformCache = /*#__PURE__*/function () { - function MemoTransformCache() { - this.cache = new WeakMap(); - } - - var _proto = MemoTransformCache.prototype; - - _proto.getOrCreateMemoTransform = function getOrCreateMemoTransform(target, propName, baseTransform) { - var transformsPerProperty = this.cache.get(target); - - if (!transformsPerProperty) { - transformsPerProperty = new Map(); - this.cache.set(target, transformsPerProperty); - } - - var memoTransform = transformsPerProperty.get(propName); - - if (!memoTransform) { - memoTransform = toMemoPropTransform(baseTransform, function (newPropValue) { - target.$[propName] = newPropValue; - }); - transformsPerProperty.set(propName, memoTransform); - } - - return memoTransform; - }; - - return MemoTransformCache; -}(); -/** - * @ignore - * @internal - */ - - -var memoTransformCache = /*#__PURE__*/new MemoTransformCache(); -var valueNotMemoized = /*#__PURE__*/Symbol("valueNotMemoized"); - -function toMemoPropTransform(transform, propSetter) { - var lastPropValue = valueNotMemoized; - var lastDataValue = valueNotMemoized; - return { - isMemoPropTransform: true, - propToData: function propToData(propValue) { - if (lastPropValue !== propValue) { - lastDataValue = transform.propToData(propValue, propSetter); - lastPropValue = propValue; - } - - return lastDataValue; - }, - dataToProp: function dataToProp(newDataValue) { - // clear caches in this case - lastPropValue = valueNotMemoized; - lastDataValue = valueNotMemoized; - return transform.dataToProp(newDataValue); - } - }; -} -/** - * @ignore - * @internal - */ - - -function transformedProp(prop, transform, transformDefault) { - if (prop.transform) { - throw failure("a property cannot have more than one transform"); - } - - var p = _extends({}, prop, { - transform: transform - }); // transform defaults if needed - - - if (transformDefault) { - if (p.defaultValue !== noDefaultValue) { - var originalDefaultValue = p.defaultValue; - p.defaultValue = transform.dataToProp(originalDefaultValue); - } - - if (p.defaultFn !== noDefaultValue) { - var originalDefaultFn = p.defaultFn; - - p.defaultFn = function () { - return transform.dataToProp(originalDefaultFn()); - }; - } - } - - return p; -} - -/** - * @ignore - */ - -var objectParents = /*#__PURE__*/new WeakMap(); -/** - * @ignore - */ - -var objectParentsAtoms = /*#__PURE__*/new WeakMap(); -/** - * @ignore - */ - -function parentPathEquals(parentPath1, parentPath2, comparePath) { - if (comparePath === void 0) { - comparePath = true; - } - - if (!parentPath1 && !parentPath2) return true; - if (!parentPath1 || !parentPath2) return false; - var parentEquals = parentPath1.parent === parentPath2.parent; - if (!parentEquals) return false; - return comparePath ? parentPath1.path === parentPath2.path : true; -} - -function createParentPathAtom(obj) { - var atom = objectParentsAtoms.get(obj); - - if (!atom) { - atom = (0,mobx_esm.createAtom)("parentAtom"); - objectParentsAtoms.set(obj, atom); - } - - return atom; -} -/** - * @ignore - */ - - -function reportParentPathObserved(node) { - createParentPathAtom(node).reportObserved(); -} -/** - * @ignore - */ - -function reportParentPathChanged(node) { - createParentPathAtom(node).reportChanged(); -} -/** - * @ignore - */ - -var dataObjectParent = /*#__PURE__*/new WeakMap(); -/** - * @ignore - */ - -function dataToModelNode(node) { - var modelNode = dataObjectParent.get(node); - return modelNode != null ? modelNode : node; -} -/** - * @ignore - */ - -function modelToDataNode(node) { - return isModel(node) ? node.$ : node; -} - -/** - * @ignore - * @internal - */ - -var tweakedObjects = /*#__PURE__*/new WeakMap(); -/** - * @ignore - * @internal - */ - -function isTweakedObject(value, canBeDataObject) { - if (!canBeDataObject && dataObjectParent.has(value)) { - return false; - } - - return tweakedObjects.has(value); -} -/** - * Checks if a given object is now a tree node. - * - * @param value Value to check. - * @returns true if it is a tree node, false otherwise. - */ - -function isTreeNode(value) { - return !isPrimitive(value) && isTweakedObject(value, false); -} -/** - * @ignore - * @internal - */ - -function assertTweakedObject(treeNode, argName, canBeDataObject) { - if (canBeDataObject === void 0) { - canBeDataObject = false; - } - - if (!canBeDataObject && dataObjectParent.has(treeNode)) { - throw failure(argName + " must be the model object instance instead of the '$' sub-object"); - } - - if (isPrimitive(treeNode) || !isTweakedObject(treeNode, true)) { - throw failure(argName + " must be a tree node (usually a model or a shallow / deep child part of a model 'data' object)"); - } -} -/** - * Asserts a given object is now a tree node, or throws otherwise. - * - * @param value Value to check. - * @param argName Argument name, part of the thrown error description. - */ - -function assertIsTreeNode(value, argName) { - if (argName === void 0) { - argName = "argument"; - } - - assertTweakedObject(value, argName, false); -} -/** - * @ignore - * @internal - */ - -var runningWithoutSnapshotOrPatches = false; -/** - * @ignore - * @internal - */ - -function runWithoutSnapshotOrPatches(fn) { - var old = runningWithoutSnapshotOrPatches; - runningWithoutSnapshotOrPatches = true; - - try { - (0,mobx_esm.runInAction)(function () { - fn(); - }); - } finally { - runningWithoutSnapshotOrPatches = old; - } -} - -/** - * Key where model snapshots will store model type metadata. - */ -var modelTypeKey = "$modelType"; -/** - * Key where model snapshots will store model internal IDs metadata. - */ - -var modelIdKey = "$modelId"; -/** - * @internal - * Returns if a given key is a reserved key in model snapshots. - * - * @param key - * @returns - */ - -function isReservedModelKey(key) { - return key === modelTypeKey || key === modelIdKey; -} - -var defaultObservableSetOptions = { - deep: false -}; -var objectChildren = /*#__PURE__*/new WeakMap(); -/** - * @ignore - * @internal - */ - -function initializeObjectChildren(node) { - if (objectChildren.has(node)) { - return; - } - - objectChildren.set(node, { - shallow: mobx_esm.observable.set(undefined, defaultObservableSetOptions), - deep: new Set(), - deepByModelTypeAndId: new Map(), - deepDirty: true, - deepAtom: (0,mobx_esm.createAtom)("deepChildrenAtom") - }); -} -/** - * @ignore - * @internal - */ - -function getObjectChildren(node) { - return objectChildren.get(node).shallow; -} -/** - * @ignore - * @internal - */ - -function getDeepObjectChildren(node) { - var obj = objectChildren.get(node); - - if (obj.deepDirty) { - updateDeepObjectChildren(node); - } - - obj.deepAtom.reportObserved(); - return { - deep: obj.deep, - deepByModelTypeAndId: obj.deepByModelTypeAndId - }; -} - -function addNodeToDeepLists(node, deep, deepByModelTypeAndId) { - deep.add(node); - - if (isModel(node)) { - deepByModelTypeAndId.set(byModelTypeAndIdKey(node[modelTypeKey], node[modelIdKey]), node); - } -} - -var updateDeepObjectChildren = /*#__PURE__*/(0,mobx_esm.action)(function (node) { - var obj = objectChildren.get(node); - - if (!obj.deepDirty) { - return { - deep: obj.deep, - deepByModelTypeAndId: obj.deepByModelTypeAndId - }; - } - - var deep = new Set(); - var deepByModelTypeAndId = new Map(); - var childrenIter = getObjectChildren(node).values(); - var ch = childrenIter.next(); - - while (!ch.done) { - addNodeToDeepLists(ch.value, deep, deepByModelTypeAndId); - var ret = updateDeepObjectChildren(ch.value).deep; - var retIter = ret.values(); - var retCur = retIter.next(); - - while (!retCur.done) { - addNodeToDeepLists(retCur.value, deep, deepByModelTypeAndId); - retCur = retIter.next(); - } - - ch = childrenIter.next(); - } - - obj.deep = deep; - obj.deepByModelTypeAndId = deepByModelTypeAndId; - obj.deepDirty = false; - obj.deepAtom.reportChanged(); - return { - deep: deep, - deepByModelTypeAndId: deepByModelTypeAndId - }; -}); -/** - * @ignore - * @internal - */ - -var addObjectChild = /*#__PURE__*/(0,mobx_esm.action)(function (node, child) { - var obj = objectChildren.get(node); - obj.shallow.add(child); - invalidateDeepChildren(node); -}); -/** - * @ignore - * @internal - */ - -var removeObjectChild = /*#__PURE__*/(0,mobx_esm.action)(function (node, child) { - var obj = objectChildren.get(node); - obj.shallow["delete"](child); - invalidateDeepChildren(node); -}); - -function invalidateDeepChildren(node) { - var obj = objectChildren.get(node); - - if (!obj.deepDirty) { - obj.deepDirty = true; - obj.deepAtom.reportChanged(); - } - - var parent = fastGetParent(node); - - if (parent) { - invalidateDeepChildren(parent); - } -} -/** - * @ignore - * @internal - */ - - -function byModelTypeAndIdKey(modelType, modelId) { - return modelType + " " + modelId; -} - -/** - * Returns the parent of the target plus the path from the parent to the target, or undefined if it has no parent. - * - * @typeparam T Parent object type. - * @param value Target object. - * @returns - */ - -function getParentPath(value) { - assertTweakedObject(value, "value"); - return fastGetParentPath(value); -} -/** - * @ignore - * @internal - */ - -function fastGetParentPath(value) { - reportParentPathObserved(value); - return objectParents.get(value); -} -/** - * @ignore - * @internal - */ - -function fastGetParentPathIncludingDataObjects(value) { - var parentModel = dataObjectParent.get(value); - - if (parentModel) { - return { - parent: parentModel, - path: "$" - }; - } - - var parentPath = fastGetParentPath(value); - - if (parentPath && isModel(parentPath.parent)) { - return { - parent: parentPath.parent.$, - path: parentPath.path - }; - } - - return parentPath; -} -/** - * Returns the parent object of the target object, or undefined if there's no parent. - * - * @typeparam T Parent object type. - * @param value Target object. - * @returns - */ - -function getParent(value) { - assertTweakedObject(value, "value"); - return fastGetParent(value); -} -/** - * @ignore - * @internal - */ - -function fastGetParent(value) { - var parentPath = fastGetParentPath(value); - return parentPath ? parentPath.parent : undefined; -} -/** - * @ignore - * @internal - */ - -function fastGetParentIncludingDataObjects(value) { - var parentPath = fastGetParentPathIncludingDataObjects(value); - return parentPath ? parentPath.parent : undefined; -} -/** - * Returns if a given object is a model interim data object (`$`). - * - * @param value Object to check. - * @returns true if it is, false otherwise. - */ - -function isModelDataObject(value) { - assertTweakedObject(value, "value", true); - return fastIsModelDataObject(value); -} -/** - * @ignore - * @internal - */ - -function fastIsModelDataObject(value) { - return dataObjectParent.has(value); -} -/** - * Returns the root of the target plus the path from the root to get to the target. - * - * @typeparam T Root object type. - * @param value Target object. - * @returns - */ - -function getRootPath(value) { - assertTweakedObject(value, "value"); - return fastGetRootPath(value); -} // we use computeds so they are cached whenever possible - -var computedsGetRootPath = /*#__PURE__*/new WeakMap(); - -function internalGetRootPath(value) { - var rootPath = { - root: value, - path: [], - pathObjects: [value] - }; - var parentPath; - - while (parentPath = fastGetParentPath(rootPath.root)) { - rootPath.root = parentPath.parent; - rootPath.path.unshift(parentPath.path); - rootPath.pathObjects.unshift(parentPath.parent); - } - - return rootPath; -} -/** - * @ignore - * @internal - */ - - -function fastGetRootPath(value) { - var computedGetRootPathForNode = computedsGetRootPath.get(value); - - if (!computedGetRootPathForNode) { - computedGetRootPathForNode = (0,mobx_esm.computed)(function () { - return internalGetRootPath(value); - }); - computedsGetRootPath.set(value, computedGetRootPathForNode); - } - - return computedGetRootPathForNode.get(); -} -/** - * Returns the root of the target object, or itself if the target is a root. - * - * @typeparam T Root object type. - * @param value Target object. - * @returns - */ - -function getRoot(value) { - assertTweakedObject(value, "value"); - return fastGetRoot(value); -} -/** - * @ignore - * @internal - */ - -function fastGetRoot(value) { - return fastGetRootPath(value).root; -} -/** - * Returns if a given object is a root object. - * - * @param value Target object. - * @returns - */ - -function isRoot(value) { - assertTweakedObject(value, "value"); - return !fastGetParent(value); -} -/** - * Returns if the target is a "child" of the tree of the given "parent" object. - * - * @param child Target object. - * @param parent Parent object. - * @returns - */ - -function isChildOfParent(child, parent) { - assertTweakedObject(child, "child"); - assertTweakedObject(parent, "parent"); - return getDeepObjectChildren(parent).deep.has(child); -} -/** - * Returns if the target is a "parent" that has in its tree the given "child" object. - * - * @param parent Target object. - * @param child Child object. - * @returns - */ - -function isParentOfChild(parent, child) { - return isChildOfParent(child, parent); -} -var unresolved = { - resolved: false -}; -/** - * Tries to resolve a path from an object. - * - * @typeparam T Returned value type. - * @param pathRootObject Object that serves as path root. - * @param path Path as an string or number array. - * @returns An object with `{ resolved: true, value: T }` or `{ resolved: false }`. - */ - -function resolvePath(pathRootObject, path) { - // unit tests rely on this to work with any object - // assertTweakedObject(pathRootObject, "pathRootObject") - var current = modelToDataNode(pathRootObject); - var len = path.length; - - for (var i = 0; i < len; i++) { - if (!isObject(current)) { - return unresolved; - } - - var p = path[i]; // check just to avoid mobx warnings about trying to access out of bounds index - - if (isArray(current) && +p >= current.length) { - return unresolved; - } - - current = modelToDataNode(current[p]); - } - - return { - resolved: true, - value: dataToModelNode(current) - }; -} -/** - * @ignore - */ - -var skipIdChecking = /*#__PURE__*/Symbol("skipIdChecking"); -/** - * @ignore - * - * Tries to resolve a path from an object while checking ids. - * - * @typeparam T Returned value type. - * @param pathRootObject Object that serves as path root. - * @param path Path as an string or number array. - * @param pathIds An array of ids of the models that must be checked, null if not a model or `skipIdChecking` to skip it. - * @returns An object with `{ resolved: true, value: T }` or `{ resolved: false }`. - */ - -function resolvePathCheckingIds(pathRootObject, path, pathIds) { - // unit tests rely on this to work with any object - // assertTweakedObject(pathRootObject, "pathRootObject") - var current = modelToDataNode(pathRootObject); // root id is never checked - - var len = path.length; - - for (var i = 0; i < len; i++) { - if (!isObject(current)) { - return { - resolved: false - }; - } - - var p = path[i]; // check just to avoid mobx warnings about trying to access out of bounds index - - if (isArray(current) && +p >= current.length) { - return { - resolved: false - }; - } - - var currentMaybeModel = current[p]; - current = modelToDataNode(currentMaybeModel); - var expectedId = pathIds[i]; - - if (expectedId !== skipIdChecking) { - var currentId = isModel(currentMaybeModel) ? currentMaybeModel[modelIdKey] : null; - - if (expectedId !== currentId) { - return { - resolved: false - }; - } - } - } - - return { - resolved: true, - value: dataToModelNode(current) - }; -} -/** - * Gets the path to get from a parent to a given child. - * Returns an empty array if the child is actually the given parent or undefined if the child is not a child of the parent. - * - * @param fromParent - * @param toChild - * @returns - */ - -function getParentToChildPath(fromParent, toChild) { - assertTweakedObject(fromParent, "fromParent"); - assertTweakedObject(toChild, "toChild"); - - if (fromParent === toChild) { - return []; - } - - var path = []; - var current = toChild; - var parentPath; - - while (parentPath = fastGetParentPath(current)) { - path.unshift(parentPath.path); - current = parentPath.parent; - - if (current === fromParent) { - return path; - } - } - - return undefined; -} - -var snapshots = /*#__PURE__*/new WeakMap(); -/** - * @ignore - * @internal - */ - -function getInternalSnapshot(value) { - return snapshots.get(value); -} - -function getInternalSnapshotParent(sn, parentPath) { - return (0,mobx_esm.untracked)(function () { - if (!parentPath) { - return undefined; - } - - var parentSn = getInternalSnapshot(parentPath.parent); - - if (!parentSn) { - return undefined; - } - - return sn ? { - parentSnapshot: parentSn, - parentPath: parentPath - } : undefined; - }); -} -/** - * @ignore - * @internal - */ - - -var unsetInternalSnapshot = /*#__PURE__*/(0,mobx_esm.action)("unsetInternalSnapshot", function (value) { - var oldSn = getInternalSnapshot(value); - - if (oldSn) { - snapshots["delete"](value); - oldSn.atom.reportChanged(); - } -}); -/** - * @ignore - * @internal - */ - -var setInternalSnapshot = /*#__PURE__*/(0,mobx_esm.action)("setInternalSnapshot", function (value, standard) { - var oldSn = getInternalSnapshot(value); // do not actually update if not needed - - if (oldSn && oldSn.standard === standard) { - return; - } - - debugFreeze(standard); - var sn; - - if (oldSn) { - sn = oldSn; - sn.standard = standard; - } else { - sn = { - standard: standard, - atom: (0,mobx_esm.createAtom)("snapshot") - }; - snapshots.set(value, sn); - } - - sn.atom.reportChanged(); // also update parent(s) snapshot(s) if needed - - var parent = getInternalSnapshotParent(oldSn, fastGetParentPath(value)); - - if (parent) { - var parentSnapshot = parent.parentSnapshot, - parentPath = parent.parentPath; // might be false in the cases where the parent has not yet been created - - if (parentSnapshot) { - var path = parentPath.path; // patches for parent changes should not be emitted - - var parentStandardSn = parentSnapshot.standard; - - if (parentStandardSn[path] !== sn.standard) { - if (Array.isArray(parentStandardSn)) { - parentStandardSn = parentStandardSn.slice(); - } else { - parentStandardSn = Object.assign({}, parentStandardSn); - } - - parentStandardSn[path] = sn.standard; - setInternalSnapshot(parentPath.parent, parentStandardSn); - } - } - } -}); -/** - * @ignore - */ - -function reportInternalSnapshotObserved(sn) { - sn.atom.reportObserved(); -} - -/** - * Retrieves an immutable snapshot for a data structure. - * Since returned snapshots are immutable they will respect shallow equality, this is, - * if no changes are made then the snapshot will be kept the same. - * - * @typeparam T Object type. - * @param nodeOrPrimitive Data structure, including primtives. - * @returns The snapshot. - */ - -function getSnapshot(nodeOrPrimitive) { - if (isPrimitive(nodeOrPrimitive)) { - return nodeOrPrimitive; - } - - assertTweakedObject(nodeOrPrimitive, "nodeOrPrimitive"); - var snapshot = getInternalSnapshot(nodeOrPrimitive); - - if (!snapshot) { - throw failure("getSnapshot is not supported for this kind of object"); - } - - reportInternalSnapshotObserved(snapshot); - return snapshot.standard; -} - -var modelDataTypeCheckerSymbol = /*#__PURE__*/Symbol("modelDataTypeChecker"); -var modelUnwrappedClassSymbol = /*#__PURE__*/Symbol("modelUnwrappedClass"); - -/** - * Returns the associated data type for run-time checking (if any) to a model instance or class. - * - * @param modelClassOrInstance Model class or instance. - * @returns The associated data type, or undefined if none. - */ - -function getModelDataType(modelClassOrInstance) { - if (isModel(modelClassOrInstance)) { - return modelClassOrInstance.constructor[modelDataTypeCheckerSymbol]; - } else if (isModelClass(modelClassOrInstance)) { - return modelClassOrInstance[modelDataTypeCheckerSymbol]; - } else { - throw failure("modelClassOrInstance must be a model class or instance"); - } -} - -/** - * @ignore - */ - -var modelInfoByName = {}; -/** - * @ignore - */ - -var modelInfoByClass = /*#__PURE__*/new Map(); -/** - * @ignore - */ - -function getModelInfoForName(name) { - return modelInfoByName[name]; -} - -var modelPropertiesSymbol = /*#__PURE__*/Symbol("modelProperties"); -/** - * @ignore - * @internal - * - * Gets the info related to a model class properties. - * - * @param modelClass - */ - -function getInternalModelClassPropsInfo(modelClass) { - return modelClass[modelPropertiesSymbol]; -} -/** - * @ignore - * @internal - * - * Sets the info related to a model class properties. - * - * @param modelClass - */ - -function setInternalModelClassPropsInfo(modelClass, props) { - modelClass[modelPropertiesSymbol] = props; -} - -/** - * A type checking error. - */ - -var TypeCheckError = /*#__PURE__*/function () { - /** - * Creates an instance of TypeError. - * @param path Sub-path where the error occured. - * @param expectedTypeName Name of the expected type. - * @param actualValue Actual value. - */ - function TypeCheckError(path, expectedTypeName, actualValue) { - this.path = void 0; - this.expectedTypeName = void 0; - this.actualValue = void 0; - this.path = path; - this.expectedTypeName = expectedTypeName; - this.actualValue = actualValue; - } - /** - * Throws the type check error as an actual error. - * - * @param typeCheckedValue Usually the value where the type check was invoked. - */ - - - var _proto = TypeCheckError.prototype; - - _proto["throw"] = function _throw(typeCheckedValue) { - var msg = "TypeCheckError: "; - var rootPath = []; - - if (isTweakedObject(typeCheckedValue, true)) { - rootPath = getRootPath(typeCheckedValue).path; - } - - msg += "[/" + [].concat(rootPath, this.path).join("/") + "] "; - msg += "Expected: " + this.expectedTypeName; - throw failure(msg); - }; - - return TypeCheckError; -}(); - -var emptyPath = []; -var typeCheckersWithCachedResultsOfObject = /*#__PURE__*/new WeakMap(); -/** - * @ignore - */ - -function invalidateCachedTypeCheckerResult(obj) { - // we need to invalidate it for the object and all its parents - var current = obj; - - while (current) { - var set = typeCheckersWithCachedResultsOfObject.get(current); - - if (set) { - for (var _iterator = _createForOfIteratorHelperLoose(set), _step; !(_step = _iterator()).done;) { - var typeChecker = _step.value; - typeChecker.invalidateCachedResult(current); - } - - typeCheckersWithCachedResultsOfObject["delete"](current); - } - - current = fastGetParentIncludingDataObjects(current); - } -} -/** - * @ignore - */ - -var TypeChecker = /*#__PURE__*/function () { - var _proto = TypeChecker.prototype; - - _proto.createCacheIfNeeded = function createCacheIfNeeded() { - if (!this.checkResultCache) { - this.checkResultCache = new WeakMap(); - } - - return this.checkResultCache; - }; - - _proto.setCachedResult = function setCachedResult(obj, newCacheValue) { - this.createCacheIfNeeded().set(obj, newCacheValue); // register this type checker as listener of that object changes - - var typeCheckerSet = typeCheckersWithCachedResultsOfObject.get(obj); - - if (!typeCheckerSet) { - typeCheckerSet = new Set(); - typeCheckersWithCachedResultsOfObject.set(obj, typeCheckerSet); - } - - typeCheckerSet.add(this); - }; - - _proto.invalidateCachedResult = function invalidateCachedResult(obj) { - if (this.checkResultCache) { - this.checkResultCache["delete"](obj); - } - }; - - _proto.getCachedResult = function getCachedResult(obj) { - return this.checkResultCache ? this.checkResultCache.get(obj) : undefined; - }; - - _proto.check = function check(value, path) { - if (this.unchecked) { - return null; - } - - if (!isTweakedObject(value, true)) { - return this._check(value, path); - } // optimized checking with cached values - - - var cachedResult = this.getCachedResult(value); - - if (cachedResult === undefined) { - // we set the path empty since the resoult could be used for another paths other than this base - cachedResult = this._check(value, emptyPath); - this.setCachedResult(value, cachedResult); - } - - if (cachedResult) { - return new TypeCheckError([].concat(path, cachedResult.path), cachedResult.expectedTypeName, cachedResult.actualValue); - } else { - return null; - } - }; - - _createClass(TypeChecker, [{ - key: "typeInfo", - get: function get() { - return this._cachedTypeInfoGen(this); - } - }]); - - function TypeChecker(_check, getTypeName, typeInfoGen) { - this._check = void 0; - this.getTypeName = void 0; - this.checkResultCache = void 0; - this.unchecked = void 0; - this._cachedTypeInfoGen = void 0; - this._check = _check; - this.getTypeName = getTypeName; - this.unchecked = !_check; - this._cachedTypeInfoGen = lateVal(typeInfoGen); - } - - return TypeChecker; -}(); -var lateTypeCheckerSymbol = /*#__PURE__*/Symbol("lateTypeCheker"); -/** - * @ignore - */ - -function lateTypeChecker(fn, typeInfoGen) { - var cached; - - var ltc = function ltc() { - if (cached) { - return cached; - } - - cached = fn(); - return cached; - }; - - ltc[lateTypeCheckerSymbol] = true; - var cachedTypeInfoGen = lateVal(typeInfoGen); - Object.defineProperty(ltc, "typeInfo", { - enumerable: true, - configurable: true, - get: function get() { - return cachedTypeInfoGen(ltc); - } - }); - return ltc; -} -/** - * @ignore - */ - -function isLateTypeChecker(ltc) { - return typeof ltc === "function" && ltc[lateTypeCheckerSymbol]; -} -/** - * Type info base class. - */ - -var TypeInfo = function TypeInfo(thisType) { - this.thisType = void 0; - this.thisType = thisType; -}; -/** - * Gets the type info of a given type. - * - * @param type Type to get the info from. - * @returns The type info. - */ - -function getTypeInfo(type) { - var stdType = resolveStandardType(type); - var typeInfo = stdType.typeInfo; - - if (!typeInfo) { - throw failure("type info not found for " + type); - } - - return typeInfo; -} - -/** - * A refinement over a given type. This allows you to do extra checks - * over models, ensure numbers are integers, etc. - * - * Example: - * ```ts - * const integerType = types.refinement(types.number, (n) => { - * return Number.isInteger(n) - * }, "integer") - * - * const sumModelType = types.refinement(types.model(Sum), (sum) => { - * // imagine that for some reason sum includes a number 'a', a number 'b' - * // and the result - * - * const rightResult = sum.a + sum.b === sum.result - * - * // simple mode that will just return that the whole model is incorrect - * return rightResult - * - * // this will return that the result field is wrong - * return rightResult ? null : new TypeCheckError(["result"], "a+b", sum.result) - * }) - * ``` - * - * @template T Base type. - * @param baseType Base type. - * @param checkFn Function that will receive the data (if it passes the base type - * check) and return null or false if there were no errors or either a TypeCheckError instance or - * true if there were. - * @returns - */ - -function typesRefinement(baseType, checkFn, typeName) { - var typeInfoGen = function typeInfoGen(t) { - return new RefinementTypeInfo(t, resolveStandardType(baseType), checkFn, typeName); - }; - - return lateTypeChecker(function () { - var baseChecker = resolveTypeChecker(baseType); - - var getTypeName = function getTypeName() { - for (var _len = arguments.length, recursiveTypeCheckers = new Array(_len), _key = 0; _key < _len; _key++) { - recursiveTypeCheckers[_key] = arguments[_key]; - } - - var baseTypeName = baseChecker.getTypeName.apply(baseChecker, recursiveTypeCheckers.concat([baseChecker])); - var refinementName = typeName || "refinementOf"; - return refinementName + "<" + baseTypeName + ">"; - }; - - var thisTc = new TypeChecker(function (data, path) { - var baseErr = baseChecker.check(data, path); - - if (baseErr) { - return baseErr; - } - - var refinementErr = checkFn(data); - - if (refinementErr === true) { - return null; - } else if (refinementErr === false) { - return new TypeCheckError([], getTypeName(thisTc), data); - } else { - return refinementErr != null ? refinementErr : null; - } - }, getTypeName, typeInfoGen); - return thisTc; - }, typeInfoGen); -} -/** - * `types.refinement` type info. - */ - -var RefinementTypeInfo = /*#__PURE__*/function (_TypeInfo) { - _inheritsLoose(RefinementTypeInfo, _TypeInfo); - - _createClass(RefinementTypeInfo, [{ - key: "baseTypeInfo", - get: function get() { - return getTypeInfo(this.baseType); - } - }]); - - function RefinementTypeInfo(thisType, baseType, checkFunction, typeName) { - var _this; - - _this = _TypeInfo.call(this, thisType) || this; - _this.baseType = void 0; - _this.checkFunction = void 0; - _this.typeName = void 0; - _this.baseType = baseType; - _this.checkFunction = checkFunction; - _this.typeName = typeName; - return _this; - } - - return RefinementTypeInfo; -}(TypeInfo); - -/** - * A type that represents a certain value of a primitive (for example an *exact* number or string). - * - * Example - * ```ts - * const hiType = types.literal("hi") // the string with value "hi" - * const number5Type = types.literal(5) // the number with value 5 - * ``` - * - * @typeparam T Literal value type. - * @param literal Literal value. - * @returns - */ - -function typesLiteral(literal) { - assertIsPrimitive(literal, "literal"); - var typeName; - - switch (literal) { - case undefined: - typeName = "undefined"; - break; - - case null: - typeName = "null"; - break; - - default: - typeName = JSON.stringify(literal); - break; - } - - var typeInfoGen = function typeInfoGen(t) { - return new LiteralTypeInfo(t, literal); - }; - - return new TypeChecker(function (value, path) { - return value === literal ? null : new TypeCheckError(path, typeName, value); - }, function () { - return typeName; - }, typeInfoGen); -} -/** - * `types.literal` type info. - */ - -var LiteralTypeInfo = /*#__PURE__*/function (_TypeInfo) { - _inheritsLoose(LiteralTypeInfo, _TypeInfo); - - function LiteralTypeInfo(thisType, literal) { - var _this; - - _this = _TypeInfo.call(this, thisType) || this; - _this.literal = void 0; - _this.literal = literal; - return _this; - } - - return LiteralTypeInfo; -}(TypeInfo); -/** - * A type that represents the value undefined. - * Syntactic sugar for `types.literal(undefined)`. - * - * ```ts - * types.undefined - * ``` - */ - -var typesUndefined = /*#__PURE__*/typesLiteral(undefined); -/** - * A type that represents the value null. - * Syntactic sugar for `types.literal(null)`. - * - * ```ts - * types.null - * ``` - */ - -var typesNull = /*#__PURE__*/typesLiteral(null); -/** - * A type that represents any boolean value. - * - * ```ts - * types.boolean - * ``` - */ - -var typesBoolean = /*#__PURE__*/new TypeChecker(function (value, path) { - return typeof value === "boolean" ? null : new TypeCheckError(path, "boolean", value); -}, function () { - return "boolean"; -}, function (t) { - return new BooleanTypeInfo(t); -}); -/** - * `types.boolean` type info. - */ - -var BooleanTypeInfo = /*#__PURE__*/function (_TypeInfo2) { - _inheritsLoose(BooleanTypeInfo, _TypeInfo2); - - function BooleanTypeInfo() { - return _TypeInfo2.apply(this, arguments) || this; - } - - return BooleanTypeInfo; -}(TypeInfo); -/** - * A type that represents any number value. - * - * ```ts - * types.number - * ``` - */ - -var typesNumber = /*#__PURE__*/new TypeChecker(function (value, path) { - return typeof value === "number" ? null : new TypeCheckError(path, "number", value); -}, function () { - return "number"; -}, function (t) { - return new NumberTypeInfo(t); -}); -/** - * `types.number` type info. - */ - -var NumberTypeInfo = /*#__PURE__*/function (_TypeInfo3) { - _inheritsLoose(NumberTypeInfo, _TypeInfo3); - - function NumberTypeInfo() { - return _TypeInfo3.apply(this, arguments) || this; - } - - return NumberTypeInfo; -}(TypeInfo); -/** - * A type that represents any string value. - * - * ```ts - * types.string - * ``` - */ - -var typesString = /*#__PURE__*/new TypeChecker(function (value, path) { - return typeof value === "string" ? null : new TypeCheckError(path, "string", value); -}, function () { - return "string"; -}, function (t) { - return new StringTypeInfo(t); -}); -/** - * `types.string` type info. - */ - -var StringTypeInfo = /*#__PURE__*/function (_TypeInfo4) { - _inheritsLoose(StringTypeInfo, _TypeInfo4); - - function StringTypeInfo() { - return _TypeInfo4.apply(this, arguments) || this; - } - - return StringTypeInfo; -}(TypeInfo); -/** - * A type that represents any integer number value. - * Syntactic sugar for `types.refinement(types.number, n => Number.isInteger(n), "integer")` - * - * ```ts - * types.integer - * ``` - */ - -var typesInteger = /*#__PURE__*/typesRefinement(typesNumber, function (n) { - return Number.isInteger(n); -}, "integer"); -/** - * A type that represents any string value other than "". - * Syntactic sugar for `types.refinement(types.string, s => s !== "", "nonEmpty")` - * - * ```ts - * types.nonEmptyString - * ``` - */ - -var typesNonEmptyString = /*#__PURE__*/typesRefinement(typesString, function (s) { - return s !== ""; -}, "nonEmpty"); - -/** - * @ignore - */ - -function resolveTypeChecker(v) { - var next = v; - - while (true) { - if (next instanceof TypeChecker) { - return next; - } else if (v === String) { - return typesString; - } else if (v === Number) { - return typesNumber; - } else if (v === Boolean) { - return typesBoolean; - } else if (v === null) { - return typesNull; - } else if (v === undefined) { - return typesUndefined; - } else if (isLateTypeChecker(next)) { - next = next(); - } else { - throw failure("type checker could not be resolved"); - } - } -} -/** - * @ignore - */ - -function resolveStandardType(v) { - if (v instanceof TypeChecker || isLateTypeChecker(v)) { - return v; - } else if (v === String) { - return typesString; - } else if (v === Number) { - return typesNumber; - } else if (v === Boolean) { - return typesBoolean; - } else if (v === null) { - return typesNull; - } else if (v === undefined) { - return typesUndefined; - } else { - throw failure("standard type could not be resolved"); - } -} - -var cachedModelTypeChecker = /*#__PURE__*/new WeakMap(); -/** - * A type that represents a model. The type referenced in the model decorator will be used for type checking. - * - * Example: - * ```ts - * const someModelType = types.model(SomeModel) - * // or for recursive models - * const someModelType = types.model(() => SomeModel) - * ``` - * - * @typeparam M Model type. - * @param modelClass Model class. - * @returns - */ - -function typesModel(modelClass) { - // if we type it any stronger then recursive defs and so on stop working - if (!isModelClass(modelClass) && typeof modelClass === "function") { - // resolve later - var typeInfoGen = function typeInfoGen(t) { - return new ModelTypeInfo(t, modelClass()); - }; - - return lateTypeChecker(function () { - return typesModel(modelClass()); - }, typeInfoGen); - } else { - var modelClazz = modelClass; - assertIsModelClass(modelClazz, "modelClass"); - var cachedTypeChecker = cachedModelTypeChecker.get(modelClazz); - - if (cachedTypeChecker) { - return cachedTypeChecker; - } - - var _typeInfoGen = function _typeInfoGen(t) { - return new ModelTypeInfo(t, modelClazz); - }; - - var tc = lateTypeChecker(function () { - var modelInfo = modelInfoByClass.get(modelClazz); - var typeName = "Model(" + modelInfo.name + ")"; - return new TypeChecker(function (value, path) { - if (!(value instanceof modelClazz)) { - return new TypeCheckError(path, typeName, value); - } - - var dataTypeChecker = getModelDataType(value); - - if (!dataTypeChecker) { - throw failure("type checking cannot be performed over model of type '" + modelInfo.name + "' at path " + path.join("/") + " since that model type has no data type declared, consider adding a data type or using types.unchecked() instead"); - } - - var resolvedTc = resolveTypeChecker(dataTypeChecker); - - if (!resolvedTc.unchecked) { - return resolvedTc.check(value.$, path); - } - - return null; - }, function () { - return typeName; - }, _typeInfoGen); - }, _typeInfoGen); - cachedModelTypeChecker.set(modelClazz, tc); - return tc; - } -} -/** - * `types.model` type info. - */ - -var ModelTypeInfo = /*#__PURE__*/function (_TypeInfo) { - _inheritsLoose(ModelTypeInfo, _TypeInfo); - - _createClass(ModelTypeInfo, [{ - key: "props", - get: function get() { - return this._props(); - } - }, { - key: "modelType", - get: function get() { - var modelInfo = modelInfoByClass.get(this.modelClass); - return modelInfo.name; - } - }]); - - function ModelTypeInfo(thisType, modelClass) { - var _this; - - _this = _TypeInfo.call(this, thisType) || this; - _this.modelClass = void 0; - _this._props = lateVal(function () { - var objSchema = getInternalModelClassPropsInfo(_this.modelClass); - var propTypes = {}; - Object.keys(objSchema).forEach(function (propName) { - var propData = objSchema[propName]; - var type = propData.typeChecker; - var typeInfo; - - if (type) { - typeInfo = getTypeInfo(type); - } - - var hasDefault = false; - var defaultValue; - - if (propData.defaultFn !== noDefaultValue) { - defaultValue = propData.defaultFn; - hasDefault = true; - } else if (propData.defaultValue !== noDefaultValue) { - defaultValue = propData.defaultValue; - hasDefault = true; - } - - propTypes[propName] = { - type: type, - typeInfo: typeInfo, - hasDefault: hasDefault, - "default": defaultValue - }; - }); - return propTypes; - }); - _this.modelClass = modelClass; - return _this; - } - - return ModelTypeInfo; -}(TypeInfo); - -/** - * Checks if a value conforms to a given type. - * - * @typename S Type. - * @param type Type to check for. - * @param value Value to check. - * @returns A TypeError if the check fails or null if no error. - */ - -function typeCheck(type, value) { - var typeChecker = resolveTypeChecker(type); - - if (typeChecker.unchecked) { - return null; - } else { - return typeChecker.check(value, []); - } -} - -/** - * @ignore - * @internal - */ - -function canWrite() { - return !getActionProtection() || !!getCurrentActionContext(); -} -/** - * @ignore - * @internal - */ - -function assertCanWrite() { - if (!canWrite()) { - throw failure("data changes must be performed inside model actions"); - } -} -var actionProtection = true; -/** - * @ignore - * @internal - * - * Gets if the action protection is currently enabled or not. - * - * @returns - */ - -function getActionProtection() { - return actionProtection; -} // base case - -function runUnprotected(arg1, arg2) { - var name = typeof arg1 === "string" ? arg1 : undefined; - var fn = typeof arg1 === "string" ? arg2 : arg1; - - var innerAction = function innerAction() { - var oldActionProtection = actionProtection; - actionProtection = false; - - try { - return fn(); - } finally { - actionProtection = oldActionProtection; - tryRunPendingActions(); - } - }; - - if (name) { - return (0,mobx_esm.action)(name, innerAction)(); - } else { - return (0,mobx_esm.action)(innerAction)(); - } -} - -var pendingActions = []; - -function isActionRunning() { - return !getActionProtection() || getCurrentActionContext(); -} -/** - * @ignore - */ - - -function enqueuePendingAction(action) { - // delay action until all current actions are finished - if (isActionRunning()) { - pendingActions.push(action); - } else { - action(); - } -} -/** - * @ignore - */ - -function tryRunPendingActions() { - if (isActionRunning()) { - return false; - } - - while (pendingActions.length > 0) { - var nextAction = pendingActions.shift(); - nextAction(); - } - - return true; -} - -/** - * A hook action. - */ -var HookAction; - -(function (HookAction) { - /** - * onInit hook - */ - HookAction["OnInit"] = "$$onInit"; - /** - * onAttachedToRootStore hook - */ - - HookAction["OnAttachedToRootStore"] = "$$onAttachedToRootStore"; - /** - * disposer for onAttachedToRootStore hook - */ - - HookAction["OnAttachedToRootStoreDisposer"] = "$$onAttachedToRootStoreDisposer"; -})(HookAction || (HookAction = {})); - -var hookActionValues = /*#__PURE__*/new Set( /*#__PURE__*/Object.values(HookAction)); -/** - * Returns if a given action name corresponds to a hook, this is, one of: - * - onInit() hook - * - onAttachedToRootStore() hook - * - disposer returned by a onAttachedToRootStore() hook - * - * @param actionName Action name to check. - * @returns true if it is a hook, false otherwise. - */ - -function isHookAction(actionName) { - return hookActionValues.has(actionName); -} - -var perObjectActionMiddlewares = /*#__PURE__*/new WeakMap(); -var perObjectActionMiddlewaresIterator = /*#__PURE__*/new WeakMap(); -/** - * @ignore - * @internal - * - * Gets the current action middlewares to be run over a given object as an iterable object. - * - * @returns - */ - -function getActionMiddlewares(obj) { - // when we call a middleware we will call the middlewares of that object plus all parent objects - // the parent object middlewares are run last - // since an array like [a, b, c] will be called like c(b(a())) this means that we need to put - // the parent object ones at the end of the array - var iterable = perObjectActionMiddlewaresIterator.get(obj); - - if (!iterable) { - var _iterable; - - iterable = (_iterable = {}, _iterable[Symbol.iterator] = function () { - var current = obj; - - function getCurrentIterator() { - var objMwares = current ? perObjectActionMiddlewares.get(current) : undefined; - - if (!objMwares || objMwares.length <= 0) { - return undefined; - } - - return objMwares[Symbol.iterator](); - } - - function findNextIterator() { - var nextIter; - - while (current && !nextIter) { - current = fastGetParent(current); - nextIter = getCurrentIterator(); - } - - return nextIter; - } - - var iter = getCurrentIterator(); - - if (!iter) { - iter = findNextIterator(); - } - - var iterator = { - next: function next() { - if (!iter) { - return { - value: undefined, - done: true - }; - } - - var result = iter.next(); - - if (!result.done) { - return result; - } - - iter = findNextIterator(); - return this.next(); - } - }; - return iterator; - }, _iterable); - perObjectActionMiddlewaresIterator.set(obj, iterable); - } - - return iterable; -} -/** - * Adds a global action middleware to be run when an action is performed. - * It is usually preferable to use `onActionMiddleware` instead to limit it to a given tree and only to topmost level actions - * or `actionTrackingMiddleware` for a simplified middleware. - * - * @param mware Action middleware to be run. - * @returns A disposer to cancel the middleware. Note that if you don't plan to do an early disposal of the middleware - * calling this function becomes optional. - */ - -function addActionMiddleware(mware) { - assertIsObject(mware, "middleware"); - var middleware = mware.middleware, - filter = mware.filter, - subtreeRoot = mware.subtreeRoot; - assertTweakedObject(subtreeRoot, "middleware.subtreeRoot"); - assertIsFunction(middleware, "middleware.middleware"); - - if (filter && typeof filter !== "function") { - throw failure("middleware.filter must be a function or undefined"); - } - - if (!(0,mobx_esm.isAction)(middleware)) { - middleware = (0,mobx_esm.action)(middleware.name || "actionMiddleware", middleware); - } - - if (subtreeRoot) { - var targetFilter = function targetFilter(ctx) { - return ctx.target === subtreeRoot || isChildOfParent(ctx.target, subtreeRoot); - }; - - if (!filter) { - filter = targetFilter; - } else { - var customFilter = filter; - - filter = function filter(ctx) { - return targetFilter(ctx) && customFilter(ctx); - }; - } - } - - var actualMware = { - middleware: middleware, - filter: filter - }; - var objMwares = perObjectActionMiddlewares.get(subtreeRoot); - - if (!objMwares) { - objMwares = [actualMware]; - perObjectActionMiddlewares.set(subtreeRoot, objMwares); - } else { - objMwares.push(actualMware); - } - - return function () { - deleteFromArray(objMwares, actualMware); - }; -} - -/** - * @ignore - */ - -var modelActionSymbol = /*#__PURE__*/Symbol("modelAction"); -/** - * @ignore - */ - -function wrapInAction(_ref) { - var name = _ref.name, - fn = _ref.fn, - actionType = _ref.actionType, - overrideContext = _ref.overrideContext, - _ref$isFlowFinisher = _ref.isFlowFinisher, - isFlowFinisher = _ref$isFlowFinisher === void 0 ? false : _ref$isFlowFinisher; - var wrappedAction = (0,mobx_esm.action)(name, function () { - var target = this; - - if (inDevMode()) { - assertTweakedObject(target, "wrappedAction"); - } - - var parentContext = getCurrentActionContext(); - var context = { - actionName: name, - type: actionType, - target: target, - args: Array.from(arguments), - parentContext: parentContext, - data: {}, - rootContext: undefined - }; - - if (overrideContext) { - overrideContext(context); - } - - if (!context.rootContext) { - if (context.previousAsyncStepContext) { - context.rootContext = context.previousAsyncStepContext.rootContext; - } else if (context.parentContext) { - context.rootContext = context.parentContext.rootContext; - } else { - context.rootContext = context; - } - } - - setCurrentActionContext(context); - var mwareFn = fn.bind.apply(fn, [target].concat(Array.prototype.slice.call(arguments))); - var mwareIter = getActionMiddlewares(target)[Symbol.iterator](); - var mwareCur = mwareIter.next(); - - while (!mwareCur.done) { - var mware = mwareCur.value; - var filterPassed = mware.filter ? mware.filter(context) : true; - - if (filterPassed) { - mwareFn = mware.middleware.bind(undefined, context, mwareFn); - } - - mwareCur = mwareIter.next(); - } - - try { - var ret = mwareFn(); - - if (isFlowFinisher) { - var flowFinisher = ret; - var value = flowFinisher.value; - - if (flowFinisher.resolution === "accept") { - flowFinisher.accepter(value); - } else { - flowFinisher.rejecter(value); - } - - return value; // not sure if this is even needed - } else { - return ret; - } - } finally { - setCurrentActionContext(context.parentContext); - tryRunPendingActions(); - } - }); - wrappedAction[modelActionSymbol] = true; - return wrappedAction; -} -/** - * @ignore - */ - -function wrapModelMethodInActionIfNeeded(model, propertyKey, name) { - var fn = model[propertyKey]; - - if (isModelAction(fn)) { - return; - } - - var wrappedFn = wrapInAction({ - name: name, - fn: fn, - actionType: ActionContextActionType.Sync - }); - var proto = Object.getPrototypeOf(model); - var protoFn = proto[propertyKey]; - - if (protoFn === fn) { - proto[propertyKey] = wrappedFn; - } else { - model[propertyKey] = wrappedFn; - } -} - -/** - * Mode for the `walkTree` method. - */ - -var WalkTreeMode; - -(function (WalkTreeMode) { - /** - * The walk will be done parent (roots) first, then children. - */ - WalkTreeMode["ParentFirst"] = "parentFirst"; - /** - * The walk will be done children (leafs) first, then parents. - */ - - WalkTreeMode["ChildrenFirst"] = "childrenFirst"; -})(WalkTreeMode || (WalkTreeMode = {})); -/** - * Walks a tree, running the predicate function for each node. - * If the predicate function returns something other than undefined, - * then the walk will be stopped and the function will return the returned value. - * - * @typeparam T Returned object type, defaults to void. - * @param target Subtree root object. - * @param predicate Function that will be run for each node of the tree. - * @param mode Mode to walk the tree, as defined in `WalkTreeMode`. - * @returns - */ - - -function walkTree(target, predicate, mode) { - assertTweakedObject(target, "target"); - - if (mode === WalkTreeMode.ParentFirst) { - var recurse = function recurse(child) { - return walkTreeParentFirst(child, predicate, recurse); - }; - - return walkTreeParentFirst(target, predicate, recurse); - } else { - var _recurse = function _recurse(child) { - return walkTreeChildrenFirst(child, predicate, _recurse); - }; - - return walkTreeChildrenFirst(target, predicate, _recurse); - } -} - -function walkTreeParentFirst(target, rootPredicate, recurse) { - var ret = rootPredicate(target); - - if (ret !== undefined) { - return ret; - } - - var childrenIter = getObjectChildren(target).values(); - var ch = childrenIter.next(); - - while (!ch.done) { - var _ret = recurse(ch.value); - - if (_ret !== undefined) { - return _ret; - } - - ch = childrenIter.next(); - } - - return undefined; -} - -function walkTreeChildrenFirst(target, rootPredicate, recurse) { - var childrenIter = getObjectChildren(target).values(); - var ch = childrenIter.next(); - - while (!ch.done) { - var _ret2 = recurse(ch.value); - - if (_ret2 !== undefined) { - return _ret2; - } - - ch = childrenIter.next(); - } - - var ret = rootPredicate(target); - - if (ret !== undefined) { - return ret; - } - - return undefined; -} -/** - * @ignore - * @internal - */ - - -function computedWalkTreeAggregate(predicate) { - var computedFns = new WeakMap(); - - var getComputedTreeResult = function getComputedTreeResult(tree) { - var cmpted = computedFns.get(tree); - - if (!cmpted) { - cmpted = (0,mobx_esm.computed)(function () { - return walkTreeAggregate(tree, predicate, recurse); - }); - computedFns.set(tree, cmpted); - } - - return cmpted.get(); - }; - - var recurse = function recurse(ch) { - return getComputedTreeResult(ch); - }; - - return { - walk: function walk(target) { - return getComputedTreeResult(target); - } - }; -} - -function walkTreeAggregate(target, rootPredicate, recurse) { - var map; - var rootVal = rootPredicate(target); - var childrenMap = getObjectChildren(target); - var childrenIter = childrenMap.values(); - var ch = childrenIter.next(); // small optimization, if there is only one child and this - // object provides no value we can just reuse the child ones - - if (rootVal === undefined && childrenMap.size === 1) { - return recurse(ch.value); - } - - while (!ch.done) { - var childMap = recurse(ch.value); - - if (childMap) { - if (!map) { - map = new Map(); - } // add child map keys/values to own map - - - var mapIter = childMap.keys(); - var mapCur = mapIter.next(); - - while (!mapCur.done) { - var key = mapCur.value; - var val = childMap.get(key); - map.set(key, val); - mapCur = mapIter.next(); - } - } - - ch = childrenIter.next(); - } // add it at the end so parent resolutions have higher - // priority than child ones - - - if (rootVal !== undefined) { - if (!map) { - map = new Map(); - } - - map.set(rootVal, target); - } - - return map; -} - -var onAttachedDisposers = /*#__PURE__*/new WeakMap(); -/** - * @ignore - * @internal - */ - -var attachToRootStore = /*#__PURE__*/(0,mobx_esm.action)("attachToRootStore", function (rootStore, child) { - // we use an array to ensure they will get called even if the actual hook modifies the tree - var childrenToCall = []; - walkTree(child, function (ch) { - if (ch instanceof BaseModel && ch.onAttachedToRootStore) { - wrapModelMethodInActionIfNeeded(ch, "onAttachedToRootStore", HookAction.OnAttachedToRootStore); - childrenToCall.push(ch); - } - }, WalkTreeMode.ParentFirst); - var childrenToCallLen = childrenToCall.length; - - for (var i = 0; i < childrenToCallLen; i++) { - var ch = childrenToCall[i]; - var disposer = ch.onAttachedToRootStore(rootStore); - - if (disposer) { - onAttachedDisposers.set(ch, disposer); - } - } -}); -/** - * @ignore - * @internal - */ - -var detachFromRootStore = /*#__PURE__*/(0,mobx_esm.action)("detachFromRootStore", function (child) { - // we use an array to ensure they will get called even if the actual hook modifies the tree - var disposersToCall = []; - walkTree(child, function (ch) { - var disposer = onAttachedDisposers.get(ch); - - if (disposer) { - // wrap disposer in action - var disposerAction = wrapInAction({ - name: HookAction.OnAttachedToRootStoreDisposer, - fn: disposer, - actionType: ActionContextActionType.Sync - }).bind(ch); - onAttachedDisposers["delete"](ch); - disposersToCall.push(disposerAction); - } - }, WalkTreeMode.ChildrenFirst); - var disposersToCallLen = disposersToCall.length; - - for (var i = 0; i < disposersToCallLen; i++) { - disposersToCall[i](); - } -}); - -var rootStores = /*#__PURE__*/new WeakSet(); -var rootStoreAtoms = /*#__PURE__*/new WeakMap(); -/** - * Registers a model / tree node object as a root store tree. - * Marking a model object as a root store tree serves several purposes: - * - It allows the `onAttachedToRootStore` hook (plus disposer) to be invoked on models once they become part of this tree. - * These hooks can be used for example to attach effects and serve as some sort of initialization. - * - It allows auto detachable references to work properly. - * - * @typeparam T Object type. - * @param node Node object to register as root store. - * @returns The same model object that was passed. - */ - -var registerRootStore = /*#__PURE__*/(0,mobx_esm.action)("registerRootStore", function (node) { - assertTweakedObject(node, "node"); - - if (rootStores.has(node)) { - throw failure("object already registered as root store"); - } - - if (!isRoot(node)) { - throw failure("a root store must not have a parent"); - } - - rootStores.add(node); - attachToRootStore(node, node); - getOrCreateRootStoreAtom(node).reportChanged(); - return node; -}); -/** - * Unregisters an object to mark it as no longer a root store. - * - * @param node Node object to unregister as root store. - */ - -var unregisterRootStore = /*#__PURE__*/(0,mobx_esm.action)("unregisterRootStore", function (node) { - if (!isRootStore(node)) { - throw failure("not a root store"); - } - - rootStores["delete"](node); - detachFromRootStore(node); - getOrCreateRootStoreAtom(node).reportChanged(); -}); -/** - * Checks if a given object is marked as a root store. - * - * @param node Object. - * @returns - */ - -function isRootStore(node) { - assertTweakedObject(node, "node"); - return fastIsRootStore(node); -} -/** - * @ignore - * @internal - */ - -function fastIsRootStore(node) { - getOrCreateRootStoreAtom(node).reportObserved(); - return rootStores.has(node); -} -/** - * Gets the root store of a given tree child, or undefined if none. - * - * @typeparam T Root store type. - * @param node Target to find the root store for. - * @returns - */ - -function getRootStore(node) { - assertTweakedObject(node, "node"); - return fastGetRootStore(node); -} -/** - * @ignore - * @internal - */ - -function fastGetRootStore(node) { - var root = fastGetRoot(node); - return fastIsRootStore(root) ? root : undefined; -} - -function getOrCreateRootStoreAtom(node) { - var atom = rootStoreAtoms.get(node); - - if (!atom) { - atom = (0,mobx_esm.createAtom)("rootStore"); - rootStoreAtoms.set(node, atom); - } - - return atom; -} - -/** - * @ignore - * @internal - */ - -var setParent = /*#__PURE__*/(0,mobx_esm.action)("setParent", function (value, parentPath, indexChangeAllowed, isDataObject) { - if (isPrimitive(value)) { - return; - } - - if (inDevMode()) { - if (typeof value === "function" || typeof value === "symbol") { - throw failure("assertion failed: value cannot be a function or a symbol"); - } - - if (!isTweakedObject(value, true)) { - throw failure("assertion failed: value is not ready to take a parent"); - } - - if (parentPath) { - if (!isTweakedObject(parentPath.parent, true)) { - throw failure("assertion failed: parent is not ready to take children"); - } - } - } - - if (isDataObject) { - dataObjectParent.set(value, parentPath.parent); // data object will proxy to use the actual parent model for child/parent stuff - - return; - } - - initializeObjectChildren(value); // make sure the new parent actually points to models when we give model data objs - - if (parentPath) { - var actualParent = dataToModelNode(parentPath.parent); - - if (parentPath.parent !== actualParent) { - parentPath = { - parent: actualParent, - path: parentPath.path - }; - } - } - - var oldParentPath = fastGetParentPath(value); - - if (parentPathEquals(oldParentPath, parentPath)) { - return; - } - - if (isRootStore(value)) { - throw failure("root stores cannot be attached to any parents"); - } - - if (oldParentPath && parentPath) { - if (oldParentPath.parent === parentPath.parent && indexChangeAllowed) { - // just changing the index - objectParents.set(value, parentPath); - reportParentPathChanged(value); - return; - } else { - throw failure("an object cannot be assigned a new parent when it already has one"); - } - } - - var removeFromOldParent = function removeFromOldParent() { - if (oldParentPath == null ? void 0 : oldParentPath.parent) { - removeObjectChild(oldParentPath.parent, value); - } - }; - - var attachToNewParent = function attachToNewParent() { - var _parentPath; - - objectParents.set(value, parentPath); - - if ((_parentPath = parentPath) == null ? void 0 : _parentPath.parent) { - addObjectChild(parentPath.parent, value); - } - - reportParentPathChanged(value); - }; - - if (value instanceof BaseModel) { - var oldRoot = fastGetRoot(value); - var oldRootStore = isRootStore(oldRoot) ? oldRoot : undefined; - removeFromOldParent(); - attachToNewParent(); - var newRoot = fastGetRoot(value); - var newRootStore = isRootStore(newRoot) ? newRoot : undefined; // invoke model root store events - - if (oldRootStore !== newRootStore && (oldRootStore || newRootStore)) { - enqueuePendingAction(function () { - if (oldRootStore) { - detachFromRootStore(value); - } - - if (newRootStore) { - attachToRootStore(newRootStore, value); - } - }); - } - } else { - removeFromOldParent(); - attachToNewParent(); - } -}); - -/** - * @ignore - */ - -function tweakModel(value, parentPath) { - tweakedObjects.set(value, undefined); - setParent(value, parentPath, false, false); // nothing to do for models, data is already proxified and its parent is set - // for snapshots we will use its "$" object snapshot directly - - return value; -} - -/** - * @ignore - * @internal - */ - -var InternalPatchRecorder = /*#__PURE__*/function () { - function InternalPatchRecorder() { - this.patches = void 0; - this.invPatches = void 0; - } - - var _proto = InternalPatchRecorder.prototype; - - _proto.record = function record(patches, invPatches) { - this.patches = patches; - this.invPatches = invPatches; - }; - - _proto.emit = function emit(obj) { - emitPatch(obj, this.patches, this.invPatches, true); - }; - - return InternalPatchRecorder; -}(); -var patchListeners = /*#__PURE__*/new WeakMap(); -var globalPatchListeners = []; -/** - * Adds a listener that will be called every time a patch is generated for the tree of the given target object. - * - * @param subtreeRoot Subtree root object of the patch listener. - * @param listener The listener function that will be called everytime a patch is generated for the object or its children. - * @returns A disposer to stop listening to patches. - */ - -function onPatches(subtreeRoot, listener) { - assertTweakedObject(subtreeRoot, "subtreeRoot"); - assertIsFunction(listener, "listener"); - - if (!(0,mobx_esm.isAction)(listener)) { - listener = (0,mobx_esm.action)(listener.name || "onPatchesListener", listener); - } - - var listenersForObject = patchListeners.get(subtreeRoot); - - if (!listenersForObject) { - listenersForObject = []; - patchListeners.set(subtreeRoot, listenersForObject); - } - - listenersForObject.push(listener); - return function () { - deleteFromArray(listenersForObject, listener); - }; -} -/** - * Adds a listener that will be called every time a patch is generated anywhere. - * Usually prefer using `onPatches`. - * - * @param listener The listener function that will be called everytime a patch is generated anywhere. - * @returns A disposer to stop listening to patches. - */ - -function onGlobalPatches(listener) { - assertIsFunction(listener, "listener"); - - if (!(0,mobx_esm.isAction)(listener)) { - listener = (0,mobx_esm.action)(listener.name || "onGlobalPatchesListener", listener); - } - - globalPatchListeners.push(listener); - return function () { - deleteFromArray(globalPatchListeners, listener); - }; -} - -function emitPatch(obj, patches, inversePatches, emitGlobally) { - if (patches.length <= 0 && inversePatches.length <= 0) { - return; - } // first emit global listeners - - - if (emitGlobally) { - for (var i = 0; i < globalPatchListeners.length; i++) { - var listener = globalPatchListeners[i]; - listener(obj, patches, inversePatches); - } - } // then per subtree listeners - - - var listenersForObject = patchListeners.get(obj); - - if (listenersForObject) { - for (var _i = 0; _i < listenersForObject.length; _i++) { - var _listener = listenersForObject[_i]; - - _listener(patches, inversePatches); - } - } // and also emit subtree listeners all the way to the root - - - var parentPath = fastGetParentPath(obj); - - if (parentPath) { - // tweak patches so they include the child path - var childPath = parentPath.path; - var newPatches = patches.map(function (p) { - return addPathToPatch(p, childPath); - }); - var newInversePatches = inversePatches.map(function (p) { - return addPathToPatch(p, childPath); - }); // false to avoid emitting global patches again for the same change - - emitPatch(parentPath.parent, newPatches, newInversePatches, false); - } -} - -function addPathToPatch(patch, path) { - return _extends({}, patch, { - path: [path].concat(patch.path) - }); -} - -/** - * Should freeze and plain json checks be done when creating the frozen object? - */ - -var FrozenCheckMode; - -(function (FrozenCheckMode) { - /** Only when in dev mode */ - FrozenCheckMode["DevModeOnly"] = "devModeOnly"; - /** Always */ - - FrozenCheckMode["On"] = "on"; - /** Never */ - - FrozenCheckMode["Off"] = "off"; -})(FrozenCheckMode || (FrozenCheckMode = {})); -/** - * @ignore - */ - - -var frozenKey = "$frozen"; -/** - * A class that contains frozen data. - * Use `frozen` to create an instance of this class. - * - * @typeparam T Data type. - */ - -var Frozen = -/** - * Frozen data, deeply immutable. - */ - -/** - * Creates an instance of Frozen. - * Do not use directly, use `frozen` instead. - * - * @param dataToFreeze - * @param checkMode - */ -function Frozen(dataToFreeze, checkMode) { - if (checkMode === void 0) { - checkMode = FrozenCheckMode.DevModeOnly; - } - - this.data = void 0; - var check = checkMode === FrozenCheckMode.On || checkMode === FrozenCheckMode.DevModeOnly && inDevMode(); - - if (check) { - checkDataIsSerializableAndFreeze(dataToFreeze); - } - - this.data = dataToFreeze; - - if (check) { - Object.freeze(this.data); - } - - tweak(this, undefined); -}; -/** - * Marks some data as frozen. Frozen data becomes immutable (at least in dev mode), and is not enhanced - * with capabilities such as getting the parent of the objects (except for the root object), it is not - * made deeply observable (though the root object is observable by reference), etc. - * On the other hand, this means it will be much faster to create/access. Use this for big data pieces - * that are unlikely to change unless all of them change (for example lists of points for a polygon, etc). - * - * Note that data passed to frozen must be serializable to JSON, this is: - * - primitive, plain object, or array - * - without cycles - * - * @param data - * @param checkMode - */ - -function frozen(data, checkMode) { - if (checkMode === void 0) { - checkMode = FrozenCheckMode.DevModeOnly; - } - - return new Frozen(data, checkMode); -} - -function checkDataIsSerializableAndFreeze(data) { - // TODO: detect cycles and throw if present? - // primitives are ok - if (isPrimitive(data)) { - return; - } - - if (Array.isArray(data)) { - var arrLen = data.length; - - for (var i = 0; i < arrLen; i++) { - var v = data[i]; - - if (v === undefined && !getGlobalConfig().allowUndefinedArrayElements) { - throw failure("undefined is not supported inside arrays since it is not serializable in JSON, consider using null instead"); - } - - checkDataIsSerializableAndFreeze(v); - } - - Object.freeze(data); - return; - } - - if (isPlainObject(data)) { - var dataKeys = Object.keys(data); - var dataKeysLen = dataKeys.length; - - for (var _i = 0; _i < dataKeysLen; _i++) { - var k = dataKeys[_i]; - var _v = data[k]; - checkDataIsSerializableAndFreeze(k); - checkDataIsSerializableAndFreeze(_v); - } - - Object.freeze(data); - return; - } - - throw failure("frozen data must be plainly serializable to JSON, but " + data + " is not"); -} -/** - * @ignore - * @internal - * - * Checks if an snapshot is an snapshot for a frozen data. - * - * @param snapshot - * @returns - */ - - -function isFrozenSnapshot(snapshot) { - return isPlainObject(snapshot) && !!snapshot[frozenKey]; -} - -/** - * Iterates through all the parents (from the nearest until the root) - * until one of them matches the given predicate. - * If the predicate is matched it will return the found node. - * If none is found it will return undefined. - * - * @typeparam T Parent object type. - * @param child Target object. - * @param predicate Function that will be run for every parent of the target object, from immediate parent to the root. - * @param maxDepth Max depth, or 0 for infinite. - * @returns - */ - -function findParent(child, predicate, maxDepth) { - if (maxDepth === void 0) { - maxDepth = 0; - } - - var foundParentPath = findParentPath(child, predicate, maxDepth); - return foundParentPath ? foundParentPath.parent : undefined; -} -/** - * Iterates through all the parents (from the nearest until the root) - * until one of them matches the given predicate. - * If the predicate is matched it will return the found node plus the - * path to get from the parent to the child. - * If none is found it will return undefined. - * - * @typeparam T Parent object type. - * @param child Target object. - * @param predicate Function that will be run for every parent of the target object, from immediate parent to the root. - * @param maxDepth Max depth, or 0 for infinite. - * @returns - */ - -function findParentPath(child, predicate, maxDepth) { - if (maxDepth === void 0) { - maxDepth = 0; - } - - assertTweakedObject(child, "child"); - var path = []; - var current = child; - var depth = 0; - var parentPath; - - while (parentPath = fastGetParentPath(current)) { - path.unshift(parentPath.path); - current = parentPath.parent; - - if (predicate(current)) { - return { - parent: current, - path: path - }; - } - - depth++; - - if (maxDepth > 0 && depth === maxDepth) { - break; - } - } - - return undefined; -} - -/** - * A built-in action. - */ -var BuiltInAction; - -(function (BuiltInAction) { - /** - * applyPatches - */ - BuiltInAction["ApplyPatches"] = "$$applyPatches"; - /** - * applySnapshot - */ - - BuiltInAction["ApplySnapshot"] = "$$applySnapshot"; - /** - * detach - */ - - BuiltInAction["Detach"] = "$$detach"; - /** - * applySet - */ - - BuiltInAction["ApplySet"] = "$$applySet"; - /** - * applyDelete - */ - - BuiltInAction["ApplyDelete"] = "$$applyDelete"; - /** - * applyMethodCall - */ - - BuiltInAction["ApplyMethodCall"] = "$$applyMethodCall"; -})(BuiltInAction || (BuiltInAction = {})); - -var builtInActionValues = /*#__PURE__*/new Set( /*#__PURE__*/Object.values(BuiltInAction)); -/** - * Returns if a given action name is a built-in action, this is, one of: - * - applyPatches() - * - applySnapshot() - * - detach() - * - * @param actionName Action name to check. - * @returns true if it is a built-in action, false otherwise. - */ - -function isBuiltInAction(actionName) { - return builtInActionValues.has(actionName); -} - -/** - * Detaches a given object from a tree. - * If the parent is an object / model, detaching will delete the property. - * If the parent is an array detaching will remove the node by splicing it. - * If there's no parent it will throw. - * - * @param node Object to be detached. - */ - -function detach(node) { - assertTweakedObject(node, "node"); - wrappedInternalDetach().call(node); -} -var wrappedInternalDetach = /*#__PURE__*/lazy(function () { - return wrapInAction({ - name: BuiltInAction.Detach, - fn: internalDetach, - actionType: ActionContextActionType.Sync - }); -}); - -function internalDetach() { - var node = this; - var parentPath = fastGetParentPathIncludingDataObjects(node); - if (!parentPath) return; - var parent = parentPath.parent, - path = parentPath.path; - - if ((0,mobx_esm.isObservableArray)(parent)) { - parent.splice(+path, 1); - } else if ((0,mobx_esm.isObservableObject)(parent)) { - (0,mobx_esm.remove)(parent, "" + path); - } else { - throw failure("parent must be an observable object or an observable array"); - } -} - -/** - * Returns all the children objects (this is, excluding primitives) of an object. - * - * @param node Object to get the list of children from. - * @param [options] An optional object with the `deep` option (defaults to false) to true to get - * the children deeply or false to get them shallowly. - * @returns A readonly observable set with the children. - */ - -function getChildrenObjects(node, options) { - assertTweakedObject(node, "node"); - - if (!options || !options.deep) { - return getObjectChildren(node); - } else { - return getDeepObjectChildren(node).deep; - } -} - -/** - * Runs a callback everytime a new object is attached to a given node. - * The callback can optionally return a disposer which will be run when the child is detached. - * - * The optional options parameter accepts and object with the following options: - * - `deep: boolean` (default: `false`) - true if the callback should be run for all children deeply - * or false if it it should only run for shallow children. - * - `fireForCurrentChildren: boolean` (default: `true`) - true if the callback should be immediately - * called for currently attached children, false if only for future attachments. - * - * Returns a disposer, which has a boolean parameter which should be true if pending detachment - * callbacks should be run or false otherwise. - * - * @param target Function that returns the object whose children should be tracked. - * @param fn Callback called when a child is attached to the target object. - * @param [options] - * @returns - */ - -function onChildAttachedTo(target, fn, options) { - assertIsFunction(target, "target"); - assertIsFunction(fn, "fn"); - - var opts = _extends({ - deep: false, - runForCurrentChildren: true - }, options); - - var detachDisposers = new WeakMap(); - - var runDetachDisposer = function runDetachDisposer(n) { - var detachDisposer = detachDisposers.get(n); - - if (detachDisposer) { - detachDisposers["delete"](n); - detachDisposer(); - } - }; - - var addDetachDisposer = function addDetachDisposer(n, disposer) { - if (disposer) { - detachDisposers.set(n, disposer); - } - }; - - var getChildrenObjectOpts = { - deep: opts.deep - }; - - var getCurrentChildren = function getCurrentChildren() { - var t = target(); - assertTweakedObject(t, "target()"); - var children = getChildrenObjects(t, getChildrenObjectOpts); - var set = new Set(); - var iter = children.values(); - var cur = iter.next(); - - while (!cur.done) { - set.add(cur.value); - cur = iter.next(); - } - - return set; - }; - - var currentChildren = opts.runForCurrentChildren ? new Set() : getCurrentChildren(); - var disposer = (0,mobx_esm.reaction)(function () { - return getCurrentChildren(); - }, function (newChildren) { - var disposersToRun = []; // find dead - - var currentChildrenIter = currentChildren.values(); - var currentChildrenCur = currentChildrenIter.next(); - - while (!currentChildrenCur.done) { - var n = currentChildrenCur.value; - - if (!newChildren.has(n)) { - currentChildren["delete"](n); // we should run it in inverse order - - disposersToRun.push(n); - } - - currentChildrenCur = currentChildrenIter.next(); - } - - if (disposersToRun.length > 0) { - for (var i = disposersToRun.length - 1; i >= 0; i--) { - runDetachDisposer(disposersToRun[i]); - } - } // find new - - - var newChildrenIter = newChildren.values(); - var newChildrenCur = newChildrenIter.next(); - - while (!newChildrenCur.done) { - var _n = newChildrenCur.value; - - if (!currentChildren.has(_n)) { - currentChildren.add(_n); - addDetachDisposer(_n, fn(_n)); - } - - newChildrenCur = newChildrenIter.next(); - } - }, { - fireImmediately: true - }); - return function (runDetachDisposers) { - disposer(); - - if (runDetachDisposers) { - var currentChildrenIter = currentChildren.values(); - var currentChildrenCur = currentChildrenIter.next(); - - while (!currentChildrenCur.done) { - var n = currentChildrenCur.value; - runDetachDisposer(n); - currentChildrenCur = currentChildrenIter.next(); - } - } - - currentChildren.clear(); - }; -} - -/** - * Deserializers a data structure from its snapshot form. - * - * @typeparam T Object type. - * @param snapshot Snapshot, even if a primitive. - * @param [options] Options. - * @returns The deserialized object. - */ - -var fromSnapshot = function fromSnapshot(snapshot, options) { - var opts = _extends({ - generateNewIds: false, - overrideRootModelId: undefined - }, options); - - var ctx = { - options: opts - }; - ctx.snapshotToInitialData = snapshotToInitialData.bind(undefined, ctx); - return internalFromSnapshot(snapshot, ctx); -}; -fromSnapshot = /*#__PURE__*/(0,mobx_esm.action)("fromSnapshot", fromSnapshot); - -function internalFromSnapshot(sn, ctx) { - if (isPrimitive(sn)) { - return sn; - } - - if (isMap(sn)) { - throw failure("a snapshot must not contain maps"); - } - - if (isSet(sn)) { - throw failure("a snapshot must not contain sets"); - } - - if (isArray(sn)) { - return fromArraySnapshot(sn, ctx); - } - - if (isFrozenSnapshot(sn)) { - return frozen(sn.data); - } - - if (isModelSnapshot(sn)) { - return fromModelSnapshot(sn, ctx); - } - - if (isPlainObject(sn)) { - return fromPlainObjectSnapshot(sn, ctx); - } - - throw failure("unsupported snapshot - " + sn); -} - -function fromArraySnapshot(sn, ctx) { - var arr = mobx_esm.observable.array([], observableOptions); - var ln = sn.length; - - for (var i = 0; i < ln; i++) { - arr.push(internalFromSnapshot(sn[i], ctx)); - } - - return tweakArray(arr, undefined, true); -} - -function fromModelSnapshot(sn, ctx) { - var type = sn[modelTypeKey]; - - if (!type) { - throw failure("a model snapshot must contain a type key (" + modelTypeKey + "), but none was found"); - } - - var modelInfo = getModelInfoForName(type); - - if (!modelInfo) { - throw failure("model with name \"" + type + "\" not found in the registry"); - } - - if (!sn[modelIdKey]) { - throw failure("a model snapshot must contain an id key (" + modelIdKey + "), but none was found"); - } - - return new modelInfo["class"](undefined, { - snapshotInitialData: { - unprocessedSnapshot: sn, - snapshotToInitialData: ctx.snapshotToInitialData - }, - generateNewIds: ctx.options.generateNewIds - }); -} - -function snapshotToInitialData(ctx, processedSn) { - var initialData = mobx_esm.observable.object({}, undefined, observableOptions); - var processedSnKeys = Object.keys(processedSn); - var processedSnKeysLen = processedSnKeys.length; - - for (var i = 0; i < processedSnKeysLen; i++) { - var k = processedSnKeys[i]; - - if (!isReservedModelKey(k)) { - var v = processedSn[k]; - (0,mobx_esm.set)(initialData, k, internalFromSnapshot(v, ctx)); - } - } - - return initialData; -} - -function fromPlainObjectSnapshot(sn, ctx) { - var plainObj = mobx_esm.observable.object({}, undefined, observableOptions); - var snKeys = Object.keys(sn); - var snKeysLen = snKeys.length; - - for (var i = 0; i < snKeysLen; i++) { - var k = snKeys[i]; - var v = sn[k]; - (0,mobx_esm.set)(plainObj, k, internalFromSnapshot(v, ctx)); - } - - return tweakPlainObject(plainObj, undefined, undefined, true, false); -} - -var observableOptions = { - deep: false -}; - -/** - * @ignore - */ - -function reconcileSnapshot(value, sn, modelPool) { - if (isPrimitive(sn)) { - return sn; - } - - if (isArray(sn)) { - return reconcileArraySnapshot(value, sn, modelPool); - } - - if (isFrozenSnapshot(sn)) { - return reconcileFrozenSnapshot(value, sn); - } - - if (isModelSnapshot(sn)) { - return reconcileModelSnapshot(value, sn, modelPool); - } - - if (isPlainObject(sn)) { - return reconcilePlainObjectSnapshot(value, sn, modelPool); - } - - if (isMap(sn)) { - throw failure("a snapshot must not contain maps"); - } - - if (isSet(sn)) { - throw failure("a snapshot must not contain sets"); - } - - throw failure("unsupported snapshot - " + sn); -} - -function reconcileArraySnapshot(value, sn, modelPool) { - if (!isArray(value)) { - // no reconciliation possible - return fromSnapshot(sn); - } // remove excess items - - - if (value.length > sn.length) { - value.splice(sn.length, value.length - sn.length); - } // reconcile present items - - - for (var i = 0; i < value.length; i++) { - var oldValue = value[i]; - var newValue = reconcileSnapshot(oldValue, sn[i], modelPool); - detachIfNeeded(newValue, oldValue, modelPool); - (0,mobx_esm.set)(value, i, newValue); - } // add excess items - - - for (var _i = value.length; _i < sn.length; _i++) { - value.push(reconcileSnapshot(undefined, sn[_i], modelPool)); - } - - return value; -} - -function reconcileFrozenSnapshot(value, sn) { - // reconciliation is only possible if the target is a Frozen instance with the same data (by ref) - // in theory we could compare the JSON representation of both datas or do a deep comparison, but that'd be too slow - if (value instanceof Frozen && value.data === sn.data) { - return value; - } - - return frozen(sn.data); -} - -function reconcileModelSnapshot(value, sn, modelPool) { - var type = sn[modelTypeKey]; - var modelInfo = getModelInfoForName(type); - - if (!modelInfo) { - throw failure("model with name \"" + type + "\" not found in the registry"); - } - - var id = sn[modelIdKey]; // try to use model from pool if possible - - var modelInPool = modelPool.findModelForSnapshot(sn); - - if (modelInPool) { - value = modelInPool; - } - - if (!(value instanceof modelInfo["class"]) || value[modelTypeKey] !== type || value[modelIdKey] !== id) { - // different kind of model / model instance, no reconciliation possible - return fromSnapshot(sn); - } - - var modelObj = value; - var processedSn = sn; - - if (modelObj.fromSnapshot) { - processedSn = modelObj.fromSnapshot(sn); - } - - var data = modelObj.$; // remove excess props - - var dataKeys = Object.keys(data); - var dataKeysLen = dataKeys.length; - - for (var i = 0; i < dataKeysLen; i++) { - var k = dataKeys[i]; - - if (!(k in processedSn)) { - (0,mobx_esm.remove)(data, k); - } - } // reconcile the rest - - - var processedSnKeys = Object.keys(processedSn); - var processedSnKeysLen = processedSnKeys.length; - - for (var _i2 = 0; _i2 < processedSnKeysLen; _i2++) { - var _k = processedSnKeys[_i2]; - - if (!isReservedModelKey(_k)) { - var v = processedSn[_k]; - var oldValue = data[_k]; - var newValue = reconcileSnapshot(oldValue, v, modelPool); - detachIfNeeded(newValue, oldValue, modelPool); - (0,mobx_esm.set)(data, _k, newValue); - } - } - - return modelObj; -} - -function reconcilePlainObjectSnapshot(value, sn, modelPool) { - // plain obj - if (!isPlainObject(value) && !(0,mobx_esm.isObservableObject)(value)) { - // no reconciliation possible - return fromSnapshot(sn); - } - - var plainObj = value; // remove excess props - - var plainObjKeys = Object.keys(plainObj); - var plainObjKeysLen = plainObjKeys.length; - - for (var i = 0; i < plainObjKeysLen; i++) { - var k = plainObjKeys[i]; - - if (!(k in sn)) { - (0,mobx_esm.remove)(plainObj, k); - } - } // reconcile the rest - - - var snKeys = Object.keys(sn); - var snKeysLen = snKeys.length; - - for (var _i3 = 0; _i3 < snKeysLen; _i3++) { - var _k2 = snKeys[_i3]; - var v = sn[_k2]; - var oldValue = plainObj[_k2]; - var newValue = reconcileSnapshot(oldValue, v, modelPool); - detachIfNeeded(newValue, oldValue, modelPool); - (0,mobx_esm.set)(plainObj, _k2, newValue); - } - - return plainObj; -} - -function detachIfNeeded(newValue, oldValue, modelPool) { - // edge case for when we are swapping models around the tree - if (newValue === oldValue) { - // already where it should be - return; - } - - if (isModel(newValue) && modelPool.findModelByTypeAndId(newValue[modelTypeKey], newValue[modelIdKey])) { - var parentPath = fastGetParentPathIncludingDataObjects(newValue); - - if (parentPath) { - (0,mobx_esm.set)(parentPath.parent, parentPath.path, null); - } - } -} - -var ModelPool = /*#__PURE__*/function () { - function ModelPool(root) { - var _dataObjectParent$get; - - this.pool = void 0; - // make sure we don't use the sub-data $ object - root = (_dataObjectParent$get = dataObjectParent.get(root)) != null ? _dataObjectParent$get : root; - this.pool = getDeepObjectChildren(root).deepByModelTypeAndId; - } - - var _proto = ModelPool.prototype; - - _proto.findModelByTypeAndId = function findModelByTypeAndId(modelType, modelId) { - return this.pool.get(byModelTypeAndIdKey(modelType, modelId)); - }; - - _proto.findModelForSnapshot = function findModelForSnapshot(sn) { - if (!isModelSnapshot(sn)) { - return undefined; - } - - return this.findModelByTypeAndId(sn[modelTypeKey], sn[modelIdKey]); - }; - - return ModelPool; -}(); - -/** - * Applies the given patches to the given target object. - * - * @param node Target object. - * @param patches List of patches to apply. - * @param reverse Whether patches are applied in reverse order. - */ - -function applyPatches(node, patches, reverse) { - if (reverse === void 0) { - reverse = false; - } - - assertTweakedObject(node, "node"); - - if (patches.length <= 0) { - return; - } - - wrappedInternalApplyPatches().call(node, patches, reverse); -} -/** - * @ignore - * @internal - */ - -function internalApplyPatches(patches, reverse) { - if (reverse === void 0) { - reverse = false; - } - - var obj = this; - var modelPool = new ModelPool(obj); - - if (reverse) { - var i = patches.length; - - while (i--) { - var p = patches[i]; - - if (!isArray(p)) { - applySinglePatch(obj, p, modelPool); - } else { - var j = p.length; - - while (j--) { - applySinglePatch(obj, p[j], modelPool); - } - } - } - } else { - var len = patches.length; - - for (var _i = 0; _i < len; _i++) { - var _p = patches[_i]; - - if (!isArray(_p)) { - applySinglePatch(obj, _p, modelPool); - } else { - var len2 = _p.length; - - for (var _j = 0; _j < len2; _j++) { - applySinglePatch(obj, _p[_j], modelPool); - } - } - } - } -} -var wrappedInternalApplyPatches = /*#__PURE__*/lazy(function () { - return wrapInAction({ - name: BuiltInAction.ApplyPatches, - fn: internalApplyPatches, - actionType: ActionContextActionType.Sync - }); -}); - -function applySinglePatch(obj, patch, modelPool) { - var _pathArrayToObjectAnd = pathArrayToObjectAndProp(obj, patch.path), - target = _pathArrayToObjectAnd.target, - prop = _pathArrayToObjectAnd.prop; - - if (isArray(target)) { - switch (patch.op) { - case "add": - { - var index = +prop; // reconcile from the pool if possible - - var newValue = reconcileSnapshot(undefined, patch.value, modelPool); - target.splice(index, 0, newValue); - break; - } - - case "remove": - { - var _index = +prop; // no reconciliation, removing - - - target.splice(_index, 1); - break; - } - - case "replace": - { - if (prop === "length") { - target.length = patch.value; - } else { - var _index2 = +prop; // try to reconcile - - - var _newValue = reconcileSnapshot(target[_index2], patch.value, modelPool); - - (0,mobx_esm.set)(target, _index2, _newValue); - } - - break; - } - - default: - throw failure("unsupported patch operation: " + patch.op); - } - } else { - switch (patch.op) { - case "add": - { - // reconcile from the pool if possible - var _newValue2 = reconcileSnapshot(undefined, patch.value, modelPool); - - (0,mobx_esm.set)(target, prop, _newValue2); - break; - } - - case "remove": - { - // no reconciliation, removing - (0,mobx_esm.remove)(target, prop); - break; - } - - case "replace": - { - // try to reconcile - // we don't need to tweak the pool since reconcileSnapshot will do that for us - var _newValue3 = reconcileSnapshot(target[prop], patch.value, modelPool); - - (0,mobx_esm.set)(target, prop, _newValue3); - break; - } - - default: - throw failure("unsupported patch operation: " + patch.op); - } - } -} - -function pathArrayToObjectAndProp(obj, path) { - if (inDevMode()) { - if (!isArray(path)) { - throw failure("invalid path: " + path); - } - } - - var target = modelToDataNode(obj); - - if (path.length === 0) { - return { - target: target - }; - } - - for (var i = 0; i <= path.length - 2; i++) { - target = modelToDataNode(target[path[i]]); - } - - return { - target: target, - prop: path[path.length - 1] - }; -} - -/** - * @ignore - * @internal - */ - -function runTypeCheckingAfterChange(obj, patchRecorder) { - // invalidate type check cached result - invalidateCachedTypeCheckerResult(obj); - - if (isModelAutoTypeCheckingEnabled()) { - var parentModelWithTypeChecker = findNearestParentModelWithTypeChecker(obj); - - if (parentModelWithTypeChecker) { - var err = parentModelWithTypeChecker.typeCheck(); - - if (err) { - // quietly apply inverse patches (do not generate patches, snapshots, actions, etc) - runWithoutSnapshotOrPatches(function () { - internalApplyPatches.call(obj, patchRecorder.invPatches, true); - }); // at the end of apply patches it will be type checked again and its result cached once more - - err["throw"](parentModelWithTypeChecker); - } - } - } -} -/** - * @ignore - * - * Finds the closest parent model that has a type checker defined. - * - * @param child - * @returns - */ - -function findNearestParentModelWithTypeChecker(child) { - // child might be .$, so we need to check the parent model in that case - var actualChild = dataToModelNode(child); - - if (child !== actualChild) { - child = actualChild; - - if (isModel(child) && !!getModelDataType(child)) { - return child; - } - } - - return findParent(child, function (parent) { - return isModel(parent) && !!getModelDataType(parent); - }); -} - -/** - * @ignore - */ - -function tweakArray(value, parentPath, doNotTweakChildren) { - var originalArr = value; - var arrLn = originalArr.length; - var tweakedArr = (0,mobx_esm.isObservableArray)(originalArr) ? originalArr : mobx_esm.observable.array([], observableOptions$1); - - if (tweakedArr !== originalArr) { - tweakedArr.length = originalArr.length; - } - - var interceptDisposer; - var observeDisposer; - - var untweak = function untweak() { - interceptDisposer(); - observeDisposer(); - }; - - tweakedObjects.set(tweakedArr, untweak); - setParent(tweakedArr, parentPath, false, false); - var standardSn = []; - standardSn.length = arrLn; // substitute initial values by proxied values - - for (var i = 0; i < arrLn; i++) { - var v = originalArr[i]; - - if (isPrimitive(v)) { - if (!doNotTweakChildren) { - (0,mobx_esm.set)(tweakedArr, i, v); - } - - standardSn[i] = v; - } else { - var path = { - parent: tweakedArr, - path: i - }; - var tweakedValue = void 0; - - if (doNotTweakChildren) { - tweakedValue = v; - setParent(tweakedValue, path, false, false); - } else { - tweakedValue = tweak(v, path); - (0,mobx_esm.set)(tweakedArr, i, tweakedValue); - } - - var valueSn = getInternalSnapshot(tweakedValue); - standardSn[i] = valueSn.standard; - } - } - - setInternalSnapshot(tweakedArr, standardSn); - interceptDisposer = (0,mobx_esm.intercept)(tweakedArr, interceptArrayMutation.bind(undefined, tweakedArr)); - observeDisposer = (0,mobx_esm.observe)(tweakedArr, arrayDidChange); - return tweakedArr; -} - -function arrayDidChange(change -/*IArrayDidChange*/ -) { - var arr = change.object; - - var _getInternalSnapshot = getInternalSnapshot(arr), - oldSnapshot = _getInternalSnapshot.standard; - - var patchRecorder = new InternalPatchRecorder(); - var newSnapshot = oldSnapshot.slice(); - - switch (change.type) { - case "splice": - { - var index = change.index; - var addedCount = change.addedCount; - var removedCount = change.removedCount; - var addedItems = []; - addedItems.length = addedCount; - - for (var i = 0; i < addedCount; i++) { - var v = change.added[i]; - - if (isPrimitive(v)) { - addedItems[i] = v; - } else { - addedItems[i] = getInternalSnapshot(v).standard; - } - } - - var oldLen = oldSnapshot.length; - newSnapshot.splice.apply(newSnapshot, [index, removedCount].concat(addedItems)); - var patches = []; - var invPatches = []; // optimization: if we add as many as we remove then replace instead - - if (addedCount === removedCount) { - for (var _i = 0; _i < addedCount; _i++) { - var realIndex = index + _i; - var newVal = newSnapshot[realIndex]; - var oldVal = oldSnapshot[realIndex]; - - if (newVal !== oldVal) { - var path = [realIndex]; // replace 0, 1, 2... - - patches.push({ - op: "replace", - path: path, - value: newVal - }); // replace ...2, 1, 0 since inverse patches are applied in reverse - - invPatches.push({ - op: "replace", - path: path, - value: oldVal - }); - } - } - } else { - var interimLen = oldLen - removedCount; // first remove items - - if (removedCount > 0) { - // optimization, when removing from the end set the length instead - var removeUsingSetLength = index >= interimLen; - - if (removeUsingSetLength) { - patches.push({ - op: "replace", - path: ["length"], - value: interimLen - }); - } - - for (var _i2 = removedCount - 1; _i2 >= 0; _i2--) { - var _realIndex = index + _i2; - - var _path = [_realIndex]; - - if (!removeUsingSetLength) { - // remove ...2, 1, 0 - patches.push({ - op: "remove", - path: _path - }); - } // add 0, 1, 2... since inverse patches are applied in reverse - - - invPatches.push({ - op: "add", - path: _path, - value: oldSnapshot[_realIndex] - }); - } - } // then add items - - - if (addedCount > 0) { - // optimization, for inverse patches, when adding from the end set the length to restore instead - var restoreUsingSetLength = index >= interimLen; - - if (restoreUsingSetLength) { - invPatches.push({ - op: "replace", - path: ["length"], - value: interimLen - }); - } - - for (var _i3 = 0; _i3 < addedCount; _i3++) { - var _realIndex2 = index + _i3; - - var _path2 = [_realIndex2]; // add 0, 1, 2... - - patches.push({ - op: "add", - path: _path2, - value: newSnapshot[_realIndex2] - }); // remove ...2, 1, 0 since inverse patches are applied in reverse - - if (!restoreUsingSetLength) { - invPatches.push({ - op: "remove", - path: _path2 - }); - } - } - } - } - - patchRecorder.record(patches, invPatches); - } - break; - - case "update": - { - var k = change.index; - var val = change.newValue; - var _oldVal = newSnapshot[k]; - - if (isPrimitive(val)) { - newSnapshot[k] = val; - } else { - var valueSn = getInternalSnapshot(val); - newSnapshot[k] = valueSn.standard; - } - - var _path3 = [k]; - patchRecorder.record([{ - op: "replace", - path: _path3, - value: newSnapshot[k] - }], [{ - op: "replace", - path: _path3, - value: _oldVal - }]); - } - break; - } - - runTypeCheckingAfterChange(arr, patchRecorder); - - if (!runningWithoutSnapshotOrPatches) { - setInternalSnapshot(arr, newSnapshot); - patchRecorder.emit(arr); - } -} - -var undefinedInsideArrayErrorMsg = "undefined is not supported inside arrays since it is not serializable in JSON, consider using null instead"; // TODO: remove array parameter and just use change.object once mobx update event is fixed - -function interceptArrayMutation(array, change) { - assertCanWrite(); - - switch (change.type) { - case "splice": - { - if (inDevMode() && !getGlobalConfig().allowUndefinedArrayElements) { - var len = change.added.length; - - for (var i = 0; i < len; i++) { - var v = change.added[i]; - - if (v === undefined) { - throw failure(undefinedInsideArrayErrorMsg); - } - } - } - - for (var _i4 = 0; _i4 < change.removedCount; _i4++) { - var removedValue = change.object[change.index + _i4]; - tweak(removedValue, undefined); - tryUntweak(removedValue); - } - - for (var _i5 = 0; _i5 < change.added.length; _i5++) { - change.added[_i5] = tweak(change.added[_i5], { - parent: change.object, - path: change.index + _i5 - }); - } // we might also need to update the parent of the next indexes - - - var oldNextIndex = change.index + change.removedCount; - var newNextIndex = change.index + change.added.length; - - if (oldNextIndex !== newNextIndex) { - for (var _i6 = oldNextIndex, j = newNextIndex; _i6 < change.object.length; _i6++, j++) { - setParent(change.object[_i6], { - parent: change.object, - path: j - }, true, false); - } - } - } - break; - - case "update": - if (inDevMode() && !getGlobalConfig().allowUndefinedArrayElements && change.newValue === undefined) { - throw failure(undefinedInsideArrayErrorMsg); - } // TODO: should be change.object, but mobx is bugged and doesn't send the proxy - - - var oldVal = array[change.index]; - tweak(oldVal, undefined); // set old prop obj parent to undefined - - tryUntweak(oldVal); - change.newValue = tweak(change.newValue, { - parent: array, - path: change.index - }); - break; - } - - return change; -} - -var observableOptions$1 = { - deep: false -}; - -/** - * @ingore - */ - -function tweakFrozen(frozenObj, parentPath) { - var _setInternalSnapshot; - - tweakedObjects.set(frozenObj, undefined); - setParent(frozenObj, parentPath, false, false); // we DON'T want data proxified, but the snapshot is the data itself - - setInternalSnapshot(frozenObj, (_setInternalSnapshot = {}, _setInternalSnapshot[frozenKey] = true, _setInternalSnapshot.data = frozenObj.data, _setInternalSnapshot)); - return frozenObj; -} - -/** - * Turns an object (array, plain object) into a tree node, - * which then can accept calls to `getParent`, `getSnapshot`, etc. - * If a tree node is passed it will return the passed argument directly. - * - * @param value Object to turn into a tree node. - * @returns The object as a tree node. - */ - -function toTreeNode(value) { - if (!isObject(value)) { - throw failure("only objects can be turned into tree nodes"); - } - - if (!isTweakedObject(value, true)) { - return tweak(value, undefined); - } - - return value; -} -/** - * @ignore - */ - -function internalTweak(value, parentPath) { - if (isPrimitive(value)) { - return value; - } - - if (isTweakedObject(value, true)) { - setParent(value, parentPath, false, false); - return value; - } - - if (isModel(value)) { - return tweakModel(value, parentPath); - } - - if (isArray(value)) { - return tweakArray(value, parentPath, false); - } // plain object - - - if ((0,mobx_esm.isObservableObject)(value) || isPlainObject(value)) { - return tweakPlainObject(value, parentPath, undefined, false, false); - } - - if (value instanceof Frozen) { - return tweakFrozen(value, parentPath); - } // unsupported - - - if (isMap(value)) { - throw failure("maps are not directly supported. consider applying 'transformObjectAsMap' over a '{[k: string]: V}' property, or 'transformArrayAsMap' over a '[string, V][]' property instead."); - } // unsupported - - - if (isSet(value)) { - throw failure("sets are not directly supported. consider applying 'transformArrayAsSet' over a 'V[]' property instead."); - } - - throw failure("tweak can only work over models, observable objects/arrays, or primitives, but got " + value + " instead"); -} -/** - * @ignore - * @internal - */ - - -var tweak = /*#__PURE__*/(0,mobx_esm.action)("tweak", internalTweak); -/** - * @ignore - * @internal - */ - -function tryUntweak(value) { - if (isPrimitive(value)) { - return true; - } - - if (inDevMode()) { - if (fastGetParent(value)) { - throw failure("assertion error: object cannot be untweaked while it has a parent"); - } - } - - var untweaker = tweakedObjects.get(value); - - if (!untweaker) { - return false; - } // we have to make a copy since it will be changed - // we have to iterate ourselves since it seems like babel does not do downlevel iteration - - - var children = []; - var childrenIter = getObjectChildren(value).values(); - var childrenCur = childrenIter.next(); - - while (!childrenCur.done) { - children.push(childrenCur.value); - childrenCur = childrenIter.next(); - } - - for (var i = 0; i < children.length; i++) { - var v = children[i]; - setParent(v, undefined, false, false); - } - - untweaker(); - tweakedObjects["delete"](value); - unsetInternalSnapshot(value); - return true; -} - -/** - * @ignore - */ - -function tweakPlainObject(value, parentPath, snapshotModelType, doNotTweakChildren, isDataObject) { - var originalObj = value; - var tweakedObj = (0,mobx_esm.isObservableObject)(originalObj) ? originalObj : mobx_esm.observable.object({}, undefined, observableOptions$2); - var interceptDisposer; - var observeDisposer; - - var untweak = function untweak() { - interceptDisposer(); - observeDisposer(); - }; - - tweakedObjects.set(tweakedObj, untweak); - setParent(tweakedObj, parentPath, false, isDataObject); - var standardSn = {}; // substitute initial values by tweaked values - - var originalObjKeys = Object.keys(originalObj); - var originalObjKeysLen = originalObjKeys.length; - - for (var i = 0; i < originalObjKeysLen; i++) { - var k = originalObjKeys[i]; - var v = originalObj[k]; - - if (isPrimitive(v)) { - if (!doNotTweakChildren) { - (0,mobx_esm.set)(tweakedObj, k, v); - } - - standardSn[k] = v; - } else { - var path = { - parent: tweakedObj, - path: k - }; - var tweakedValue = void 0; - - if (doNotTweakChildren) { - tweakedValue = v; - setParent(tweakedValue, path, false, false); - } else { - tweakedValue = tweak(v, path); - (0,mobx_esm.set)(tweakedObj, k, tweakedValue); - } - - var valueSn = getInternalSnapshot(tweakedValue); - standardSn[k] = valueSn.standard; - } - } - - if (snapshotModelType) { - standardSn[modelTypeKey] = snapshotModelType; - } - - setInternalSnapshot(isDataObject ? dataToModelNode(tweakedObj) : tweakedObj, standardSn); - interceptDisposer = (0,mobx_esm.intercept)(tweakedObj, interceptObjectMutation); - observeDisposer = (0,mobx_esm.observe)(tweakedObj, objectDidChange); - return tweakedObj; -} -var observableOptions$2 = { - deep: false -}; - -function objectDidChange(change) { - var obj = change.object; - var actualNode = dataToModelNode(obj); - - var _getInternalSnapshot = getInternalSnapshot(actualNode), - standardSn = _getInternalSnapshot.standard; - - var patchRecorder = new InternalPatchRecorder(); - standardSn = Object.assign({}, standardSn); - - switch (change.type) { - case "add": - case "update": - { - var k = change.name; - var val = change.newValue; - var oldVal = standardSn[k]; - - if (isPrimitive(val)) { - standardSn[k] = val; - } else { - var valueSn = getInternalSnapshot(val); - standardSn[k] = valueSn.standard; - } - - var path = [k]; - - if (change.type === "add") { - patchRecorder.record([{ - op: "add", - path: path, - value: standardSn[k] - }], [{ - op: "remove", - path: path - }]); - } else { - patchRecorder.record([{ - op: "replace", - path: path, - value: standardSn[k] - }], [{ - op: "replace", - path: path, - value: oldVal - }]); - } - } - break; - - case "remove": - { - var _k = change.name; - var _oldVal = standardSn[_k]; - delete standardSn[_k]; - var _path = [_k]; - patchRecorder.record([{ - op: "remove", - path: _path - }], [{ - op: "add", - path: _path, - value: _oldVal - }]); - } - break; - } - - runTypeCheckingAfterChange(obj, patchRecorder); - - if (!runningWithoutSnapshotOrPatches) { - setInternalSnapshot(actualNode, standardSn); - patchRecorder.emit(actualNode); - } -} - -function interceptObjectMutation(change) { - assertCanWrite(); - - if (typeof change.name === "symbol") { - throw failure("symbol properties are not supported"); - } - - switch (change.type) { - case "add": - change.newValue = tweak(change.newValue, { - parent: change.object, - path: "" + change.name - }); - break; - - case "remove": - { - var oldVal = change.object[change.name]; - tweak(oldVal, undefined); - tryUntweak(oldVal); - break; - } - - case "update": - { - var _oldVal2 = change.object[change.name]; - tweak(_oldVal2, undefined); - tryUntweak(_oldVal2); - change.newValue = tweak(change.newValue, { - parent: change.object, - path: "" + change.name - }); - break; - } - } - - return change; -} - -/** - * @internal - * @ignore - */ -var modelInitializersSymbol = /*#__PURE__*/Symbol("modelInitializers"); -/** - * @internal - * @ignore - */ - -function addModelClassInitializer(modelClass, init) { - var initializers = modelClass[modelInitializersSymbol]; - - if (!initializers) { - initializers = []; - modelClass[modelInitializersSymbol] = initializers; - } - - initializers.push(init); -} -/** - * @internal - * @ignore - */ - -function getModelClassInitializers(modelClass) { - return modelClass[modelInitializersSymbol]; -} - -/** - * @ignore - * @internal - */ - -var internalNewModel = /*#__PURE__*/(0,mobx_esm.action)("newModel", function (origModelObj, initialData, options) { - var _modelClass = options.modelClass, - snapshotInitialData = options.snapshotInitialData, - generateNewIds = options.generateNewIds; - var modelClass = _modelClass; - - if (inDevMode()) { - assertIsModelClass(modelClass, "modelClass"); - } - - var modelObj = origModelObj; - var modelInfo = modelInfoByClass.get(modelClass); - - if (!modelInfo) { - throw failure("no model info for class " + modelClass.name + " could be found - did you forget to add the @model decorator?"); - } - - var id; - - if (snapshotInitialData) { - var sn = snapshotInitialData.unprocessedSnapshot; - - if (generateNewIds) { - id = getGlobalConfig().modelIdGenerator(); - } else { - id = sn[modelIdKey]; - } - - if (modelObj.fromSnapshot) { - sn = modelObj.fromSnapshot(sn); - } - - initialData = snapshotInitialData.snapshotToInitialData(sn); - } else { - // use symbol if provided - if (initialData[modelIdKey]) { - id = initialData[modelIdKey]; - } else { - id = getGlobalConfig().modelIdGenerator(); - } - } - - modelObj[modelTypeKey] = modelInfo.name; // fill in defaults in initial data - - var modelProps = getInternalModelClassPropsInfo(modelClass); - var modelPropsKeys = Object.keys(modelProps); - - for (var i = 0; i < modelPropsKeys.length; i++) { - var k = modelPropsKeys[i]; - var v = initialData[k]; - - if (v === undefined || v === null) { - var newValue = v; - var propData = modelProps[k]; - - if (propData.defaultFn !== noDefaultValue) { - newValue = propData.defaultFn(); - } else if (propData.defaultValue !== noDefaultValue) { - newValue = propData.defaultValue; - } - - (0,mobx_esm.set)(initialData, k, newValue); - } - } - - (0,mobx_esm.set)(initialData, modelIdKey, id); - tweakModel(modelObj, undefined); // create observable data object with initial data - - var obsData = tweakPlainObject(initialData, { - parent: modelObj, - path: "$" - }, modelObj[modelTypeKey], false, true); // hide $.$modelId - - Object.defineProperty(obsData, modelIdKey, _extends({}, Object.getOwnPropertyDescriptor(obsData, modelIdKey), { - enumerable: false - })); // link it, and make it readonly - - modelObj.$ = obsData; - - if (inDevMode()) { - makePropReadonly(modelObj, "$", true); - } // type check it if needed - - - if (isModelAutoTypeCheckingEnabled() && getModelDataType(modelClass)) { - var err = modelObj.typeCheck(); - - if (err) { - err["throw"](modelObj); - } - } // run any extra initializers for the class as needed - - - var initializers = getModelClassInitializers(modelClass); - - if (initializers) { - var len = initializers.length; - - for (var _i = 0; _i < len; _i++) { - var init = initializers[_i]; - init(modelObj); - } - } - - return modelObj; -}); - -/** - * @ignore - */ - -var propsDataTypeSymbol = /*#__PURE__*/Symbol(); -/** - * @ignore - */ - -var propsCreationDataTypeSymbol = /*#__PURE__*/Symbol(); -/** - * @ignore - */ - -var instanceDataTypeSymbol = /*#__PURE__*/Symbol(); -/** - * @ignore - */ - -var instanceCreationDataTypeSymbol = /*#__PURE__*/Symbol(); -/** - * @ignore - * @internal - */ - -var modelInitializedSymbol = /*#__PURE__*/Symbol("modelInitialized"); -/** - * Base abstract class for models. Use `Model` instead when extending. - * - * Never override the constructor, use `onInit` or `onAttachedToRootStore` instead. - * - * @typeparam Data Data type. - * @typeparam CreationData Creation data type. - */ - -var BaseModel = /*#__PURE__*/function () { - var _proto = BaseModel.prototype; - - // just to make typing work properly - - /** - * Model type name. - */ - - /** - * Model internal id. Can be modified inside a model action. - */ - - /** - * Can be overriden to offer a reference id to be used in reference resolution. - * By default it will use `$modelId`. - */ - _proto.getRefId = function getRefId() { - return this[modelIdKey]; - } - /** - * Data part of the model, which is observable and will be serialized in snapshots. - * Use it if one of the data properties matches one of the model properties/functions. - * This also allows access to the backed values of transformed properties. - */ - ; - - /** - * Performs a type check over the model instance. - * For this to work a data type has to be declared in the model decorator. - * - * @returns A `TypeCheckError` or `null` if there is no error. - */ - _proto.typeCheck = function typeCheck$1() { - var type = typesModel(this.constructor); - return typeCheck(type, this); - } - /** - * Creates an instance of Model. - */ - ; - - function BaseModel(data) { - this[propsDataTypeSymbol] = void 0; - this[propsCreationDataTypeSymbol] = void 0; - this[instanceDataTypeSymbol] = void 0; - this[instanceCreationDataTypeSymbol] = void 0; - this[modelTypeKey] = void 0; - this[modelIdKey] = void 0; - this.$ = void 0; - var initialData = data; - var _arguments$ = arguments[1], - snapshotInitialData = _arguments$.snapshotInitialData, - modelClass = _arguments$.modelClass, - propsWithTransforms = _arguments$.propsWithTransforms, - generateNewIds = _arguments$.generateNewIds; - Object.setPrototypeOf(this, modelClass.prototype); - var self = this; // let's always use the one from the prototype - - delete self[modelIdKey]; // delete unnecessary props - - delete self[propsDataTypeSymbol]; - delete self[propsCreationDataTypeSymbol]; - delete self[instanceDataTypeSymbol]; - delete self[instanceCreationDataTypeSymbol]; - - if (!snapshotInitialData) { - // plain new - assertIsObject(initialData, "initialData"); // apply transforms to initial data if needed - - var propsWithTransformsLen = propsWithTransforms.length; - - if (propsWithTransformsLen > 0) { - initialData = Object.assign(initialData); - - for (var i = 0; i < propsWithTransformsLen; i++) { - var propWithTransform = propsWithTransforms[i]; - var propName = propWithTransform[0]; - var propTransform = propWithTransform[1]; - var memoTransform = memoTransformCache.getOrCreateMemoTransform(this, propName, propTransform); - initialData[propName] = memoTransform.dataToProp(initialData[propName]); - } - } - - internalNewModel(this, mobx_esm.observable.object(initialData, undefined, { - deep: false - }), { - modelClass: modelClass, - generateNewIds: true - }); - } else { - // from snapshot - internalNewModel(this, undefined, { - modelClass: modelClass, - snapshotInitialData: snapshotInitialData, - generateNewIds: generateNewIds - }); - } - } - - _proto.toString = function toString(options) { - var finalOptions = _extends({ - withData: true - }, options); - - var firstPart = this.constructor.name + "#" + this[modelTypeKey]; - return finalOptions.withData ? "[" + firstPart + " " + JSON.stringify(getSnapshot(this)) + "]" : "[" + firstPart + "]"; - }; - - return BaseModel; -}(); // these props will never be hoisted to this (except for model id) - -/** - * @internal - */ - -var baseModelPropNames = /*#__PURE__*/new Set([modelTypeKey, modelIdKey, "onInit", "$", "getRefId", "onAttachedToRootStore", "fromSnapshot", "typeCheck"]); -/** - * @deprecated Should not be needed anymore. - * - * Tricks Typescript into accepting abstract classes as a parameter for `ExtendedModel`. - * Does nothing in runtime. - * - * @typeparam T Abstract model class type. - * @param type Abstract model class. - * @returns - */ - -function abstractModelClass(type) { - return type; -} -/** - * Tricks Typescript into accepting a particular kind of generic class as a parameter for `ExtendedModel`. - * Does nothing in runtime. - * - * @typeparam T Generic model class type. - * @param type Generic model class. - * @returns - */ - -function modelClass(type) { - return type; -} -/** - * Add missing model metadata to a model creation snapshot to generate a proper model snapshot. - * Usually used alongside `fromSnapshot`. - * - * @typeparam M Model type. - * @param modelClass Model class. - * @param snapshot Model creation snapshot without metadata. - * @param [internalId] Model internal ID, or `undefined` to generate a new one. - * @returns The model snapshot (including metadata). - */ - -function modelSnapshotInWithMetadata(modelClass, snapshot, internalId) { - var _extends2; - - if (internalId === void 0) { - internalId = getGlobalConfig().modelIdGenerator(); - } - - assertIsModelClass(modelClass, "modelClass"); - assertIsObject(snapshot, "initialData"); - var modelInfo = modelInfoByClass.get(modelClass); - return _extends({}, snapshot, (_extends2 = {}, _extends2[modelTypeKey] = modelInfo.name, _extends2[modelIdKey] = internalId, _extends2)); -} -/** - * Add missing model metadata to a model output snapshot to generate a proper model snapshot. - * Usually used alongside `applySnapshot`. - * - * @typeparam M Model type. - * @param modelClass Model class. - * @param snapshot Model output snapshot without metadata. - * @param [internalId] Model internal ID, or `undefined` to generate a new one. - * @returns The model snapshot (including metadata). - */ - -function modelSnapshotOutWithMetadata(modelClass, snapshot, internalId) { - var _extends3; - - if (internalId === void 0) { - internalId = getGlobalConfig().modelIdGenerator(); - } - - assertIsModelClass(modelClass, "modelClass"); - assertIsObject(snapshot, "initialData"); - var modelInfo = modelInfoByClass.get(modelClass); - return _extends({}, snapshot, (_extends3 = {}, _extends3[modelTypeKey] = modelInfo.name, _extends3[modelIdKey] = internalId, _extends3)); -} - -/** - * Checks if an object is a model instance. - * - * @param model - * @returns - */ - -function isModel(model) { - return model instanceof BaseModel; -} -/** - * @ignore - * @internal - * - * Asserts something is actually a model. - * - * @param model - * @param argName - */ - -function assertIsModel(model, argName, customErrMsg) { - if (customErrMsg === void 0) { - customErrMsg = "must be a model instance"; - } - - if (!isModel(model)) { - throw failure(argName + " " + customErrMsg); - } -} -/** - * @ignore - * @internal - */ - -function isModelClass(modelClass) { - if (typeof modelClass !== "function") { - return false; - } - - if (modelClass !== BaseModel && !(modelClass.prototype instanceof BaseModel)) { - return false; - } - - return true; -} -/** - * @ignore - * @internal - */ - -function assertIsModelClass(modelClass, argName) { - if (typeof modelClass !== "function") { - throw failure(argName + " must be a class"); - } - - if (modelClass !== BaseModel && !(modelClass.prototype instanceof BaseModel)) { - throw failure(argName + " must extend Model"); - } -} -/** - * @ignore - * @internal - */ - -function isModelSnapshot(sn) { - return isPlainObject(sn) && !!sn[modelTypeKey]; -} -/** - * @ignore - * @internal - */ - -function checkModelDecoratorArgs(fnName, target, propertyKey) { - if (typeof propertyKey !== "string") { - throw failure(fnName + " cannot be used over symbol properties"); - } - - var errMessage = fnName + " must be used over model classes or instances"; - - if (!target) { - throw failure(errMessage); - } // check target is a model object or extended class - - - if (!(target instanceof BaseModel) && target !== BaseModel && !(target.prototype instanceof BaseModel)) { - throw failure(errMessage); - } -} - -/** - * Returns if the given function is a model action or not. - * - * @param fn Function to check. - * @returns - */ - -function isModelAction(fn) { - return typeof fn === "function" && !!fn[modelActionSymbol]; -} - -function checkModelActionArgs(target, propertyKey, value) { - if (typeof value !== "function") { - throw failure("modelAction has to be used over functions"); - } - - checkModelDecoratorArgs("modelAction", target, propertyKey); -} -/** - * Decorator that turns a function into a model action. - * - * @param target - * @param propertyKey - * @param [baseDescriptor] - * @returns - */ - - -function modelAction(target, propertyKey, baseDescriptor) { - return decorateWrapMethodOrField("modelAction", { - target: target, - propertyKey: propertyKey, - baseDescriptor: baseDescriptor - }, function (data, fn) { - if (isModelAction(fn)) { - return fn; - } else { - checkModelActionArgs(data.target, data.propertyKey, fn); - return wrapInAction({ - name: data.propertyKey, - fn: fn, - actionType: ActionContextActionType.Sync - }); - } - }); -} - -var modelFlowSymbol = /*#__PURE__*/Symbol("modelFlow"); -/** - * @ignore - * @internal - */ - -function flow(name, generator) { - // Implementation based on https://github.com/tj/co/blob/master/index.js - var flowFn = function flowFn() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - var target = this; - - if (inDevMode()) { - assertTweakedObject(target, "flow"); - } - - var previousAsyncStepContext; - - var ctxOverride = function ctxOverride(stepType) { - return function (ctx) { - ctx.previousAsyncStepContext = previousAsyncStepContext; - ctx.spawnAsyncStepContext = previousAsyncStepContext ? previousAsyncStepContext.spawnAsyncStepContext : ctx; - ctx.asyncStepType = stepType; - ctx.args = args; - previousAsyncStepContext = ctx; - }; - }; - - var generatorRun = false; - var gen = wrapInAction({ - name: name, - fn: function fn() { - generatorRun = true; - return generator.apply(target, args); - }, - actionType: ActionContextActionType.Async, - overrideContext: ctxOverride(ActionContextAsyncStepType.Spawn) - }).apply(target); - - if (!generatorRun) { - // maybe it got overridden into a sync action - return gen instanceof Promise ? gen : Promise.resolve(gen); - } // use bound functions to fix es6 compilation - - - var genNext = gen.next.bind(gen); - var genThrow = gen["throw"].bind(gen); - var promise = new Promise(function (resolve, reject) { - function onFulfilled(res) { - var ret; - - try { - ret = wrapInAction({ - name: name, - fn: genNext, - actionType: ActionContextActionType.Async, - overrideContext: ctxOverride(ActionContextAsyncStepType.Resume) - }).call(target, res); - } catch (e) { - wrapInAction({ - name: name, - fn: function fn(err) { - // we use a flow finisher to allow middlewares to tweak the return value before resolution - return { - value: err, - resolution: "reject", - accepter: resolve, - rejecter: reject - }; - }, - actionType: ActionContextActionType.Async, - overrideContext: ctxOverride(ActionContextAsyncStepType.Throw), - isFlowFinisher: true - }).call(target, e); - return; - } - - next(ret); - } - - function onRejected(err) { - var ret; - - try { - ret = wrapInAction({ - name: name, - fn: genThrow, - actionType: ActionContextActionType.Async, - overrideContext: ctxOverride(ActionContextAsyncStepType.ResumeError) - }).call(target, err); - } catch (e) { - wrapInAction({ - name: name, - fn: function fn(err) { - // we use a flow finisher to allow middlewares to tweak the return value before resolution - return { - value: err, - resolution: "reject", - accepter: resolve, - rejecter: reject - }; - }, - actionType: ActionContextActionType.Async, - overrideContext: ctxOverride(ActionContextAsyncStepType.Throw), - isFlowFinisher: true - }).call(target, e); - return; - } - - next(ret); - } - - function next(ret) { - if (ret && typeof ret.then === "function") { - // an async iterator - ret.then(next, reject); - } else if (ret.done) { - // done - wrapInAction({ - name: name, - fn: function fn(val) { - // we use a flow finisher to allow middlewares to tweak the return value before resolution - return { - value: val, - resolution: "accept", - accepter: resolve, - rejecter: reject - }; - }, - actionType: ActionContextActionType.Async, - overrideContext: ctxOverride(ActionContextAsyncStepType.Return), - isFlowFinisher: true - }).call(target, ret.value); - } else { - // continue - Promise.resolve(ret.value).then(onFulfilled, onRejected); - } - } - - onFulfilled(undefined); // kick off the process - }); - return promise; - }; - - flowFn[modelFlowSymbol] = true; - return flowFn; -} -/** - * Returns if the given function is a model flow or not. - * - * @param fn Function to check. - * @returns - */ - -function isModelFlow(fn) { - return typeof fn === "function" && fn[modelFlowSymbol]; -} -/** - * Decorator that turns a function generator into a model flow. - * - * @param target - * @param propertyKey - * @param [baseDescriptor] - * @returns - */ - -function modelFlow(target, propertyKey, baseDescriptor) { - return decorateWrapMethodOrField("modelFlow", { - target: target, - propertyKey: propertyKey, - baseDescriptor: baseDescriptor - }, function (data, fn) { - if (isModelFlow(fn)) { - return fn; - } else { - checkModelFlowArgs(data.target, data.propertyKey, fn); - return flow(data.propertyKey, fn); - } - }); -} - -function checkModelFlowArgs(target, propertyKey, value) { - if (typeof value !== "function") { - throw failure("modelFlow has to be used over functions"); - } - - checkModelDecoratorArgs("modelFlow", target, propertyKey); -} -/** - * Tricks the TS compiler into thinking that a model flow generator function can be awaited - * (is a promise). - * - * @typeparam A Function arguments. - * @typeparam R Return value. - * @param fn Flow function. - * @returns - */ - - -function _async(fn) { - return fn; -} -/** - * Makes a promise a flow, so it can be awaited with yield*. - * - * @typeparam T Promise return type. - * @param promise Promise. - * @returns - */ - -function _await(promise) { - return promiseGenerator.call(promise); -} -/* -function* promiseGenerator( - this: Promise -) { - const ret: T = yield this - return ret -} -*/ -// above code but compiled by TS for ES5 -// so we don't include a dependency to regenerator runtime - -var mobxkeystone_esm_generator = function __generator(thisArg, body) { - var _ = { - label: 0, - sent: function sent() { - if (t[0] & 1) throw t[1]; - return t[1]; - }, - trys: [], - ops: [] - }, - f, - y, - t, - g; - return g = { - next: verb(0), - "throw": verb(1), - "return": verb(2) - }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { - return this; - }), g; - - function verb(n) { - return function (v) { - return step([n, v]); - }; - } - - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - - while (_) { - try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - - switch (op[0]) { - case 0: - case 1: - t = op; - break; - - case 4: - _.label++; - return { - value: op[1], - done: false - }; - - case 5: - _.label++; - y = op[1]; - op = [0]; - continue; - - case 7: - op = _.ops.pop(); - - _.trys.pop(); - - continue; - - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _ = 0; - continue; - } - - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _.label = op[1]; - break; - } - - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; - } - - if (t && _.label < t[2]) { - _.label = t[2]; - - _.ops.push(op); - - break; - } - - if (t[2]) _.ops.pop(); - - _.trys.pop(); - - continue; - } - - op = body.call(thisArg, _); - } catch (e) { - op = [6, e]; - y = 0; - } finally { - f = t = 0; - } - } - - if (op[0] & 5) throw op[1]; - return { - value: op[0] ? op[1] : void 0, - done: true - }; - } -}; - -function promiseGenerator() { - var ret; - return mobxkeystone_esm_generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 - /*yield*/ - , this]; - - case 1: - ret = _a.sent(); - return [2 - /*return*/ - , ret]; - - default: - return; - } - }); -} - -/** - * @ignore - * @internal - */ - -function assertFnModelKeyNotInUse(fnModelObj, key) { - if (fnModelObj[key] !== undefined) { - throw failure("key '" + key + "' cannot be redeclared"); - } -} - -var fnModelActionRegistry = /*#__PURE__*/new Map(); -/** - * @ignore - * @internal - */ - -function getFnModelAction(actionName) { - return fnModelActionRegistry.get(actionName); -} -/** - * @ignore - * @internal - */ - -function extendFnModelActions(fnModelObj, namespace, actions) { - for (var _i = 0, _Object$entries = Object.entries(actions); _i < _Object$entries.length; _i++) { - var _Object$entries$_i = _Object$entries[_i], - name = _Object$entries$_i[0], - fn = _Object$entries$_i[1]; - addActionToFnModel(fnModelObj, namespace, name, fn, false); - } - - return fnModelObj; -} -/** - * @ignore - * @internal - */ - -function addActionToFnModel(fnModelObj, namespace, name, fn, isFlow) { - assertFnModelKeyNotInUse(fnModelObj, name); - var fullActionName = namespace + "::" + name; - assertIsFunction(fn, fullActionName); - - if (fnModelActionRegistry.has(fullActionName)) { - logWarning("warn", "an standalone action with name \"" + fullActionName + "\" already exists (if you are using hot-reloading you may safely ignore this warning)", "duplicateActionName - " + name); - } - - if (isModelAction(fn)) { - throw failure("the standalone action must not be previously marked as an action"); - } - - if (isModelFlow(fn)) { - throw failure("the standalone action must not be previously marked as a flow action"); - } - - var wrappedAction = isFlow ? flow(fullActionName, fn) : wrapInAction({ - name: fullActionName, - fn: fn, - actionType: ActionContextActionType.Sync - }); - - fnModelObj[name] = function (target) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - return wrappedAction.apply(target, args); - }; - - fnModelActionRegistry.set(fullActionName, fnModelObj[name]); -} - -/** - * Applies a full snapshot over an object, reconciling it with the current contents of the object. - * - * @typeparam T Object type. - * @param node Target object (model object, object or array). - * @param snapshot Snapshot to apply. - */ - -function applySnapshot(node, snapshot) { - assertTweakedObject(node, "node"); - assertIsObject(snapshot, "snapshot"); - wrappedInternalApplySnapshot().call(node, snapshot); -} - -function internalApplySnapshot(sn) { - var obj = this; - - var reconcile = function reconcile() { - var modelPool = new ModelPool(obj); - var ret = reconcileSnapshot(obj, sn, modelPool); - - if (inDevMode()) { - if (ret !== obj) { - throw failure("assertion error: reconciled object has to be the same"); - } - } - }; - - if (isArray(sn)) { - if (!isArray(obj)) { - throw failure("if the snapshot is an array the target must be an array too"); - } - - return reconcile(); - } - - if (isFrozenSnapshot(sn)) { - throw failure("applySnapshot cannot be used over frozen objects"); - } - - if (isModelSnapshot(sn)) { - var type = sn[modelTypeKey]; - var modelInfo = getModelInfoForName(type); - - if (!modelInfo) { - throw failure("model with name \"" + type + "\" not found in the registry"); - } // we don't check by actual instance since it might be a different one due to hot reloading - - - if (!isModel(obj)) { - // not a model instance, no reconciliation possible - throw failure("the target for a model snapshot must be a model instance"); - } - - if (obj[modelTypeKey] !== type) { - // different kind of model, no reconciliation possible - throw failure("snapshot model type '" + type + "' does not match target model type '" + obj[modelTypeKey] + "'"); - } - - var id = sn[modelIdKey]; - - if (obj[modelIdKey] !== id) { - // different id, no reconciliation possible - throw failure("snapshot model id '" + id + "' does not match target model id '" + obj[modelIdKey] + "'"); - } - - return reconcile(); - } - - if (isPlainObject(sn)) { - if (!isPlainObject(obj) && !(0,mobx_esm.isObservableObject)(obj)) { - // no reconciliation possible - throw failure("if the snapshot is an object the target must be an object too"); - } - - return reconcile(); - } - - throw failure("unsupported snapshot - " + sn); -} - -var wrappedInternalApplySnapshot = /*#__PURE__*/lazy(function () { - return wrapInAction({ - name: BuiltInAction.ApplySnapshot, - fn: internalApplySnapshot, - actionType: ActionContextActionType.Sync - }); -}); - -/** - * Deletes an object field wrapped in an action. - * - * @param node Target object. - * @param fieldName Field name. - */ - -function applyDelete(node, fieldName) { - assertTweakedObject(node, "node"); - wrappedInternalApplyDelete().call(node, fieldName); -} -/** - * @ignore - * @internal - */ - -function internalApplyDelete(fieldName) { - (0,mobx_esm.remove)(this, "" + fieldName); -} -var wrappedInternalApplyDelete = /*#__PURE__*/lazy(function () { - return wrapInAction({ - name: BuiltInAction.ApplyDelete, - fn: internalApplyDelete, - actionType: ActionContextActionType.Sync - }); -}); - -/** - * Calls an object method wrapped in an action. - * - * @param node Target object. - * @param methodName Method name. - */ - -function applyMethodCall(node, methodName) { - assertTweakedObject(node, "node"); - - for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { - args[_key - 2] = arguments[_key]; - } - - return wrappedInternalApplyMethodCall().call(node, methodName, args); -} -/** - * @ignore - * @internal - */ - -function internalApplyMethodCall(methodName, args) { - return this[methodName].apply(this, args); -} -var wrappedInternalApplyMethodCall = /*#__PURE__*/lazy(function () { - return wrapInAction({ - name: BuiltInAction.ApplyMethodCall, - fn: internalApplyMethodCall, - actionType: ActionContextActionType.Sync - }); -}); - -/** - * Sets an object field wrapped in an action. - * - * @param node Target object. - * @param fieldName Field name. - * @param value Value to set. - */ - -function applySet(node, fieldName, value) { - assertTweakedObject(node, "node"); - wrappedInternalApplySet().call(node, fieldName, value); -} - -function internalApplySet(fieldName, value) { - // we need to check if it is a model since models can become observable objects - // (e.g. by having a computed value) - if (!isModel(this) && (0,mobx_esm.isObservable)(this)) { - (0,mobx_esm.set)(this, fieldName, value); - } else { - this[fieldName] = value; - } -} - -var wrappedInternalApplySet = /*#__PURE__*/lazy(function () { - return wrapInAction({ - name: BuiltInAction.ApplySet, - fn: internalApplySet, - actionType: ActionContextActionType.Sync - }); -}); - -var _builtInActionToFunct; -var builtInActionToFunction = (_builtInActionToFunct = {}, _builtInActionToFunct[BuiltInAction.ApplySnapshot] = applySnapshot, _builtInActionToFunct[BuiltInAction.ApplyPatches] = applyPatches, _builtInActionToFunct[BuiltInAction.Detach] = detach, _builtInActionToFunct[BuiltInAction.ApplySet] = applySet, _builtInActionToFunct[BuiltInAction.ApplyDelete] = applyDelete, _builtInActionToFunct[BuiltInAction.ApplyMethodCall] = applyMethodCall, _builtInActionToFunct); -/** - * Applies (runs) an action over a target object. - * - * If you intend to apply serialized actions check one of the `applySerializedAction` methods instead. - * - * @param subtreeRoot Subtree root target object to run the action over. - * @param call The action, usually as coming from `onActionMiddleware`. - * @returns The return value of the action, if any. - */ - -function applyAction(subtreeRoot, call) { - if (call.serialized) { - throw failure("cannot apply a serialized action call, use one of the 'applySerializedAction' methods instead"); - } - - assertTweakedObject(subtreeRoot, "subtreeRoot"); // resolve path while checking ids - - var _resolvePathCheckingI = resolvePathCheckingIds(subtreeRoot, call.targetPath, call.targetPathIds), - current = _resolvePathCheckingI.value, - resolved = _resolvePathCheckingI.resolved; - - if (!resolved) { - throw failure("object at path " + JSON.stringify(call.targetPath) + " with ids " + JSON.stringify(call.targetPathIds) + " could not be resolved"); - } - - assertTweakedObject(current, "resolved " + current, true); - - if (isBuiltInAction(call.actionName)) { - var fnToCall = builtInActionToFunction[call.actionName]; - - if (!fnToCall) { - throw failure("assertion error: unknown built-in action - " + call.actionName); - } - - return fnToCall.apply(current, [current].concat(call.args)); - } else if (isHookAction(call.actionName)) { - throw failure("calls to hooks (" + call.actionName + ") cannot be applied"); - } else { - var standaloneAction = getFnModelAction(call.actionName); - - if (standaloneAction) { - return standaloneAction.apply(current, call.args); - } else { - return current[call.actionName].apply(current, call.args); - } - } -} - -var cannotSerialize = /*#__PURE__*/Symbol("cannotSerialize"); - -var arraySerializer = { - id: "mobx-keystone/array", - serialize: function serialize(value, _serialize) { - if (!isArray(value)) return cannotSerialize; // this will also transform observable arrays into non-observable ones - - return value.map(_serialize); - }, - deserialize: function deserialize(arr, _deserialize) { - return arr.map(_deserialize); - } -}; - -var dateSerializer = { - id: "mobx-keystone/dateAsTimestamp", - serialize: function serialize(date) { - if (!(date instanceof Date)) return cannotSerialize; - return +date; - }, - deserialize: function deserialize(timestamp) { - return new Date(timestamp); - } -}; - -var mapSerializer = { - id: "mobx-keystone/mapAsArray", - serialize: function serialize(map, _serialize) { - if (!(map instanceof Map) && !(0,mobx_esm.isObservableMap)(map)) return cannotSerialize; - var arr = []; - var iter = map.keys(); - var cur = iter.next(); - - while (!cur.done) { - var k = cur.value; - var v = map.get(k); - arr.push([_serialize(k), _serialize(v)]); - cur = iter.next(); - } - - return arr; - }, - deserialize: function deserialize(arr, _deserialize) { - var map = new Map(); - var len = arr.length; - - for (var i = 0; i < len; i++) { - var k = arr[i][0]; - var v = arr[i][1]; - map.set(_deserialize(k), _deserialize(v)); - } - - return map; - } -}; - -/** - * @ignore - */ - -function rootPathToTargetPathIds(rootPath) { - var targetPathIds = []; - - for (var i = 0; i < rootPath.path.length; i++) { - var targetObj = rootPath.pathObjects[i + 1]; // first is root, we don't care about its ID - - var targetObjId = isModel(targetObj) ? targetObj[modelIdKey] : null; - targetPathIds.push(targetObjId); - } - - return targetPathIds; -} -/** - * @ignore - */ - -function pathToTargetPathIds(root, path) { - var targetPathIds = []; - var current = root; // we don't care about the root ID - - for (var i = 0; i < path.length; i++) { - current = current[path[i]]; - var targetObjId = isModel(current) ? current[modelIdKey] : null; - targetPathIds.push(targetObjId); - } - - return targetPathIds; -} - -var objectPathSerializer = { - id: "mobx-keystone/objectPath", - serialize: function serialize(value, _, targetRoot) { - if (typeof value !== "object" || value === null || !isTweakedObject(value, false)) return cannotSerialize; // try to serialize a ref to its path if possible instead - - if (targetRoot) { - var rootPath = fastGetRootPath(value); - - if (rootPath.root === targetRoot) { - return { - targetPath: rootPath.path, - targetPathIds: rootPathToTargetPathIds(rootPath) - }; - } - } - - return cannotSerialize; - }, - deserialize: function deserialize(ref, _, targetRoot) { - // try to resolve the node back - if (targetRoot) { - var result = resolvePathCheckingIds(targetRoot, ref.targetPath, ref.targetPathIds); - - if (result.resolved) { - return result.value; - } - } - - throw failure("object at path " + JSON.stringify(ref.targetPath) + " with ids " + JSON.stringify(ref.targetPathIds) + " could not be resolved"); - } -}; - -var objectSnapshotSerializer = { - id: "mobx-keystone/objectSnapshot", - serialize: function serialize(value) { - if (typeof value !== "object" || value === null || !isTweakedObject(value, false)) return cannotSerialize; - return getSnapshot(value); - }, - deserialize: function deserialize(snapshot) { - return fromSnapshot(snapshot); - } -}; - -var plainObjectSerializer = { - id: "mobx-keystone/plainObject", - serialize: function serialize(value, _serialize) { - if (!isPlainObject(value) && !(0,mobx_esm.isObservableObject)(value)) return cannotSerialize; // this will make observable objects non-observable ones - - return mapObjectFields(value, _serialize); - }, - deserialize: function deserialize(obj, serialize) { - return mapObjectFields(obj, serialize); - } -}; - -function mapObjectFields(originalObj, mapFn) { - var obj = {}; - var keys = Object.keys(originalObj); - var len = keys.length; - - for (var i = 0; i < len; i++) { - var k = keys[i]; - var v = originalObj[k]; - obj[k] = mapFn(v); - } - - return obj; -} - -var setSerializer = { - id: "mobx-keystone/setAsArray", - serialize: function serialize(set, _serialize) { - if (!(set instanceof Set)) return cannotSerialize; - var arr = []; - var iter = set.keys(); - var cur = iter.next(); - - while (!cur.done) { - var k = cur.value; - arr.push(_serialize(k)); - cur = iter.next(); - } - - return arr; - }, - deserialize: function deserialize(arr, _deserialize) { - var set = new Set(); - var len = arr.length; - - for (var i = 0; i < len; i++) { - var k = arr[i]; - set.add(_deserialize(k)); - } - - return set; - } -}; - -var serializersArray = []; -var serializersMap = /*#__PURE__*/new Map(); -/** - * Registers a new action call argument serializers. - * Serializers are called in the inverse order they are registered, meaning the - * latest one registered will be called first. - * - * @param serializer Serializer to register. - * @returns A disposer to unregister the serializer. - */ - -function registerActionCallArgumentSerializer(serializer) { - if (serializersArray.includes(serializer)) { - throw failure("action call argument serializer already registered"); - } - - if (serializersMap.has(serializer.id)) { - throw failure("action call argument serializer with id '" + serializer.id + "' already registered"); - } - - serializersArray.unshift(serializer); - serializersMap.set(serializer.id, serializer); - return function () { - var index = serializersArray.indexOf(serializer); - - if (index >= 0) { - serializersArray.splice(index, 1); - } - - serializersMap["delete"](serializer.id); - }; -} -/** - * Transforms an action call argument by returning a `SerializedActionCallArgument`. - * The following are supported out of the box: - * - Primitives. - * - Nodes that are under the same root node as the target root (when provided) will be serialized - * as a path. - * - Nodes that are not under the same root node as the target root will be serialized as their snapshot. - * - Arrays (observable or not). - * - Dates. - * - Maps (observable or not). - * - Sets (observable or not). - * - Plain objects (observable or not). - * - * If the value cannot be serialized it will throw an exception. - * - * @param argValue Argument value to be transformed into its serializable form. - * @param [targetRoot] Target root node of the model where this action is being performed. - * @returns The serializable form of the passed value. - */ - -function serializeActionCallArgument(argValue, targetRoot) { - if (isPrimitive(argValue)) { - return argValue; - } - - var origValue = argValue; - - var serialize = function serialize(v) { - return serializeActionCallArgument(v, targetRoot); - }; // try serializers - - - for (var i = 0; i < serializersArray.length; i++) { - var serializer = serializersArray[i]; - var serializedValue = serializer.serialize(argValue, serialize, targetRoot); - - if (serializedValue !== cannotSerialize) { - return { - $mobxKeystoneSerializer: serializer.id, - value: serializedValue - }; - } - } - - throw failure("serializeActionCallArgument could not serialize the given value: " + origValue); -} -/** - * Ensures that an action call is serializable by mapping the action arguments into its - * serializable version by using `serializeActionCallArgument`. - * - * @param actionCall Action call to convert. - * @param [targetRoot] Target root node of the model where this action is being performed. - * @returns The serializable action call. - */ - -function serializeActionCall(actionCall, targetRoot) { - if (actionCall.serialized) { - throw failure("cannot serialize an already serialized action call"); - } - - if (targetRoot !== undefined) { - assertTweakedObject(targetRoot, "targetRoot"); - } - - var serialize = function serialize(v) { - return serializeActionCallArgument(v, targetRoot); - }; - - return _extends({}, actionCall, { - serialized: true, - args: actionCall.args.map(serialize) - }); -} -/** - * Transforms an action call argument by returning its deserialized equivalent. - * - * @param argValue Argument value to be transformed into its deserialized form. - * @param [targetRoot] Target root node of the model where this action is being performed. - * @returns The deserialized form of the passed value. - */ - -function deserializeActionCallArgument(argValue, targetRoot) { - if (isPrimitive(argValue)) { - return argValue; - } - - if (!isPlainObject(argValue) || typeof argValue.$mobxKeystoneSerializer !== "string") { - throw failure("invalid serialized action call argument"); - } - - var serializerId = argValue.$mobxKeystoneSerializer; - var serializer = serializersMap.get(serializerId); - - if (!serializer) { - throw failure("a serializer with id '" + serializerId + "' could not be found"); - } - - var serializedValue = argValue; - - var deserialize = function deserialize(v) { - return deserializeActionCallArgument(v, targetRoot); - }; - - return serializer.deserialize(serializedValue.value, deserialize, targetRoot); -} -/** - * Ensures that an action call is deserialized by mapping the action arguments into its - * deserialized version by using `deserializeActionCallArgument`. - * - * @param actionCall Action call to convert. - * @param [targetRoot] Target root node of the model where this action is being performed. - * @returns The deserialized action call. - */ - -function deserializeActionCall(actionCall, targetRoot) { - if (!actionCall.serialized) { - throw failure("cannot deserialize a non-serialized action call"); - } - - if (targetRoot !== undefined) { - assertTweakedObject(targetRoot, "targetRoot"); - } - - var deserialize = function deserialize(v) { - return deserializeActionCallArgument(v, targetRoot); - }; - - var deserializedActionCall = _extends({}, actionCall, { - serialized: undefined, - args: actionCall.args.map(deserialize) - }); - - delete deserializedActionCall.serialized; - return deserializedActionCall; -} // serializer registration (from low priority to high priority) - -registerActionCallArgumentSerializer(plainObjectSerializer); -registerActionCallArgumentSerializer(setSerializer); -registerActionCallArgumentSerializer(mapSerializer); -registerActionCallArgumentSerializer(dateSerializer); -registerActionCallArgumentSerializer(arraySerializer); -registerActionCallArgumentSerializer(objectSnapshotSerializer); -registerActionCallArgumentSerializer(objectPathSerializer); - -function typesObjectHelper(objFn, frozen, typeInfoGen) { - assertIsFunction(objFn, "objFn"); - return lateTypeChecker(function () { - var objectSchema = objFn(); - assertIsObject(objectSchema, "objectSchema"); - var schemaEntries = Object.entries(objectSchema); - - var getTypeName = function getTypeName() { - var propsMsg = []; - - for (var _len = arguments.length, recursiveTypeCheckers = new Array(_len), _key = 0; _key < _len; _key++) { - recursiveTypeCheckers[_key] = arguments[_key]; - } - - for (var _iterator = _createForOfIteratorHelperLoose(schemaEntries), _step; !(_step = _iterator()).done;) { - var _step$value = _step.value, - k = _step$value[0], - unresolvedTc = _step$value[1]; - var tc = resolveTypeChecker(unresolvedTc); - var propTypename = "..."; - - if (!recursiveTypeCheckers.includes(tc)) { - propTypename = tc.getTypeName.apply(tc, recursiveTypeCheckers.concat([tc])); - } - - propsMsg.push(k + ": " + propTypename + ";"); - } - - return "{ " + propsMsg.join(" ") + " }"; - }; - - var thisTc = new TypeChecker(function (obj, path) { - if (!isObject(obj) || frozen && !(obj instanceof Frozen)) return new TypeCheckError(path, getTypeName(thisTc), obj); // note: we allow excess properties when checking objects - - for (var _iterator2 = _createForOfIteratorHelperLoose(schemaEntries), _step2; !(_step2 = _iterator2()).done;) { - var _step2$value = _step2.value, - k = _step2$value[0], - unresolvedTc = _step2$value[1]; - var tc = resolveTypeChecker(unresolvedTc); - var objVal = obj[k]; - var valueError = !tc.unchecked ? tc.check(objVal, [].concat(path, [k])) : null; - - if (valueError) { - return valueError; - } - } - - return null; - }, getTypeName, typeInfoGen); - return thisTc; - }, typeInfoGen); -} -/** - * A type that represents a plain object. - * Note that the parameter must be a function that returns an object. This is done so objects can support self / cross types. - * - * Example: - * ```ts - * // notice the ({ ... }), not just { ... } - * const pointType = types.object(() => ({ - * x: types.number, - * y: types.number - * })) - * ``` - * - * @typeparam T Type. - * @param objectFunction Function that generates an object with types. - * @returns - */ - - -function typesObject(objectFunction) { - // we can't type this function or else we won't be able to make it work recursively - var typeInfoGen = function typeInfoGen(t) { - return new ObjectTypeInfo(t, objectFunction); - }; - - return typesObjectHelper(objectFunction, false, typeInfoGen); -} -/** - * `types.object` type info. - */ - -var ObjectTypeInfo = /*#__PURE__*/function (_TypeInfo) { - _inheritsLoose(ObjectTypeInfo, _TypeInfo); - - _createClass(ObjectTypeInfo, [{ - key: "props", - // memoize to always return the same object - get: function get() { - return this._props(); - } - }]); - - function ObjectTypeInfo(thisType, _objTypeFn) { - var _this; - - _this = _TypeInfo.call(this, thisType) || this; - _this._objTypeFn = void 0; - _this._props = lateVal(function () { - var objSchema = _this._objTypeFn(); - - var propTypes = {}; - Object.keys(objSchema).forEach(function (propName) { - var type = resolveStandardType(objSchema[propName]); - propTypes[propName] = { - type: type, - typeInfo: getTypeInfo(type) - }; - }); - return propTypes; - }); - _this._objTypeFn = _objTypeFn; - return _this; - } - - return ObjectTypeInfo; -}(TypeInfo); -/** - * A type that represents frozen data. - * - * Example: - * ```ts - * const frozenNumberType = types.frozen(types.number) - * const frozenAnyType = types.frozen(types.unchecked()) - * const frozenNumberArrayType = types.frozen(types.array(types.number)) - * const frozenUncheckedNumberArrayType = types.frozen(types.unchecked()) - * ``` - * - * @typeParam T Type. - * @param dataType Type of the frozen data. - * @returns - */ - -function typesFrozen(dataType) { - return typesObjectHelper(function () { - return { - data: dataType - }; - }, true, function (t) { - return new FrozenTypeInfo(t, resolveStandardType(dataType)); - }); -} -/** - * `types.frozen` type info. - */ - -var FrozenTypeInfo = /*#__PURE__*/function (_TypeInfo2) { - _inheritsLoose(FrozenTypeInfo, _TypeInfo2); - - _createClass(FrozenTypeInfo, [{ - key: "dataTypeInfo", - get: function get() { - return getTypeInfo(this.dataType); - } - }]); - - function FrozenTypeInfo(thisType, dataType) { - var _this2; - - _this2 = _TypeInfo2.call(this, thisType) || this; - _this2.dataType = void 0; - _this2.dataType = dataType; - return _this2; - } - - return FrozenTypeInfo; -}(TypeInfo); - -var unchecked = /*#__PURE__*/new TypeChecker(null, function () { - return "any"; -}, function (t) { - return new UncheckedTypeInfo(t); -}); -/** - * A type that represents a given value that won't be type checked. - * This is basically a way to bail out of the runtime type checking system. - * - * Example: - * ```ts - * const uncheckedSomeModel = types.unchecked() - * const anyType = types.unchecked() - * const customUncheckedType = types.unchecked<(A & B) | C>() - * ``` - * - * @typeparam T Type of the value, or unkown if not given. - * @returns - */ - -function typesUnchecked() { - return unchecked; -} -/** - * `types.unchecked` type info. - */ - -var UncheckedTypeInfo = /*#__PURE__*/function (_TypeInfo) { - _inheritsLoose(UncheckedTypeInfo, _TypeInfo); - - function UncheckedTypeInfo() { - return _TypeInfo.apply(this, arguments) || this; - } - - return UncheckedTypeInfo; -}(TypeInfo); - -/** - * Base abstract class for models that extends another model. - * - * @typeparam TProps New model properties type. - * @typeparam TBaseModel Base class type. - * @param baseModel Base model type. - * @param modelProps Model properties. - * @returns - */ - -function ExtendedModel(baseModel, modelProps) { - // note that & Object is there to support abstract classes - return internalModel(modelProps, baseModel); -} -/** - * Base abstract class for models. - * - * Never override the constructor, use `onInit` or `onAttachedToRootStore` instead. - * - * @typeparam TProps Model properties type. - * @param modelProps Model properties. - */ - -function Model(modelProps) { - return internalModel(modelProps); -} - -function internalModel(modelProps, baseModel) { - var _baseModel; - - assertIsObject(modelProps, "modelProps"); - - if (baseModel) { - assertIsModelClass(baseModel, "baseModel"); // if the baseModel is wrapped with the model decorator get the original one - - var unwrappedClass = baseModel[modelUnwrappedClassSymbol]; - - if (unwrappedClass) { - baseModel = unwrappedClass; - assertIsModelClass(baseModel, "baseModel"); - } - } - - var extraDescriptors = {}; - var composedModelProps = modelProps; - - if (baseModel) { - var oldModelProps = getInternalModelClassPropsInfo(baseModel); - - for (var _i = 0, _Object$keys = Object.keys(oldModelProps); _i < _Object$keys.length; _i++) { - var oldModelPropKey = _Object$keys[_i]; - - if (modelProps[oldModelPropKey]) { - throw failure("extended model cannot redeclare base model property named '" + oldModelPropKey + "'"); - } - - composedModelProps[oldModelPropKey] = oldModelProps[oldModelPropKey]; - } - } else { - // define $modelId on the base - extraDescriptors[modelIdKey] = createModelPropDescriptor(modelIdKey, undefined, true); - } // create type checker if needed - - - var dataTypeChecker; - - if (Object.values(composedModelProps).some(function (mp) { - return !!mp.typeChecker; - })) { - var typeCheckerObj = {}; - - for (var _i2 = 0, _Object$entries = Object.entries(composedModelProps); _i2 < _Object$entries.length; _i2++) { - var _Object$entries$_i = _Object$entries[_i2], - k = _Object$entries$_i[0], - mp = _Object$entries$_i[1]; - typeCheckerObj[k] = !mp.typeChecker ? typesUnchecked() : mp.typeChecker; - } - - dataTypeChecker = typesObject(function () { - return typeCheckerObj; - }); - } // skip props that are on base model, these have to be accessed through $ - // we only need to proxy new props, not old ones - - - for (var _iterator = _createForOfIteratorHelperLoose(Object.keys(modelProps).filter(function (mp) { - return !baseModelPropNames.has(mp); - })), _step; !(_step = _iterator()).done;) { - var modelPropName = _step.value; - extraDescriptors[modelPropName] = createModelPropDescriptor(modelPropName, modelProps[modelPropName], false); - } - - var extraPropNames = Object.keys(extraDescriptors); - var extraPropNamesLen = extraPropNames.length; - var base = (_baseModel = baseModel) != null ? _baseModel : BaseModel; - var propsWithTransforms = Object.entries(modelProps).filter(function (_ref) { - var _propName = _ref[0], - prop = _ref[1]; - return !!prop.transform; - }).map(function (_ref2) { - var propName = _ref2[0], - prop = _ref2[1]; - return [propName, prop.transform]; - }); // we use this weird hack rather than just class CustomBaseModel extends base {} - // in order to work around problems with ES5 classes extending ES6 classes - // see https://github.com/xaviergonz/mobx-keystone/issues/15 - - var CustomBaseModel = function (_base) { - _inheritsLoose$1(CustomBaseModel, _base); - - function CustomBaseModel(initialData, constructorOptions) { - var _constructorOptions$m; - - var baseModel = new base(initialData, _extends({}, constructorOptions, { - modelClass: (_constructorOptions$m = constructorOptions == null ? void 0 : constructorOptions.modelClass) != null ? _constructorOptions$m : this.constructor, - propsWithTransforms: propsWithTransforms - })); // make sure abstract classes do not override prototype props - - for (var i = 0; i < extraPropNamesLen; i++) { - var extraPropName = extraPropNames[i]; - - if (Object.getOwnPropertyDescriptor(baseModel, extraPropName)) { - delete baseModel[extraPropName]; - } - } - - return baseModel; - } - - return CustomBaseModel; - }(base); - - var initializers = base[modelInitializersSymbol]; - - if (initializers) { - CustomBaseModel[modelInitializersSymbol] = initializers.slice(); - } - - setInternalModelClassPropsInfo(CustomBaseModel, composedModelProps); - CustomBaseModel[modelDataTypeCheckerSymbol] = dataTypeChecker; - Object.defineProperties(CustomBaseModel.prototype, extraDescriptors); - return CustomBaseModel; -} - -function _inheritsLoose$1(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = superClass; -} - -function createModelPropDescriptor(modelPropName, modelProp, enumerable) { - return { - enumerable: enumerable, - configurable: true, - get: function get() { - return getModelInstanceDataField(this, modelProp, modelPropName); - }, - set: function set(v) { - // hack to only permit setting these values once fully constructed - // this is to ignore abstract properties being set by babel - // see https://github.com/xaviergonz/mobx-keystone/issues/18 - if (!this[modelInitializedSymbol]) { - return; - } - - setModelInstanceDataField(this, modelProp, modelPropName, v); - } - }; -} - -function getModelInstanceDataField(model, modelProp, modelPropName) { - var transform = modelProp ? modelProp.transform : undefined; - - if (transform) { - // no need to use get since these vars always get on the initial $ - var memoTransform = memoTransformCache.getOrCreateMemoTransform(model, modelPropName, transform); - return memoTransform.propToData(model.$[modelPropName]); - } else { - // no need to use get since these vars always get on the initial $ - return model.$[modelPropName]; - } -} - -function setModelInstanceDataField(model, modelProp, modelPropName, value) { - if ((modelProp == null ? void 0 : modelProp.options.setterAction) && !getCurrentActionContext()) { - // use apply set instead to wrap it in an action - applySet(model, modelPropName, value); - return; - } - - var transform = modelProp == null ? void 0 : modelProp.transform; - - if (transform) { - // no need to use set since these vars always get on the initial $ - var memoTransform = memoTransformCache.getOrCreateMemoTransform(model, modelPropName, transform); - model.$[modelPropName] = memoTransform.dataToProp(value); - } else { - // no need to use set since these vars always get on the initial $ - model.$[modelPropName] = value; - } -} - -/** - * Decorator that marks this class (which MUST inherit from the `Model` abstract class) - * as a model. - * - * @param name Unique name for the model type. Note that this name must be unique for your whole - * application, so it is usually a good idea to use some prefix unique to your application domain. - */ - -var model = function model(name) { - return function (clazz) { - return internalModel$1(name)(clazz); - }; -}; - -var internalModel$1 = function internalModel(name) { - return function (clazz) { - assertIsModelClass(clazz, "a model class"); - - if (modelInfoByName[name]) { - logWarning("warn", "a model with name \"" + name + "\" already exists (if you are using hot-reloading you may safely ignore this warning)", "duplicateModelName - " + name); - } - - if (clazz[modelUnwrappedClassSymbol]) { - throw failure("a class already decorated with `@model` cannot be re-decorated"); - } // trick so plain new works - - - var newClazz = function newClazz(initialData, snapshotInitialData, generateNewIds) { - var instance = new clazz(initialData, snapshotInitialData, this.constructor, generateNewIds); - runLateInitializationFunctions(instance); // compatibility with mobx 6 - - if (getMobxVersion() >= 6) { - try { - ; - (0,mobx_esm.makeObservable)(instance); - } catch (err) { - // sadly we need to use this hack since the PR to do this the proper way - // was rejected on the mobx side - if (err.message !== "[MobX] No annotations were passed to makeObservable, but no decorator members have been found either") { - throw err; - } - } - } // the object is ready - - - addHiddenProp(instance, modelInitializedSymbol, true, false); - - if (instance.onInit) { - wrapModelMethodInActionIfNeeded(instance, "onInit", HookAction.OnInit); - instance.onInit(); - } - - return instance; - }; - - clazz.toString = function () { - return "class " + clazz.name + "#" + name; - }; - - clazz[modelTypeKey] = name; // this also gives access to modelInitializersSymbol, modelPropertiesSymbol, modelDataTypeCheckerSymbol - - Object.setPrototypeOf(newClazz, clazz); - newClazz.prototype = clazz.prototype; - Object.defineProperty(newClazz, "name", _extends({}, Object.getOwnPropertyDescriptor(newClazz, "name"), { - value: clazz.name - })); - newClazz[modelUnwrappedClassSymbol] = clazz; - var modelInfo = { - name: name, - "class": newClazz - }; - modelInfoByName[name] = modelInfo; - modelInfoByClass.set(newClazz, modelInfo); - modelInfoByClass.set(clazz, modelInfo); - return newClazz; - }; -}; // basically taken from TS - - -function tsDecorate(decorators, target, key, desc) { - var c = arguments.length, - r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, - d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) { - if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - } // eslint-disable-next-line no-sequences - - return c > 3 && r && Object.defineProperty(target, key, r), r; -} -/** - * Marks a class (which MUST inherit from the `Model` abstract class) - * as a model and decorates some of its methods/properties. - * - * @param name Unique name for the model type. Note that this name must be unique for your whole - * application, so it is usually a good idea to use some prefix unique to your application domain. - * If you don't want to assign a name yet (e.g. for a base model) pass `undefined`. - * @param clazz Model class. - * @param decorators Decorators. - */ - - -function decoratedModel(name, clazz, decorators) { - // decorate class members - for (var _i = 0, _Object$entries = Object.entries(decorators); _i < _Object$entries.length; _i++) { - var _Object$entries$_i = _Object$entries[_i], - k = _Object$entries$_i[0], - decorator = _Object$entries$_i[1]; - var prototypeValueDesc = Object.getOwnPropertyDescriptor(clazz.prototype, k); // TS seems to send null for methods in the prototype - // (which we substitute for the descriptor to avoid a double look-up) and void 0 (undefined) for props - - tsDecorate(Array.isArray(decorator) ? decorator : [decorator], clazz.prototype, k, prototypeValueDesc ? prototypeValueDesc : void 0); - } - - return name ? model(name)(clazz) : clazz; -} - -/** - * Applies (runs) a serialized action over a target object. - * In this mode newly generated / modified model IDs will be tracked - * so they can be later synchronized when applying it on another machine - * via `applySerializedActionAndSyncNewModelIds`. - * This means this method is usually used on the server side. - * - * If you intend to apply non-serialized actions check `applyAction` instead. - * - * @param subtreeRoot Subtree root target object to run the action over. - * @param call The serialized action, usually as coming from the server/client. - * @returns The return value of the action, if any, plus a new serialized action - * with model overrides. - */ - -function applySerializedActionAndTrackNewModelIds(subtreeRoot, call) { - if (!call.serialized) { - throw failure("cannot apply a non-serialized action call, use 'applyAction' instead"); - } - - assertTweakedObject(subtreeRoot, "subtreeRoot"); - var deserializedCall = deserializeActionCall(call, subtreeRoot); - var modelIdOverrides = []; // set a patch listener to track changes to model ids - - var patchDisposer = onPatches(subtreeRoot, function (patches) { - scanPatchesForModelIdChanges(subtreeRoot, modelIdOverrides, patches); - }); - - try { - var returnValue = applyAction(subtreeRoot, deserializedCall); - return { - returnValue: returnValue, - serializedActionCall: _extends({}, call, { - modelIdOverrides: modelIdOverrides - }) - }; - } finally { - patchDisposer(); - } -} - -function scanPatchesForModelIdChanges(root, modelIdOverrides, patches) { - var len = patches.length; - - for (var i = 0; i < len; i++) { - var patch = patches[i]; - - if (patch.op === "replace" || patch.op === "add") { - deepScanValueForModelIdChanges(root, modelIdOverrides, patch.value, patch.path); - } - } -} - -function deepScanValueForModelIdChanges(root, modelIdOverrides, value, path) { - if (path.length >= 1 && path[path.length - 1] === modelIdKey && typeof value === "string") { - // ensure the parent is an actual model - var parent = resolvePath(root, path.slice(0, path.length - 1)).value; - - if (isModel(parent)) { - // found one - modelIdOverrides.push({ - op: "replace", - path: path.slice(), - value: value - }); - } - } else if (Array.isArray(value)) { - var len = value.length; - - for (var i = 0; i < len; i++) { - path.push(i); - deepScanValueForModelIdChanges(root, modelIdOverrides, value[i], path); - path.pop(); - } - } else if (isObject(value)) { - // skip frozen values - if (!value[frozenKey]) { - var keys = Object.keys(value); - var _len = keys.length; - - for (var _i = 0; _i < _len; _i++) { - var propName = keys[_i]; - var propValue = value[propName]; - path.push(propName); - deepScanValueForModelIdChanges(root, modelIdOverrides, propValue, path); - path.pop(); - } - } - } -} -/** - * Applies (runs) a serialized action over a target object. - * In this mode newly generated / modified model IDs will be tracked - * so they can be later synchronized when applying it on another machine - * via `applySerializedActionAndSyncNewModelIds`. - * This means this method is usually used on the server side. - * - * If you intend to apply non-serialized actions check `applyAction` instead. - * - * @param subtreeRoot Subtree root target object to run the action over. - * @param call The serialized action, usually as coming from the server/client. - * @returns The return value of the action, if any, plus a new serialized action - * with model overrides. - */ - - -function applySerializedActionAndSyncNewModelIds(subtreeRoot, call) { - if (!call.serialized) { - throw failure("cannot apply a non-serialized action call, use 'applyAction' instead"); - } - - assertTweakedObject(subtreeRoot, "subtreeRoot"); - var deserializedCall = deserializeActionCall(call, subtreeRoot); - var returnValue; - (0,mobx_esm.runInAction)(function () { - returnValue = applyAction(subtreeRoot, deserializedCall); // apply model id overrides - - applyPatches(subtreeRoot, call.modelIdOverrides); - }); - return returnValue; -} - -/** - * Action tracking middleware finish result. - */ - -var ActionTrackingResult; - -(function (ActionTrackingResult) { - /** - * The action returned normally (without throwing). - */ - ActionTrackingResult["Return"] = "return"; - /** - * The action threw an error. - */ - - ActionTrackingResult["Throw"] = "throw"; -})(ActionTrackingResult || (ActionTrackingResult = {})); -/** - * Creates an action tracking middleware, which is a simplified version - * of the standard action middleware. - * - * @param subtreeRoot Subtree root target object. - * @param hooks Middleware hooks. - * @returns The middleware disposer. - */ - - -function actionTrackingMiddleware(subtreeRoot, hooks) { - assertTweakedObject(subtreeRoot, "subtreeRoot"); - var dataSymbol = Symbol("actionTrackingMiddlewareData"); - - function getCtxData(ctx) { - return ctx.data[dataSymbol]; - } - - function setCtxData(ctx, partialData) { - var currentData = ctx.data[dataSymbol]; - - if (!currentData) { - ctx.data[dataSymbol] = partialData; - } else { - Object.assign(currentData, partialData); - } - } - - var userFilter = function userFilter(ctx) { - if (hooks.filter) { - return hooks.filter(simplifyActionContext(ctx)); - } - - return true; - }; - - var resumeSuspendSupport = !!hooks.onResume || !!hooks.onSuspend; - - var filter = function filter(ctx) { - if (ctx.type === ActionContextActionType.Sync) { - // start and finish is on the same context - var accepted = userFilter(ctx); - - if (accepted) { - setCtxData(ctx, { - startAccepted: true, - state: "idle" - }); - } - - return accepted; - } else { - switch (ctx.asyncStepType) { - case ActionContextAsyncStepType.Spawn: - var _accepted = userFilter(ctx); - - if (_accepted) { - setCtxData(ctx, { - startAccepted: true, - state: "idle" - }); - } - - return _accepted; - - case ActionContextAsyncStepType.Return: - case ActionContextAsyncStepType.Throw: - // depends if the spawn one was accepted or not - var data = getCtxData(ctx.spawnAsyncStepContext); - return data ? data.startAccepted : false; - - case ActionContextAsyncStepType.Resume: - case ActionContextAsyncStepType.ResumeError: - if (!resumeSuspendSupport) { - return false; - } else { - // depends if the spawn one was accepted or not - var _data = getCtxData(ctx.spawnAsyncStepContext); - - return _data ? _data.startAccepted : false; - } - - default: - return false; - } - } - }; - - var start = function start(simpleCtx) { - setCtxData(simpleCtx, { - state: "started" - }); - - if (hooks.onStart) { - return hooks.onStart(simpleCtx) || undefined; - } - - return undefined; - }; - - var finish = function finish(simpleCtx, ret) { - // fakely resume and suspend the parent if needed - var parentCtx = simpleCtx.parentContext; - var parentResumed = false; - - if (parentCtx) { - var parentData = getCtxData(parentCtx); - - if (parentData && parentData.startAccepted && parentData.state === "suspended") { - parentResumed = true; - resume(parentCtx, false); - } - } - - setCtxData(simpleCtx, { - state: "finished" - }); - - if (hooks.onFinish) { - ret = hooks.onFinish(simpleCtx, ret) || ret; - } - - if (parentResumed) { - suspend(parentCtx); - } - - return ret; - }; - - var resume = function resume(simpleCtx, real) { - // ensure parents are resumed - var parentCtx = simpleCtx.parentContext; - - if (parentCtx) { - var parentData = getCtxData(parentCtx); - - if (parentData && parentData.startAccepted && parentData.state === "suspended") { - resume(parentCtx, false); - } - } - - setCtxData(simpleCtx, { - state: real ? "realResumed" : "fakeResumed" - }); - - if (hooks.onResume) { - hooks.onResume(simpleCtx); - } - }; - - var suspend = function suspend(simpleCtx) { - setCtxData(simpleCtx, { - state: "suspended" - }); - - if (hooks.onSuspend) { - hooks.onSuspend(simpleCtx); - } // ensure parents are suspended if they were fakely resumed - - - var parentCtx = simpleCtx.parentContext; - - if (parentCtx) { - var parentData = getCtxData(parentCtx); - - if (parentData && parentData.startAccepted && parentData.state === "fakeResumed") { - suspend(parentCtx); - } - } - }; - - var mware = function mware(ctx, next) { - var simpleCtx = simplifyActionContext(ctx); - var origNext = next; - - next = function next() { - resume(simpleCtx, true); - - try { - return origNext(); - } finally { - suspend(simpleCtx); - } - }; - - if (ctx.type === ActionContextActionType.Sync) { - var retObj = start(simpleCtx); - - if (retObj) { - // action cancelled / overriden by onStart - resume(simpleCtx, true); - suspend(simpleCtx); - retObj = finish(simpleCtx, retObj); - } else { - try { - retObj = finish(simpleCtx, { - result: ActionTrackingResult.Return, - value: next() - }); - } catch (err) { - retObj = finish(simpleCtx, { - result: ActionTrackingResult.Throw, - value: err - }); - } - } - - return returnOrThrowActionTrackingReturn(retObj); - } else { - // async - switch (ctx.asyncStepType) { - case ActionContextAsyncStepType.Spawn: - { - var _retObj = start(simpleCtx); - - if (_retObj) { - // action cancelled / overriden by onStart - resume(simpleCtx, true); - suspend(simpleCtx); - _retObj = finish(simpleCtx, _retObj); - return returnOrThrowActionTrackingReturn(_retObj); - } else { - return next(); - } - } - - case ActionContextAsyncStepType.Return: - { - var flowFinisher = next(); - - var _retObj2 = finish(simpleCtx, { - result: ActionTrackingResult.Return, - value: flowFinisher.value - }); - - flowFinisher.resolution = _retObj2.result === ActionTrackingResult.Return ? "accept" : "reject"; - flowFinisher.value = _retObj2.value; - return flowFinisher; - } - - case ActionContextAsyncStepType.Throw: - { - var _flowFinisher = next(); - - var _retObj3 = finish(simpleCtx, { - result: ActionTrackingResult.Throw, - value: _flowFinisher.value - }); - - _flowFinisher.resolution = _retObj3.result === ActionTrackingResult.Return ? "accept" : "reject"; - _flowFinisher.value = _retObj3.value; - return _flowFinisher; - } - - case ActionContextAsyncStepType.Resume: - case ActionContextAsyncStepType.ResumeError: - if (resumeSuspendSupport) { - return next(); - } else { - throw failure("asssertion error: async step should have been filtered out - " + ctx.asyncStepType); - } - - default: - throw failure("asssertion error: async step should have been filtered out - " + ctx.asyncStepType); - } - } - }; - - return addActionMiddleware({ - middleware: mware, - filter: filter, - subtreeRoot: subtreeRoot - }); -} - -function returnOrThrowActionTrackingReturn(retObj) { - if (retObj.result === ActionTrackingResult.Return) { - return retObj.value; - } else { - throw retObj.value; - } -} - -var simpleDataContextSymbol = /*#__PURE__*/Symbol("simpleDataContext"); -/** - * Simplifies an action context by converting an async call hierarchy into a simpler one. - * - * @param ctx Action context to convert. - * @returns Simplified action context. - */ - -function simplifyActionContext(ctx) { - while (ctx.previousAsyncStepContext) { - ctx = ctx.previousAsyncStepContext; - } - - var simpleCtx = ctx.data[simpleDataContextSymbol]; - - if (!simpleCtx) { - var parentContext = ctx.parentContext ? simplifyActionContext(ctx.parentContext) : undefined; - simpleCtx = { - actionName: ctx.actionName, - type: ctx.type, - target: ctx.target, - args: ctx.args, - data: ctx.data, - parentContext: parentContext - }; - simpleCtx.rootContext = parentContext ? parentContext.rootContext : simpleCtx; - ctx.data[simpleDataContextSymbol] = simpleCtx; - } - - return simpleCtx; -} - -/** - * Attaches an action middleware that invokes a listener for all actions of a given tree. - * Note that the listener will only be invoked for the topmost level actions, so it won't run for child actions or intermediary flow steps. - * Also it won't trigger the listener for calls to hooks such as `onAttachedToRootStore` or its returned disposer. - * - * Its main use is to keep track of top level actions that can be later replicated via `applyAction` somewhere else (another machine, etc.). - * - * There are two kind of possible listeners, `onStart` and `onFinish` listeners. - * `onStart` listeners are called before the action executes and allow cancellation by returning a new return value (which might be a return or a throw). - * `onFinish` listeners are called after the action executes, have access to the action actual return value and allow overriding by returning a - * new return value (which might be a return or a throw). - * - * If you want to ensure that the actual action calls are serializable you should use either `serializeActionCallArgument` over the arguments - * or `serializeActionCall` over the whole action before sending the action call over the wire / storing them . - * - * @param subtreeRoot Subtree root target object. - * @param listeners Listener functions that will be invoked everytime a topmost action is invoked on the model or any children. - * @returns The middleware disposer. - */ - -function onActionMiddleware(subtreeRoot, listeners) { - assertTweakedObject(subtreeRoot, "subtreeRoot"); - assertIsObject(listeners, "listeners"); - return actionTrackingMiddleware(subtreeRoot, { - filter: function filter(ctx) { - if (ctx.parentContext) { - // sub-action, do nothing - return false; - } // skip hooks - - - if (isHookAction(ctx.actionName)) { - return false; - } - - return true; - }, - onStart: function onStart(ctx) { - if (listeners.onStart) { - var actionCall = actionContextToActionCall(ctx); - return listeners.onStart(actionCall, ctx); - } - }, - onFinish: function onFinish(ctx, ret) { - if (listeners.onFinish) { - var actionCall = actionContextToActionCall(ctx); - return listeners.onFinish(actionCall, ctx, ret); - } - } - }); -} - -function actionContextToActionCall(ctx) { - var rootPath = fastGetRootPath(ctx.target); - return { - actionName: ctx.actionName, - args: ctx.args, - targetPath: rootPath.path, - targetPathIds: rootPathToTargetPathIds(rootPath) - }; -} - -/** - * Attaches an action middleware that will throw when any action is started - * over the node or any of the child nodes, thus effectively making the subtree - * readonly. - * - * It will return an object with a `dispose` function to remove the middleware and a `allowWrite` function - * that will allow actions to be started inside the provided code block. - * - * Example: - * ```ts - * // given a model instance named todo - * const { dispose, allowWrite } = readonlyMiddleware(todo) - * - * // this will throw - * todo.setDone(false) - * await todo.setDoneAsync(false) - * - * // this will work - * allowWrite(() => todo.setDone(false)) - * // note: for async always use one action invocation per allowWrite! - * await allowWrite(() => todo.setDoneAsync(false)) - * ``` - * - * @param subtreeRoot Subtree root target object. - * @returns An object with the middleware disposer (`dispose`) and a `allowWrite` function. - */ - -function readonlyMiddleware(subtreeRoot) { - assertTweakedObject(subtreeRoot, "subtreeRoot"); - var writable = false; - var writableSymbol = Symbol("writable"); - var disposer = actionTrackingMiddleware(subtreeRoot, { - filter: function filter(ctx) { - // skip hooks - if (isHookAction(ctx.actionName)) { - return false; - } // if we are inside allowWrite it is writable - - - var currentlyWritable = writable; - - if (!currentlyWritable) { - // if a parent context was writable then the child should be as well - var currentCtx = ctx; - - while (currentCtx && !currentlyWritable) { - currentlyWritable = !!currentCtx.data[writableSymbol]; - currentCtx = currentCtx.parentContext; - } - } - - if (currentlyWritable) { - ctx.data[writableSymbol] = true; - return false; - } - - return true; - }, - onStart: function onStart(ctx) { - // if we get here (wasn't filtered out) it is not writable - return { - result: ActionTrackingResult.Throw, - value: failure("tried to invoke action '" + ctx.actionName + "' over a readonly node") - }; - } - }); - return { - dispose: disposer, - allowWrite: function allowWrite(fn) { - var oldWritable = writable; - writable = true; - - try { - return fn(); - } finally { - writable = oldWritable; - } - } - }; -} - -/** - * Escapes a json pointer path. - * - * @param path The raw pointer - * @return the Escaped path - */ - -function escapePathComponent(path) { - if (typeof path === "number") { - return "" + path; - } - - if (path.indexOf("/") === -1 && path.indexOf("~") === -1) { - return path; - } - - return path.replace(/~/g, "~0").replace(/\//g, "~1"); -} -/** - * Unescapes a json pointer path. - * - * @param path The escaped pointer - * @return The unescaped path - */ - - -function unescapePathComponent(path) { - return path.replace(/~1/g, "/").replace(/~0/g, "~"); -} -/** - * Converts a path into a JSON pointer. - * - * @param path Path to convert. - * @returns Converted JSON pointer. - */ - - -function pathToJsonPointer(path) { - if (path.length <= 0) { - return ""; - } - - return "/" + path.map(escapePathComponent).join("/"); -} -/** - * Converts a JSON pointer into a path. - * - * @param jsonPointer JSON pointer to convert. - * @returns Converted path. - */ - -function jsonPointerToPath(jsonPointer) { - if (jsonPointer === "") { - return []; - } - - if (!jsonPointer.startsWith("/")) { - throw failure("a JSON pointer must start with '/' or be empty"); - } - - jsonPointer = jsonPointer.slice(1); - return jsonPointer.split("/").map(unescapePathComponent); -} -/** - * Convert a patch into a JSON patch. - * - * @param patch A patch. - * @returns A JSON patch. - */ - -function patchToJsonPatch(patch) { - return _extends({}, patch, { - path: pathToJsonPointer(patch.path) - }); -} -/** - * Converts a JSON patch into a patch. - * - * @param jsonPatch A JSON patch. - * @returns A patch. - */ - -function jsonPatchToPatch(jsonPatch) { - return _extends({}, jsonPatch, { - path: jsonPointerToPath(jsonPatch.path) - }); -} - -/** - * Creates a patch recorder. - * - * @param subtreeRoot - * @param [opts] - * @returns The patch recorder. - */ - -function patchRecorder(subtreeRoot, opts) { - assertTweakedObject(subtreeRoot, "subtreeRoot"); - return internalPatchRecorder(subtreeRoot, opts); -} -/** - * @ignore - * @internal - * - * Creates a global or local patch recorder. - * - * @param subtreeRoot - * @param [opts] - * @returns The patch recorder. - */ - -function internalPatchRecorder(subtreeRoot, opts) { - var _recording$filter$opt = _extends({ - recording: true, - filter: alwaysAcceptFilter - }, opts), - recording = _recording$filter$opt.recording, - filter = _recording$filter$opt.filter; - - var events = mobx_esm.observable.array([], { - deep: false - }); - var onPatchesDisposer; - - if (subtreeRoot) { - onPatchesDisposer = onPatches(subtreeRoot, function (p, invP) { - if (recording && filter(p, invP)) { - events.push({ - target: subtreeRoot, - patches: p, - inversePatches: invP - }); - opts == null ? void 0 : opts.onPatches == null ? void 0 : opts.onPatches(p, invP); - } - }); - } else { - onPatchesDisposer = onGlobalPatches(function (target, p, invP) { - if (recording && filter(p, invP)) { - events.push({ - target: target, - patches: p, - inversePatches: invP - }); - opts == null ? void 0 : opts.onPatches == null ? void 0 : opts.onPatches(p, invP); - } - }); - } - - return { - get recording() { - return recording; - }, - - set recording(enabled) { - recording = enabled; - }, - - get events() { - return events; - }, - - dispose: function dispose() { - onPatchesDisposer(); - } - }; -} - -var alwaysAcceptFilter = function alwaysAcceptFilter() { - return true; -}; - -/** - * Creates a transaction middleware, which reverts changes made by an action / child - * actions when the root action throws an exception by applying inverse patches. - * - * @typeparam M Model - * @param target Object with the root target model object (`model`) and root action name (`actionName`). - * @returns The middleware disposer. - */ - -function transactionMiddleware(target) { - assertIsObject(target, "target"); - var model = target.model, - actionName = target.actionName; - assertIsModel(model, "target.model"); - - if (typeof actionName !== "string") { - throw failure("target.actionName must be a string"); - } - - var patchRecorderSymbol = Symbol("patchRecorder"); - - function initPatchRecorder(ctx) { - ctx.rootContext.data[patchRecorderSymbol] = internalPatchRecorder(undefined, { - recording: false - }); - } - - function getPatchRecorder(ctx) { - return ctx.rootContext.data[patchRecorderSymbol]; - } - - return actionTrackingMiddleware(model, { - filter: function filter(ctx) { - // the primary action must be on the root object - var rootContext = ctx.rootContext; - return rootContext.target === model && rootContext.actionName === actionName; - }, - onStart: function onStart(ctx) { - if (ctx === ctx.rootContext) { - initPatchRecorder(ctx); - } - }, - onResume: function onResume(ctx) { - getPatchRecorder(ctx).recording = true; - }, - onSuspend: function onSuspend(ctx) { - getPatchRecorder(ctx).recording = false; - }, - onFinish: function onFinish(ctx, ret) { - if (ctx === ctx.rootContext) { - var patchRecorder = getPatchRecorder(ctx); - - try { - if (ret.result === ActionTrackingResult.Throw) { - // undo changes (backwards for inverse patches) - var events = patchRecorder.events; - - for (var i = events.length - 1; i >= 0; i--) { - var event = events[i]; - applyPatches(event.target, event.inversePatches, true); - } - } - } finally { - patchRecorder.dispose(); - } - } - } - }); -} -/** - * Transaction middleware as a decorator. - * - * @param target - * @param propertyKey - */ - -function transaction(target, propertyKey) { - checkModelDecoratorArgs("transaction", target, propertyKey); - addModelClassInitializer(target.constructor, function (modelInstance) { - transactionMiddleware({ - model: modelInstance, - actionName: propertyKey - }); - }); -} - -/** - * A type that represents an array of values of a given type. - * - * Example: - * ```ts - * const numberArrayType = types.array(types.number) - * ``` - * - * @typeparam T Item type. - * @param itemType Type of inner items. - * @returns - */ - -function typesArray(itemType) { - var typeInfoGen = function typeInfoGen(t) { - return new ArrayTypeInfo(t, resolveStandardType(itemType)); - }; - - return lateTypeChecker(function () { - var itemChecker = resolveTypeChecker(itemType); - - var getTypeName = function getTypeName() { - for (var _len = arguments.length, recursiveTypeCheckers = new Array(_len), _key = 0; _key < _len; _key++) { - recursiveTypeCheckers[_key] = arguments[_key]; - } - - return "Array<" + itemChecker.getTypeName.apply(itemChecker, recursiveTypeCheckers.concat([itemChecker])) + ">"; - }; - - var thisTc = new TypeChecker(function (array, path) { - if (!isArray(array)) { - return new TypeCheckError(path, getTypeName(thisTc), array); - } - - if (!itemChecker.unchecked) { - for (var i = 0; i < array.length; i++) { - var itemError = itemChecker.check(array[i], [].concat(path, [i])); - - if (itemError) { - return itemError; - } - } - } - - return null; - }, getTypeName, typeInfoGen); - return thisTc; - }, typeInfoGen); -} -/** - * `types.array` type info. - */ - -var ArrayTypeInfo = /*#__PURE__*/function (_TypeInfo) { - _inheritsLoose(ArrayTypeInfo, _TypeInfo); - - _createClass(ArrayTypeInfo, [{ - key: "itemTypeInfo", - get: function get() { - return getTypeInfo(this.itemType); - } - }]); - - function ArrayTypeInfo(thisType, itemType) { - var _this; - - _this = _TypeInfo.call(this, thisType) || this; - _this.itemType = void 0; - _this.itemType = itemType; - return _this; - } - - return ArrayTypeInfo; -}(TypeInfo); - -function tProp(typeOrDefaultValue, arg1, arg2) { - var def; - var opts = {}; - var hasDefaultValue = false; - - switch (typeof typeOrDefaultValue) { - case "string": - return tProp(typesString, typeOrDefaultValue, arg1); - - case "number": - return tProp(typesNumber, typeOrDefaultValue, arg1); - - case "boolean": - return tProp(typesBoolean, typeOrDefaultValue, arg1); - } - - if (arguments.length >= 3) { - // type, default, options - def = arg1; - hasDefaultValue = true; - opts = _extends({}, arg2); - } else if (arguments.length === 2) { - // type, default | options - if (isObject(arg1)) { - // options - opts = _extends({}, arg1); - } else { - // default - def = arg1; - hasDefaultValue = true; - } - } - - var isDefFn = typeof def === "function"; - return { - $propValueType: null, - $propCreationValueType: null, - $isOptional: null, - $instanceValueType: null, - $instanceCreationValueType: null, - defaultFn: hasDefaultValue && isDefFn ? def : noDefaultValue, - defaultValue: hasDefaultValue && !isDefFn ? def : noDefaultValue, - typeChecker: resolveStandardType(typeOrDefaultValue), - transform: undefined, - options: opts - }; -} - -/** - * Store model instance for undo/redo actions. - * Do not manipulate directly, other that creating it. - */ - -var UndoStore = /*#__PURE__*/function (_Model) { - _inheritsLoose(UndoStore, _Model); - - function UndoStore() { - return _Model.apply(this, arguments) || this; - } - - var _proto = UndoStore.prototype; - - /** - * @ignore - */ - _proto._clearUndo = function _clearUndo() { - var _this = this; - - withoutUndo(function () { - _this.undoEvents.length = 0; - }); - } - /** - * @ignore - */ - ; - - _proto._clearRedo = function _clearRedo() { - var _this2 = this; - - withoutUndo(function () { - _this2.redoEvents.length = 0; - }); - } - /** - * @ignore - */ - ; - - _proto._undo = function _undo() { - var _this3 = this; - - withoutUndo(function () { - var event = _this3.undoEvents.pop(); - - _this3.redoEvents.push(event); - }); - } - /** - * @ignore - */ - ; - - _proto._redo = function _redo() { - var _this4 = this; - - withoutUndo(function () { - var event = _this4.redoEvents.pop(); - - _this4.undoEvents.push(event); - }); - } - /** - * @ignore - */ - ; - - _proto._addUndo = function _addUndo(event) { - var _this5 = this; - - withoutUndo(function () { - _this5.undoEvents.push(event); // once an undo event is added redo queue is no longer valid - - - _this5.redoEvents.length = 0; - }); - }; - - return UndoStore; -}( /*#__PURE__*/Model({ - // TODO: add proper type checking to undo store - undoEvents: /*#__PURE__*/tProp( /*#__PURE__*/typesArray( /*#__PURE__*/typesUnchecked()), function () { - return []; - }), - redoEvents: /*#__PURE__*/tProp( /*#__PURE__*/typesArray( /*#__PURE__*/typesUnchecked()), function () { - return []; - }) -})); - -__decorate([modelAction], UndoStore.prototype, "_clearUndo", null); - -__decorate([modelAction], UndoStore.prototype, "_clearRedo", null); - -__decorate([modelAction], UndoStore.prototype, "_undo", null); - -__decorate([modelAction], UndoStore.prototype, "_redo", null); - -__decorate([modelAction], UndoStore.prototype, "_addUndo", null); - -UndoStore = /*#__PURE__*/__decorate([/*#__PURE__*/model("mobx-keystone/UndoStore")], UndoStore); -/** - * Manager class returned by `undoMiddleware` that allows you to perform undo/redo actions. - */ - -var UndoManager = /*#__PURE__*/function () { - var _proto2 = UndoManager.prototype; - - /** - * Clears the undo queue. - */ - _proto2.clearUndo = function clearUndo() { - this.store._clearUndo(); - } - /** - * The number of redo actions available. - */ - ; - - /** - * Clears the redo queue. - */ - _proto2.clearRedo = function clearRedo() { - this.store._clearRedo(); - } - /** - * Undoes the last action. - * Will throw if there is no action to undo. - */ - ; - - _proto2.undo = function undo() { - var _this6 = this; - - if (!this.canUndo) { - throw failure("nothing to undo"); - } - - var event = this.undoQueue[this.undoQueue.length - 1]; - withoutUndo(function () { - applyPatches(_this6.subtreeRoot, event.inversePatches, true); - }); - - this.store._undo(); - } - /** - * Redoes the previous action. - * Will throw if there is no action to redo. - */ - ; - - _proto2.redo = function redo() { - var _this7 = this; - - if (!this.canRedo) { - throw failure("nothing to redo"); - } - - var event = this.redoQueue[this.redoQueue.length - 1]; - withoutUndo(function () { - applyPatches(_this7.subtreeRoot, event.patches); - }); - - this.store._redo(); - } - /** - * Disposes the undo middleware. - */ - ; - - _proto2.dispose = function dispose() { - this.disposer(); - } - /** - * Creates an instance of `UndoManager`. - * Do not use directly, use `undoMiddleware` instead. - * - * @param disposer - * @param subtreeRoot - * @param [store] - */ - ; - - _createClass(UndoManager, [{ - key: "undoQueue", - - /** - * The store currently being used to store undo/redo action events. - */ - - /** - * The undo stack, where the first operation to undo will be the last of the array. - * Do not manipulate this array directly. - */ - get: function get() { - return this.store.undoEvents; - } - /** - * The redo stack, where the first operation to redo will be the last of the array. - * Do not manipulate this array directly. - */ - - }, { - key: "redoQueue", - get: function get() { - return this.store.redoEvents; - } - /** - * The number of undo actions available. - */ - - }, { - key: "undoLevels", - get: function get() { - return this.undoQueue.length; - } - /** - * If undo can be performed (if there is at least one undo action available). - */ - - }, { - key: "canUndo", - get: function get() { - return this.undoLevels > 0; - } - }, { - key: "redoLevels", - get: function get() { - return this.redoQueue.length; - } - /** - * If redo can be performed (if there is at least one redo action available) - */ - - }, { - key: "canRedo", - get: function get() { - return this.redoLevels > 0; - } - }]); - - function UndoManager(disposer, subtreeRoot, store) { - this.disposer = void 0; - this.subtreeRoot = void 0; - this.store = void 0; - this.disposer = disposer; - this.subtreeRoot = subtreeRoot; - this.store = store != null ? store : new UndoStore({}); - } - - return UndoManager; -}(); - -__decorate([mobx_esm.computed], UndoManager.prototype, "undoQueue", null); - -__decorate([mobx_esm.computed], UndoManager.prototype, "redoQueue", null); - -__decorate([mobx_esm.computed], UndoManager.prototype, "undoLevels", null); - -__decorate([mobx_esm.computed], UndoManager.prototype, "canUndo", null); - -__decorate([mobx_esm.action], UndoManager.prototype, "clearUndo", null); - -__decorate([mobx_esm.computed], UndoManager.prototype, "redoLevels", null); - -__decorate([mobx_esm.computed], UndoManager.prototype, "canRedo", null); - -__decorate([mobx_esm.action], UndoManager.prototype, "clearRedo", null); - -__decorate([mobx_esm.action], UndoManager.prototype, "undo", null); - -__decorate([mobx_esm.action], UndoManager.prototype, "redo", null); -/** - * Creates an undo middleware. - * - * @param subtreeRoot Subtree root target object. - * @param [store] Optional `UndoStore` where to store the undo/redo queues. Use this if you want to - * store such queues somewhere in your models. If none is provided it will reside in memory. - * @returns An `UndoManager` which allows you to do the manage the undo/redo operations and dispose of the middleware. - */ - - -function undoMiddleware(subtreeRoot, store) { - assertTweakedObject(subtreeRoot, "subtreeRoot"); - var patchRecorderSymbol = Symbol("patchRecorder"); - - function initPatchRecorder(ctx) { - ctx.rootContext.data[patchRecorderSymbol] = { - recorder: patchRecorder(subtreeRoot, { - recording: false, - filter: undoDisabledFilter - }), - recorderStack: 0, - undoRootContext: ctx - }; - } - - function getPatchRecorderData(ctx) { - return ctx.rootContext.data[patchRecorderSymbol]; - } - - var manager; - var middlewareDisposer = actionTrackingMiddleware(subtreeRoot, { - onStart: function onStart(ctx) { - if (!getPatchRecorderData(ctx)) { - initPatchRecorder(ctx); - } - }, - onResume: function onResume(ctx) { - var patchRecorderData = getPatchRecorderData(ctx); - patchRecorderData.recorderStack++; - patchRecorderData.recorder.recording = patchRecorderData.recorderStack > 0; - }, - onSuspend: function onSuspend(ctx) { - var patchRecorderData = getPatchRecorderData(ctx); - patchRecorderData.recorderStack--; - patchRecorderData.recorder.recording = patchRecorderData.recorderStack > 0; - }, - onFinish: function onFinish(ctx) { - var patchRecorderData = getPatchRecorderData(ctx); - - if (patchRecorderData && patchRecorderData.undoRootContext === ctx) { - var _patchRecorder = patchRecorderData.recorder; - - if (_patchRecorder.events.length > 0) { - var patches = []; - var inversePatches = []; - - for (var _iterator = _createForOfIteratorHelperLoose(_patchRecorder.events), _step; !(_step = _iterator()).done;) { - var event = _step.value; - patches.push.apply(patches, event.patches); - inversePatches.push.apply(inversePatches, event.inversePatches); - } - - manager.store._addUndo({ - targetPath: fastGetRootPath(ctx.target).path, - actionName: ctx.actionName, - patches: patches, - inversePatches: inversePatches - }); - } - - _patchRecorder.dispose(); - } - } - }); - manager = new UndoManager(middlewareDisposer, subtreeRoot, store); - return manager; -} -var undoDisabled = false; - -var undoDisabledFilter = function undoDisabledFilter() { - return !undoDisabled; -}; -/** - * Skips the undo recording mechanism for the code block that gets run synchronously inside. - * - * @typeparam T - * @param fn - * @returns - */ - - -function withoutUndo(fn) { - var savedUndoDisabled = undoDisabled; - undoDisabled = true; - - try { - return fn(); - } finally { - undoDisabled = savedUndoDisabled; - } -} - -function getContextValue(contextValue) { - if (contextValue.type === "value") { - return contextValue.value; - } else { - return contextValue.value.get(); - } -} - -var ContextClass = /*#__PURE__*/function () { - var _proto = ContextClass.prototype; - - _proto.getNodeAtom = function getNodeAtom(node) { - var atomPerNode = this.nodeAtom.get(node); - - if (!atomPerNode) { - atomPerNode = (0,mobx_esm.createAtom)("contextValue"); - this.nodeAtom.set(node, atomPerNode); - } - - return atomPerNode; - }; - - _proto.fastGet = function fastGet(node) { - this.getNodeAtom(node).reportObserved(); - var obsForNode = this.nodeContextValue.get(node); - - if (obsForNode) { - return getContextValue(obsForNode); - } - - var parent = fastGetParent(node); - - if (!parent) { - return this.getDefault(); - } - - return this.fastGet(parent); - }; - - _proto.get = function get(node) { - assertTweakedObject(node, "node"); - return this.fastGet(node); - }; - - _proto.fastGetProviderNode = function fastGetProviderNode(node) { - this.getNodeAtom(node).reportObserved(); - var obsForNode = this.nodeContextValue.get(node); - - if (obsForNode) { - return node; - } - - var parent = fastGetParent(node); - - if (!parent) { - return undefined; - } - - return this.fastGetProviderNode(parent); - }; - - _proto.getProviderNode = function getProviderNode(node) { - assertTweakedObject(node, "node"); - return this.fastGetProviderNode(node); - }; - - _proto.getDefault = function getDefault() { - return getContextValue(this.defaultContextValue); - }; - - _proto.setDefault = function setDefault(value) { - this.defaultContextValue = { - type: "value", - value: value - }; - }; - - _proto.setDefaultComputed = function setDefaultComputed(valueFn) { - this.defaultContextValue = { - type: "computed", - value: (0,mobx_esm.computed)(valueFn) - }; - }; - - _proto.set = function set(node, value) { - assertTweakedObject(node, "node"); - this.nodeContextValue.set(node, { - type: "value", - value: value - }); - this.getNodeAtom(node).reportChanged(); - }; - - _proto.setComputed = function setComputed(node, valueFn) { - assertTweakedObject(node, "node"); - this.nodeContextValue.set(node, { - type: "computed", - value: (0,mobx_esm.computed)(valueFn) - }); - this.getNodeAtom(node).reportChanged(); - }; - - _proto.unset = function unset(node) { - assertTweakedObject(node, "node"); - this.nodeContextValue["delete"](node); - this.getNodeAtom(node).reportChanged(); - }; - - function ContextClass(defaultValue) { - this.defaultContextValue = void 0; - this.nodeContextValue = new WeakMap(); - this.nodeAtom = new WeakMap(); - - if (getMobxVersion() >= 6) { - (0,mobx_esm.makeObservable)(this); - } - - this.setDefault(defaultValue); - } - - return ContextClass; -}(); - -__decorate([mobx_esm.observable.ref], ContextClass.prototype, "defaultContextValue", void 0); - -__decorate([mobx_esm.action], ContextClass.prototype, "setDefault", null); - -__decorate([mobx_esm.action], ContextClass.prototype, "setDefaultComputed", null); - -__decorate([mobx_esm.action], ContextClass.prototype, "set", null); - -__decorate([mobx_esm.action], ContextClass.prototype, "setComputed", null); - -__decorate([mobx_esm.action], ContextClass.prototype, "unset", null); // base - - -function createContext(defaultValue) { - return new ContextClass(defaultValue); -} - -/** - * @ignore - * @internal - */ - -function extendFnModelFlowActions(fnModelObj, namespace, flowActions) { - for (var _i = 0, _Object$entries = Object.entries(flowActions); _i < _Object$entries.length; _i++) { - var _Object$entries$_i = _Object$entries[_i], - name = _Object$entries$_i[0], - fn = _Object$entries$_i[1]; - addActionToFnModel(fnModelObj, namespace, name, fn, true); - } - - return fnModelObj; -} - -/** - * @ignore - * @internal - */ - -function extendFnModelSetterActions(fnModelObj, namespace, setterActions) { - var _loop = function _loop() { - var _Object$entries$_i = _Object$entries[_i], - name = _Object$entries$_i[0], - fieldName = _Object$entries$_i[1]; - - // make strings setters - var fn = function fn(value) { - this[fieldName] = value; - }; - - addActionToFnModel(fnModelObj, namespace, name, fn, false); - }; - - for (var _i = 0, _Object$entries = Object.entries(setterActions); _i < _Object$entries.length; _i++) { - _loop(); - } - - return fnModelObj; -} - -/** - * @ignore - * @internal - */ - -function extendFnModelViews(fnModelObj, views) { - var _loop = function _loop() { - var _Object$entries$_i = _Object$entries[_i], - name = _Object$entries$_i[0], - fnOrFnWithOptions = _Object$entries$_i[1]; - assertFnModelKeyNotInUse(fnModelObj, name); - var computedsPerObject = new WeakMap(); - var fn = void 0; - var equals = void 0; - - if (typeof fnOrFnWithOptions === "function") { - fn = fnOrFnWithOptions; - } else { - fn = fnOrFnWithOptions.get; - equals = fnOrFnWithOptions.equals; - } - - fnModelObj[name] = function (target) { - var computedFn = computedsPerObject.get(target); - - if (!computedFn) { - computedFn = (0,mobx_esm.computed)(fn, { - name: name, - context: target, - equals: equals - }); - computedsPerObject.set(target, computedFn); - } - - return computedFn.get(); - }; - }; - - for (var _i = 0, _Object$entries = Object.entries(views); _i < _Object$entries.length; _i++) { - _loop(); - } - - return fnModelObj; -} - -function fnModel(arg1, arg2) { - var actualType = arguments.length >= 2 ? arg1 : null; - var namespace = arguments.length >= 2 ? arg2 : arg1; - assertIsString(namespace, "namespace"); - var fnModelObj = { - create: actualType ? fnModelCreateWithType.bind(undefined, actualType) : fnModelCreateWithoutType, - type: actualType - }; - fnModelObj.views = extendFnModelViews.bind(undefined, fnModelObj); - fnModelObj.actions = extendFnModelActions.bind(undefined, fnModelObj, namespace); - fnModelObj.flowActions = extendFnModelFlowActions.bind(undefined, fnModelObj, namespace); - fnModelObj.setterActions = extendFnModelSetterActions.bind(undefined, fnModelObj, namespace); - return fnModelObj; -} - -function fnModelCreateWithoutType(data) { - return toTreeNode(data); -} - -function fnModelCreateWithType(actualType, data) { - if (isModelAutoTypeCheckingEnabled()) { - var errors = typeCheck(actualType, data); - - if (errors) { - errors["throw"](data); - } - } - - return toTreeNode(data); -} - -function _splice() { - return this.splice.apply(this, arguments); -} - -var _fnArray = /*#__PURE__*/fnModel("mobx-keystone/fnArray").actions({ - set: function set$1(index, value) { - (0,mobx_esm.set)(this, index, value); - }, - "delete": function _delete(index) { - return (0,mobx_esm.remove)(this, "" + index); - }, - setLength: function setLength(length) { - this.length = length; - }, - concat: function concat() { - return this.concat.apply(this, arguments); - }, - copyWithin: function copyWithin(target, start, end) { - return this.copyWithin(target, start, end); - }, - fill: function fill(value, start, end) { - return this.fill(value, start, end); - }, - pop: function pop() { - return this.pop(); - }, - push: function push() { - return this.push.apply(this, arguments); - }, - reverse: function reverse() { - return this.reverse(); - }, - shift: function shift() { - return this.shift(); - }, - slice: function slice(start, end) { - return this.slice(start, end); - }, - sort: function sort(compareFn) { - return this.sort(compareFn); - }, - splice: _splice, - unshift: function unshift() { - return this.unshift.apply(this, arguments); - } -}); - -var fnArray = { - set: _fnArray.set, - "delete": _fnArray["delete"], - setLength: _fnArray.setLength, - concat: _fnArray.concat, - copyWithin: _fnArray.copyWithin, - fill: _fnArray.fill, - pop: _fnArray.pop, - push: _fnArray.push, - reverse: _fnArray.reverse, - shift: _fnArray.shift, - slice: _fnArray.slice, - sort: _fnArray.sort, - splice: _fnArray.splice, - unshift: _fnArray.unshift, - create: _fnArray.create -}; - -var _fnObject = /*#__PURE__*/fnModel("mobx-keystone/fnObject").actions({ - set: function set$1(key, value) { - (0,mobx_esm.set)(this, key, value); - }, - "delete": function _delete(key) { - return (0,mobx_esm.remove)(this, key); - }, - call: function call(methodName) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - return this[methodName].apply(this, args); - } -}); - -var fnObject = { - set: _fnObject.set, - "delete": _fnObject["delete"], - call: _fnObject.call, - create: _fnObject.create -}; - -var Lock = /*#__PURE__*/function () { - function Lock() { - this._locked = true; - } - - var _proto = Lock.prototype; - - _proto.unlockedFn = function unlockedFn(fn) { - var _this = this; - - var innerFn = function innerFn() { - var oldLocked = _this._locked; - _this._locked = false; - - try { - return fn.apply(void 0, arguments); - } finally { - _this._locked = oldLocked; - } - }; - - return innerFn; - }; - - _proto.withUnlock = function withUnlock(fn) { - var oldLocked = this._locked; - this._locked = false; - - try { - return fn(); - } finally { - this._locked = oldLocked; - } - }; - - _createClass(Lock, [{ - key: "isLocked", - get: function get() { - return this._locked; - } - }]); - - return Lock; -}(); - -/** - * Creates a tag data accessor for a target object of a certain type. - * Tag data will be lazy created on access and reused for the same target object. - * - * @typeparam Target Target type. - * @typeparam TagData Tag data type. - * @param tagDataConstructor Function that will be called the first time the tag - * for a given object is requested. - * @returns The tag data associated with the target object. - */ -function tag(tagDataConstructor) { - var map = new WeakMap(); - return { - "for": function _for(target) { - if (!map.has(target)) { - var data = tagDataConstructor(target); - map.set(target, data); - return data; - } else { - return map.get(target); - } - } - }; -} - -var observableMapBackedByObservableObject = /*#__PURE__*/(0,mobx_esm.action)(function (obj) { - if (inDevMode()) { - if (!(0,mobx_esm.isObservableObject)(obj)) { - throw failure("assertion failed: expected an observable object"); - } - } - - var map = mobx_esm.observable.map(); - map.dataObject = obj; - var keys = Object.keys(obj); - - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - map.set(k, obj[k]); - } - - var mutationLock = new Lock(); // when the object changes the map changes - - (0,mobx_esm.observe)(obj, (0,mobx_esm.action)(mutationLock.unlockedFn(function (change) { - switch (change.type) { - case "add": - case "update": - { - map.set(change.name, change.newValue); - break; - } - - case "remove": - { - map["delete"](change.name); - break; - } - } - }))); // when the map changes also change the object - - (0,mobx_esm.intercept)(map, (0,mobx_esm.action)(function (change) { - if (!mutationLock.isLocked) { - return null; // already changed - } - - switch (change.type) { - case "add": - case "update": - { - (0,mobx_esm.set)(obj, change.name, change.newValue); - break; - } - - case "delete": - { - (0,mobx_esm.remove)(obj, change.name); - break; - } - } - - return change; - })); - return map; -}); -var observableMapBackedByObservableArray = /*#__PURE__*/(0,mobx_esm.action)(function (array) { - if (inDevMode()) { - if (!(0,mobx_esm.isObservableArray)(array)) { - throw failure("assertion failed: expected an observable array"); - } - } - - var map = mobx_esm.observable.map(array); - map.dataObject = array; - - if (map.size !== array.length) { - throw failure("arrays backing a map cannot contain duplicate keys"); - } - - var mutationLock = new Lock(); // for speed reasons we will just assume distinct values are only once in the array - // also we assume tuples themselves are immutable - // when the array changes the map changes - - (0,mobx_esm.observe)(array, (0,mobx_esm.action)(mutationLock.unlockedFn(function (change - /*IArrayDidChange<[string, T]>*/ - ) { - switch (change.type) { - case "splice": - { - { - var removed = change.removed; - - for (var i = 0; i < removed.length; i++) { - map["delete"](removed[i][0]); - } - } - { - var added = change.added; - - for (var _i = 0; _i < added.length; _i++) { - map.set(added[_i][0], added[_i][1]); - } - } - break; - } - - case "update": - { - map["delete"](change.oldValue[0]); - map.set(change.newValue[0], change.newValue[1]); - break; - } - } - }))); // when the map changes also change the array - - (0,mobx_esm.intercept)(map, (0,mobx_esm.action)(function (change) { - if (!mutationLock.isLocked) { - return null; // already changed - } - - switch (change.type) { - case "update": - { - // replace the whole tuple to keep tuple immutability - var i = array.findIndex(function (i) { - return i[0] === change.name; - }); - array[i] = [change.name, change.newValue]; - break; - } - - case "add": - { - array.push([change.name, change.newValue]); - break; - } - - case "delete": - { - var _i2 = array.findIndex(function (i) { - return i[0] === change.name; - }); - - if (_i2 >= 0) { - array.splice(_i2, 1); - } - - break; - } - } - - return change; - })); - return map; -}); -var asMapTag = /*#__PURE__*/tag(function (objOrArray) { - if (isArray(objOrArray)) { - assertIsObservableArray(objOrArray, "objOrArray"); - return observableMapBackedByObservableArray(objOrArray); - } else { - assertIsObservableObject(objOrArray, "objOrArray"); - return observableMapBackedByObservableObject(objOrArray); - } -}); -/** - * Wraps an observable object or a tuple array to offer a map like interface. - * - * @param objOrArray Object or array. - */ - -function asMap(objOrArray) { - return asMapTag["for"](objOrArray); -} -/** - * Converts a map to an object. If the map is a collection wrapper it will return the backed object. - * - * @param map - */ - -function mapToObject(map) { - assertIsMap(map, "map"); - var dataObject = map.dataObject; - - if (dataObject && !isArray(dataObject)) { - return dataObject; - } - - var obj = {}; - - for (var _iterator = _createForOfIteratorHelperLoose(map.keys()), _step; !(_step = _iterator()).done;) { - var k = _step.value; - obj[k] = map.get(k); - } - - return obj; -} -/** - * Converts a map to an array. If the map is a collection wrapper it will return the backed array. - * - * @param map - */ - -function mapToArray(map) { - assertIsMap(map, "map"); - var dataObject = map.dataObject; - - if (dataObject && isArray(dataObject)) { - return dataObject; - } - - var arr = []; - - for (var _iterator2 = _createForOfIteratorHelperLoose(map.keys()), _step2; !(_step2 = _iterator2()).done;) { - var k = _step2.value; - arr.push([k, map.get(k)]); - } - - return arr; -} - -var arrayAsMapInnerTransform = { - propToData: function propToData(arr) { - return isArray(arr) ? asMap(arr) : arr; - }, - dataToProp: function dataToProp(newMap) { - if (!isMap(newMap)) { - return newMap; - } - - return mapToArray(newMap); - } -}; -function prop_mapArray(def) { - return transformedProp(prop(def), arrayAsMapInnerTransform, true); -} -function tProp_mapArray(typeOrDefaultValue, def) { - return transformedProp(tProp(typeOrDefaultValue, def), arrayAsMapInnerTransform, true); -} - -var observableSetBackedByObservableArray = /*#__PURE__*/(0,mobx_esm.action)(function (array) { - if (inDevMode()) { - if (!(0,mobx_esm.isObservableArray)(array)) { - throw failure("assertion failed: expected an observable array"); - } - } - - var set = mobx_esm.observable.set(array); - set.dataObject = array; - - if (set.size !== array.length) { - throw failure("arrays backing a set cannot contain duplicate values"); - } - - var mutationLock = new Lock(); // for speed reasons we will just assume distinct values are only once in the array - // when the array changes the set changes - - (0,mobx_esm.observe)(array, (0,mobx_esm.action)(mutationLock.unlockedFn(function (change - /*IArrayDidChange*/ - ) { - switch (change.type) { - case "splice": - { - { - var removed = change.removed; - - for (var i = 0; i < removed.length; i++) { - set["delete"](removed[i]); - } - } - { - var added = change.added; - - for (var _i = 0; _i < added.length; _i++) { - set.add(added[_i]); - } - } - break; - } - - case "update": - { - set["delete"](change.oldValue); - set.add(change.newValue); - break; - } - } - }))); // when the set changes also change the array - - (0,mobx_esm.intercept)(set, (0,mobx_esm.action)(function (change) { - if (!mutationLock.isLocked) { - return null; // already changed - } - - switch (change.type) { - case "add": - { - array.push(change.newValue); - break; - } - - case "delete": - { - var i = array.indexOf(change.oldValue); - - if (i >= 0) { - array.splice(i, 1); - } - - break; - } - } - - return change; - })); - return set; -}); -var asSetTag = /*#__PURE__*/tag(function (array) { - assertIsObservableArray(array, "array"); - return observableSetBackedByObservableArray(array); -}); -/** - * Wraps an observable array to offer a set like interface. - * - * @param array - */ - -function asSet(array) { - return asSetTag["for"](array); -} -/** - * Converts a set to an array. If the set is a collection wrapper it will return the backed array. - * - * @param set - */ - -function setToArray(set) { - assertIsSet(set, "set"); - var dataObject = set.dataObject; - - if (dataObject) { - return dataObject; - } - - return Array.from(set.values()); -} - -var arrayAsSetInnerTransform = { - propToData: function propToData(arr) { - return isArray(arr) ? asSet(arr) : arr; - }, - dataToProp: function dataToProp(newSet) { - return isSet(newSet) ? setToArray(newSet) : newSet; - } -}; -function prop_setArray(def) { - return transformedProp(prop(def), arrayAsSetInnerTransform, true); -} -function tProp_setArray(typeOrDefaultValue, def) { - return transformedProp(tProp(typeOrDefaultValue, def), arrayAsSetInnerTransform, true); -} - -var objectAsMapInnerTransform = { - propToData: function propToData(obj) { - return isObject(obj) ? asMap(obj) : obj; - }, - dataToProp: function dataToProp(newMap) { - if (!isMap(newMap)) { - return newMap; - } - - return mapToObject(newMap); - } -}; -function prop_mapObject(def) { - return transformedProp(prop(def), objectAsMapInnerTransform, true); -} -function tProp_mapObject(typeOrDefaultValue, def) { - return transformedProp(tProp(typeOrDefaultValue, def), objectAsMapInnerTransform, true); -} - -/** - * @ignore - * @internal - */ - -function immutableDate(value) { - return new InternalImmutableDate(value); -} -var errMessage = "this Date object is immutable"; - -var InternalImmutableDate = /*#__PURE__*/function (_Date) { - _inheritsLoose(InternalImmutableDate, _Date); - - function InternalImmutableDate() { - return _Date.apply(this, arguments) || this; - } - - var _proto = InternalImmutableDate.prototype; - - // disable mutable methods - _proto.setTime = function setTime() { - throw failure(errMessage); - }; - - _proto.setMilliseconds = function setMilliseconds() { - throw failure(errMessage); - }; - - _proto.setUTCMilliseconds = function setUTCMilliseconds() { - throw failure(errMessage); - }; - - _proto.setSeconds = function setSeconds() { - throw failure(errMessage); - }; - - _proto.setUTCSeconds = function setUTCSeconds() { - throw failure(errMessage); - }; - - _proto.setMinutes = function setMinutes() { - throw failure(errMessage); - }; - - _proto.setUTCMinutes = function setUTCMinutes() { - throw failure(errMessage); - }; - - _proto.setHours = function setHours() { - throw failure(errMessage); - }; - - _proto.setUTCHours = function setUTCHours() { - throw failure(errMessage); - }; - - _proto.setDate = function setDate() { - throw failure(errMessage); - }; - - _proto.setUTCDate = function setUTCDate() { - throw failure(errMessage); - }; - - _proto.setMonth = function setMonth() { - throw failure(errMessage); - }; - - _proto.setUTCMonth = function setUTCMonth() { - throw failure(errMessage); - }; - - _proto.setFullYear = function setFullYear() { - throw failure(errMessage); - }; - - _proto.setUTCFullYear = function setUTCFullYear() { - throw failure(errMessage); - }; - - return InternalImmutableDate; -}( /*#__PURE__*/_wrapNativeSuper(Date)); - -/** - * Property transform for ISO date strings to Date objects and vice-versa. - * If a model property, consider using `prop_dateString` or `tProp_dateString` instead. - */ - -var stringAsDate = /*#__PURE__*/propTransform({ - propToData: function propToData(prop) { - if (typeof prop !== "string") { - return prop; - } - - return immutableDate(prop); - }, - dataToProp: function dataToProp(date) { - return date instanceof Date ? date.toJSON() : date; - } -}); -function prop_dateString(def) { - return transformedProp(prop(def), stringAsDate, true); -} -function tProp_dateString(typeOrDefaultValue, def) { - return transformedProp(tProp(typeOrDefaultValue, def), stringAsDate, true); -} - -/** - * Property transform for number timestamps to Date objects and vice-versa. - * If a model property, consider using `prop_dateTimestamp` or `tProp_dateTimestamp` instead. - */ - -var timestampAsDate = /*#__PURE__*/propTransform({ - propToData: function propToData(prop) { - if (typeof prop !== "number") { - return prop; - } - - return immutableDate(prop); - }, - dataToProp: function dataToProp(date) { - return date instanceof Date ? date.getTime() : date; - } -}); -function prop_dateTimestamp(def) { - return transformedProp(prop(def), timestampAsDate, true); -} -function tProp_dateTimestamp(typeOrDefaultValue, def) { - return transformedProp(tProp(typeOrDefaultValue, def), timestampAsDate, true); -} - -/** - * Connects a tree node to a redux dev tools instance. - * - * @param remotedevPackage The remotedev package (usually the result of `require("remoteDev")`) (https://www.npmjs.com/package/remotedev). - * @param remotedevConnection The result of a connect method from the remotedev package (usually the result of `remoteDev.connectViaExtension(...)`). - * @param target Object to use as root. - * @param storeName Name to be shown in the redux dev tools. - * @param [options] Optional options object. `logArgsNearName` if it should show the arguments near the action name (default is `true`). - */ - -function connectReduxDevTools(remotedevPackage, remotedevConnection, target, options) { - assertTweakedObject(target, "target"); - - var opts = _extends({ - logArgsNearName: true - }, options); - - var handlingMonitorAction = 0; // subscribe to change state (if need more than just logging) - - remotedevConnection.subscribe(function (message) { - if (message.type === "DISPATCH") { - handleMonitorActions(remotedevConnection, target, message); - } - }); - var initialState = getSnapshot(target); - remotedevConnection.init(initialState); - var currentActionId = 0; - var actionIdSymbol = Symbol("actionId"); - actionTrackingMiddleware(target, { - onStart: function onStart(ctx) { - ctx.data[actionIdSymbol] = currentActionId++; - }, - onResume: function onResume(ctx) { - // give a chance to the parent to log its own changes before the child starts - if (ctx.parentContext) { - log(ctx.parentContext, undefined); - } - - log(ctx, undefined); - }, - onSuspend: function onSuspend(ctx) { - log(ctx, undefined); - }, - onFinish: function onFinish(ctx, ret) { - log(ctx, ret.result); - } - }); - - function handleMonitorActions(remotedev2, target2, message) { - try { - handlingMonitorAction++; - - switch (message.payload.type) { - case "RESET": - applySnapshot(target2, initialState); - return remotedev2.init(initialState); - - case "COMMIT": - return remotedev2.init(getSnapshot(target2)); - - case "ROLLBACK": - return remotedev2.init(remotedevPackage.extractState(message)); - - case "JUMP_TO_STATE": - case "JUMP_TO_ACTION": - applySnapshot(target2, remotedevPackage.extractState(message)); - return; - - case "IMPORT_STATE": - var nextLiftedState = message.payload.nextLiftedState; - var computedStates = nextLiftedState.computedStates; - applySnapshot(target2, computedStates[computedStates.length - 1].state); - remotedev2.send(null, nextLiftedState); - return; - - default: - } - } finally { - handlingMonitorAction--; - } - } - - var lastLoggedSnapshot = initialState; - - function log(ctx, result) { - if (handlingMonitorAction) { - return; - } - - var sn = getSnapshot(target); // ignore actions that don't change anything (unless it is a throw) - - if (sn === lastLoggedSnapshot && result !== ActionTrackingResult.Throw) { - return; - } - - lastLoggedSnapshot = sn; - var rootPath = fastGetRootPath(ctx.target); - var name = getActionContextNameAndTypePath(ctx, rootPath, result); - var copy = { - type: name, - path: rootPath.path, - args: ctx.args - }; - remotedevConnection.send(copy, sn); - } - - function getActionContextNameAndTypePath(ctx, rootPath, result) { - var pathStr = "[/" + rootPath.path.join("/") + "] "; - var name = pathStr + ctx.actionName; - - if (opts.logArgsNearName) { - var args = ctx.args.map(function (a) { - try { - return JSON.stringify(a); - } catch (_unused) { - return "**unserializable**"; - } - }).join(", "); - - if (args.length > 64) { - args = args.slice(0, 64) + "..."; - } - - name += "(" + args + ")"; - } - - var actionId = ctx.data[actionIdSymbol]; - name += " (id " + (actionId !== undefined ? actionId : "?"); - - if (ctx.type === ActionContextActionType.Async) { - name += ", async"; - } - - name += ")"; - - if (result === ActionTrackingResult.Throw) { - name += " -error thrown-"; - } - - if (ctx.parentContext) { - var parentName = getActionContextNameAndTypePath(ctx.parentContext, fastGetRootPath(ctx.parentContext.target), undefined); - - if (parentName) { - name = parentName + " >>> " + name; - } - } - - return name; - } -} - -/** - * Adds a reaction that will trigger every time an snapshot changes. - * - * @typeparam T Object type. - * @param node Object to get the snapshot from. - * @param listener Function that will be triggered when the snapshot changes. - * @returns A disposer. - */ - -function onSnapshot(node, listener) { - assertTweakedObject(node, "node"); - var currentSnapshot = getSnapshot(node); - return (0,mobx_esm.reaction)(function () { - return getSnapshot(node); - }, function (newSnapshot) { - var prevSn = currentSnapshot; - currentSnapshot = newSnapshot; - listener(newSnapshot, prevSn); - }); -} - -var reduxActionType = "applyAction"; -/** - * Transforms an action call into a redux action. - * - * @param actionCall Action call. - * @returns A redux action. - */ - -function actionCallToReduxAction(actionCall) { - return { - type: reduxActionType, - payload: actionCall - }; -} -/** - * Generates a redux compatible store out of a mobx-keystone object. - * - * @template T Object type. - * @param target Root object. - * @param middlewares Optional list of redux middlewares. - * @returns A redux compatible store. - */ - -function asReduxStore(target) { - assertTweakedObject(target, "target"); - - var defaultDispatch = function defaultDispatch(action) { - if (action.type !== reduxActionType) { - throw failure("action type was expected to be '" + reduxActionType + "', but it was '" + action.type + "'"); - } - - applyAction(target, action.payload); - return action; - }; - - var store = { - getState: function getState() { - return getSnapshot(target); - }, - dispatch: function dispatch(action) { - return runMiddlewares(action, runners, defaultDispatch); - }, - subscribe: function subscribe(listener) { - return onSnapshot(target, listener); - } - }; - - for (var _len = arguments.length, middlewares = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - middlewares[_key - 1] = arguments[_key]; - } - - var runners = middlewares.map(function (mw) { - return mw(store); - }); - return store; -} - -function runMiddlewares(initialAction, runners, next) { - var i = 0; - - function runNextMiddleware(action) { - var runner = runners[i]; - i++; - - if (runner) { - return runner(runNextMiddleware)(action); - } else { - return next(action); - } - } - - return runNextMiddleware(initialAction); -} - -/** - * A reference model base type. - * Use `customRef` to create a custom ref constructor. - */ - -var Ref = /*#__PURE__*/function (_Model) { - _inheritsLoose(Ref, _Model); - - function Ref() { - return _Model.apply(this, arguments) || this; - } - - _createClass(Ref, [{ - key: "maybeCurrent", - - /** - * The object this reference points to, or `undefined` if the reference is currently invalid. - */ - get: function get() { - return this.resolve(); - } - /** - * If the reference is currently valid. - */ - - }, { - key: "isValid", - get: function get() { - return !!this.maybeCurrent; - } - /** - * The object this reference points to, or throws if invalid. - */ - - }, { - key: "current", - get: function get() { - var current = this.maybeCurrent; - - if (!current) { - throw failure("a reference of type '" + this[modelTypeKey] + "' could not resolve an object with id '" + this.id + "'"); - } - - return current; - } - }]); - - return Ref; -}( /*#__PURE__*/Model({ - /** - * Reference id. - */ - id: /*#__PURE__*/tProp(typesString) -})); - -__decorate([mobx_esm.computed], Ref.prototype, "maybeCurrent", null); - -__decorate([mobx_esm.computed], Ref.prototype, "isValid", null); - -__decorate([mobx_esm.computed], Ref.prototype, "current", null); -/** - * Checks if a ref object is of a given ref type. - * - * @typeparam T Referenced object type. - * @param ref Reference object. - * @param refType Reference type. - * @returns `true` if it is of the given type, false otherwise. - */ - - -function isRefOfType(ref, refType) { - return ref instanceof refType.refClass; -} - -/** - * Back-references from object to the references that point to it. - */ - -var objectBackRefs = /*#__PURE__*/new WeakMap(); -/** - * @ignore - * @internal - */ - -function internalCustomRef(modelTypeId, resolverGen, getId, onResolvedValueChange) { - var _temp; - - var CustomRef = (_temp = /*#__PURE__*/function (_Ref) { - _inheritsLoose(CustomRef, _Ref); - - function CustomRef() { - var _this; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - _this = _Ref.call.apply(_Ref, [this].concat(args)) || this; - _this.resolver = void 0; - return _this; - } - - var _proto = CustomRef.prototype; - - _proto.resolve = function resolve() { - if (!this.resolver) { - this.resolver = resolverGen(this); - } - - return this.resolver(this); - }; - - _proto.onInit = function onInit() { - var _this2 = this; - - // listen to changes - var savedOldTarget; - var savedFirstTime = true; // according to mwestrate this won't leak as long as we don't keep the disposer around - - (0,mobx_esm.reaction)(function () { - return _this2.maybeCurrent; - }, function (newTarget) { - var oldTarget = savedOldTarget; - var firstTime = savedFirstTime; // update early in case of thrown exceptions - - savedOldTarget = newTarget; - savedFirstTime = false; - updateBackRefs(_this2, fn, newTarget, oldTarget); - - if (!firstTime && onResolvedValueChange && newTarget !== oldTarget) { - onResolvedValueChange(_this2, newTarget, oldTarget); - } - }, { - fireImmediately: true - }); - }; - - return CustomRef; - }(Ref), _temp); - CustomRef = __decorate([model(modelTypeId)], CustomRef); - - var fn = function fn(target) { - var id; - - if (typeof target === "string") { - id = target; - } else { - assertIsObject(target, "target"); - id = getId(target); - } - - if (typeof id !== "string") { - throw failure("ref target object must have an id of string type"); - } - - var ref = new CustomRef({ - id: id - }); - return ref; - }; - - fn.refClass = CustomRef; - return fn; -} -/** - * Uses a model `getRefId()` method whenever possible to get a reference ID. - * If the model does not have an implementation of that method it returns `undefined`. - * If the model has an implementation, but that implementation returns anything other than - * a `string` it will throw. - * - * @param target Target object to get the ID from. - * @returns The string ID or `undefined`. - */ - -function getModelRefId(target) { - if (isModel(target) && target.getRefId) { - var id = target.getRefId(); - - if (typeof id !== "string") { - throw failure("'getRefId()' must return a string when present"); - } - - return id; - } - - return undefined; -} - -function getBackRefs(target, refType) { - var backRefs = objectBackRefs.get(target); - - if (!backRefs) { - backRefs = { - all: mobx_esm.observable.set(undefined, { - deep: false - }), - byType: new WeakMap() - }; - objectBackRefs.set(target, backRefs); - } - - if (!refType) { - return backRefs.all; - } else { - var byType = backRefs.byType.get(refType); - - if (!byType) { - byType = mobx_esm.observable.set(undefined, { - deep: false - }); - backRefs.byType.set(refType, byType); - } - - return byType; - } -} -/** - * Gets all references that resolve to a given object. - * - * @typeparam T Referenced object type. - * @param target Node the references point to. - * @param [refType] Pass it to filter by only references of a given type, or do not to get references of any type. - * @returns An observable set with all reference objects that point to the given object. - */ - - -function getRefsResolvingTo(target, refType) { - assertTweakedObject(target, "target"); - var refTypeObject = refType; - return getBackRefs(target, refTypeObject); -} - -function updateBackRefs(ref, refClass, newTarget, oldTarget) { - if (newTarget === oldTarget) { - return; - } - - if (oldTarget) { - getBackRefs(oldTarget)["delete"](ref); - getBackRefs(oldTarget, refClass)["delete"](ref); - } - - if (newTarget) { - getBackRefs(newTarget).add(ref); - getBackRefs(newTarget, refClass).add(ref); - } -} - -/** - * Creates a custom ref to an object, which in its snapshot form has an id. - * - * @typeparam T Target object type. - * @param modelTypeId Unique model type id. - * @param options Custom reference options. - * @returns A function that allows you to construct that type of custom reference. - */ - -var customRef = /*#__PURE__*/(0,mobx_esm.action)("customRef", function (modelTypeId, options) { - var _options$getId; - - var getId = (_options$getId = options.getId) != null ? _options$getId : getModelRefId; - return internalCustomRef(modelTypeId, function () { - return options.resolve; - }, getId, options.onResolvedValueChange); -}); - -var computedIdTrees = /*#__PURE__*/new WeakMap(); -/** - * Creates a root ref to an object, which in its snapshot form has an id. - * A root ref will only be able to resolve references as long as both the Ref - * and the referenced object share a common root. - * - * @typeparam T Target object type. - * @param modelTypeId Unique model type id. - * @param [options] Root reference options. - * @returns A function that allows you to construct that type of root reference. - */ - -var rootRef = /*#__PURE__*/(0,mobx_esm.action)("rootRef", function (modelTypeId, options) { - var _options$getId; - - var getId = (_options$getId = options == null ? void 0 : options.getId) != null ? _options$getId : getModelRefId; - var onResolvedValueChange = options == null ? void 0 : options.onResolvedValueChange; // cache/reuse computedIdTrees for same getId function - - var computedIdTree = computedIdTrees.get(getId); - - if (!computedIdTree) { - computedIdTree = computedWalkTreeAggregate(getId); - computedIdTrees.set(getId, computedIdTree); - } - - var resolverGen = function resolverGen(ref) { - var cachedTarget; - return function () { - var refRoot = fastGetRoot(ref); - - if (isRefRootCachedTargetOk(ref, refRoot, cachedTarget, getId)) { - return cachedTarget; - } // when not found, everytime a child is added/removed or its id changes we will perform another search - // this search is only done once for every distinct getId function - - - var idMap = computedIdTree.walk(refRoot); - var newTarget = idMap ? idMap.get(ref.id) : undefined; - - if (newTarget) { - cachedTarget = newTarget; - } - - return newTarget; - }; - }; - - return internalCustomRef(modelTypeId, resolverGen, getId, onResolvedValueChange); -}); - -function isRefRootCachedTargetOk(ref, refRoot, cachedTarget, getId) { - if (!cachedTarget) return false; - if (ref.id !== getId(cachedTarget)) return false; - if (refRoot !== fastGetRoot(cachedTarget)) return false; - return true; -} - -/** - * Clones an object by doing a `fromSnapshot(getSnapshot(value), { generateNewIds: true })`. - * - * @typeparam T Object type. - * @param node Object to clone. - * @param [options] Options. - * @returns The cloned object. - */ - -function clone(node, options) { - assertTweakedObject(node, "node"); - - var opts = _extends({ - generateNewIds: true - }, options); - - var sn = getSnapshot(node); - return fromSnapshot(sn, opts); -} - -/** - * Deeply compares two values. - * - * Supported values are: - * - Primitives - * - Boxed observables - * - Objects, observable objects - * - Arrays, observable arrays - * - Typed arrays - * - Maps, observable maps - * - Sets, observable sets - * - Tree nodes (optimized by using snapshot comparison internally) - * - * Note that in the case of models the result will be false if their model IDs are different. - * - * @param a First value to compare. - * @param b Second value to compare. - * @returns `true` if they are the equivalent, `false` otherwise. - */ - -function deepEquals(a, b) { - // quick check for reference - if (a === b) { - return true; - } // use snapshots to compare if possible - // since snapshots use structural sharing it is more likely - // to speed up comparisons - - - if (isTreeNode(a)) { - a = getSnapshot(a); - } else if ((0,mobx_esm.isObservable)(a)) { - a = (0,mobx_esm.toJS)(a, toJSOptions); - } - - if (isTreeNode(b)) { - b = getSnapshot(b); - } else if ((0,mobx_esm.isObservable)(b)) { - b = (0,mobx_esm.toJS)(b, toJSOptions); - } - - return es6_default()(a, b); -} -var toJSOptions = /*#__PURE__*/getMobxVersion() >= 6 ? undefined : { - exportMapsAsObjects: false, - recurseEverything: false -}; - -/** - * A class with the implementationm of draft. - * Use `draft` to create an instance of this class. - * - * @typeparam T Data type. - */ - -var Draft = /*#__PURE__*/function () { - var _proto = Draft.prototype; - - /** - * Draft data object. - */ - - /** - * Commits current draft changes to the original object. - */ - _proto.commit = function commit() { - applySnapshot(this.originalData, getSnapshot(this.data)); - } - /** - * Partially commits current draft changes to the original object. - * If the path cannot be resolved in either the draft or the original object it will throw. - * Note that model IDs are checked to be the same when resolving the paths. - * - * @param path Path to commit. - */ - ; - - _proto.commitByPath = function commitByPath(path) { - var draftTarget = resolvePath(this.data, path); - - if (!draftTarget.resolved) { - throw failure("path " + JSON.stringify(path) + " could not be resolved in draft object"); - } - - var draftPathIds = pathToTargetPathIdsIgnoringLast(this.data, path); - var originalTarget = resolvePathCheckingIds(this.originalData, path, draftPathIds); - - if (!originalTarget.resolved) { - throw failure("path " + JSON.stringify(path) + " could not be resolved in original object"); - } - - applyPatches(this.originalData, [{ - path: path, - op: "replace", - value: getSnapshot(draftTarget.value) - }]); - } - /** - * Resets the draft to be an exact copy of the current state of the original object. - */ - ; - - _proto.reset = function reset() { - applySnapshot(this.data, this.originalSnapshot); - } - /** - * Partially resets current draft changes to be the same as the original object. - * If the path cannot be resolved in either the draft or the original object it will throw. - * Note that model IDs are checked to be the same when resolving the paths. - * - * @param path Path to reset. - */ - ; - - _proto.resetByPath = function resetByPath(path) { - var originalTarget = resolvePath(this.originalData, path); - - if (!originalTarget.resolved) { - throw failure("path " + JSON.stringify(path) + " could not be resolved in original object"); - } - - var originalPathIds = pathToTargetPathIdsIgnoringLast(this.originalData, path); - var draftTarget = resolvePathCheckingIds(this.data, path, originalPathIds); - - if (!draftTarget.resolved) { - throw failure("path " + JSON.stringify(path) + " could not be resolved in draft object"); - } - - applyPatches(this.data, [{ - path: path, - op: "replace", - value: getSnapshot(originalTarget.value) - }]); - } - /** - * Returns `true` if the draft has changed compared to the original object, `false` otherwise. - */ - ; - - /** - * Returns `true` if the value at the given path of the draft has changed compared to the original object. - * If the path cannot be resolved in the draft it will throw. - * If the path cannot be resolved in the original object it will return `true`. - * Note that model IDs are checked to be the same when resolving the paths. - * - * @param path Path to check. - */ - _proto.isDirtyByPath = function isDirtyByPath(path) { - var draftTarget = resolvePath(this.data, path); - - if (!draftTarget.resolved) { - throw failure("path " + JSON.stringify(path) + " could not be resolved in draft object"); - } - - var draftPathIds = pathToTargetPathIdsIgnoringLast(this.data, path); - var originalTarget = resolvePathCheckingIds(this.originalData, path, draftPathIds); - - if (!originalTarget.resolved) { - return true; - } - - return !deepEquals(draftTarget.value, originalTarget.value); - } - /** - * Original data object. - */ - ; - - _createClass(Draft, [{ - key: "isDirty", - get: function get() { - return !deepEquals(getSnapshot(this.data), this.originalSnapshot); - } - }, { - key: "originalSnapshot", - get: function get() { - return getSnapshot(this.originalData); - } - /** - * Creates an instance of Draft. - * Do not use directly, use `draft` instead. - * - * @param original - */ - - }]); - - function Draft(original) { - this.data = void 0; - this.originalData = void 0; - assertTweakedObject(original, "original"); - this.originalData = original; - this.data = fromSnapshot(this.originalSnapshot, { - generateNewIds: false - }); - } - - return Draft; -}(); - -__decorate([mobx_esm.action], Draft.prototype, "commit", null); - -__decorate([mobx_esm.action], Draft.prototype, "commitByPath", null); - -__decorate([mobx_esm.action], Draft.prototype, "reset", null); - -__decorate([mobx_esm.action], Draft.prototype, "resetByPath", null); - -__decorate([mobx_esm.computed], Draft.prototype, "isDirty", null); - -__decorate([mobx_esm.computed], Draft.prototype, "originalSnapshot", null); -/** - * Creates a draft copy of a tree node and all its children. - * - * @typeparam T Data type. - * @param original Original node. - * @returns The draft object. - */ - - -function draft(original) { - return new Draft(original); -} - -function pathToTargetPathIdsIgnoringLast(root, path) { - var pathIds = pathToTargetPathIds(root, path); - - if (pathIds.length >= 1) { - // never check the last object id - pathIds[pathIds.length - 1] = skipIdChecking; - } - - return pathIds; -} - -/** - * Context that allows access to the sandbox manager this node runs under (if any). - */ - -var sandboxManagerContext = /*#__PURE__*/createContext(); -/** - * Returns the sandbox manager of a node, or `undefined` if none. - * - * @param node Node to check. - * @returns The sandbox manager of a node, or `undefined` if none. - */ - -function getNodeSandboxManager(node) { - return sandboxManagerContext.get(node); -} -/** - * Returns if a given node is a sandboxed node. - * - * @param node Node to check. - * @returns `true` if it is sandboxed, `false` - */ - -function isSandboxedNode(node) { - return !!getNodeSandboxManager(node); -} -/** - * Manager class returned by `sandbox` that allows you to make changes to a sandbox copy of the - * original subtree and apply them to the original subtree or reject them. - */ - -var SandboxManager = /*#__PURE__*/function () { - /** - * The sandbox copy of the original subtree. - */ - - /** - * The internal disposer. - */ - - /** - * The internal `withSandbox` patch recorder. If `undefined`, no `withSandbox` call is being - * executed. - */ - - /** - * Function from `readonlyMiddleware` that will allow actions to be started inside the provided - * code block on a readonly node. - */ - - /** - * Creates an instance of `SandboxManager`. - * Do not use directly, use `sandbox` instead. - * - * @param subtreeRoot Subtree root target object. - */ - function SandboxManager(subtreeRoot) { - var _this = this; - - this.subtreeRoot = void 0; - this.subtreeRootClone = void 0; - this.disposer = void 0; - this.withSandboxPatchRecorder = void 0; - this.allowWrite = void 0; - this.subtreeRoot = subtreeRoot; - assertTweakedObject(subtreeRoot, "subtreeRoot"); // we temporarily set the default value of the context manager so that - // cloned nodes can access it while in their onInit phase - - var previousContextDefault = sandboxManagerContext.getDefault(); - sandboxManagerContext.setDefault(this); - - try { - this.subtreeRootClone = clone(subtreeRoot, { - generateNewIds: false - }); - sandboxManagerContext.set(this.subtreeRootClone, this); - } catch (err) { - throw err; - } finally { - sandboxManagerContext.setDefault(previousContextDefault); - } - - var wasRS = false; - var disposeReactionRS = (0,mobx_esm.reaction)(function () { - return isRootStore(subtreeRoot); - }, function (isRS) { - if (isRS !== wasRS) { - wasRS = isRS; - - if (isRS) { - registerRootStore(_this.subtreeRootClone); - } else { - unregisterRootStore(_this.subtreeRootClone); - } - } - }, { - fireImmediately: true - }); - var disposeOnPatches = onPatches(subtreeRoot, function (patches) { - if (_this.withSandboxPatchRecorder) { - throw failure("original subtree must not change while 'withSandbox' executes"); - } - - _this.allowWrite(function () { - applyPatches(_this.subtreeRootClone, patches); - }); - }); - - var _readonlyMiddleware = readonlyMiddleware(this.subtreeRootClone), - allowWrite = _readonlyMiddleware.allowWrite, - disposeReadonlyMW = _readonlyMiddleware.dispose; - - this.allowWrite = allowWrite; - - this.disposer = function () { - disposeReactionRS(); - disposeOnPatches(); - disposeReadonlyMW(); - - if (isRootStore(_this.subtreeRootClone)) { - unregisterRootStore(_this.subtreeRootClone); - } - - _this.disposer = function () {}; - }; - } - /** - * Executes `fn` with a sandbox copy of `node`. The changes made to the sandbox in `fn` can be - * accepted, i.e. applied to the original subtree, or rejected. - * - * @typeparam T Object type. - * @typeparam R Return type. - * @param node Object or tuple of objects for which to obtain a sandbox copy. - * @param fn Function that is called with a sandbox copy of `node`. Any changes made to the - * sandbox are applied to the original subtree when `fn` returns `true` or - * `{ commit: true, ... }`. When `fn` returns `false` or `{ commit: false, ... }` the changes made - * to the sandbox are rejected. - * @returns Value of type `R` when `fn` returns an object of type `{ commit: boolean; return: R }` - * or `void` when `fn` returns a boolean. - */ - - - var _proto = SandboxManager.prototype; - - _proto.withSandbox = function withSandbox(node, fn) { - assertIsFunction(fn, "fn"); - var isNodesArray = Array.isArray(node) && !isTweakedObject(node, false); - var nodes = isNodesArray ? node : [node]; - - var _this$prepareSandboxC = this.prepareSandboxChanges(nodes), - sandboxNodes = _this$prepareSandboxC.sandboxNodes, - applyRecorderChanges = _this$prepareSandboxC.applyRecorderChanges; - - var commit = false; - - try { - var returnValue = this.allowWrite(function () { - return fn(isNodesArray ? sandboxNodes : sandboxNodes[0]); - }); - - if (typeof returnValue === "boolean") { - commit = returnValue; - return undefined; - } else { - commit = returnValue.commit; - return returnValue["return"]; - } - } finally { - applyRecorderChanges(commit); - } - } - /** - * Disposes of the sandbox. - */ - ; - - _proto.dispose = function dispose() { - this.disposer(); - }; - - _proto.prepareSandboxChanges = function prepareSandboxChanges(nodes) { - var _this2 = this; - - var isNestedWithSandboxCall = !!this.withSandboxPatchRecorder; - var sandboxNodes = nodes.map(function (node) { - assertTweakedObject(node, "node"); - var path = getParentToChildPath(isNestedWithSandboxCall ? _this2.subtreeRootClone : _this2.subtreeRoot, node); - - if (!path) { - throw failure("node is not a child of subtreeRoot" + (isNestedWithSandboxCall ? "Clone" : "")); - } - - var sandboxNode = resolvePath(_this2.subtreeRootClone, path).value; - - if (!sandboxNode) { - throw failure("path could not be resolved - sandbox may be out of sync with original tree"); - } - - return sandboxNode; - }); - - if (!this.withSandboxPatchRecorder) { - this.withSandboxPatchRecorder = patchRecorder(this.subtreeRootClone); - } - - var recorder = this.withSandboxPatchRecorder; - var numRecorderEvents = recorder.events.length; - - var applyRecorderChanges = function applyRecorderChanges(commit) { - if (!isNestedWithSandboxCall) { - recorder.dispose(); - _this2.withSandboxPatchRecorder = undefined; - } - - (0,mobx_esm.runInAction)(function () { - if (commit) { - if (!isNestedWithSandboxCall) { - var len = recorder.events.length; - - for (var i = 0; i < len; i++) { - applyPatches(_this2.subtreeRoot, recorder.events[i].patches); - } - } - } else { - _this2.allowWrite(function () { - var i = recorder.events.length; - - while (i-- > numRecorderEvents) { - applyPatches(_this2.subtreeRootClone, recorder.events[i].inversePatches, true); - } - }); - } - }); - }; - - return { - sandboxNodes: sandboxNodes, - applyRecorderChanges: applyRecorderChanges - }; - }; - - return SandboxManager; -}(); -/** - * Creates a sandbox. - * - * @param subtreeRoot Subtree root target object. - * @returns A `SandboxManager` which allows you to manage the sandbox operations and dispose of the - * sandbox. - */ - -function sandbox(subtreeRoot) { - return new SandboxManager(subtreeRoot); -} - -/** - * A set that is backed by an array. - * Use `arraySet` to create it. - */ - -var ArraySet = /*#__PURE__*/function (_Model) { - _inheritsLoose(ArraySet, _Model); - - function ArraySet() { - return _Model.apply(this, arguments) || this; - } - - var _proto = ArraySet.prototype; - - _proto.add = function add(value) { - var items = this.items; - - if (!items.includes(value)) { - items.push(value); - } - - return this; - }; - - _proto.clear = function clear() { - this.items.length = 0; - }; - - _proto["delete"] = function _delete(value) { - var items = this.items; - var index = items.findIndex(function (t) { - return t === value; - }); - - if (index >= 0) { - items.splice(index, 1); - return true; - } else { - return false; - } - }; - - _proto.forEach = function forEach(callbackfn, thisArg) { - // we cannot use the set implementation since we need to pass this as set - var items = this.items; - var len = items.length; - - for (var i = 0; i < len; i++) { - var k = items[i]; - callbackfn.call(thisArg, k, k, this); - } - }; - - _proto.has = function has(value) { - return this.items.includes(value); - }; - - _proto.keys = function keys() { - return this.values(); // yes, values - }; - - _proto.values = function values$1() { - var items = this.items; - return (0,mobx_esm.values)(items)[Symbol.iterator](); - }; - - _proto.entries = function entries() { - var items = this.items; // TODO: should use an actual iterator - - return items.map(function (v) { - return [v, v]; - }).values(); - }; - - _proto[Symbol.iterator] = function () { - return this.values(); - }; - - _createClass(ArraySet, [{ - key: "size", - get: function get() { - return this.items.length; - } - }, { - key: Symbol.toStringTag, - get: function get() { - return "ArraySet"; - } - }]); - - return ArraySet; -}( /*#__PURE__*/Model({ - items: /*#__PURE__*/tProp( /*#__PURE__*/typesArray( /*#__PURE__*/typesUnchecked()), function () { - return []; - }) -})); - -__decorate([modelAction], ArraySet.prototype, "add", null); - -__decorate([modelAction], ArraySet.prototype, "clear", null); - -__decorate([modelAction], ArraySet.prototype, "delete", null); - -ArraySet = /*#__PURE__*/__decorate([/*#__PURE__*/model("mobx-keystone/ArraySet")], ArraySet); -/** - * Creates a new ArraySet model instance. - * - * @typeparam V Value type. - * @param [entries] Optional initial values. - */ - -function arraySet(values) { - var initialArr = values ? values.slice() : []; - return new ArraySet({ - items: initialArr - }); -} - -/** - * A type that represents an array backed set ArraySet. - * - * Example: - * ```ts - * const numberSetType = types.arraySet(types.number) - * ``` - * - * @typeparam T Value type. - * @param valueType Value type. - * @returns - */ - -function typesArraySet(valueType) { - var typeInfoGen = function typeInfoGen(t) { - return new ArraySetTypeInfo(t, resolveStandardType(valueType)); - }; - - return lateTypeChecker(function () { - var valueChecker = resolveTypeChecker(valueType); - - var getTypeName = function getTypeName() { - for (var _len = arguments.length, recursiveTypeCheckers = new Array(_len), _key = 0; _key < _len; _key++) { - recursiveTypeCheckers[_key] = arguments[_key]; - } - - return "ArraySet<" + valueChecker.getTypeName.apply(valueChecker, recursiveTypeCheckers.concat([valueChecker])) + ">"; - }; - - var thisTc = new TypeChecker(function (obj, path) { - if (!(obj instanceof ArraySet)) { - return new TypeCheckError(path, getTypeName(thisTc), obj); - } - - var dataTypeChecker = typesObject(function () { - return { - items: typesArray(valueChecker) - }; - }); - var resolvedTc = resolveTypeChecker(dataTypeChecker); - return resolvedTc.check(obj.$, path); - }, getTypeName, typeInfoGen); - return thisTc; - }, typeInfoGen); -} -/** - * `types.arraySet` type info. - */ - -var ArraySetTypeInfo = /*#__PURE__*/function (_TypeInfo) { - _inheritsLoose(ArraySetTypeInfo, _TypeInfo); - - _createClass(ArraySetTypeInfo, [{ - key: "valueTypeInfo", - get: function get() { - return getTypeInfo(this.valueType); - } - }]); - - function ArraySetTypeInfo(originalType, valueType) { - var _this; - - _this = _TypeInfo.call(this, originalType) || this; - _this.valueType = void 0; - _this.valueType = valueType; - return _this; - } - - return ArraySetTypeInfo; -}(TypeInfo); - -/** - * A type that represents the union of several other types (a | b | c | ...). - * - * Example: - * ```ts - * const booleanOrNumberType = types.or(types.boolean, types.number) - * ``` - * - * @typeparam T Type. - * @param orTypes Possible types. - * @returns - */ - -function typesOr() { - for (var _len = arguments.length, orTypes = new Array(_len), _key = 0; _key < _len; _key++) { - orTypes[_key] = arguments[_key]; - } - - var typeInfoGen = function typeInfoGen(t) { - return new OrTypeInfo(t, orTypes.map(resolveStandardType)); - }; - - return lateTypeChecker(function () { - var checkers = orTypes.map(resolveTypeChecker); // if the or includes unchecked then it is unchecked - - if (checkers.some(function (tc) { - return tc.unchecked; - })) { - return typesUnchecked(); - } - - var getTypeName = function getTypeName() { - for (var _len2 = arguments.length, recursiveTypeCheckers = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - recursiveTypeCheckers[_key2] = arguments[_key2]; - } - - var typeNames = checkers.map(function (tc) { - if (recursiveTypeCheckers.includes(tc)) { - return "..."; - } - - return tc.getTypeName.apply(tc, recursiveTypeCheckers.concat([tc])); - }); - return typeNames.join(" | "); - }; - - var thisTc = new TypeChecker(function (value, path) { - var noMatchingType = checkers.every(function (tc) { - return !!tc.check(value, path); - }); - - if (noMatchingType) { - return new TypeCheckError(path, getTypeName(thisTc), value); - } else { - return null; - } - }, getTypeName, typeInfoGen); - return thisTc; - }, typeInfoGen); -} -/** - * `types.or` type info. - */ - -var OrTypeInfo = /*#__PURE__*/function (_TypeInfo) { - _inheritsLoose(OrTypeInfo, _TypeInfo); - - _createClass(OrTypeInfo, [{ - key: "orTypeInfos", - // memoize to always return the same array on the getter - get: function get() { - return this._orTypeInfos(); - } - }]); - - function OrTypeInfo(thisType, orTypes) { - var _this; - - _this = _TypeInfo.call(this, thisType) || this; - _this.orTypes = void 0; - _this._orTypeInfos = lateVal(function () { - return _this.orTypes.map(getTypeInfo); - }); - _this.orTypes = orTypes; - return _this; - } - - return OrTypeInfo; -}(TypeInfo); - -function enumValues(e) { - var vals = []; - - for (var _i = 0, _Object$keys = Object.keys(e); _i < _Object$keys.length; _i++) { - var k = _Object$keys[_i]; - var v = e[k]; // we have to do this since TS does something weird - // to number values - // Hi = 0 -> { Hi: 0, 0: "Hi" } - - if (typeof v !== "string" || e[v] !== +k) { - vals.push(v); - } - } - - return vals; -} - -function typesEnum(enumObject) { - assertIsObject(enumObject, "enumObject"); - var literals = enumValues(enumObject).map(function (e) { - return typesLiteral(e); - }); - return typesOr.apply(void 0, literals); -} - -/** - * A type that represents either a type or undefined. - * Syntactic sugar for `types.or(baseType, types.undefined)` - * - * Example: - * ```ts - * const numberOrUndefinedType = types.maybe(types.number) - * ``` - * - * @typeparam S Type. - * @param baseType Type. - * @returns - */ - -function typesMaybe(baseType) { - return typesOr(baseType, typesUndefined); -} -/** - * A type that represents either a type or null. - * Syntactic sugar for `types.or(baseType, types.null)` - * - * * Example: - * ```ts - * const numberOrNullType = types.maybeNull(types.number) - * ``` - * - * @typeparam S Type. - * @param type Type. - * @returns - */ - -function typesMaybeNull(type) { - return typesOr(type, typesNull); -} - -/** - * A type that represents an object-like map, an object with string keys and values all of a same given type. - * - * Example: - * ```ts - * // { [k: string]: number } - * const numberMapType = types.record(types.number) - * ``` - * - * @typeparam T Type. - * @param valueType Type of the values of the object-like map. - * @returns - */ - -function typesRecord(valueType) { - var typeInfoGen = function typeInfoGen(tc) { - return new RecordTypeInfo(tc, resolveStandardType(valueType)); - }; - - return lateTypeChecker(function () { - var valueChecker = resolveTypeChecker(valueType); - - var getTypeName = function getTypeName() { - for (var _len = arguments.length, recursiveTypeCheckers = new Array(_len), _key = 0; _key < _len; _key++) { - recursiveTypeCheckers[_key] = arguments[_key]; - } - - return "Record<" + valueChecker.getTypeName.apply(valueChecker, recursiveTypeCheckers.concat([valueChecker])) + ">"; - }; - - var thisTc = new TypeChecker(function (obj, path) { - if (!isObject(obj)) return new TypeCheckError(path, getTypeName(thisTc), obj); - - if (!valueChecker.unchecked) { - var keys = Object.keys(obj); - - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - var v = obj[k]; - var valueError = valueChecker.check(v, [].concat(path, [k])); - - if (valueError) { - return valueError; - } - } - } - - return null; - }, getTypeName, typeInfoGen); - return thisTc; - }, typeInfoGen); -} -/** - * `types.record` type info. - */ - -var RecordTypeInfo = /*#__PURE__*/function (_TypeInfo) { - _inheritsLoose(RecordTypeInfo, _TypeInfo); - - _createClass(RecordTypeInfo, [{ - key: "valueTypeInfo", - get: function get() { - return getTypeInfo(this.valueType); - } - }]); - - function RecordTypeInfo(thisType, valueType) { - var _this; - - _this = _TypeInfo.call(this, thisType) || this; - _this.valueType = void 0; - _this.valueType = valueType; - return _this; - } - - return RecordTypeInfo; -}(TypeInfo); - -/** - * A map that is backed by an object-like map. - * Use `objectMap` to create it. - */ - -var ObjectMap = /*#__PURE__*/function (_Model) { - _inheritsLoose(ObjectMap, _Model); - - function ObjectMap() { - return _Model.apply(this, arguments) || this; - } - - var _proto = ObjectMap.prototype; - - _proto.clear = function clear() { - var items = this.items; - var keys = Object.keys(items); - var len = keys.length; - - for (var i = 0; i < len; i++) { - var k = keys[i]; - (0,mobx_esm.remove)(items, k); - } - }; - - _proto["delete"] = function _delete(key) { - var hasKey = this.has(key); - - if (hasKey) { - (0,mobx_esm.remove)(this.items, key); - return true; - } else { - return false; - } - }; - - _proto.forEach = function forEach(callbackfn, thisArg) { - // we cannot use the map implementation since we need to pass this as map - var items = this.items; - var keys = Object.keys(items); - var len = keys.length; - - for (var i = 0; i < len; i++) { - var k = keys[i]; - callbackfn.call(thisArg, items[k], k, this); - } - }; - - _proto.get = function get$1(key) { - return (0,mobx_esm.get)(this.items, key); - }; - - _proto.has = function has$1(key) { - return (0,mobx_esm.has)(this.items, key); - }; - - _proto.set = function set$1(key, value) { - (0,mobx_esm.set)(this.items, key, value); - - return this; - }; - - _proto.keys = function keys$1() { - // TODO: should use an actual iterator - return (0,mobx_esm.keys)(this.items)[Symbol.iterator](); - }; - - _proto.values = function values$1() { - // TODO: should use an actual iterator - return (0,mobx_esm.values)(this.items)[Symbol.iterator](); - }; - - _proto.entries = function entries$1() { - // TODO: should use an actual iterator - return (0,mobx_esm.entries)(this.items)[Symbol.iterator](); - }; - - _proto[Symbol.iterator] = function () { - return this.entries(); - }; - - _createClass(ObjectMap, [{ - key: "size", - get: function get() { - return (0,mobx_esm.keys)(this.items).length; - } - }, { - key: Symbol.toStringTag, - get: function get() { - return "ObjectMap"; - } - }]); - - return ObjectMap; -}( /*#__PURE__*/Model({ - items: /*#__PURE__*/tProp( /*#__PURE__*/typesRecord( /*#__PURE__*/typesUnchecked()), function () { - return {}; - }) -})); - -__decorate([modelAction], ObjectMap.prototype, "clear", null); - -__decorate([modelAction], ObjectMap.prototype, "delete", null); - -__decorate([modelAction], ObjectMap.prototype, "set", null); - -ObjectMap = /*#__PURE__*/__decorate([/*#__PURE__*/model("mobx-keystone/ObjectMap")], ObjectMap); -/** - * Creates a new ObjectMap model instance. - * - * @typeparam V Value type. - * @param [entries] Optional initial values. - */ - -function objectMap(entries) { - var initialObj = {}; - - if (entries) { - var len = entries.length; - - for (var i = 0; i < len; i++) { - var entry = entries[i]; - initialObj[entry[0]] = entry[1]; - } - } - - return new ObjectMap({ - items: initialObj - }); -} - -/** - * A type that represents an object-like map ObjectMap. - * - * Example: - * ```ts - * const numberMapType = types.objectMap(types.number) - * ``` - * - * @typeparam T Value type. - * @param valueType Value type. - * @returns - */ - -function typesObjectMap(valueType) { - var typeInfoGen = function typeInfoGen(t) { - return new ObjectMapTypeInfo(t, resolveStandardType(valueType)); - }; - - return lateTypeChecker(function () { - var valueChecker = resolveTypeChecker(valueType); - - var getTypeName = function getTypeName() { - for (var _len = arguments.length, recursiveTypeCheckers = new Array(_len), _key = 0; _key < _len; _key++) { - recursiveTypeCheckers[_key] = arguments[_key]; - } - - return "ObjectMap<" + valueChecker.getTypeName.apply(valueChecker, recursiveTypeCheckers.concat([valueChecker])) + ">"; - }; - - var thisTc = new TypeChecker(function (obj, path) { - if (!(obj instanceof ObjectMap)) { - return new TypeCheckError(path, getTypeName(thisTc), obj); - } - - var dataTypeChecker = typesObject(function () { - return { - items: typesRecord(valueChecker) - }; - }); - var resolvedTc = resolveTypeChecker(dataTypeChecker); - return resolvedTc.check(obj.$, path); - }, getTypeName, typeInfoGen); - return thisTc; - }, typeInfoGen); -} -/** - * `types.objectMap` type info. - */ - -var ObjectMapTypeInfo = /*#__PURE__*/function (_TypeInfo) { - _inheritsLoose(ObjectMapTypeInfo, _TypeInfo); - - _createClass(ObjectMapTypeInfo, [{ - key: "valueTypeInfo", - get: function get() { - return getTypeInfo(this.valueType); - } - }]); - - function ObjectMapTypeInfo(thisType, valueType) { - var _this; - - _this = _TypeInfo.call(this, thisType) || this; - _this.valueType = void 0; - _this.valueType = valueType; - return _this; - } - - return ObjectMapTypeInfo; -}(TypeInfo); - -/** - * A type that represents a reference to an object or model. - * - * Example: - * ```ts - * const refToSomeObject = types.ref() - * ``` - * - * @typeparam M Model type. - * @returns - */ - -function typesRef() { - return refTypeChecker; -} -var typeName = "Ref"; -var refDataTypeChecker = /*#__PURE__*/typesObject(function () { - return { - id: typesString - }; -}); -var refTypeChecker = /*#__PURE__*/new TypeChecker(function (value, path) { - if (!(value instanceof Ref)) { - return new TypeCheckError(path, typeName, value); - } - - var resolvedTc = resolveTypeChecker(refDataTypeChecker); - return resolvedTc.check(value.$, path); -}, function () { - return typeName; -}, function (t) { - return new RefTypeInfo(t); -}); -/** - * `types.ref` type info. - */ - -var RefTypeInfo = /*#__PURE__*/function (_TypeInfo) { - _inheritsLoose(RefTypeInfo, _TypeInfo); - - function RefTypeInfo() { - return _TypeInfo.apply(this, arguments) || this; - } - - return RefTypeInfo; -}(TypeInfo); - -/** - * A type that represents an tuple of values of a given type. - * - * Example: - * ```ts - * const stringNumberTupleType = types.tuple(types.string, types.number) - * ``` - * - * @typeparam T Item types. - * @param itemType Type of inner items. - * @returns - */ - -function typesTuple() { - for (var _len = arguments.length, itemTypes = new Array(_len), _key = 0; _key < _len; _key++) { - itemTypes[_key] = arguments[_key]; - } - - var typeInfoGen = function typeInfoGen(t) { - return new TupleTypeInfo(t, itemTypes.map(resolveStandardType)); - }; - - return lateTypeChecker(function () { - var checkers = itemTypes.map(resolveTypeChecker); - - var getTypeName = function getTypeName() { - for (var _len2 = arguments.length, recursiveTypeCheckers = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - recursiveTypeCheckers[_key2] = arguments[_key2]; - } - - var typeNames = checkers.map(function (tc) { - if (recursiveTypeCheckers.includes(tc)) { - return "..."; - } - - return tc.getTypeName.apply(tc, recursiveTypeCheckers.concat([tc])); - }); - return "[" + typeNames.join(", ") + "]"; - }; - - var thisTc = new TypeChecker(function (array, path) { - if (!isArray(array) || array.length !== itemTypes.length) { - return new TypeCheckError(path, getTypeName(thisTc), array); - } - - for (var i = 0; i < array.length; i++) { - var itemChecker = checkers[i]; - - if (!itemChecker.unchecked) { - var itemError = itemChecker.check(array[i], [].concat(path, [i])); - - if (itemError) { - return itemError; - } - } - } - - return null; - }, getTypeName, typeInfoGen); - return thisTc; - }, typeInfoGen); -} -/** - * `types.tuple` type info. - */ - -var TupleTypeInfo = /*#__PURE__*/function (_TypeInfo) { - _inheritsLoose(TupleTypeInfo, _TypeInfo); - - _createClass(TupleTypeInfo, [{ - key: "itemTypeInfos", - // memoize to always return the same array on the getter - get: function get() { - return this._itemTypeInfos(); - } - }]); - - function TupleTypeInfo(thisType, itemTypes) { - var _this; - - _this = _TypeInfo.call(this, thisType) || this; - _this.itemTypes = void 0; - _this._itemTypeInfos = lateVal(function () { - return _this.itemTypes.map(getTypeInfo); - }); - _this.itemTypes = itemTypes; - return _this; - } - - return TupleTypeInfo; -}(TypeInfo); - -var types = { - literal: typesLiteral, - undefined: typesUndefined, - "null": typesNull, - "boolean": typesBoolean, - number: typesNumber, - string: typesString, - or: typesOr, - maybe: typesMaybe, - maybeNull: typesMaybeNull, - array: typesArray, - record: typesRecord, - unchecked: typesUnchecked, - model: typesModel, - object: typesObject, - ref: typesRef, - frozen: typesFrozen, - "enum": typesEnum, - refinement: typesRefinement, - integer: typesInteger, - nonEmptyString: typesNonEmptyString, - objectMap: typesObjectMap, - arraySet: typesArraySet, - tuple: typesTuple, - mapArray: function mapArray(valueType) { - return typesArray(typesTuple(typesString, valueType)); - }, - setArray: function setArray(valueType) { - return typesArray(valueType); - }, - mapObject: function mapObject(valueType) { - return typesRecord(valueType); - }, - dateString: typesNonEmptyString, - dateTimestamp: typesInteger -}; - - - - -/***/ }), - -/***/ 5412: -/*!************************************************!*\ - !*** ../../node_modules/mobx/dist/mobx.esm.js ***! - \************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "$mobx": () => (/* binding */ $mobx), -/* harmony export */ "FlowCancellationError": () => (/* binding */ FlowCancellationError), -/* harmony export */ "ObservableMap": () => (/* binding */ ObservableMap), -/* harmony export */ "ObservableSet": () => (/* binding */ ObservableSet), -/* harmony export */ "Reaction": () => (/* binding */ Reaction), -/* harmony export */ "_allowStateChanges": () => (/* binding */ allowStateChanges), -/* harmony export */ "_allowStateChangesInsideComputed": () => (/* binding */ runInAction), -/* harmony export */ "_allowStateReadsEnd": () => (/* binding */ allowStateReadsEnd), -/* harmony export */ "_allowStateReadsStart": () => (/* binding */ allowStateReadsStart), -/* harmony export */ "_autoAction": () => (/* binding */ autoAction), -/* harmony export */ "_endAction": () => (/* binding */ _endAction), -/* harmony export */ "_getAdministration": () => (/* binding */ getAdministration), -/* harmony export */ "_getGlobalState": () => (/* binding */ getGlobalState), -/* harmony export */ "_interceptReads": () => (/* binding */ interceptReads), -/* harmony export */ "_isComputingDerivation": () => (/* binding */ isComputingDerivation), -/* harmony export */ "_resetGlobalState": () => (/* binding */ resetGlobalState), -/* harmony export */ "_startAction": () => (/* binding */ _startAction), -/* harmony export */ "action": () => (/* binding */ action), -/* harmony export */ "autorun": () => (/* binding */ autorun), -/* harmony export */ "comparer": () => (/* binding */ comparer), -/* harmony export */ "computed": () => (/* binding */ computed), -/* harmony export */ "configure": () => (/* binding */ configure), -/* harmony export */ "createAtom": () => (/* binding */ createAtom), -/* harmony export */ "entries": () => (/* binding */ entries), -/* harmony export */ "extendObservable": () => (/* binding */ extendObservable), -/* harmony export */ "flow": () => (/* binding */ flow), -/* harmony export */ "flowResult": () => (/* binding */ flowResult), -/* harmony export */ "get": () => (/* binding */ get), -/* harmony export */ "getAtom": () => (/* binding */ getAtom), -/* harmony export */ "getDebugName": () => (/* binding */ getDebugName), -/* harmony export */ "getDependencyTree": () => (/* binding */ getDependencyTree), -/* harmony export */ "getObserverTree": () => (/* binding */ getObserverTree), -/* harmony export */ "has": () => (/* binding */ has), -/* harmony export */ "intercept": () => (/* binding */ intercept), -/* harmony export */ "isAction": () => (/* binding */ isAction), -/* harmony export */ "isBoxedObservable": () => (/* binding */ isObservableValue), -/* harmony export */ "isComputed": () => (/* binding */ isComputed), -/* harmony export */ "isComputedProp": () => (/* binding */ isComputedProp), -/* harmony export */ "isFlowCancellationError": () => (/* binding */ isFlowCancellationError), -/* harmony export */ "isObservable": () => (/* binding */ isObservable), -/* harmony export */ "isObservableArray": () => (/* binding */ isObservableArray), -/* harmony export */ "isObservableMap": () => (/* binding */ isObservableMap), -/* harmony export */ "isObservableObject": () => (/* binding */ isObservableObject), -/* harmony export */ "isObservableProp": () => (/* binding */ isObservableProp), -/* harmony export */ "isObservableSet": () => (/* binding */ isObservableSet), -/* harmony export */ "keys": () => (/* binding */ keys), -/* harmony export */ "makeAutoObservable": () => (/* binding */ makeAutoObservable), -/* harmony export */ "makeObservable": () => (/* binding */ makeObservable), -/* harmony export */ "observable": () => (/* binding */ observable), -/* harmony export */ "observe": () => (/* binding */ observe), -/* harmony export */ "onBecomeObserved": () => (/* binding */ onBecomeObserved), -/* harmony export */ "onBecomeUnobserved": () => (/* binding */ onBecomeUnobserved), -/* harmony export */ "onReactionError": () => (/* binding */ onReactionError), -/* harmony export */ "reaction": () => (/* binding */ reaction), -/* harmony export */ "remove": () => (/* binding */ remove), -/* harmony export */ "runInAction": () => (/* binding */ runInAction), -/* harmony export */ "set": () => (/* binding */ set), -/* harmony export */ "spy": () => (/* binding */ spy), -/* harmony export */ "toJS": () => (/* binding */ toJS), -/* harmony export */ "trace": () => (/* binding */ trace), -/* harmony export */ "transaction": () => (/* binding */ transaction), -/* harmony export */ "untracked": () => (/* binding */ untracked), -/* harmony export */ "values": () => (/* binding */ values), -/* harmony export */ "when": () => (/* binding */ when) -/* harmony export */ }); -var niceErrors = { - 0: "Invalid value for configuration 'enforceActions', expected 'never', 'always' or 'observed'", - 1: function _(prop) { - return "Cannot decorate undefined property: '" + prop.toString() + "'"; - }, - 2: function _(prop) { - return "invalid decorator for '" + prop.toString() + "'"; - }, - 3: function _(prop) { - return "Cannot decorate '" + prop.toString() + "': action can only be used on properties with a function value."; - }, - 4: function _(prop) { - return "Cannot decorate '" + prop.toString() + "': computed can only be used on getter properties."; - }, - 5: "'keys()' can only be used on observable objects, arrays, sets and maps", - 6: "'values()' can only be used on observable objects, arrays, sets and maps", - 7: "'entries()' can only be used on observable objects, arrays and maps", - 8: "'set()' can only be used on observable objects, arrays and maps", - 9: "'remove()' can only be used on observable objects, arrays and maps", - 10: "'has()' can only be used on observable objects, arrays and maps", - 11: "'get()' can only be used on observable objects, arrays and maps", - 12: "Invalid annotation", - 13: "Dynamic observable objects cannot be frozen", - 14: "Intercept handlers should return nothing or a change object", - 15: "Observable arrays cannot be frozen", - 16: "Modification exception: the internal structure of an observable array was changed.", - 17: function _(index, length) { - return "[mobx.array] Index out of bounds, " + index + " is larger than " + length; - }, - 18: "mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js", - 19: function _(other) { - return "Cannot initialize from classes that inherit from Map: " + other.constructor.name; - }, - 20: function _(other) { - return "Cannot initialize map from " + other; - }, - 21: function _(dataStructure) { - return "Cannot convert to map from '" + dataStructure + "'"; - }, - 22: "mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js", - 23: "It is not possible to get index atoms from arrays", - 24: function _(thing) { - return "Cannot obtain administration from " + thing; - }, - 25: function _(property, name) { - return "the entry '" + property + "' does not exist in the observable map '" + name + "'"; - }, - 26: "please specify a property", - 27: function _(property, name) { - return "no observable property '" + property.toString() + "' found on the observable object '" + name + "'"; - }, - 28: function _(thing) { - return "Cannot obtain atom from " + thing; - }, - 29: "Expecting some object", - 30: "invalid action stack. did you forget to finish an action?", - 31: "missing option for computed: get", - 32: function _(name, derivation) { - return "Cycle detected in computation " + name + ": " + derivation; - }, - 33: function _(name) { - return "The setter of computed value '" + name + "' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?"; - }, - 34: function _(name) { - return "[ComputedValue '" + name + "'] It is not possible to assign a new value to a computed value."; - }, - 35: "There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`", - 36: "isolateGlobalState should be called before MobX is running any reactions", - 37: function _(method) { - return "[mobx] `observableArray." + method + "()` mutates the array in-place, which is not allowed inside a derivation. Use `array.slice()." + method + "()` instead"; - } -}; -var errors = false ? 0 : {}; -function die(error) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - - if (false) { var e; } - - throw new Error(typeof error === "number" ? "[MobX] minified error nr: " + error + (args.length ? " " + args.join(",") : "") + ". Find the full error at: https://github.com/mobxjs/mobx/blob/mobx6/src/errors.ts" : "[MobX] " + error); -} - -var mockGlobal = {}; -function getGlobal() { - if (typeof window !== "undefined") { - return window; - } - - if (typeof __webpack_require__.g !== "undefined") { - return __webpack_require__.g; - } - - if (typeof self !== "undefined") { - return self; - } - - return mockGlobal; -} - -var assign = Object.assign; -var getDescriptor = Object.getOwnPropertyDescriptor; -var defineProperty = Object.defineProperty; -var objectPrototype = Object.prototype; -var EMPTY_ARRAY = []; -Object.freeze(EMPTY_ARRAY); -var EMPTY_OBJECT = {}; -Object.freeze(EMPTY_OBJECT); -var hasProxy = typeof Proxy !== "undefined"; -var plainObjectString = /*#__PURE__*/Object.toString(); -function assertProxies() { - if (!hasProxy) { - die( false ? 0 : "Proxy not available"); - } -} -function warnAboutProxyRequirement(msg) { - if (false) {} -} -function getNextId() { - return ++globalState.mobxGuid; -} -/** - * Makes sure that the provided function is invoked at most once. - */ - -function once(func) { - var invoked = false; - return function () { - if (invoked) return; - invoked = true; - return func.apply(this, arguments); - }; -} -var noop = function noop() {}; -function isFunction(fn) { - return typeof fn === "function"; -} -function isStringish(value) { - var t = typeof value; - - switch (t) { - case "string": - case "symbol": - case "number": - return true; - } - - return false; -} -function isObject(value) { - return value !== null && typeof value === "object"; -} -function isPlainObject(value) { - var _proto$constructor; - - if (!isObject(value)) return false; - var proto = Object.getPrototypeOf(value); - if (proto == null) return true; - return ((_proto$constructor = proto.constructor) == null ? void 0 : _proto$constructor.toString()) === plainObjectString; -} // https://stackoverflow.com/a/37865170 - -function isGenerator(obj) { - var constructor = obj == null ? void 0 : obj.constructor; - if (!constructor) return false; - if ("GeneratorFunction" === constructor.name || "GeneratorFunction" === constructor.displayName) return true; - return false; -} -function addHiddenProp(object, propName, value) { - defineProperty(object, propName, { - enumerable: false, - writable: true, - configurable: true, - value: value - }); -} -function addHiddenFinalProp(object, propName, value) { - defineProperty(object, propName, { - enumerable: false, - writable: false, - configurable: true, - value: value - }); -} -function assertPropertyConfigurable(object, prop) { - if (false) { var descriptor; } -} -function createInstanceofPredicate(name, theClass) { - var propName = "isMobX" + name; - theClass.prototype[propName] = true; - return function (x) { - return isObject(x) && x[propName] === true; - }; -} -function isES6Map(thing) { - return thing instanceof Map; -} -function isES6Set(thing) { - return thing instanceof Set; -} -var hasGetOwnPropertySymbols = typeof Object.getOwnPropertySymbols !== "undefined"; -/** - * Returns the following: own keys, prototype keys & own symbol keys, if they are enumerable. - */ - -function getPlainObjectKeys(object) { - var keys = Object.keys(object); // Not supported in IE, so there are not going to be symbol props anyway... - - if (!hasGetOwnPropertySymbols) return keys; - var symbols = Object.getOwnPropertySymbols(object); - if (!symbols.length) return keys; - return [].concat(keys, symbols.filter(function (s) { - return objectPrototype.propertyIsEnumerable.call(object, s); - })); -} // From Immer utils -// Returns all own keys, including non-enumerable and symbolic - -var ownKeys = typeof Reflect !== "undefined" && Reflect.ownKeys ? Reflect.ownKeys : hasGetOwnPropertySymbols ? function (obj) { - return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj)); -} : -/* istanbul ignore next */ -Object.getOwnPropertyNames; -function stringifyKey(key) { - if (typeof key === "string") return key; - if (typeof key === "symbol") return key.toString(); - return new String(key).toString(); -} -function toPrimitive(value) { - return value === null ? null : typeof value === "object" ? "" + value : value; -} -function hasProp(target, prop) { - return objectPrototype.hasOwnProperty.call(target, prop); -} // From Immer utils - -var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors(target) { - // Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274 - var res = {}; // Note: without polyfill for ownKeys, symbols won't be picked up - - ownKeys(target).forEach(function (key) { - res[key] = getDescriptor(target, key); - }); - return res; -}; - -var mobxDecoratorsSymbol = /*#__PURE__*/Symbol("mobx-decorators"); -var mobxAppliedDecoratorsSymbol = /*#__PURE__*/Symbol("mobx-applied-decorators"); -function createDecorator(type) { - return assign(function (target, property) { - if (property === undefined) { - // @decorator(arg) member - createDecoratorAndAnnotation(type, target); - } else { - // @decorator member - storeDecorator(target, property, type); - } - }, { - annotationType_: type - }); -} -function createDecoratorAndAnnotation(type, arg_) { - return assign(function (target, property) { - storeDecorator(target, property, type, arg_); - }, { - annotationType_: type, - arg_: arg_ - }); -} -function storeDecorator(target, property, type, arg_) { - var desc = getDescriptor(target, mobxDecoratorsSymbol); - var map; - - if (desc) { - map = desc.value; - } else { - map = {}; - addHiddenProp(target, mobxDecoratorsSymbol, map); - } - - map[property] = { - annotationType_: type, - arg_: arg_ - }; -} -function applyDecorators(target) { - if (target[mobxAppliedDecoratorsSymbol]) return true; - var current = target; // optimization: this could be cached per prototype! - // (then we can remove the weird short circuiting as well..) - - var annotations = []; - - while (current && current !== objectPrototype) { - var desc = getDescriptor(current, mobxDecoratorsSymbol); - - if (desc) { - if (!annotations.length) { - for (var key in desc.value) { - // second conditions is to recognize actions - if (!hasProp(target, key) && !hasProp(current, key)) { - // not all fields are defined yet, so we are in the makeObservable call of some super class, - // short circuit, here, we will do this again in a later makeObservable call - return true; - } - } - } - - annotations.unshift(desc.value); - } - - current = Object.getPrototypeOf(current); - } - - annotations.forEach(function (a) { - makeObservable(target, a); - }); - addHiddenProp(target, mobxAppliedDecoratorsSymbol, true); - return annotations.length > 0; -} - -var $mobx = /*#__PURE__*/Symbol("mobx administration"); -var Atom = /*#__PURE__*/function () { - // for effective unobserving. BaseAtom has true, for extra optimization, so its onBecomeUnobserved never gets called, because it's not needed - - /** - * Create a new atom. For debugging purposes it is recommended to give it a name. - * The onBecomeObserved and onBecomeUnobserved callbacks can be used for resource management. - */ - function Atom(name_) { - if (name_ === void 0) { - name_ = "Atom@" + getNextId(); - } - - this.name_ = void 0; - this.isPendingUnobservation_ = false; - this.isBeingObserved_ = false; - this.observers_ = new Set(); - this.diffValue_ = 0; - this.lastAccessedBy_ = 0; - this.lowestObserverState_ = IDerivationState_.NOT_TRACKING_; - this.onBOL = void 0; - this.onBUOL = void 0; - this.name_ = name_; - } // onBecomeObservedListeners - - - var _proto = Atom.prototype; - - _proto.onBO = function onBO() { - if (this.onBOL) { - this.onBOL.forEach(function (listener) { - return listener(); - }); - } - }; - - _proto.onBUO = function onBUO() { - if (this.onBUOL) { - this.onBUOL.forEach(function (listener) { - return listener(); - }); - } - } - /** - * Invoke this method to notify mobx that your atom has been used somehow. - * Returns true if there is currently a reactive context. - */ - ; - - _proto.reportObserved = function reportObserved$1() { - return reportObserved(this); - } - /** - * Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate. - */ - ; - - _proto.reportChanged = function reportChanged() { - startBatch(); - propagateChanged(this); - endBatch(); - }; - - _proto.toString = function toString() { - return this.name_; - }; - - return Atom; -}(); -var isAtom = /*#__PURE__*/createInstanceofPredicate("Atom", Atom); -function createAtom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) { - if (onBecomeObservedHandler === void 0) { - onBecomeObservedHandler = noop; - } - - if (onBecomeUnobservedHandler === void 0) { - onBecomeUnobservedHandler = noop; - } - - var atom = new Atom(name); // default `noop` listener will not initialize the hook Set - - if (onBecomeObservedHandler !== noop) { - onBecomeObserved(atom, onBecomeObservedHandler); - } - - if (onBecomeUnobservedHandler !== noop) { - onBecomeUnobserved(atom, onBecomeUnobservedHandler); - } - - return atom; -} - -function identityComparer(a, b) { - return a === b; -} - -function structuralComparer(a, b) { - return deepEqual(a, b); -} - -function shallowComparer(a, b) { - return deepEqual(a, b, 1); -} - -function defaultComparer(a, b) { - return Object.is(a, b); -} - -var comparer = { - identity: identityComparer, - structural: structuralComparer, - "default": defaultComparer, - shallow: shallowComparer -}; - -function deepEnhancer(v, _, name) { - // it is an observable already, done - if (isObservable(v)) return v; // something that can be converted and mutated? - - if (Array.isArray(v)) return observable.array(v, { - name: name - }); - if (isPlainObject(v)) return observable.object(v, undefined, { - name: name - }); - if (isES6Map(v)) return observable.map(v, { - name: name - }); - if (isES6Set(v)) return observable.set(v, { - name: name - }); - return v; -} -function shallowEnhancer(v, _, name) { - if (v === undefined || v === null) return v; - if (isObservableObject(v) || isObservableArray(v) || isObservableMap(v) || isObservableSet(v)) return v; - if (Array.isArray(v)) return observable.array(v, { - name: name, - deep: false - }); - if (isPlainObject(v)) return observable.object(v, undefined, { - name: name, - deep: false - }); - if (isES6Map(v)) return observable.map(v, { - name: name, - deep: false - }); - if (isES6Set(v)) return observable.set(v, { - name: name, - deep: false - }); - if (false) {} -} -function referenceEnhancer(newValue) { - // never turn into an observable - return newValue; -} -function refStructEnhancer(v, oldValue) { - if (false) {} - if (deepEqual(v, oldValue)) return oldValue; - return v; -} - -var _annotationToEnhancer; -var OBSERVABLE = "observable"; -var OBSERVABLE_REF = "observable.ref"; -var OBSERVABLE_SHALLOW = "observable.shallow"; -var OBSERVABLE_STRUCT = "observable.struct"; // Predefined bags of create observable options, to avoid allocating temporarily option objects -// in the majority of cases - -var defaultCreateObservableOptions = { - deep: true, - name: undefined, - defaultDecorator: undefined, - proxy: true -}; -Object.freeze(defaultCreateObservableOptions); -function asCreateObservableOptions(thing) { - return thing || defaultCreateObservableOptions; -} -function getEnhancerFromOption(options) { - return options.deep === true ? deepEnhancer : options.deep === false ? referenceEnhancer : getEnhancerFromAnnotation(options.defaultDecorator); -} -var annotationToEnhancer = (_annotationToEnhancer = {}, _annotationToEnhancer[OBSERVABLE] = deepEnhancer, _annotationToEnhancer[OBSERVABLE_REF] = referenceEnhancer, _annotationToEnhancer[OBSERVABLE_SHALLOW] = shallowEnhancer, _annotationToEnhancer[OBSERVABLE_STRUCT] = refStructEnhancer, _annotationToEnhancer); -function getEnhancerFromAnnotation(annotation) { - var _annotationToEnhancer2; - - return !annotation ? deepEnhancer : (_annotationToEnhancer2 = annotationToEnhancer[annotation.annotationType_]) != null ? _annotationToEnhancer2 : die(12); -} -/** - * Turns an object, array or function into a reactive structure. - * @param v the value which should become observable. - */ - -function createObservable(v, arg2, arg3) { - // @observable someProp; - if (isStringish(arg2)) { - storeDecorator(v, arg2, OBSERVABLE); - return; - } // it is an observable already, done - - - if (isObservable(v)) return v; // something that can be converted and mutated? - - var res = isPlainObject(v) ? observable.object(v, arg2, arg3) : Array.isArray(v) ? observable.array(v, arg2) : isES6Map(v) ? observable.map(v, arg2) : isES6Set(v) ? observable.set(v, arg2) : v; // this value could be converted to a new observable data structure, return it - - if (res !== v) return res; - return observable.box(v); -} - -createObservable.annotationType_ = OBSERVABLE; -var observableFactories = { - box: function box(value, options) { - var o = asCreateObservableOptions(options); - return new ObservableValue(value, getEnhancerFromOption(o), o.name, true, o.equals); - }, - array: function array(initialValues, options) { - var o = asCreateObservableOptions(options); - return (globalState.useProxies === false || o.proxy === false ? createLegacyArray : createObservableArray)(initialValues, getEnhancerFromOption(o), o.name); - }, - map: function map(initialValues, options) { - var o = asCreateObservableOptions(options); - return new ObservableMap(initialValues, getEnhancerFromOption(o), o.name); - }, - set: function set(initialValues, options) { - var o = asCreateObservableOptions(options); - return new ObservableSet(initialValues, getEnhancerFromOption(o), o.name); - }, - object: function object(props, decorators, options) { - var o = asCreateObservableOptions(options); - var base = {}; - asObservableObject(base, options == null ? void 0 : options.name, getEnhancerFromOption(o)); - return extendObservable(globalState.useProxies === false || o.proxy === false ? base : createDynamicObservableObject(base), props, decorators, options); - }, - ref: /*#__PURE__*/createDecorator(OBSERVABLE_REF), - shallow: /*#__PURE__*/createDecorator(OBSERVABLE_SHALLOW), - deep: /*#__PURE__*/createDecorator(OBSERVABLE), - struct: /*#__PURE__*/createDecorator(OBSERVABLE_STRUCT) -}; // eslint-disable-next-line - -var observable = /*#__PURE__*/assign(createObservable, observableFactories); - -var COMPUTED = "computed"; -var COMPUTED_STRUCT = "computed.struct"; -/** - * Decorator for class properties: @computed get value() { return expr; }. - * For legacy purposes also invokable as ES5 observable created: `computed(() => expr)`; - */ - -var computed = function computed(arg1, arg2, arg3) { - if (isStringish(arg2)) { - // @computed - return storeDecorator(arg1, arg2, COMPUTED); - } - - if (isPlainObject(arg1)) { - // @computed({ options }) - return createDecoratorAndAnnotation(COMPUTED, arg1); - } // computed(expr, options?) - - - if (false) {} - - var opts = isPlainObject(arg2) ? arg2 : {}; - opts.get = arg1; - opts.name = opts.name || arg1.name || ""; - /* for generated name */ - - return new ComputedValue(opts); -}; -computed.annotationType_ = COMPUTED; -computed.struct = /*#__PURE__*/assign(function (target, property) { - storeDecorator(target, property, COMPUTED_STRUCT); -}, { - annotationType_: COMPUTED_STRUCT -}); - -var _getDescriptor$config, _getDescriptor; -// mobx versions - -var currentActionId = 0; -var nextActionId = 1; -var isFunctionNameConfigurable = (_getDescriptor$config = (_getDescriptor = /*#__PURE__*/getDescriptor(function () {}, "name")) == null ? void 0 : _getDescriptor.configurable) != null ? _getDescriptor$config : false; // we can safely recycle this object - -var tmpNameDescriptor = { - value: "action", - configurable: true, - writable: false, - enumerable: false -}; -function createAction(actionName, fn, autoAction, ref) { - if (autoAction === void 0) { - autoAction = false; - } - - if (false) {} - - function res() { - return executeAction(actionName, autoAction, fn, ref || this, arguments); - } - - res.isMobxAction = true; - - if (isFunctionNameConfigurable) { - tmpNameDescriptor.value = actionName; - Object.defineProperty(res, "name", tmpNameDescriptor); - } - - return res; -} -function executeAction(actionName, canRunAsDerivation, fn, scope, args) { - var runInfo = _startAction(actionName, canRunAsDerivation, scope, args); - - try { - return fn.apply(scope, args); - } catch (err) { - runInfo.error_ = err; - throw err; - } finally { - _endAction(runInfo); - } -} -function _startAction(actionName, canRunAsDerivation, // true for autoAction -scope, args) { - var notifySpy_ = false && 0; - var startTime_ = 0; - - if (false) { var flattenedArgs; } - - var prevDerivation_ = globalState.trackingDerivation; - var runAsAction = !canRunAsDerivation || !prevDerivation_; - startBatch(); - var prevAllowStateChanges_ = globalState.allowStateChanges; // by default preserve previous allow - - if (runAsAction) { - untrackedStart(); - prevAllowStateChanges_ = allowStateChangesStart(true); - } - - var prevAllowStateReads_ = allowStateReadsStart(true); - var runInfo = { - runAsAction_: runAsAction, - prevDerivation_: prevDerivation_, - prevAllowStateChanges_: prevAllowStateChanges_, - prevAllowStateReads_: prevAllowStateReads_, - notifySpy_: notifySpy_, - startTime_: startTime_, - actionId_: nextActionId++, - parentActionId_: currentActionId - }; - currentActionId = runInfo.actionId_; - return runInfo; -} -function _endAction(runInfo) { - if (currentActionId !== runInfo.actionId_) { - die(30); - } - - currentActionId = runInfo.parentActionId_; - - if (runInfo.error_ !== undefined) { - globalState.suppressReactionErrors = true; - } - - allowStateChangesEnd(runInfo.prevAllowStateChanges_); - allowStateReadsEnd(runInfo.prevAllowStateReads_); - endBatch(); - if (runInfo.runAsAction_) untrackedEnd(runInfo.prevDerivation_); - - if (false) {} - - globalState.suppressReactionErrors = false; -} -function allowStateChanges(allowStateChanges, func) { - var prev = allowStateChangesStart(allowStateChanges); - - try { - return func(); - } finally { - allowStateChangesEnd(prev); - } -} -function allowStateChangesStart(allowStateChanges) { - var prev = globalState.allowStateChanges; - globalState.allowStateChanges = allowStateChanges; - return prev; -} -function allowStateChangesEnd(prev) { - globalState.allowStateChanges = prev; -} - -function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } -} - -function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; -} - -function _extends() { - _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; - }; - - return _extends.apply(this, arguments); -} - -function _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - subClass.__proto__ = superClass; -} - -function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return self; -} - -function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); -} - -function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - - return arr2; -} - -function _createForOfIteratorHelperLoose(o, allowArrayLike) { - var it; - - if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { - if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { - if (it) o = it; - var i = 0; - return function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - it = o[Symbol.iterator](); - return it.next.bind(it); -} - -var _Symbol$toPrimitive; -var CREATE = "create"; -_Symbol$toPrimitive = Symbol.toPrimitive; -var ObservableValue = /*#__PURE__*/function (_Atom) { - _inheritsLoose(ObservableValue, _Atom); - - function ObservableValue(value, enhancer, name_, notifySpy, equals) { - var _this; - - if (name_ === void 0) { - name_ = "ObservableValue@" + getNextId(); - } - - if (notifySpy === void 0) { - notifySpy = true; - } - - if (equals === void 0) { - equals = comparer["default"]; - } - - _this = _Atom.call(this, name_) || this; - _this.enhancer = void 0; - _this.name_ = void 0; - _this.equals = void 0; - _this.hasUnreportedChange_ = false; - _this.interceptors_ = void 0; - _this.changeListeners_ = void 0; - _this.value_ = void 0; - _this.dehancer = void 0; - _this.enhancer = enhancer; - _this.name_ = name_; - _this.equals = equals; - _this.value_ = enhancer(value, undefined, name_); - - if (false) {} - - return _this; - } - - var _proto = ObservableValue.prototype; - - _proto.dehanceValue = function dehanceValue(value) { - if (this.dehancer !== undefined) return this.dehancer(value); - return value; - }; - - _proto.set = function set(newValue) { - var oldValue = this.value_; - newValue = this.prepareNewValue_(newValue); - - if (newValue !== globalState.UNCHANGED) { - var notifySpy = isSpyEnabled(); - - if (false) {} - - this.setNewValue_(newValue); - if (false) {} - } - }; - - _proto.prepareNewValue_ = function prepareNewValue_(newValue) { - checkIfStateModificationsAreAllowed(this); - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - object: this, - type: UPDATE, - newValue: newValue - }); - if (!change) return globalState.UNCHANGED; - newValue = change.newValue; - } // apply modifier - - - newValue = this.enhancer(newValue, this.value_, this.name_); - return this.equals(this.value_, newValue) ? globalState.UNCHANGED : newValue; - }; - - _proto.setNewValue_ = function setNewValue_(newValue) { - var oldValue = this.value_; - this.value_ = newValue; - this.reportChanged(); - - if (hasListeners(this)) { - notifyListeners(this, { - type: UPDATE, - object: this, - newValue: newValue, - oldValue: oldValue - }); - } - }; - - _proto.get = function get() { - this.reportObserved(); - return this.dehanceValue(this.value_); - }; - - _proto.intercept_ = function intercept_(handler) { - return registerInterceptor(this, handler); - }; - - _proto.observe_ = function observe_(listener, fireImmediately) { - if (fireImmediately) listener({ - observableKind: "value", - debugObjectName: this.name_, - object: this, - type: UPDATE, - newValue: this.value_, - oldValue: undefined - }); - return registerListener(this, listener); - }; - - _proto.raw = function raw() { - // used by MST ot get undehanced value - return this.value_; - }; - - _proto.toJSON = function toJSON() { - return this.get(); - }; - - _proto.toString = function toString() { - return this.name_ + "[" + this.value_ + "]"; - }; - - _proto.valueOf = function valueOf() { - return toPrimitive(this.get()); - }; - - _proto[_Symbol$toPrimitive] = function () { - return this.valueOf(); - }; - - return ObservableValue; -}(Atom); -var isObservableValue = /*#__PURE__*/createInstanceofPredicate("ObservableValue", ObservableValue); - -var _Symbol$toPrimitive$1; -/** - * A node in the state dependency root that observes other nodes, and can be observed itself. - * - * ComputedValue will remember the result of the computation for the duration of the batch, or - * while being observed. - * - * During this time it will recompute only when one of its direct dependencies changed, - * but only when it is being accessed with `ComputedValue.get()`. - * - * Implementation description: - * 1. First time it's being accessed it will compute and remember result - * give back remembered result until 2. happens - * 2. First time any deep dependency change, propagate POSSIBLY_STALE to all observers, wait for 3. - * 3. When it's being accessed, recompute if any shallow dependency changed. - * if result changed: propagate STALE to all observers, that were POSSIBLY_STALE from the last step. - * go to step 2. either way - * - * If at any point it's outside batch and it isn't observed: reset everything and go to 1. - */ - -_Symbol$toPrimitive$1 = Symbol.toPrimitive; -var ComputedValue = /*#__PURE__*/function () { - // nodes we are looking at. Our value depends on these nodes - // during tracking it's an array with new observed observers - // to check for cycles - // N.B: unminified as it is used by MST - - /** - * Create a new computed value based on a function expression. - * - * The `name` property is for debug purposes only. - * - * The `equals` property specifies the comparer function to use to determine if a newly produced - * value differs from the previous value. Two comparers are provided in the library; `defaultComparer` - * compares based on identity comparison (===), and `structuralComparer` deeply compares the structure. - * Structural comparison can be convenient if you always produce a new aggregated object and - * don't want to notify observers if it is structurally the same. - * This is useful for working with vectors, mouse coordinates etc. - */ - function ComputedValue(options) { - this.dependenciesState_ = IDerivationState_.NOT_TRACKING_; - this.observing_ = []; - this.newObserving_ = null; - this.isBeingObserved_ = false; - this.isPendingUnobservation_ = false; - this.observers_ = new Set(); - this.diffValue_ = 0; - this.runId_ = 0; - this.lastAccessedBy_ = 0; - this.lowestObserverState_ = IDerivationState_.UP_TO_DATE_; - this.unboundDepsCount_ = 0; - this.mapid_ = "#" + getNextId(); - this.value_ = new CaughtException(null); - this.name_ = void 0; - this.triggeredBy_ = void 0; - this.isComputing_ = false; - this.isRunningSetter_ = false; - this.derivation = void 0; - this.setter_ = void 0; - this.isTracing_ = TraceMode.NONE; - this.scope_ = void 0; - this.equals_ = void 0; - this.requiresReaction_ = void 0; - this.keepAlive_ = void 0; - this.onBOL = void 0; - this.onBUOL = void 0; - if (!options.get) die(31); - this.derivation = options.get; - this.name_ = options.name || "ComputedValue@" + getNextId(); - if (options.set) this.setter_ = createAction(this.name_ + "-setter", options.set); - this.equals_ = options.equals || (options.compareStructural || options.struct ? comparer.structural : comparer["default"]); - this.scope_ = options.context; - this.requiresReaction_ = !!options.requiresReaction; - this.keepAlive_ = !!options.keepAlive; - } - - var _proto = ComputedValue.prototype; - - _proto.onBecomeStale_ = function onBecomeStale_() { - propagateMaybeChanged(this); - }; - - _proto.onBO = function onBO() { - if (this.onBOL) { - this.onBOL.forEach(function (listener) { - return listener(); - }); - } - }; - - _proto.onBUO = function onBUO() { - if (this.onBUOL) { - this.onBUOL.forEach(function (listener) { - return listener(); - }); - } - } - /** - * Returns the current value of this computed value. - * Will evaluate its computation first if needed. - */ - ; - - _proto.get = function get() { - if (this.isComputing_) die(32, this.name_, this.derivation); - - if (globalState.inBatch === 0 && // !globalState.trackingDerivatpion && - this.observers_.size === 0 && !this.keepAlive_) { - if (shouldCompute(this)) { - this.warnAboutUntrackedRead_(); - startBatch(); // See perf test 'computed memoization' - - this.value_ = this.computeValue_(false); - endBatch(); - } - } else { - reportObserved(this); - - if (shouldCompute(this)) { - var prevTrackingContext = globalState.trackingContext; - if (this.keepAlive_ && !prevTrackingContext) globalState.trackingContext = this; - if (this.trackAndCompute()) propagateChangeConfirmed(this); - globalState.trackingContext = prevTrackingContext; - } - } - - var result = this.value_; - if (isCaughtException(result)) throw result.cause; - return result; - }; - - _proto.set = function set(value) { - if (this.setter_) { - if (this.isRunningSetter_) die(33, this.name_); - this.isRunningSetter_ = true; - - try { - this.setter_.call(this.scope_, value); - } finally { - this.isRunningSetter_ = false; - } - } else die(34, this.name_); - }; - - _proto.trackAndCompute = function trackAndCompute() { - // N.B: unminified as it is used by MST - var oldValue = this.value_; - var wasSuspended = - /* see #1208 */ - this.dependenciesState_ === IDerivationState_.NOT_TRACKING_; - var newValue = this.computeValue_(true); - - if (false) {} - - var changed = wasSuspended || isCaughtException(oldValue) || isCaughtException(newValue) || !this.equals_(oldValue, newValue); - - if (changed) { - this.value_ = newValue; - } - - return changed; - }; - - _proto.computeValue_ = function computeValue_(track) { - this.isComputing_ = true; // don't allow state changes during computation - - var prev = allowStateChangesStart(false); - var res; - - if (track) { - res = trackDerivedFunction(this, this.derivation, this.scope_); - } else { - if (globalState.disableErrorBoundaries === true) { - res = this.derivation.call(this.scope_); - } else { - try { - res = this.derivation.call(this.scope_); - } catch (e) { - res = new CaughtException(e); - } - } - } - - allowStateChangesEnd(prev); - this.isComputing_ = false; - return res; - }; - - _proto.suspend_ = function suspend_() { - if (!this.keepAlive_) { - clearObserving(this); - this.value_ = undefined; // don't hold on to computed value! - } - }; - - _proto.observe_ = function observe_(listener, fireImmediately) { - var _this = this; - - var firstTime = true; - var prevValue = undefined; - return autorun(function () { - // TODO: why is this in a different place than the spyReport() function? in all other observables it's called in the same place - var newValue = _this.get(); - - if (!firstTime || fireImmediately) { - var prevU = untrackedStart(); - listener({ - observableKind: "computed", - debugObjectName: _this.name_, - type: UPDATE, - object: _this, - newValue: newValue, - oldValue: prevValue - }); - untrackedEnd(prevU); - } - - firstTime = false; - prevValue = newValue; - }); - }; - - _proto.warnAboutUntrackedRead_ = function warnAboutUntrackedRead_() { - if (true) return; - - if (this.requiresReaction_ === true) { - die("[mobx] Computed value " + this.name_ + " is read outside a reactive context"); - } - - if (this.isTracing_ !== TraceMode.NONE) { - console.log("[mobx.trace] '" + this.name_ + "' is being read outside a reactive context. Doing a full recompute"); - } - - if (globalState.computedRequiresReaction) { - console.warn("[mobx] Computed value " + this.name_ + " is being read outside a reactive context. Doing a full recompute"); - } - }; - - _proto.toString = function toString() { - return this.name_ + "[" + this.derivation.toString() + "]"; - }; - - _proto.valueOf = function valueOf() { - return toPrimitive(this.get()); - }; - - _proto[_Symbol$toPrimitive$1] = function () { - return this.valueOf(); - }; - - return ComputedValue; -}(); -var isComputedValue = /*#__PURE__*/createInstanceofPredicate("ComputedValue", ComputedValue); - -var IDerivationState_; - -(function (IDerivationState_) { - // before being run or (outside batch and not being observed) - // at this point derivation is not holding any data about dependency tree - IDerivationState_[IDerivationState_["NOT_TRACKING_"] = -1] = "NOT_TRACKING_"; // no shallow dependency changed since last computation - // won't recalculate derivation - // this is what makes mobx fast - - IDerivationState_[IDerivationState_["UP_TO_DATE_"] = 0] = "UP_TO_DATE_"; // some deep dependency changed, but don't know if shallow dependency changed - // will require to check first if UP_TO_DATE or POSSIBLY_STALE - // currently only ComputedValue will propagate POSSIBLY_STALE - // - // having this state is second big optimization: - // don't have to recompute on every dependency change, but only when it's needed - - IDerivationState_[IDerivationState_["POSSIBLY_STALE_"] = 1] = "POSSIBLY_STALE_"; // A shallow dependency has changed since last computation and the derivation - // will need to recompute when it's needed next. - - IDerivationState_[IDerivationState_["STALE_"] = 2] = "STALE_"; -})(IDerivationState_ || (IDerivationState_ = {})); - -var TraceMode; - -(function (TraceMode) { - TraceMode[TraceMode["NONE"] = 0] = "NONE"; - TraceMode[TraceMode["LOG"] = 1] = "LOG"; - TraceMode[TraceMode["BREAK"] = 2] = "BREAK"; -})(TraceMode || (TraceMode = {})); - -var CaughtException = function CaughtException(cause) { - this.cause = void 0; - this.cause = cause; // Empty -}; -function isCaughtException(e) { - return e instanceof CaughtException; -} -/** - * Finds out whether any dependency of the derivation has actually changed. - * If dependenciesState is 1 then it will recalculate dependencies, - * if any dependency changed it will propagate it by changing dependenciesState to 2. - * - * By iterating over the dependencies in the same order that they were reported and - * stopping on the first change, all the recalculations are only called for ComputedValues - * that will be tracked by derivation. That is because we assume that if the first x - * dependencies of the derivation doesn't change then the derivation should run the same way - * up until accessing x-th dependency. - */ - -function shouldCompute(derivation) { - switch (derivation.dependenciesState_) { - case IDerivationState_.UP_TO_DATE_: - return false; - - case IDerivationState_.NOT_TRACKING_: - case IDerivationState_.STALE_: - return true; - - case IDerivationState_.POSSIBLY_STALE_: - { - // state propagation can occur outside of action/reactive context #2195 - var prevAllowStateReads = allowStateReadsStart(true); - var prevUntracked = untrackedStart(); // no need for those computeds to be reported, they will be picked up in trackDerivedFunction. - - var obs = derivation.observing_, - l = obs.length; - - for (var i = 0; i < l; i++) { - var obj = obs[i]; - - if (isComputedValue(obj)) { - if (globalState.disableErrorBoundaries) { - obj.get(); - } else { - try { - obj.get(); - } catch (e) { - // we are not interested in the value *or* exception at this moment, but if there is one, notify all - untrackedEnd(prevUntracked); - allowStateReadsEnd(prevAllowStateReads); - return true; - } - } // if ComputedValue `obj` actually changed it will be computed and propagated to its observers. - // and `derivation` is an observer of `obj` - // invariantShouldCompute(derivation) - - - if (derivation.dependenciesState_ === IDerivationState_.STALE_) { - untrackedEnd(prevUntracked); - allowStateReadsEnd(prevAllowStateReads); - return true; - } - } - } - - changeDependenciesStateTo0(derivation); - untrackedEnd(prevUntracked); - allowStateReadsEnd(prevAllowStateReads); - return false; - } - } -} -function isComputingDerivation() { - return globalState.trackingDerivation !== null; // filter out actions inside computations -} -function checkIfStateModificationsAreAllowed(atom) { - if (true) { - return; - } - - var hasObservers = atom.observers_.size > 0; // Should not be possible to change observed state outside strict mode, except during initialization, see #563 - - if (!globalState.allowStateChanges && (hasObservers || globalState.enforceActions === "always")) console.warn("[MobX] " + (globalState.enforceActions ? "Since strict-mode is enabled, changing (observed) observable values without using an action is not allowed. Tried to modify: " : "Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, a computed value or the render function of a React component? You can wrap side effects in 'runInAction' (or decorate functions with 'action') if needed. Tried to modify: ") + atom.name_); -} -function checkIfStateReadsAreAllowed(observable) { - if (false) {} -} -/** - * Executes the provided function `f` and tracks which observables are being accessed. - * The tracking information is stored on the `derivation` object and the derivation is registered - * as observer of any of the accessed observables. - */ - -function trackDerivedFunction(derivation, f, context) { - var prevAllowStateReads = allowStateReadsStart(true); // pre allocate array allocation + room for variation in deps - // array will be trimmed by bindDependencies - - changeDependenciesStateTo0(derivation); - derivation.newObserving_ = new Array(derivation.observing_.length + 100); - derivation.unboundDepsCount_ = 0; - derivation.runId_ = ++globalState.runId; - var prevTracking = globalState.trackingDerivation; - globalState.trackingDerivation = derivation; - globalState.inBatch++; - var result; - - if (globalState.disableErrorBoundaries === true) { - result = f.call(context); - } else { - try { - result = f.call(context); - } catch (e) { - result = new CaughtException(e); - } - } - - globalState.inBatch--; - globalState.trackingDerivation = prevTracking; - bindDependencies(derivation); - warnAboutDerivationWithoutDependencies(derivation); - allowStateReadsEnd(prevAllowStateReads); - return result; -} - -function warnAboutDerivationWithoutDependencies(derivation) { - if (true) return; - if (derivation.observing_.length !== 0) return; - - if (globalState.reactionRequiresObservable || derivation.requiresObservable_) { - console.warn("[mobx] Derivation " + derivation.name_ + " is created/updated without reading any observable value"); - } -} -/** - * diffs newObserving with observing. - * update observing to be newObserving with unique observables - * notify observers that become observed/unobserved - */ - - -function bindDependencies(derivation) { - // invariant(derivation.dependenciesState !== IDerivationState.NOT_TRACKING, "INTERNAL ERROR bindDependencies expects derivation.dependenciesState !== -1"); - var prevObserving = derivation.observing_; - var observing = derivation.observing_ = derivation.newObserving_; - var lowestNewObservingDerivationState = IDerivationState_.UP_TO_DATE_; // Go through all new observables and check diffValue: (this list can contain duplicates): - // 0: first occurrence, change to 1 and keep it - // 1: extra occurrence, drop it - - var i0 = 0, - l = derivation.unboundDepsCount_; - - for (var i = 0; i < l; i++) { - var dep = observing[i]; - - if (dep.diffValue_ === 0) { - dep.diffValue_ = 1; - if (i0 !== i) observing[i0] = dep; - i0++; - } // Upcast is 'safe' here, because if dep is IObservable, `dependenciesState` will be undefined, - // not hitting the condition - - - if (dep.dependenciesState_ > lowestNewObservingDerivationState) { - lowestNewObservingDerivationState = dep.dependenciesState_; - } - } - - observing.length = i0; - derivation.newObserving_ = null; // newObserving shouldn't be needed outside tracking (statement moved down to work around FF bug, see #614) - // Go through all old observables and check diffValue: (it is unique after last bindDependencies) - // 0: it's not in new observables, unobserve it - // 1: it keeps being observed, don't want to notify it. change to 0 - - l = prevObserving.length; - - while (l--) { - var _dep = prevObserving[l]; - - if (_dep.diffValue_ === 0) { - removeObserver(_dep, derivation); - } - - _dep.diffValue_ = 0; - } // Go through all new observables and check diffValue: (now it should be unique) - // 0: it was set to 0 in last loop. don't need to do anything. - // 1: it wasn't observed, let's observe it. set back to 0 - - - while (i0--) { - var _dep2 = observing[i0]; - - if (_dep2.diffValue_ === 1) { - _dep2.diffValue_ = 0; - addObserver(_dep2, derivation); - } - } // Some new observed derivations may become stale during this derivation computation - // so they have had no chance to propagate staleness (#916) - - - if (lowestNewObservingDerivationState !== IDerivationState_.UP_TO_DATE_) { - derivation.dependenciesState_ = lowestNewObservingDerivationState; - derivation.onBecomeStale_(); - } -} - -function clearObserving(derivation) { - // invariant(globalState.inBatch > 0, "INTERNAL ERROR clearObserving should be called only inside batch"); - var obs = derivation.observing_; - derivation.observing_ = []; - var i = obs.length; - - while (i--) { - removeObserver(obs[i], derivation); - } - - derivation.dependenciesState_ = IDerivationState_.NOT_TRACKING_; -} -function untracked(action) { - var prev = untrackedStart(); - - try { - return action(); - } finally { - untrackedEnd(prev); - } -} -function untrackedStart() { - var prev = globalState.trackingDerivation; - globalState.trackingDerivation = null; - return prev; -} -function untrackedEnd(prev) { - globalState.trackingDerivation = prev; -} -function allowStateReadsStart(allowStateReads) { - var prev = globalState.allowStateReads; - globalState.allowStateReads = allowStateReads; - return prev; -} -function allowStateReadsEnd(prev) { - globalState.allowStateReads = prev; -} -/** - * needed to keep `lowestObserverState` correct. when changing from (2 or 1) to 0 - * - */ - -function changeDependenciesStateTo0(derivation) { - if (derivation.dependenciesState_ === IDerivationState_.UP_TO_DATE_) return; - derivation.dependenciesState_ = IDerivationState_.UP_TO_DATE_; - var obs = derivation.observing_; - var i = obs.length; - - while (i--) { - obs[i].lowestObserverState_ = IDerivationState_.UP_TO_DATE_; - } -} - -/** - * These values will persist if global state is reset - */ - -var persistentKeys = ["mobxGuid", "spyListeners", "enforceActions", "computedRequiresReaction", "reactionRequiresObservable", "observableRequiresReaction", "allowStateReads", "disableErrorBoundaries", "runId", "UNCHANGED", "useProxies"]; -var MobXGlobals = function MobXGlobals() { - this.version = 6; - this.UNCHANGED = {}; - this.trackingDerivation = null; - this.trackingContext = null; - this.runId = 0; - this.mobxGuid = 0; - this.inBatch = 0; - this.pendingUnobservations = []; - this.pendingReactions = []; - this.isRunningReactions = false; - this.allowStateChanges = false; - this.allowStateReads = true; - this.enforceActions = true; - this.spyListeners = []; - this.globalReactionErrorHandlers = []; - this.computedRequiresReaction = false; - this.reactionRequiresObservable = false; - this.observableRequiresReaction = false; - this.disableErrorBoundaries = false; - this.suppressReactionErrors = false; - this.useProxies = true; - this.verifyProxies = false; -}; -var canMergeGlobalState = true; -var isolateCalled = false; -var globalState = /*#__PURE__*/function () { - var global = /*#__PURE__*/getGlobal(); - if (global.__mobxInstanceCount > 0 && !global.__mobxGlobals) canMergeGlobalState = false; - if (global.__mobxGlobals && global.__mobxGlobals.version !== new MobXGlobals().version) canMergeGlobalState = false; - - if (!canMergeGlobalState) { - setTimeout(function () { - if (!isolateCalled) { - die(35); - } - }, 1); - return new MobXGlobals(); - } else if (global.__mobxGlobals) { - global.__mobxInstanceCount += 1; - if (!global.__mobxGlobals.UNCHANGED) global.__mobxGlobals.UNCHANGED = {}; // make merge backward compatible - - return global.__mobxGlobals; - } else { - global.__mobxInstanceCount = 1; - return global.__mobxGlobals = /*#__PURE__*/new MobXGlobals(); - } -}(); -function isolateGlobalState() { - if (globalState.pendingReactions.length || globalState.inBatch || globalState.isRunningReactions) die(36); - isolateCalled = true; - - if (canMergeGlobalState) { - var global = getGlobal(); - if (--global.__mobxInstanceCount === 0) global.__mobxGlobals = undefined; - globalState = new MobXGlobals(); - } -} -function getGlobalState() { - return globalState; -} -/** - * For testing purposes only; this will break the internal state of existing observables, - * but can be used to get back at a stable state after throwing errors - */ - -function resetGlobalState() { - var defaultGlobals = new MobXGlobals(); - - for (var key in defaultGlobals) { - if (persistentKeys.indexOf(key) === -1) globalState[key] = defaultGlobals[key]; - } - - globalState.allowStateChanges = !globalState.enforceActions; -} - -function hasObservers(observable) { - return observable.observers_ && observable.observers_.size > 0; -} -function getObservers(observable) { - return observable.observers_; -} // function invariantObservers(observable: IObservable) { -// const list = observable.observers -// const map = observable.observersIndexes -// const l = list.length -// for (let i = 0; i < l; i++) { -// const id = list[i].__mapid -// if (i) { -// invariant(map[id] === i, "INTERNAL ERROR maps derivation.__mapid to index in list") // for performance -// } else { -// invariant(!(id in map), "INTERNAL ERROR observer on index 0 shouldn't be held in map.") // for performance -// } -// } -// invariant( -// list.length === 0 || Object.keys(map).length === list.length - 1, -// "INTERNAL ERROR there is no junk in map" -// ) -// } - -function addObserver(observable, node) { - // invariant(node.dependenciesState !== -1, "INTERNAL ERROR, can add only dependenciesState !== -1"); - // invariant(observable._observers.indexOf(node) === -1, "INTERNAL ERROR add already added node"); - // invariantObservers(observable); - observable.observers_.add(node); - if (observable.lowestObserverState_ > node.dependenciesState_) observable.lowestObserverState_ = node.dependenciesState_; // invariantObservers(observable); - // invariant(observable._observers.indexOf(node) !== -1, "INTERNAL ERROR didn't add node"); -} -function removeObserver(observable, node) { - // invariant(globalState.inBatch > 0, "INTERNAL ERROR, remove should be called only inside batch"); - // invariant(observable._observers.indexOf(node) !== -1, "INTERNAL ERROR remove already removed node"); - // invariantObservers(observable); - observable.observers_["delete"](node); - - if (observable.observers_.size === 0) { - // deleting last observer - queueForUnobservation(observable); - } // invariantObservers(observable); - // invariant(observable._observers.indexOf(node) === -1, "INTERNAL ERROR remove already removed node2"); - -} -function queueForUnobservation(observable) { - if (observable.isPendingUnobservation_ === false) { - // invariant(observable._observers.length === 0, "INTERNAL ERROR, should only queue for unobservation unobserved observables"); - observable.isPendingUnobservation_ = true; - globalState.pendingUnobservations.push(observable); - } -} -/** - * Batch starts a transaction, at least for purposes of memoizing ComputedValues when nothing else does. - * During a batch `onBecomeUnobserved` will be called at most once per observable. - * Avoids unnecessary recalculations. - */ - -function startBatch() { - globalState.inBatch++; -} -function endBatch() { - if (--globalState.inBatch === 0) { - runReactions(); // the batch is actually about to finish, all unobserving should happen here. - - var list = globalState.pendingUnobservations; - - for (var i = 0; i < list.length; i++) { - var observable = list[i]; - observable.isPendingUnobservation_ = false; - - if (observable.observers_.size === 0) { - if (observable.isBeingObserved_) { - // if this observable had reactive observers, trigger the hooks - observable.isBeingObserved_ = false; - observable.onBUO(); - } - - if (observable instanceof ComputedValue) { - // computed values are automatically teared down when the last observer leaves - // this process happens recursively, this computed might be the last observabe of another, etc.. - observable.suspend_(); - } - } - } - - globalState.pendingUnobservations = []; - } -} -function reportObserved(observable) { - checkIfStateReadsAreAllowed(observable); - var derivation = globalState.trackingDerivation; - - if (derivation !== null) { - /** - * Simple optimization, give each derivation run an unique id (runId) - * Check if last time this observable was accessed the same runId is used - * if this is the case, the relation is already known - */ - if (derivation.runId_ !== observable.lastAccessedBy_) { - observable.lastAccessedBy_ = derivation.runId_; // Tried storing newObserving, or observing, or both as Set, but performance didn't come close... - - derivation.newObserving_[derivation.unboundDepsCount_++] = observable; - - if (!observable.isBeingObserved_ && globalState.trackingContext) { - observable.isBeingObserved_ = true; - observable.onBO(); - } - } - - return true; - } else if (observable.observers_.size === 0 && globalState.inBatch > 0) { - queueForUnobservation(observable); - } - - return false; -} // function invariantLOS(observable: IObservable, msg: string) { -// // it's expensive so better not run it in produciton. but temporarily helpful for testing -// const min = getObservers(observable).reduce((a, b) => Math.min(a, b.dependenciesState), 2) -// if (min >= observable.lowestObserverState) return // <- the only assumption about `lowestObserverState` -// throw new Error( -// "lowestObserverState is wrong for " + -// msg + -// " because " + -// min + -// " < " + -// observable.lowestObserverState -// ) -// } - -/** - * NOTE: current propagation mechanism will in case of self reruning autoruns behave unexpectedly - * It will propagate changes to observers from previous run - * It's hard or maybe impossible (with reasonable perf) to get it right with current approach - * Hopefully self reruning autoruns aren't a feature people should depend on - * Also most basic use cases should be ok - */ -// Called by Atom when its value changes - -function propagateChanged(observable) { - // invariantLOS(observable, "changed start"); - if (observable.lowestObserverState_ === IDerivationState_.STALE_) return; - observable.lowestObserverState_ = IDerivationState_.STALE_; // Ideally we use for..of here, but the downcompiled version is really slow... - - observable.observers_.forEach(function (d) { - if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) { - if (false) {} - - d.onBecomeStale_(); - } - - d.dependenciesState_ = IDerivationState_.STALE_; - }); // invariantLOS(observable, "changed end"); -} // Called by ComputedValue when it recalculate and its value changed - -function propagateChangeConfirmed(observable) { - // invariantLOS(observable, "confirmed start"); - if (observable.lowestObserverState_ === IDerivationState_.STALE_) return; - observable.lowestObserverState_ = IDerivationState_.STALE_; - observable.observers_.forEach(function (d) { - if (d.dependenciesState_ === IDerivationState_.POSSIBLY_STALE_) d.dependenciesState_ = IDerivationState_.STALE_;else if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_ // this happens during computing of `d`, just keep lowestObserverState up to date. - ) observable.lowestObserverState_ = IDerivationState_.UP_TO_DATE_; - }); // invariantLOS(observable, "confirmed end"); -} // Used by computed when its dependency changed, but we don't wan't to immediately recompute. - -function propagateMaybeChanged(observable) { - // invariantLOS(observable, "maybe start"); - if (observable.lowestObserverState_ !== IDerivationState_.UP_TO_DATE_) return; - observable.lowestObserverState_ = IDerivationState_.POSSIBLY_STALE_; - observable.observers_.forEach(function (d) { - if (d.dependenciesState_ === IDerivationState_.UP_TO_DATE_) { - d.dependenciesState_ = IDerivationState_.POSSIBLY_STALE_; - - if (false) {} - - d.onBecomeStale_(); - } - }); // invariantLOS(observable, "maybe end"); -} - -function logTraceInfo(derivation, observable) { - console.log("[mobx.trace] '" + derivation.name_ + "' is invalidated due to a change in: '" + observable.name_ + "'"); - - if (derivation.isTracing_ === TraceMode.BREAK) { - var lines = []; - printDepTree(getDependencyTree(derivation), lines, 1); // prettier-ignore - - new Function("debugger;\n/*\nTracing '" + derivation.name_ + "'\n\nYou are entering this break point because derivation '" + derivation.name_ + "' is being traced and '" + observable.name_ + "' is now forcing it to update.\nJust follow the stacktrace you should now see in the devtools to see precisely what piece of your code is causing this update\nThe stackframe you are looking for is at least ~6-8 stack-frames up.\n\n" + (derivation instanceof ComputedValue ? derivation.derivation.toString().replace(/[*]\//g, "/") : "") + "\n\nThe dependencies for this derivation are:\n\n" + lines.join("\n") + "\n*/\n ")(); - } -} - -function printDepTree(tree, lines, depth) { - if (lines.length >= 1000) { - lines.push("(and many more)"); - return; - } - - lines.push("" + new Array(depth).join("\t") + tree.name); // MWE: not the fastest, but the easiest way :) - - if (tree.dependencies) tree.dependencies.forEach(function (child) { - return printDepTree(child, lines, depth + 1); - }); -} - -var Reaction = /*#__PURE__*/function () { - // nodes we are looking at. Our value depends on these nodes - function Reaction(name_, onInvalidate_, errorHandler_, requiresObservable_) { - if (name_ === void 0) { - name_ = "Reaction@" + getNextId(); - } - - if (requiresObservable_ === void 0) { - requiresObservable_ = false; - } - - this.name_ = void 0; - this.onInvalidate_ = void 0; - this.errorHandler_ = void 0; - this.requiresObservable_ = void 0; - this.observing_ = []; - this.newObserving_ = []; - this.dependenciesState_ = IDerivationState_.NOT_TRACKING_; - this.diffValue_ = 0; - this.runId_ = 0; - this.unboundDepsCount_ = 0; - this.mapid_ = "#" + getNextId(); - this.isDisposed_ = false; - this.isScheduled_ = false; - this.isTrackPending_ = false; - this.isRunning_ = false; - this.isTracing_ = TraceMode.NONE; - this.name_ = name_; - this.onInvalidate_ = onInvalidate_; - this.errorHandler_ = errorHandler_; - this.requiresObservable_ = requiresObservable_; - } - - var _proto = Reaction.prototype; - - _proto.onBecomeStale_ = function onBecomeStale_() { - this.schedule_(); - }; - - _proto.schedule_ = function schedule_() { - if (!this.isScheduled_) { - this.isScheduled_ = true; - globalState.pendingReactions.push(this); - runReactions(); - } - }; - - _proto.isScheduled = function isScheduled() { - return this.isScheduled_; - } - /** - * internal, use schedule() if you intend to kick off a reaction - */ - ; - - _proto.runReaction_ = function runReaction_() { - if (!this.isDisposed_) { - startBatch(); - this.isScheduled_ = false; - - if (shouldCompute(this)) { - this.isTrackPending_ = true; - - try { - this.onInvalidate_(); - - if (false) {} - } catch (e) { - this.reportExceptionInDerivation_(e); - } - } - - endBatch(); - } - }; - - _proto.track = function track(fn) { - if (this.isDisposed_) { - return; // console.warn("Reaction already disposed") // Note: Not a warning / error in mobx 4 either - } - - startBatch(); - var notify = isSpyEnabled(); - var startTime; - - if (false) {} - - this.isRunning_ = true; - var prevReaction = globalState.trackingContext; // reactions could create reactions... - - globalState.trackingContext = this; - var result = trackDerivedFunction(this, fn, undefined); - globalState.trackingContext = prevReaction; - this.isRunning_ = false; - this.isTrackPending_ = false; - - if (this.isDisposed_) { - // disposed during last run. Clean up everything that was bound after the dispose call. - clearObserving(this); - } - - if (isCaughtException(result)) this.reportExceptionInDerivation_(result.cause); - - if (false) {} - - endBatch(); - }; - - _proto.reportExceptionInDerivation_ = function reportExceptionInDerivation_(error) { - var _this = this; - - if (this.errorHandler_) { - this.errorHandler_(error, this); - return; - } - - if (globalState.disableErrorBoundaries) throw error; - var message = false ? 0 : "[mobx] uncaught error in '" + this + "'"; - - if (!globalState.suppressReactionErrors) { - console.error(message, error); - /** If debugging brought you here, please, read the above message :-). Tnx! */ - } else if (false) {} // prettier-ignore - - - if (false) {} - - globalState.globalReactionErrorHandlers.forEach(function (f) { - return f(error, _this); - }); - }; - - _proto.dispose = function dispose() { - if (!this.isDisposed_) { - this.isDisposed_ = true; - - if (!this.isRunning_) { - // if disposed while running, clean up later. Maybe not optimal, but rare case - startBatch(); - clearObserving(this); - endBatch(); - } - } - }; - - _proto.getDisposer_ = function getDisposer_() { - var r = this.dispose.bind(this); - r[$mobx] = this; - return r; - }; - - _proto.toString = function toString() { - return "Reaction[" + this.name_ + "]"; - }; - - _proto.trace = function trace$1(enterBreakPoint) { - if (enterBreakPoint === void 0) { - enterBreakPoint = false; - } - - trace(this, enterBreakPoint); - }; - - return Reaction; -}(); -function onReactionError(handler) { - globalState.globalReactionErrorHandlers.push(handler); - return function () { - var idx = globalState.globalReactionErrorHandlers.indexOf(handler); - if (idx >= 0) globalState.globalReactionErrorHandlers.splice(idx, 1); - }; -} -/** - * Magic number alert! - * Defines within how many times a reaction is allowed to re-trigger itself - * until it is assumed that this is gonna be a never ending loop... - */ - -var MAX_REACTION_ITERATIONS = 100; - -var reactionScheduler = function reactionScheduler(f) { - return f(); -}; - -function runReactions() { - // Trampolining, if runReactions are already running, new reactions will be picked up - if (globalState.inBatch > 0 || globalState.isRunningReactions) return; - reactionScheduler(runReactionsHelper); -} - -function runReactionsHelper() { - globalState.isRunningReactions = true; - var allReactions = globalState.pendingReactions; - var iterations = 0; // While running reactions, new reactions might be triggered. - // Hence we work with two variables and check whether - // we converge to no remaining reactions after a while. - - while (allReactions.length > 0) { - if (++iterations === MAX_REACTION_ITERATIONS) { - console.error( false ? 0 : "[mobx] cycle in reaction: " + allReactions[0]); - allReactions.splice(0); // clear reactions - } - - var remainingReactions = allReactions.splice(0); - - for (var i = 0, l = remainingReactions.length; i < l; i++) { - remainingReactions[i].runReaction_(); - } - } - - globalState.isRunningReactions = false; -} - -var isReaction = /*#__PURE__*/createInstanceofPredicate("Reaction", Reaction); -function setReactionScheduler(fn) { - var baseScheduler = reactionScheduler; - - reactionScheduler = function reactionScheduler(f) { - return fn(function () { - return baseScheduler(f); - }); - }; -} - -function isSpyEnabled() { - return false && 0; -} -function spyReport(event) { - if (true) return; // dead code elimination can do the rest - - if (!globalState.spyListeners.length) return; - var listeners = globalState.spyListeners; - - for (var i = 0, l = listeners.length; i < l; i++) { - listeners[i](event); - } -} -function spyReportStart(event) { - if (true) return; - - var change = _extends({}, event, { - spyReportStart: true - }); - - spyReport(change); -} -var END_EVENT = { - type: "report-end", - spyReportEnd: true -}; -function spyReportEnd(change) { - if (true) return; - if (change) spyReport(_extends({}, change, { - type: "report-end", - spyReportEnd: true - }));else spyReport(END_EVENT); -} -function spy(listener) { - if (true) { - console.warn("[mobx.spy] Is a no-op in production builds"); - return function () {}; - } else {} -} - -var ACTION = "action"; -var ACTION_BOUND = "action.bound"; -var AUTOACTION = "autoAction"; -var AUTOACTION_BOUND = "autoAction.bound"; -var ACTION_UNNAMED = ""; - -function createActionFactory(autoAction, annotation) { - var res = function action(arg1, arg2) { - // action(fn() {}) - if (isFunction(arg1)) return createAction(arg1.name || ACTION_UNNAMED, arg1, autoAction); // action("name", fn() {}) - - if (isFunction(arg2)) return createAction(arg1, arg2, autoAction); // @action - - if (isStringish(arg2)) { - return storeDecorator(arg1, arg2, annotation); - } // Annation: action("name") & @action("name") - - - if (isStringish(arg1)) { - return createDecoratorAndAnnotation(annotation, arg1); - } - - if (false) {} - }; - - res.annotationType_ = annotation; - return res; -} - -var action = /*#__PURE__*/createActionFactory(false, ACTION); -var autoAction = /*#__PURE__*/createActionFactory(true, AUTOACTION); -action.bound = /*#__PURE__*/createDecorator(ACTION_BOUND); -autoAction.bound = /*#__PURE__*/createDecorator(AUTOACTION_BOUND); -function runInAction(fn) { - return executeAction(fn.name || ACTION_UNNAMED, false, fn, this, undefined); -} -function isAction(thing) { - return isFunction(thing) && thing.isMobxAction === true; -} - -/** - * Creates a named reactive view and keeps it alive, so that the view is always - * updated if one of the dependencies changes, even when the view is not further used by something else. - * @param view The reactive view - * @returns disposer function, which can be used to stop the view from being updated in the future. - */ - -function autorun(view, opts) { - if (opts === void 0) { - opts = EMPTY_OBJECT; - } - - if (false) {} - - var name = opts && opts.name || view.name || "Autorun@" + getNextId(); - var runSync = !opts.scheduler && !opts.delay; - var reaction; - - if (runSync) { - // normal autorun - reaction = new Reaction(name, function () { - this.track(reactionRunner); - }, opts.onError, opts.requiresObservable); - } else { - var scheduler = createSchedulerFromOptions(opts); // debounced autorun - - var isScheduled = false; - reaction = new Reaction(name, function () { - if (!isScheduled) { - isScheduled = true; - scheduler(function () { - isScheduled = false; - if (!reaction.isDisposed_) reaction.track(reactionRunner); - }); - } - }, opts.onError, opts.requiresObservable); - } - - function reactionRunner() { - view(reaction); - } - - reaction.schedule_(); - return reaction.getDisposer_(); -} - -var run = function run(f) { - return f(); -}; - -function createSchedulerFromOptions(opts) { - return opts.scheduler ? opts.scheduler : opts.delay ? function (f) { - return setTimeout(f, opts.delay); - } : run; -} - -function reaction(expression, effect, opts) { - if (opts === void 0) { - opts = EMPTY_OBJECT; - } - - if (false) {} - - var name = opts.name || "Reaction@" + getNextId(); - var effectAction = action(name, opts.onError ? wrapErrorHandler(opts.onError, effect) : effect); - var runSync = !opts.scheduler && !opts.delay; - var scheduler = createSchedulerFromOptions(opts); - var firstTime = true; - var isScheduled = false; - var value; - var oldValue = undefined; // only an issue with fireImmediately - - var equals = opts.compareStructural ? comparer.structural : opts.equals || comparer["default"]; - var r = new Reaction(name, function () { - if (firstTime || runSync) { - reactionRunner(); - } else if (!isScheduled) { - isScheduled = true; - scheduler(reactionRunner); - } - }, opts.onError, opts.requiresObservable); - - function reactionRunner() { - isScheduled = false; - if (r.isDisposed_) return; - var changed = false; - r.track(function () { - var nextValue = allowStateChanges(false, function () { - return expression(r); - }); - changed = firstTime || !equals(value, nextValue); - oldValue = value; - value = nextValue; - }); - if (firstTime && opts.fireImmediately) effectAction(value, oldValue, r);else if (!firstTime && changed) effectAction(value, oldValue, r); - firstTime = false; - } - - r.schedule_(); - return r.getDisposer_(); -} - -function wrapErrorHandler(errorHandler, baseFn) { - return function () { - try { - return baseFn.apply(this, arguments); - } catch (e) { - errorHandler.call(this, e); - } - }; -} - -var ON_BECOME_OBSERVED = "onBO"; -var ON_BECOME_UNOBSERVED = "onBUO"; -function onBecomeObserved(thing, arg2, arg3) { - return interceptHook(ON_BECOME_OBSERVED, thing, arg2, arg3); -} -function onBecomeUnobserved(thing, arg2, arg3) { - return interceptHook(ON_BECOME_UNOBSERVED, thing, arg2, arg3); -} - -function interceptHook(hook, thing, arg2, arg3) { - var atom = typeof arg3 === "function" ? getAtom(thing, arg2) : getAtom(thing); - var cb = isFunction(arg3) ? arg3 : arg2; - var listenersKey = hook + "L"; - - if (atom[listenersKey]) { - atom[listenersKey].add(cb); - } else { - atom[listenersKey] = new Set([cb]); - } - - return function () { - var hookListeners = atom[listenersKey]; - - if (hookListeners) { - hookListeners["delete"](cb); - - if (hookListeners.size === 0) { - delete atom[listenersKey]; - } - } - }; -} - -var NEVER = "never"; -var ALWAYS = "always"; -var OBSERVED = "observed"; // const IF_AVAILABLE = "ifavailable" - -function configure(options) { - if (options.isolateGlobalState === true) { - isolateGlobalState(); - } - - var useProxies = options.useProxies, - enforceActions = options.enforceActions; - - if (useProxies !== undefined) { - globalState.useProxies = useProxies === ALWAYS ? true : useProxies === NEVER ? false : typeof Proxy !== "undefined"; - } - - if (useProxies === "ifavailable") globalState.verifyProxies = true; - - if (enforceActions !== undefined) { - var ea = enforceActions === ALWAYS ? ALWAYS : enforceActions === OBSERVED; - globalState.enforceActions = ea; - globalState.allowStateChanges = ea === true || ea === ALWAYS ? false : true; - } - ["computedRequiresReaction", "reactionRequiresObservable", "observableRequiresReaction", "disableErrorBoundaries"].forEach(function (key) { - if (key in options) globalState[key] = !!options[key]; - }); - globalState.allowStateReads = !globalState.observableRequiresReaction; - - if (false) {} - - if (options.reactionScheduler) { - setReactionScheduler(options.reactionScheduler); - } -} - -function extendObservable(target, properties, annotations, options) { - if (false) {} - - var o = asCreateObservableOptions(options); - var adm = asObservableObject(target, o.name, getEnhancerFromOption(o)); - startBatch(); - - try { - var descs = getOwnPropertyDescriptors(properties); - getPlainObjectKeys(descs).forEach(function (key) { - makeProperty(adm, target, key, descs[key], !annotations ? true : key in annotations ? annotations[key] : true, true, !!(options == null ? void 0 : options.autoBind)); - }); - } finally { - endBatch(); - } - - return target; -} - -function getDependencyTree(thing, property) { - return nodeToDependencyTree(getAtom(thing, property)); -} - -function nodeToDependencyTree(node) { - var result = { - name: node.name_ - }; - if (node.observing_ && node.observing_.length > 0) result.dependencies = unique(node.observing_).map(nodeToDependencyTree); - return result; -} - -function getObserverTree(thing, property) { - return nodeToObserverTree(getAtom(thing, property)); -} - -function nodeToObserverTree(node) { - var result = { - name: node.name_ - }; - if (hasObservers(node)) result.observers = Array.from(getObservers(node)).map(nodeToObserverTree); - return result; -} - -function unique(list) { - return Array.from(new Set(list)); -} - -var FLOW = "flow"; -var generatorId = 0; -function FlowCancellationError() { - this.message = "FLOW_CANCELLED"; -} -FlowCancellationError.prototype = /*#__PURE__*/Object.create(Error.prototype); -function isFlowCancellationError(error) { - return error instanceof FlowCancellationError; -} -var flow = /*#__PURE__*/Object.assign(function flow(arg1, arg2) { - // @flow - if (isStringish(arg2)) { - return storeDecorator(arg1, arg2, "flow"); - } // flow(fn) - - - if (false) {} - var generator = arg1; - var name = generator.name || ""; // Implementation based on https://github.com/tj/co/blob/master/index.js - - var res = function res() { - var ctx = this; - var args = arguments; - var runId = ++generatorId; - var gen = action(name + " - runid: " + runId + " - init", generator).apply(ctx, args); - var rejector; - var pendingPromise = undefined; - var promise = new Promise(function (resolve, reject) { - var stepId = 0; - rejector = reject; - - function onFulfilled(res) { - pendingPromise = undefined; - var ret; - - try { - ret = action(name + " - runid: " + runId + " - yield " + stepId++, gen.next).call(gen, res); - } catch (e) { - return reject(e); - } - - next(ret); - } - - function onRejected(err) { - pendingPromise = undefined; - var ret; - - try { - ret = action(name + " - runid: " + runId + " - yield " + stepId++, gen["throw"]).call(gen, err); - } catch (e) { - return reject(e); - } - - next(ret); - } - - function next(ret) { - if (isFunction(ret == null ? void 0 : ret.then)) { - // an async iterator - ret.then(next, reject); - return; - } - - if (ret.done) return resolve(ret.value); - pendingPromise = Promise.resolve(ret.value); - return pendingPromise.then(onFulfilled, onRejected); - } - - onFulfilled(undefined); // kick off the process - }); - promise.cancel = action(name + " - runid: " + runId + " - cancel", function () { - try { - if (pendingPromise) cancelPromise(pendingPromise); // Finally block can return (or yield) stuff.. - - var _res = gen["return"](undefined); // eat anything that promise would do, it's cancelled! - - - var yieldedPromise = Promise.resolve(_res.value); - yieldedPromise.then(noop, noop); - cancelPromise(yieldedPromise); // maybe it can be cancelled :) - // reject our original promise - - rejector(new FlowCancellationError()); - } catch (e) { - rejector(e); // there could be a throwing finally block - } - }); - return promise; - }; - - res.isMobXFlow = true; - return res; -}, { - annotationType_: "flow" -}); - -function cancelPromise(promise) { - if (isFunction(promise.cancel)) promise.cancel(); -} - -function flowResult(result) { - return result; // just tricking TypeScript :) -} -function isFlow(fn) { - return (fn == null ? void 0 : fn.isMobXFlow) === true; -} - -function interceptReads(thing, propOrHandler, handler) { - var target; - - if (isObservableMap(thing) || isObservableArray(thing) || isObservableValue(thing)) { - target = getAdministration(thing); - } else if (isObservableObject(thing)) { - if (false) {} - target = getAdministration(thing, propOrHandler); - } else if (false) {} - - if (false) {} - target.dehancer = typeof propOrHandler === "function" ? propOrHandler : handler; - return function () { - target.dehancer = undefined; - }; -} - -function intercept(thing, propOrHandler, handler) { - if (isFunction(handler)) return interceptProperty(thing, propOrHandler, handler);else return interceptInterceptable(thing, propOrHandler); -} - -function interceptInterceptable(thing, handler) { - return getAdministration(thing).intercept_(handler); -} - -function interceptProperty(thing, property, handler) { - return getAdministration(thing, property).intercept_(handler); -} - -function _isComputed(value, property) { - if (property !== undefined) { - if (isObservableObject(value) === false) return false; - if (!value[$mobx].values_.has(property)) return false; - var atom = getAtom(value, property); - return isComputedValue(atom); - } - - return isComputedValue(value); -} -function isComputed(value) { - if (false) {} - return _isComputed(value); -} -function isComputedProp(value, propName) { - if (false) {} - return _isComputed(value, propName); -} - -function _isObservable(value, property) { - if (!value) return false; - - if (property !== undefined) { - if (false) {} - - if (isObservableObject(value)) { - return value[$mobx].values_.has(property); - } - - return false; - } // For first check, see #701 - - - return isObservableObject(value) || !!value[$mobx] || isAtom(value) || isReaction(value) || isComputedValue(value); -} - -function isObservable(value) { - if (false) {} - return _isObservable(value); -} -function isObservableProp(value, propName) { - if (false) {} - return _isObservable(value, propName); -} - -function keys(obj) { - if (isObservableObject(obj)) { - return obj[$mobx].getKeys_(); - } - - if (isObservableMap(obj) || isObservableSet(obj)) { - return Array.from(obj.keys()); - } - - if (isObservableArray(obj)) { - return obj.map(function (_, index) { - return index; - }); - } - - die(5); -} -function values(obj) { - if (isObservableObject(obj)) { - return keys(obj).map(function (key) { - return obj[key]; - }); - } - - if (isObservableMap(obj)) { - return keys(obj).map(function (key) { - return obj.get(key); - }); - } - - if (isObservableSet(obj)) { - return Array.from(obj.values()); - } - - if (isObservableArray(obj)) { - return obj.slice(); - } - - die(6); -} -function entries(obj) { - if (isObservableObject(obj)) { - return keys(obj).map(function (key) { - return [key, obj[key]]; - }); - } - - if (isObservableMap(obj)) { - return keys(obj).map(function (key) { - return [key, obj.get(key)]; - }); - } - - if (isObservableSet(obj)) { - return Array.from(obj.entries()); - } - - if (isObservableArray(obj)) { - return obj.map(function (key, index) { - return [index, key]; - }); - } - - die(7); -} -function set(obj, key, value) { - if (arguments.length === 2 && !isObservableSet(obj)) { - startBatch(); - var _values = key; - - try { - for (var _key in _values) { - set(obj, _key, _values[_key]); - } - } finally { - endBatch(); - } - - return; - } - - if (isObservableObject(obj)) { - var adm = obj[$mobx]; - var existingObservable = adm.values_.get(key); - - if (existingObservable) { - adm.write_(key, value); - } else { - adm.addObservableProp_(key, value, adm.defaultEnhancer_); - } - } else if (isObservableMap(obj)) { - obj.set(key, value); - } else if (isObservableSet(obj)) { - obj.add(key); - } else if (isObservableArray(obj)) { - if (typeof key !== "number") key = parseInt(key, 10); - if (key < 0) die("Invalid index: '" + key + "'"); - startBatch(); - if (key >= obj.length) obj.length = key + 1; - obj[key] = value; - endBatch(); - } else die(8); -} -function remove(obj, key) { - if (isObservableObject(obj)) { - obj[$mobx].remove_(key); - } else if (isObservableMap(obj)) { - obj["delete"](key); - } else if (isObservableSet(obj)) { - obj["delete"](key); - } else if (isObservableArray(obj)) { - if (typeof key !== "number") key = parseInt(key, 10); - obj.splice(key, 1); - } else { - die(9); - } -} -function has(obj, key) { - if (isObservableObject(obj)) { - // return keys(obj).indexOf(key) >= 0 - return getAdministration(obj).has_(key); - } else if (isObservableMap(obj)) { - return obj.has(key); - } else if (isObservableSet(obj)) { - return obj.has(key); - } else if (isObservableArray(obj)) { - return key >= 0 && key < obj.length; - } - - die(10); -} -function get(obj, key) { - if (!has(obj, key)) return undefined; - - if (isObservableObject(obj)) { - return obj[key]; - } else if (isObservableMap(obj)) { - return obj.get(key); - } else if (isObservableArray(obj)) { - return obj[key]; - } - - die(11); -} - -function observe(thing, propOrCb, cbOrFire, fireImmediately) { - if (isFunction(cbOrFire)) return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately);else return observeObservable(thing, propOrCb, cbOrFire); -} - -function observeObservable(thing, listener, fireImmediately) { - return getAdministration(thing).observe_(listener, fireImmediately); -} - -function observeObservableProperty(thing, property, listener, fireImmediately) { - return getAdministration(thing, property).observe_(listener, fireImmediately); -} - -function cache(map, key, value) { - map.set(key, value); - return value; -} - -function toJSHelper(source, __alreadySeen) { - if (source == null || typeof source !== "object" || source instanceof Date || !isObservable(source)) return source; - if (isObservableValue(source)) return toJSHelper(source.get(), __alreadySeen); - - if (__alreadySeen.has(source)) { - return __alreadySeen.get(source); - } - - if (isObservableArray(source)) { - var res = cache(__alreadySeen, source, new Array(source.length)); - source.forEach(function (value, idx) { - res[idx] = toJSHelper(value, __alreadySeen); - }); - return res; - } - - if (isObservableSet(source)) { - var _res = cache(__alreadySeen, source, new Set()); - - source.forEach(function (value) { - _res.add(toJSHelper(value, __alreadySeen)); - }); - return _res; - } - - if (isObservableMap(source)) { - var _res2 = cache(__alreadySeen, source, new Map()); - - source.forEach(function (value, key) { - _res2.set(key, toJSHelper(value, __alreadySeen)); - }); - return _res2; - } else { - // must be observable object - keys(source); // make sure keys are observed - - var _res3 = cache(__alreadySeen, source, {}); - - getPlainObjectKeys(source).forEach(function (key) { - _res3[key] = toJSHelper(source[key], __alreadySeen); - }); - return _res3; - } -} -/** - * Basically, a deep clone, so that no reactive property will exist anymore. - */ - - -function toJS(source, options) { - if (false) {} - return toJSHelper(source, new Map()); -} - -function trace() { - if (true) die("trace() is not available in production builds"); - var enterBreakPoint = false; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - if (typeof args[args.length - 1] === "boolean") enterBreakPoint = args.pop(); - var derivation = getAtomFromArgs(args); - - if (!derivation) { - return die("'trace(break?)' can only be used inside a tracked computed value or a Reaction. Consider passing in the computed value or reaction explicitly"); - } - - if (derivation.isTracing_ === TraceMode.NONE) { - console.log("[mobx.trace] '" + derivation.name_ + "' tracing enabled"); - } - - derivation.isTracing_ = enterBreakPoint ? TraceMode.BREAK : TraceMode.LOG; -} - -function getAtomFromArgs(args) { - switch (args.length) { - case 0: - return globalState.trackingDerivation; - - case 1: - return getAtom(args[0]); - - case 2: - return getAtom(args[0], args[1]); - } -} - -/** - * During a transaction no views are updated until the end of the transaction. - * The transaction will be run synchronously nonetheless. - * - * @param action a function that updates some reactive state - * @returns any value that was returned by the 'action' parameter. - */ - -function transaction(action, thisArg) { - if (thisArg === void 0) { - thisArg = undefined; - } - - startBatch(); - - try { - return action.apply(thisArg); - } finally { - endBatch(); - } -} - -function when(predicate, arg1, arg2) { - if (arguments.length === 1 || arg1 && typeof arg1 === "object") return whenPromise(predicate, arg1); - return _when(predicate, arg1, arg2 || {}); -} - -function _when(predicate, effect, opts) { - var timeoutHandle; - - if (typeof opts.timeout === "number") { - timeoutHandle = setTimeout(function () { - if (!disposer[$mobx].isDisposed_) { - disposer(); - var error = new Error("WHEN_TIMEOUT"); - if (opts.onError) opts.onError(error);else throw error; - } - }, opts.timeout); - } - - opts.name = opts.name || "When@" + getNextId(); - var effectAction = createAction(opts.name + "-effect", effect); // eslint-disable-next-line - - var disposer = autorun(function (r) { - // predicate should not change state - var cond = allowStateChanges(false, predicate); - - if (cond) { - r.dispose(); - if (timeoutHandle) clearTimeout(timeoutHandle); - effectAction(); - } - }, opts); - return disposer; -} - -function whenPromise(predicate, opts) { - if (false) {} - var cancel; - var res = new Promise(function (resolve, reject) { - var disposer = _when(predicate, resolve, _extends({}, opts, { - onError: reject - })); - - cancel = function cancel() { - disposer(); - reject("WHEN_CANCELLED"); - }; - }); - res.cancel = cancel; - return res; -} - -function getAdm(target) { - return target[$mobx]; -} // Optimization: we don't need the intermediate objects and could have a completely custom administration for DynamicObjects, -// and skip either the internal values map, or the base object with its property descriptors! - - -var objectProxyTraps = { - has: function has(target, name) { - if (name === $mobx || name === "constructor") return true; - if (false) {} - var adm = getAdm(target); // MWE: should `in` operator be reactive? If not, below code path will be faster / more memory efficient - // check performance stats! - // if (adm.values.get(name as string)) return true - - if (isStringish(name)) return adm.has_(name); - return name in target; - }, - get: function get(target, name) { - if (name === $mobx || name === "constructor") return target[name]; - var adm = getAdm(target); - var observable = adm.values_.get(name); - - if (observable instanceof Atom) { - var result = observable.get(); - - if (result === undefined) { - // This fixes #1796, because deleting a prop that has an - // undefined value won't retrigger a observer (no visible effect), - // the autorun wouldn't subscribe to future key changes (see also next comment) - adm.has_(name); - } - - return result; - } // make sure we start listening to future keys - // note that we only do this here for optimization - - - if (isStringish(name)) adm.has_(name); - return target[name]; - }, - set: function set$1(target, name, value) { - if (!isStringish(name)) return false; - - if (false) {} - - set(target, name, value); - - return true; - }, - deleteProperty: function deleteProperty(target, name) { - if (false) {} - if (!isStringish(name)) return false; - var adm = getAdm(target); - adm.remove_(name); - return true; - }, - ownKeys: function ownKeys(target) { - if (false) {} - var adm = getAdm(target); - adm.keysAtom_.reportObserved(); - return Reflect.ownKeys(target); - }, - preventExtensions: function preventExtensions(target) { - die(13); - } -}; -function createDynamicObservableObject(base) { - assertProxies(); - var proxy = new Proxy(base, objectProxyTraps); - base[$mobx].proxy_ = proxy; - return proxy; -} - -function hasInterceptors(interceptable) { - return interceptable.interceptors_ !== undefined && interceptable.interceptors_.length > 0; -} -function registerInterceptor(interceptable, handler) { - var interceptors = interceptable.interceptors_ || (interceptable.interceptors_ = []); - interceptors.push(handler); - return once(function () { - var idx = interceptors.indexOf(handler); - if (idx !== -1) interceptors.splice(idx, 1); - }); -} -function interceptChange(interceptable, change) { - var prevU = untrackedStart(); - - try { - // Interceptor can modify the array, copy it to avoid concurrent modification, see #1950 - var interceptors = [].concat(interceptable.interceptors_ || []); - - for (var i = 0, l = interceptors.length; i < l; i++) { - change = interceptors[i](change); - if (change && !change.type) die(14); - if (!change) break; - } - - return change; - } finally { - untrackedEnd(prevU); - } -} - -function hasListeners(listenable) { - return listenable.changeListeners_ !== undefined && listenable.changeListeners_.length > 0; -} -function registerListener(listenable, handler) { - var listeners = listenable.changeListeners_ || (listenable.changeListeners_ = []); - listeners.push(handler); - return once(function () { - var idx = listeners.indexOf(handler); - if (idx !== -1) listeners.splice(idx, 1); - }); -} -function notifyListeners(listenable, change) { - var prevU = untrackedStart(); - var listeners = listenable.changeListeners_; - if (!listeners) return; - listeners = listeners.slice(); - - for (var i = 0, l = listeners.length; i < l; i++) { - listeners[i](change); - } - - untrackedEnd(prevU); -} - -var CACHED_ANNOTATIONS = /*#__PURE__*/Symbol("mobx-cached-annotations"); - -function makeAction(target, key, name, fn, asAutoAction) { - addHiddenProp(target, key, asAutoAction ? autoAction(name || key, fn) : action(name || key, fn)); -} - -function getInferredAnnotation(desc, defaultAnnotation, autoBind) { - if (desc.get) return computed; - if (desc.set) return false; // ignore pure setters - // if already wrapped in action, don't do that another time, but assume it is already set up properly - - if (isFunction(desc.value)) return isGenerator(desc.value) ? flow : isAction(desc.value) ? false : autoBind ? autoAction.bound : autoAction; // if (!desc.configurable || !desc.writable) return false - - return defaultAnnotation != null ? defaultAnnotation : observable.deep; -} - -function getDescriptorInChain(target, prop) { - var current = target; - - while (current && current !== objectPrototype) { - // Optimization: cache meta data, especially for members from prototypes? - var desc = getDescriptor(current, prop); - - if (desc) { - return [desc, current]; - } - - current = Object.getPrototypeOf(current); - } - - die(1, prop); -} - -function makeProperty(adm, owner, key, descriptor, annotation, forceCopy, // extend observable will copy even unannotated properties -autoBind) { - var _annotation$annotatio; - - var target = adm.target_; - var defaultAnnotation = observable; // ideally grap this from adm's defaultEnahncer instead! - - var originAnnotation = annotation; - - if (annotation === true) { - annotation = getInferredAnnotation(descriptor, defaultAnnotation, autoBind); - } - - if (annotation === false) { - if (forceCopy) { - defineProperty(target, key, descriptor); - } - - return; - } - - if (!annotation || annotation === true || !annotation.annotationType_) { - return die(2, key); - } - - var type = annotation.annotationType_; - - switch (type) { - case AUTOACTION: - case ACTION: - { - var fn = descriptor.value; - if (!isFunction(fn)) die(3, key); - - if (owner !== target && !forceCopy) { - if (!isAction(owner[key])) makeAction(owner, key, annotation.arg_, fn, type === AUTOACTION); - } else { - makeAction(target, key, annotation.arg_, fn, type === AUTOACTION); - } - - break; - } - - case AUTOACTION_BOUND: - case ACTION_BOUND: - { - var _fn = descriptor.value; - if (!isFunction(_fn)) die(3, key); - makeAction(target, key, annotation.arg_, _fn.bind(adm.proxy_ || target), type === AUTOACTION_BOUND); - break; - } - - case FLOW: - { - if (owner !== target && !forceCopy) { - if (!isFlow(owner[key])) addHiddenProp(owner, key, flow(descriptor.value)); - } else { - addHiddenProp(target, key, flow(descriptor.value)); - } - - break; - } - - case COMPUTED: - case COMPUTED_STRUCT: - { - if (!descriptor.get) die(4, key); - adm.addComputedProp_(target, key, _extends({ - get: descriptor.get, - set: descriptor.set, - compareStructural: annotation.annotationType_ === COMPUTED_STRUCT - }, annotation.arg_)); - break; - } - - case OBSERVABLE: - case OBSERVABLE_REF: - case OBSERVABLE_SHALLOW: - case OBSERVABLE_STRUCT: - { - if (false) {} - if (false) {} // if the originAnnotation was true, preferred the adm's default enhancer over the inferred one - - var enhancer = originAnnotation === true ? adm.defaultEnhancer_ : getEnhancerFromAnnotation(annotation); - adm.addObservableProp_(key, descriptor.value, enhancer); - break; - } - - default: - if (false) {} - } -} -function makeObservable(target, annotations, options) { - var autoBind = !!(options == null ? void 0 : options.autoBind); - var adm = asObservableObject(target, options == null ? void 0 : options.name, getEnhancerFromAnnotation(options == null ? void 0 : options.defaultDecorator)); - startBatch(); - - try { - if (!annotations) { - var didDecorate = applyDecorators(target); - if (false) {} - return target; - } - - var make = function make(key) { - var annotation = annotations[key]; - - var _getDescriptorInChain = getDescriptorInChain(target, key), - desc = _getDescriptorInChain[0], - owner = _getDescriptorInChain[1]; - - makeProperty(adm, owner, key, desc, annotation, false, autoBind); - }; - - ownKeys(annotations).forEach(make); - } finally { - endBatch(); - } - - return target; -} -function makeAutoObservable(target, overrides, options) { - var proto = Object.getPrototypeOf(target); - var isPlain = proto == null || proto === objectPrototype; - - if (false) {} - - var annotations; - - if (!isPlain && hasProp(proto, CACHED_ANNOTATIONS)) { - // shortcut, reuse inferred annotations for this type from the previous time - annotations = proto[CACHED_ANNOTATIONS]; - } else { - annotations = _extends({}, overrides); - extractAnnotationsFromObject(target, annotations, options); - - if (!isPlain) { - extractAnnotationsFromProto(proto, annotations, options); - addHiddenProp(proto, CACHED_ANNOTATIONS, annotations); - } - } - - makeObservable(target, annotations, options); - return target; -} - -function extractAnnotationsFromObject(target, collector, options) { - var _options$defaultDecor; - - var autoBind = !!(options == null ? void 0 : options.autoBind); - var defaultAnnotation = (options == null ? void 0 : options.deep) === undefined ? (_options$defaultDecor = options == null ? void 0 : options.defaultDecorator) != null ? _options$defaultDecor : observable.deep : (options == null ? void 0 : options.deep) ? observable.deep : observable.ref; - Object.entries(getOwnPropertyDescriptors(target)).forEach(function (_ref) { - var key = _ref[0], - descriptor = _ref[1]; - if (key in collector || key === "constructor") return; - collector[key] = getInferredAnnotation(descriptor, defaultAnnotation, autoBind); - }); -} - -function extractAnnotationsFromProto(proto, collector, options) { - Object.entries(getOwnPropertyDescriptors(proto)).forEach(function (_ref2) { - var key = _ref2[0], - prop = _ref2[1]; - if (key in collector || key === "constructor") return; - - if (prop.get) { - collector[key] = computed; - } else if (isFunction(prop.value)) { - collector[key] = isGenerator(prop.value) ? flow : (options == null ? void 0 : options.autoBind) ? autoAction.bound : autoAction; - } - }); -} - -var SPLICE = "splice"; -var UPDATE = "update"; -var MAX_SPLICE_SIZE = 10000; // See e.g. https://github.com/mobxjs/mobx/issues/859 - -var arrayTraps = { - get: function get(target, name) { - var adm = target[$mobx]; - if (name === $mobx) return adm; - if (name === "length") return adm.getArrayLength_(); - - if (typeof name === "string" && !isNaN(name)) { - return adm.get_(parseInt(name)); - } - - if (hasProp(arrayExtensions, name)) { - return arrayExtensions[name]; - } - - return target[name]; - }, - set: function set(target, name, value) { - var adm = target[$mobx]; - - if (name === "length") { - adm.setArrayLength_(value); - } - - if (typeof name === "symbol" || isNaN(name)) { - target[name] = value; - } else { - // numeric string - adm.set_(parseInt(name), value); - } - - return true; - }, - preventExtensions: function preventExtensions() { - die(15); - } -}; -var ObservableArrayAdministration = /*#__PURE__*/function () { - // this is the prop that gets proxied, so can't replace it! - function ObservableArrayAdministration(name, enhancer, owned_, legacyMode_) { - this.owned_ = void 0; - this.legacyMode_ = void 0; - this.atom_ = void 0; - this.values_ = []; - this.interceptors_ = void 0; - this.changeListeners_ = void 0; - this.enhancer_ = void 0; - this.dehancer = void 0; - this.proxy_ = void 0; - this.lastKnownLength_ = 0; - this.owned_ = owned_; - this.legacyMode_ = legacyMode_; - this.atom_ = new Atom(name || "ObservableArray@" + getNextId()); - - this.enhancer_ = function (newV, oldV) { - return enhancer(newV, oldV, name + "[..]"); - }; - } - - var _proto = ObservableArrayAdministration.prototype; - - _proto.dehanceValue_ = function dehanceValue_(value) { - if (this.dehancer !== undefined) return this.dehancer(value); - return value; - }; - - _proto.dehanceValues_ = function dehanceValues_(values) { - if (this.dehancer !== undefined && values.length > 0) return values.map(this.dehancer); - return values; - }; - - _proto.intercept_ = function intercept_(handler) { - return registerInterceptor(this, handler); - }; - - _proto.observe_ = function observe_(listener, fireImmediately) { - if (fireImmediately === void 0) { - fireImmediately = false; - } - - if (fireImmediately) { - listener({ - observableKind: "array", - object: this.proxy_, - debugObjectName: this.atom_.name_, - type: "splice", - index: 0, - added: this.values_.slice(), - addedCount: this.values_.length, - removed: [], - removedCount: 0 - }); - } - - return registerListener(this, listener); - }; - - _proto.getArrayLength_ = function getArrayLength_() { - this.atom_.reportObserved(); - return this.values_.length; - }; - - _proto.setArrayLength_ = function setArrayLength_(newLength) { - if (typeof newLength !== "number" || newLength < 0) die("Out of range: " + newLength); - var currentLength = this.values_.length; - if (newLength === currentLength) return;else if (newLength > currentLength) { - var newItems = new Array(newLength - currentLength); - - for (var i = 0; i < newLength - currentLength; i++) { - newItems[i] = undefined; - } // No Array.fill everywhere... - - - this.spliceWithArray_(currentLength, 0, newItems); - } else this.spliceWithArray_(newLength, currentLength - newLength); - }; - - _proto.updateArrayLength_ = function updateArrayLength_(oldLength, delta) { - if (oldLength !== this.lastKnownLength_) die(16); - this.lastKnownLength_ += delta; - if (this.legacyMode_ && delta > 0) reserveArrayBuffer(oldLength + delta + 1); - }; - - _proto.spliceWithArray_ = function spliceWithArray_(index, deleteCount, newItems) { - var _this = this; - - checkIfStateModificationsAreAllowed(this.atom_); - var length = this.values_.length; - if (index === undefined) index = 0;else if (index > length) index = length;else if (index < 0) index = Math.max(0, length + index); - if (arguments.length === 1) deleteCount = length - index;else if (deleteCount === undefined || deleteCount === null) deleteCount = 0;else deleteCount = Math.max(0, Math.min(deleteCount, length - index)); - if (newItems === undefined) newItems = EMPTY_ARRAY; - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - object: this.proxy_, - type: SPLICE, - index: index, - removedCount: deleteCount, - added: newItems - }); - if (!change) return EMPTY_ARRAY; - deleteCount = change.removedCount; - newItems = change.added; - } - - newItems = newItems.length === 0 ? newItems : newItems.map(function (v) { - return _this.enhancer_(v, undefined); - }); - - if (this.legacyMode_ || "production" !== "production") { - var lengthDelta = newItems.length - deleteCount; - this.updateArrayLength_(length, lengthDelta); // checks if internal array wasn't modified - } - - var res = this.spliceItemsIntoValues_(index, deleteCount, newItems); - if (deleteCount !== 0 || newItems.length !== 0) this.notifyArraySplice_(index, newItems, res); - return this.dehanceValues_(res); - }; - - _proto.spliceItemsIntoValues_ = function spliceItemsIntoValues_(index, deleteCount, newItems) { - if (newItems.length < MAX_SPLICE_SIZE) { - var _this$values_; - - return (_this$values_ = this.values_).splice.apply(_this$values_, [index, deleteCount].concat(newItems)); - } else { - var res = this.values_.slice(index, index + deleteCount); - var oldItems = this.values_.slice(index + deleteCount); - this.values_.length = index + newItems.length - deleteCount; - - for (var i = 0; i < newItems.length; i++) { - this.values_[index + i] = newItems[i]; - } - - for (var _i = 0; _i < oldItems.length; _i++) { - this.values_[index + newItems.length + _i] = oldItems[_i]; - } - - return res; - } - }; - - _proto.notifyArrayChildUpdate_ = function notifyArrayChildUpdate_(index, newValue, oldValue) { - var notifySpy = !this.owned_ && isSpyEnabled(); - var notify = hasListeners(this); - var change = notify || notifySpy ? { - observableKind: "array", - object: this.proxy_, - type: UPDATE, - debugObjectName: this.atom_.name_, - index: index, - newValue: newValue, - oldValue: oldValue - } : null; // The reason why this is on right hand side here (and not above), is this way the uglifier will drop it, but it won't - // cause any runtime overhead in development mode without NODE_ENV set, unless spying is enabled - - if (false) {} - this.atom_.reportChanged(); - if (notify) notifyListeners(this, change); - if (false) {} - }; - - _proto.notifyArraySplice_ = function notifyArraySplice_(index, added, removed) { - var notifySpy = !this.owned_ && isSpyEnabled(); - var notify = hasListeners(this); - var change = notify || notifySpy ? { - observableKind: "array", - object: this.proxy_, - debugObjectName: this.atom_.name_, - type: SPLICE, - index: index, - removed: removed, - added: added, - removedCount: removed.length, - addedCount: added.length - } : null; - if (false) {} - this.atom_.reportChanged(); // conform: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/observe - - if (notify) notifyListeners(this, change); - if (false) {} - }; - - _proto.get_ = function get_(index) { - if (index < this.values_.length) { - this.atom_.reportObserved(); - return this.dehanceValue_(this.values_[index]); - } - - console.warn( false ? 0 : "[mobx.array] Attempt to read an array index (" + index + ") that is out of bounds (" + this.values_.length + "). Please check length first. Out of bound indices will not be tracked by MobX"); - }; - - _proto.set_ = function set_(index, newValue) { - var values = this.values_; - - if (index < values.length) { - // update at index in range - checkIfStateModificationsAreAllowed(this.atom_); - var oldValue = values[index]; - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: UPDATE, - object: this.proxy_, - index: index, - newValue: newValue - }); - if (!change) return; - newValue = change.newValue; - } - - newValue = this.enhancer_(newValue, oldValue); - var changed = newValue !== oldValue; - - if (changed) { - values[index] = newValue; - this.notifyArrayChildUpdate_(index, newValue, oldValue); - } - } else if (index === values.length) { - // add a new item - this.spliceWithArray_(index, 0, [newValue]); - } else { - // out of bounds - die(17, index, values.length); - } - }; - - return ObservableArrayAdministration; -}(); -function createObservableArray(initialValues, enhancer, name, owned) { - if (name === void 0) { - name = "ObservableArray@" + getNextId(); - } - - if (owned === void 0) { - owned = false; - } - - assertProxies(); - var adm = new ObservableArrayAdministration(name, enhancer, owned, false); - addHiddenFinalProp(adm.values_, $mobx, adm); - var proxy = new Proxy(adm.values_, arrayTraps); - adm.proxy_ = proxy; - - if (initialValues && initialValues.length) { - var prev = allowStateChangesStart(true); - adm.spliceWithArray_(0, 0, initialValues); - allowStateChangesEnd(prev); - } - - return proxy; -} // eslint-disable-next-line - -var arrayExtensions = { - clear: function clear() { - return this.splice(0); - }, - replace: function replace(newItems) { - var adm = this[$mobx]; - return adm.spliceWithArray_(0, adm.values_.length, newItems); - }, - // Used by JSON.stringify - toJSON: function toJSON() { - return this.slice(); - }, - - /* - * functions that do alter the internal structure of the array, (based on lib.es6.d.ts) - * since these functions alter the inner structure of the array, the have side effects. - * Because the have side effects, they should not be used in computed function, - * and for that reason the do not call dependencyState.notifyObserved - */ - splice: function splice(index, deleteCount) { - for (var _len = arguments.length, newItems = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { - newItems[_key - 2] = arguments[_key]; - } - - var adm = this[$mobx]; - - switch (arguments.length) { - case 0: - return []; - - case 1: - return adm.spliceWithArray_(index); - - case 2: - return adm.spliceWithArray_(index, deleteCount); - } - - return adm.spliceWithArray_(index, deleteCount, newItems); - }, - spliceWithArray: function spliceWithArray(index, deleteCount, newItems) { - return this[$mobx].spliceWithArray_(index, deleteCount, newItems); - }, - push: function push() { - var adm = this[$mobx]; - - for (var _len2 = arguments.length, items = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - items[_key2] = arguments[_key2]; - } - - adm.spliceWithArray_(adm.values_.length, 0, items); - return adm.values_.length; - }, - pop: function pop() { - return this.splice(Math.max(this[$mobx].values_.length - 1, 0), 1)[0]; - }, - shift: function shift() { - return this.splice(0, 1)[0]; - }, - unshift: function unshift() { - var adm = this[$mobx]; - - for (var _len3 = arguments.length, items = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - items[_key3] = arguments[_key3]; - } - - adm.spliceWithArray_(0, 0, items); - return adm.values_.length; - }, - reverse: function reverse() { - // reverse by default mutates in place before returning the result - // which makes it both a 'derivation' and a 'mutation'. - if (globalState.trackingDerivation) { - die(37, "reverse"); - } - - this.replace(this.slice().reverse()); - return this; - }, - sort: function sort() { - // sort by default mutates in place before returning the result - // which goes against all good practices. Let's not change the array in place! - if (globalState.trackingDerivation) { - die(37, "sort"); - } - - var copy = this.slice(); - copy.sort.apply(copy, arguments); - this.replace(copy); - return this; - }, - remove: function remove(value) { - var adm = this[$mobx]; - var idx = adm.dehanceValues_(adm.values_).indexOf(value); - - if (idx > -1) { - this.splice(idx, 1); - return true; - } - - return false; - } -}; -/** - * Wrap function from prototype - * Without this, everything works as well, but this works - * faster as everything works on unproxied values - */ - -addArrayExtension("concat", simpleFunc); -addArrayExtension("flat", simpleFunc); -addArrayExtension("includes", simpleFunc); -addArrayExtension("indexOf", simpleFunc); -addArrayExtension("join", simpleFunc); -addArrayExtension("lastIndexOf", simpleFunc); -addArrayExtension("slice", simpleFunc); -addArrayExtension("toString", simpleFunc); -addArrayExtension("toLocaleString", simpleFunc); // map - -addArrayExtension("every", mapLikeFunc); -addArrayExtension("filter", mapLikeFunc); -addArrayExtension("find", mapLikeFunc); -addArrayExtension("findIndex", mapLikeFunc); -addArrayExtension("flatMap", mapLikeFunc); -addArrayExtension("forEach", mapLikeFunc); -addArrayExtension("map", mapLikeFunc); -addArrayExtension("some", mapLikeFunc); // reduce - -addArrayExtension("reduce", reduceLikeFunc); -addArrayExtension("reduceRight", reduceLikeFunc); - -function addArrayExtension(funcName, funcFactory) { - if (typeof Array.prototype[funcName] === "function") { - arrayExtensions[funcName] = funcFactory(funcName); - } -} // Report and delegate to dehanced array - - -function simpleFunc(funcName) { - return function () { - var adm = this[$mobx]; - adm.atom_.reportObserved(); - var dehancedValues = adm.dehanceValues_(adm.values_); - return dehancedValues[funcName].apply(dehancedValues, arguments); - }; -} // Make sure callbacks recieve correct array arg #2326 - - -function mapLikeFunc(funcName) { - return function (callback, thisArg) { - var _this2 = this; - - var adm = this[$mobx]; - adm.atom_.reportObserved(); - var dehancedValues = adm.dehanceValues_(adm.values_); - return dehancedValues[funcName](function (element, index) { - return callback.call(thisArg, element, index, _this2); - }); - }; -} // Make sure callbacks recieve correct array arg #2326 - - -function reduceLikeFunc(funcName) { - return function () { - var _this3 = this; - - var adm = this[$mobx]; - adm.atom_.reportObserved(); - var dehancedValues = adm.dehanceValues_(adm.values_); // #2432 - reduce behavior depends on arguments.length - - var callback = arguments[0]; - - arguments[0] = function (accumulator, currentValue, index) { - return callback(accumulator, currentValue, index, _this3); - }; - - return dehancedValues[funcName].apply(dehancedValues, arguments); - }; -} - -var isObservableArrayAdministration = /*#__PURE__*/createInstanceofPredicate("ObservableArrayAdministration", ObservableArrayAdministration); -function isObservableArray(thing) { - return isObject(thing) && isObservableArrayAdministration(thing[$mobx]); -} - -var _Symbol$iterator, _Symbol$toStringTag; -var ObservableMapMarker = {}; -var ADD = "add"; -var DELETE = "delete"; // just extend Map? See also https://gist.github.com/nestharus/13b4d74f2ef4a2f4357dbd3fc23c1e54 -// But: https://github.com/mobxjs/mobx/issues/1556 - -_Symbol$iterator = Symbol.iterator; -_Symbol$toStringTag = Symbol.toStringTag; -var ObservableMap = /*#__PURE__*/function () { - // hasMap, not hashMap >-). - function ObservableMap(initialData, enhancer_, name_) { - if (enhancer_ === void 0) { - enhancer_ = deepEnhancer; - } - - if (name_ === void 0) { - name_ = "ObservableMap@" + getNextId(); - } - - this.enhancer_ = void 0; - this.name_ = void 0; - this[$mobx] = ObservableMapMarker; - this.data_ = void 0; - this.hasMap_ = void 0; - this.keysAtom_ = void 0; - this.interceptors_ = void 0; - this.changeListeners_ = void 0; - this.dehancer = void 0; - this.enhancer_ = enhancer_; - this.name_ = name_; - - if (!isFunction(Map)) { - die(18); - } - - this.keysAtom_ = createAtom(this.name_ + ".keys()"); - this.data_ = new Map(); - this.hasMap_ = new Map(); - this.merge(initialData); - } - - var _proto = ObservableMap.prototype; - - _proto.has_ = function has_(key) { - return this.data_.has(key); - }; - - _proto.has = function has(key) { - var _this = this; - - if (!globalState.trackingDerivation) return this.has_(key); - var entry = this.hasMap_.get(key); - - if (!entry) { - var newEntry = entry = new ObservableValue(this.has_(key), referenceEnhancer, this.name_ + "." + stringifyKey(key) + "?", false); - this.hasMap_.set(key, newEntry); - onBecomeUnobserved(newEntry, function () { - return _this.hasMap_["delete"](key); - }); - } - - return entry.get(); - }; - - _proto.set = function set(key, value) { - var hasKey = this.has_(key); - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: hasKey ? UPDATE : ADD, - object: this, - newValue: value, - name: key - }); - if (!change) return this; - value = change.newValue; - } - - if (hasKey) { - this.updateValue_(key, value); - } else { - this.addValue_(key, value); - } - - return this; - }; - - _proto["delete"] = function _delete(key) { - var _this2 = this; - - checkIfStateModificationsAreAllowed(this.keysAtom_); - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: DELETE, - object: this, - name: key - }); - if (!change) return false; - } - - if (this.has_(key)) { - var notifySpy = isSpyEnabled(); - var notify = hasListeners(this); - - var _change = notify || notifySpy ? { - observableKind: "map", - debugObjectName: this.name_, - type: DELETE, - object: this, - oldValue: this.data_.get(key).value_, - name: key - } : null; - - if (false) {} - transaction(function () { - _this2.keysAtom_.reportChanged(); - - _this2.updateHasMapEntry_(key, false); - - var observable = _this2.data_.get(key); - - observable.setNewValue_(undefined); - - _this2.data_["delete"](key); - }); - if (notify) notifyListeners(this, _change); - if (false) {} - return true; - } - - return false; - }; - - _proto.updateHasMapEntry_ = function updateHasMapEntry_(key, value) { - var entry = this.hasMap_.get(key); - - if (entry) { - entry.setNewValue_(value); - } - }; - - _proto.updateValue_ = function updateValue_(key, newValue) { - var observable = this.data_.get(key); - newValue = observable.prepareNewValue_(newValue); - - if (newValue !== globalState.UNCHANGED) { - var notifySpy = isSpyEnabled(); - var notify = hasListeners(this); - var change = notify || notifySpy ? { - observableKind: "map", - debugObjectName: this.name_, - type: UPDATE, - object: this, - oldValue: observable.value_, - name: key, - newValue: newValue - } : null; - if (false) {} - observable.setNewValue_(newValue); - if (notify) notifyListeners(this, change); - if (false) {} - } - }; - - _proto.addValue_ = function addValue_(key, newValue) { - var _this3 = this; - - checkIfStateModificationsAreAllowed(this.keysAtom_); - transaction(function () { - var observable = new ObservableValue(newValue, _this3.enhancer_, _this3.name_ + "." + stringifyKey(key), false); - - _this3.data_.set(key, observable); - - newValue = observable.value_; // value might have been changed - - _this3.updateHasMapEntry_(key, true); - - _this3.keysAtom_.reportChanged(); - }); - var notifySpy = isSpyEnabled(); - var notify = hasListeners(this); - var change = notify || notifySpy ? { - observableKind: "map", - debugObjectName: this.name_, - type: ADD, - object: this, - name: key, - newValue: newValue - } : null; - if (false) {} - if (notify) notifyListeners(this, change); - if (false) {} - }; - - _proto.get = function get(key) { - if (this.has(key)) return this.dehanceValue_(this.data_.get(key).get()); - return this.dehanceValue_(undefined); - }; - - _proto.dehanceValue_ = function dehanceValue_(value) { - if (this.dehancer !== undefined) { - return this.dehancer(value); - } - - return value; - }; - - _proto.keys = function keys() { - this.keysAtom_.reportObserved(); - return this.data_.keys(); - }; - - _proto.values = function values() { - var self = this; - var keys = this.keys(); - return makeIterable({ - next: function next() { - var _keys$next = keys.next(), - done = _keys$next.done, - value = _keys$next.value; - - return { - done: done, - value: done ? undefined : self.get(value) - }; - } - }); - }; - - _proto.entries = function entries() { - var self = this; - var keys = this.keys(); - return makeIterable({ - next: function next() { - var _keys$next2 = keys.next(), - done = _keys$next2.done, - value = _keys$next2.value; - - return { - done: done, - value: done ? undefined : [value, self.get(value)] - }; - } - }); - }; - - _proto[_Symbol$iterator] = function () { - return this.entries(); - }; - - _proto.forEach = function forEach(callback, thisArg) { - for (var _iterator = _createForOfIteratorHelperLoose(this), _step; !(_step = _iterator()).done;) { - var _step$value = _step.value, - key = _step$value[0], - value = _step$value[1]; - callback.call(thisArg, value, key, this); - } - } - /** Merge another object into this object, returns this. */ - ; - - _proto.merge = function merge(other) { - var _this4 = this; - - if (isObservableMap(other)) { - other = new Map(other); - } - - transaction(function () { - if (isPlainObject(other)) getPlainObjectKeys(other).forEach(function (key) { - return _this4.set(key, other[key]); - });else if (Array.isArray(other)) other.forEach(function (_ref) { - var key = _ref[0], - value = _ref[1]; - return _this4.set(key, value); - });else if (isES6Map(other)) { - if (other.constructor !== Map) die(19, other); - other.forEach(function (value, key) { - return _this4.set(key, value); - }); - } else if (other !== null && other !== undefined) die(20, other); - }); - return this; - }; - - _proto.clear = function clear() { - var _this5 = this; - - transaction(function () { - untracked(function () { - for (var _iterator2 = _createForOfIteratorHelperLoose(_this5.keys()), _step2; !(_step2 = _iterator2()).done;) { - var key = _step2.value; - - _this5["delete"](key); - } - }); - }); - }; - - _proto.replace = function replace(values) { - var _this6 = this; - - // Implementation requirements: - // - respect ordering of replacement map - // - allow interceptors to run and potentially prevent individual operations - // - don't recreate observables that already exist in original map (so we don't destroy existing subscriptions) - // - don't _keysAtom.reportChanged if the keys of resulting map are indentical (order matters!) - // - note that result map may differ from replacement map due to the interceptors - transaction(function () { - // Convert to map so we can do quick key lookups - var replacementMap = convertToMap(values); - var orderedData = new Map(); // Used for optimization - - var keysReportChangedCalled = false; // Delete keys that don't exist in replacement map - // if the key deletion is prevented by interceptor - // add entry at the beginning of the result map - - for (var _iterator3 = _createForOfIteratorHelperLoose(_this6.data_.keys()), _step3; !(_step3 = _iterator3()).done;) { - var key = _step3.value; - - // Concurrently iterating/deleting keys - // iterator should handle this correctly - if (!replacementMap.has(key)) { - var deleted = _this6["delete"](key); // Was the key removed? - - - if (deleted) { - // _keysAtom.reportChanged() was already called - keysReportChangedCalled = true; - } else { - // Delete prevented by interceptor - var value = _this6.data_.get(key); - - orderedData.set(key, value); - } - } - } // Merge entries - - - for (var _iterator4 = _createForOfIteratorHelperLoose(replacementMap.entries()), _step4; !(_step4 = _iterator4()).done;) { - var _step4$value = _step4.value, - _key = _step4$value[0], - _value = _step4$value[1]; - - // We will want to know whether a new key is added - var keyExisted = _this6.data_.has(_key); // Add or update value - - - _this6.set(_key, _value); // The addition could have been prevent by interceptor - - - if (_this6.data_.has(_key)) { - // The update could have been prevented by interceptor - // and also we want to preserve existing values - // so use value from _data map (instead of replacement map) - var _value2 = _this6.data_.get(_key); - - orderedData.set(_key, _value2); // Was a new key added? - - if (!keyExisted) { - // _keysAtom.reportChanged() was already called - keysReportChangedCalled = true; - } - } - } // Check for possible key order change - - - if (!keysReportChangedCalled) { - if (_this6.data_.size !== orderedData.size) { - // If size differs, keys are definitely modified - _this6.keysAtom_.reportChanged(); - } else { - var iter1 = _this6.data_.keys(); - - var iter2 = orderedData.keys(); - var next1 = iter1.next(); - var next2 = iter2.next(); - - while (!next1.done) { - if (next1.value !== next2.value) { - _this6.keysAtom_.reportChanged(); - - break; - } - - next1 = iter1.next(); - next2 = iter2.next(); - } - } - } // Use correctly ordered map - - - _this6.data_ = orderedData; - }); - return this; - }; - - _proto.toString = function toString() { - return "[object ObservableMap]"; - }; - - _proto.toJSON = function toJSON() { - return Array.from(this); - }; - - /** - * Observes this object. Triggers for the events 'add', 'update' and 'delete'. - * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe - * for callback details - */ - _proto.observe_ = function observe_(listener, fireImmediately) { - if (false) {} - return registerListener(this, listener); - }; - - _proto.intercept_ = function intercept_(handler) { - return registerInterceptor(this, handler); - }; - - _createClass(ObservableMap, [{ - key: "size", - get: function get() { - this.keysAtom_.reportObserved(); - return this.data_.size; - } - }, { - key: _Symbol$toStringTag, - get: function get() { - return "Map"; - } - }]); - - return ObservableMap; -}(); // eslint-disable-next-line - -var isObservableMap = /*#__PURE__*/createInstanceofPredicate("ObservableMap", ObservableMap); - -function convertToMap(dataStructure) { - if (isES6Map(dataStructure) || isObservableMap(dataStructure)) { - return dataStructure; - } else if (Array.isArray(dataStructure)) { - return new Map(dataStructure); - } else if (isPlainObject(dataStructure)) { - var map = new Map(); - - for (var key in dataStructure) { - map.set(key, dataStructure[key]); - } - - return map; - } else { - return die(21, dataStructure); - } -} - -var _Symbol$iterator$1, _Symbol$toStringTag$1; -var ObservableSetMarker = {}; -_Symbol$iterator$1 = Symbol.iterator; -_Symbol$toStringTag$1 = Symbol.toStringTag; -var ObservableSet = /*#__PURE__*/function () { - function ObservableSet(initialData, enhancer, name_) { - if (enhancer === void 0) { - enhancer = deepEnhancer; - } - - if (name_ === void 0) { - name_ = "ObservableSet@" + getNextId(); - } - - this.name_ = void 0; - this[$mobx] = ObservableSetMarker; - this.data_ = new Set(); - this.atom_ = void 0; - this.changeListeners_ = void 0; - this.interceptors_ = void 0; - this.dehancer = void 0; - this.enhancer_ = void 0; - this.name_ = name_; - - if (!isFunction(Set)) { - die(22); - } - - this.atom_ = createAtom(this.name_); - - this.enhancer_ = function (newV, oldV) { - return enhancer(newV, oldV, name_); - }; - - if (initialData) { - this.replace(initialData); - } - } - - var _proto = ObservableSet.prototype; - - _proto.dehanceValue_ = function dehanceValue_(value) { - if (this.dehancer !== undefined) { - return this.dehancer(value); - } - - return value; - }; - - _proto.clear = function clear() { - var _this = this; - - transaction(function () { - untracked(function () { - for (var _iterator = _createForOfIteratorHelperLoose(_this.data_.values()), _step; !(_step = _iterator()).done;) { - var value = _step.value; - - _this["delete"](value); - } - }); - }); - }; - - _proto.forEach = function forEach(callbackFn, thisArg) { - for (var _iterator2 = _createForOfIteratorHelperLoose(this), _step2; !(_step2 = _iterator2()).done;) { - var value = _step2.value; - callbackFn.call(thisArg, value, value, this); - } - }; - - _proto.add = function add(value) { - var _this2 = this; - - checkIfStateModificationsAreAllowed(this.atom_); - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: ADD, - object: this, - newValue: value - }); - if (!change) return this; // ideally, value = change.value would be done here, so that values can be - // changed by interceptor. Same applies for other Set and Map api's. - } - - if (!this.has(value)) { - transaction(function () { - _this2.data_.add(_this2.enhancer_(value, undefined)); - - _this2.atom_.reportChanged(); - }); - var notifySpy = false && 0; - var notify = hasListeners(this); - - var _change = notify || notifySpy ? { - observableKind: "set", - debugObjectName: this.name_, - type: ADD, - object: this, - newValue: value - } : null; - - if (notifySpy && "production" !== "production") spyReportStart(_change); - if (notify) notifyListeners(this, _change); - if (notifySpy && "production" !== "production") spyReportEnd(); - } - - return this; - }; - - _proto["delete"] = function _delete(value) { - var _this3 = this; - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: DELETE, - object: this, - oldValue: value - }); - if (!change) return false; - } - - if (this.has(value)) { - var notifySpy = false && 0; - var notify = hasListeners(this); - - var _change2 = notify || notifySpy ? { - observableKind: "set", - debugObjectName: this.name_, - type: DELETE, - object: this, - oldValue: value - } : null; - - if (notifySpy && "production" !== "production") spyReportStart(_change2); - transaction(function () { - _this3.atom_.reportChanged(); - - _this3.data_["delete"](value); - }); - if (notify) notifyListeners(this, _change2); - if (notifySpy && "production" !== "production") spyReportEnd(); - return true; - } - - return false; - }; - - _proto.has = function has(value) { - this.atom_.reportObserved(); - return this.data_.has(this.dehanceValue_(value)); - }; - - _proto.entries = function entries() { - var nextIndex = 0; - var keys = Array.from(this.keys()); - var values = Array.from(this.values()); - return makeIterable({ - next: function next() { - var index = nextIndex; - nextIndex += 1; - return index < values.length ? { - value: [keys[index], values[index]], - done: false - } : { - done: true - }; - } - }); - }; - - _proto.keys = function keys() { - return this.values(); - }; - - _proto.values = function values() { - this.atom_.reportObserved(); - var self = this; - var nextIndex = 0; - var observableValues = Array.from(this.data_.values()); - return makeIterable({ - next: function next() { - return nextIndex < observableValues.length ? { - value: self.dehanceValue_(observableValues[nextIndex++]), - done: false - } : { - done: true - }; - } - }); - }; - - _proto.replace = function replace(other) { - var _this4 = this; - - if (isObservableSet(other)) { - other = new Set(other); - } - - transaction(function () { - if (Array.isArray(other)) { - _this4.clear(); - - other.forEach(function (value) { - return _this4.add(value); - }); - } else if (isES6Set(other)) { - _this4.clear(); - - other.forEach(function (value) { - return _this4.add(value); - }); - } else if (other !== null && other !== undefined) { - die("Cannot initialize set from " + other); - } - }); - return this; - }; - - _proto.observe_ = function observe_(listener, fireImmediately) { - // ... 'fireImmediately' could also be true? - if (false) {} - return registerListener(this, listener); - }; - - _proto.intercept_ = function intercept_(handler) { - return registerInterceptor(this, handler); - }; - - _proto.toJSON = function toJSON() { - return Array.from(this); - }; - - _proto.toString = function toString() { - return "[object ObservableSet]"; - }; - - _proto[_Symbol$iterator$1] = function () { - return this.values(); - }; - - _createClass(ObservableSet, [{ - key: "size", - get: function get() { - this.atom_.reportObserved(); - return this.data_.size; - } - }, { - key: _Symbol$toStringTag$1, - get: function get() { - return "Set"; - } - }]); - - return ObservableSet; -}(); // eslint-disable-next-line - -var isObservableSet = /*#__PURE__*/createInstanceofPredicate("ObservableSet", ObservableSet); - -var REMOVE = "remove"; -var ObservableObjectAdministration = /*#__PURE__*/function () { - function ObservableObjectAdministration(target_, values_, name_, defaultEnhancer_) { - if (values_ === void 0) { - values_ = new Map(); - } - - this.target_ = void 0; - this.values_ = void 0; - this.name_ = void 0; - this.defaultEnhancer_ = void 0; - this.keysAtom_ = void 0; - this.changeListeners_ = void 0; - this.interceptors_ = void 0; - this.proxy_ = void 0; - this.pendingKeys_ = void 0; - this.keysValue_ = []; - this.isStaledKeysValue_ = true; - this.target_ = target_; - this.values_ = values_; - this.name_ = name_; - this.defaultEnhancer_ = defaultEnhancer_; - this.keysAtom_ = new Atom(name_ + ".keys"); - } - - var _proto = ObservableObjectAdministration.prototype; - - _proto.read_ = function read_(key) { - return this.values_.get(key).get(); - }; - - _proto.write_ = function write_(key, newValue) { - var instance = this.target_; - var observable = this.values_.get(key); - - if (observable instanceof ComputedValue) { - observable.set(newValue); - return; - } // intercept - - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - type: UPDATE, - object: this.proxy_ || instance, - name: key, - newValue: newValue - }); - if (!change) return; - newValue = change.newValue; - } - - newValue = observable.prepareNewValue_(newValue); // notify spy & observers - - if (newValue !== globalState.UNCHANGED) { - var notify = hasListeners(this); - var notifySpy = false && 0; - - var _change = notify || notifySpy ? { - type: UPDATE, - observableKind: "object", - debugObjectName: this.name_, - object: this.proxy_ || instance, - oldValue: observable.value_, - name: key, - newValue: newValue - } : null; - - if (false) {} - observable.setNewValue_(newValue); - if (notify) notifyListeners(this, _change); - if (false) {} - } - }; - - _proto.has_ = function has_(key) { - var map = this.pendingKeys_ || (this.pendingKeys_ = new Map()); - var entry = map.get(key); - if (entry) return entry.get();else { - var exists = !!this.values_.get(key); // Possible optimization: Don't have a separate map for non existing keys, - // but store them in the values map instead, using a special symbol to denote "not existing" - - entry = new ObservableValue(exists, referenceEnhancer, this.name_ + "." + stringifyKey(key) + "?", false); - map.set(key, entry); - return entry.get(); // read to subscribe - } - }; - - _proto.addObservableProp_ = function addObservableProp_(propName, newValue, enhancer) { - if (enhancer === void 0) { - enhancer = this.defaultEnhancer_; - } - - var target = this.target_; - if (false) {} - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - object: this.proxy_ || target, - name: propName, - type: ADD, - newValue: newValue - }); - if (!change) return; - newValue = change.newValue; - } - - var observable = new ObservableValue(newValue, enhancer, this.name_ + "." + stringifyKey(propName), false); - this.values_.set(propName, observable); - newValue = observable.value_; // observableValue might have changed it - - defineProperty(target, propName, generateObservablePropConfig(propName)); - this.notifyPropertyAddition_(propName, newValue); - }; - - _proto.addComputedProp_ = function addComputedProp_(propertyOwner, // where is the property declared? - propName, options) { - var target = this.target_; - options.name = options.name || this.name_ + "." + stringifyKey(propName); - options.context = this.proxy_ || target; - this.values_.set(propName, new ComputedValue(options)); // Doesn't seem we need this condition: - // if (propertyOwner === target || isPropertyConfigurable(propertyOwner, propName)) - - defineProperty(propertyOwner, propName, generateComputedPropConfig(propName)); - }; - - _proto.remove_ = function remove_(key) { - if (!this.values_.has(key)) return; - var target = this.target_; - - if (hasInterceptors(this)) { - var change = interceptChange(this, { - object: this.proxy_ || target, - name: key, - type: REMOVE - }); - if (!change) return; - } - - try { - startBatch(); - var notify = hasListeners(this); - var notifySpy = false && 0; - var oldObservable = this.values_.get(key); - var oldValue = oldObservable && oldObservable.get(); - oldObservable && oldObservable.set(undefined); // notify key and keyset listeners - - this.reportKeysChanged(); - this.values_["delete"](key); - - if (this.pendingKeys_) { - var entry = this.pendingKeys_.get(key); - if (entry) entry.set(false); - } // delete the prop - - - delete this.target_[key]; - - var _change2 = notify || notifySpy ? { - type: REMOVE, - observableKind: "object", - object: this.proxy_ || target, - debugObjectName: this.name_, - oldValue: oldValue, - name: key - } : null; - - if (false) {} - if (notify) notifyListeners(this, _change2); - if (false) {} - } finally { - endBatch(); - } - } - /** - * Observes this object. Triggers for the events 'add', 'update' and 'delete'. - * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe - * for callback details - */ - ; - - _proto.observe_ = function observe_(callback, fireImmediately) { - if (false) {} - return registerListener(this, callback); - }; - - _proto.intercept_ = function intercept_(handler) { - return registerInterceptor(this, handler); - }; - - _proto.notifyPropertyAddition_ = function notifyPropertyAddition_(key, newValue) { - var notify = hasListeners(this); - var notifySpy = false && 0; - var change = notify || notifySpy ? { - type: ADD, - observableKind: "object", - debugObjectName: this.name_, - object: this.proxy_ || this.target_, - name: key, - newValue: newValue - } : null; - if (false) {} - if (notify) notifyListeners(this, change); - if (false) {} - - if (this.pendingKeys_) { - var entry = this.pendingKeys_.get(key); - if (entry) entry.set(true); - } - - this.reportKeysChanged(); - }; - - _proto.getKeys_ = function getKeys_() { - this.keysAtom_.reportObserved(); - - if (!this.isStaledKeysValue_) { - return this.keysValue_; - } // return Reflect.ownKeys(this.values) as any - - - this.keysValue_ = []; - - for (var _iterator = _createForOfIteratorHelperLoose(this.values_), _step; !(_step = _iterator()).done;) { - var _step$value = _step.value, - key = _step$value[0], - value = _step$value[1]; - if (value instanceof ObservableValue) this.keysValue_.push(key); - } - - if (false) {} - this.isStaledKeysValue_ = false; - return this.keysValue_; - }; - - _proto.reportKeysChanged = function reportKeysChanged() { - this.isStaledKeysValue_ = true; - this.keysAtom_.reportChanged(); - }; - - return ObservableObjectAdministration; -}(); -function asObservableObject(target, name, defaultEnhancer) { - if (name === void 0) { - name = ""; - } - - if (defaultEnhancer === void 0) { - defaultEnhancer = deepEnhancer; - } - - if (hasProp(target, $mobx)) return target[$mobx]; - if (false) {} - if (!isPlainObject(target)) name = (target.constructor.name || "ObservableObject") + "@" + getNextId(); - if (!name) name = "ObservableObject@" + getNextId(); - var adm = new ObservableObjectAdministration(target, new Map(), stringifyKey(name), defaultEnhancer); - addHiddenProp(target, $mobx, adm); - return adm; -} -var observablePropertyConfigs = /*#__PURE__*/Object.create(null); -var computedPropertyConfigs = /*#__PURE__*/Object.create(null); -function generateObservablePropConfig(propName) { - return observablePropertyConfigs[propName] || (observablePropertyConfigs[propName] = { - configurable: true, - enumerable: true, - get: function get() { - return this[$mobx].read_(propName); - }, - set: function set(v) { - this[$mobx].write_(propName, v); - } - }); -} -function generateComputedPropConfig(propName) { - return computedPropertyConfigs[propName] || (computedPropertyConfigs[propName] = { - configurable: true, - enumerable: false, - get: function get() { - return this[$mobx].read_(propName); - }, - set: function set(v) { - this[$mobx].write_(propName, v); - } - }); -} -var isObservableObjectAdministration = /*#__PURE__*/createInstanceofPredicate("ObservableObjectAdministration", ObservableObjectAdministration); -function isObservableObject(thing) { - if (isObject(thing)) { - return isObservableObjectAdministration(thing[$mobx]); - } - - return false; -} - -/** - * This array buffer contains two lists of properties, so that all arrays - * can recycle their property definitions, which significantly improves performance of creating - * properties on the fly. - */ - -var OBSERVABLE_ARRAY_BUFFER_SIZE = 0; // Typescript workaround to make sure ObservableArray extends Array - -var StubArray = function StubArray() {}; - -function inherit(ctor, proto) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(ctor.prototype, proto); - } else if (ctor.prototype.__proto__ !== undefined) { - ctor.prototype.__proto__ = proto; - } else { - ctor.prototype = proto; - } -} - -inherit(StubArray, Array.prototype); // Weex proto freeze protection was here, -// but it is unclear why the hack is need as MobX never changed the prototype -// anyway, so removed it in V6 - -var LegacyObservableArray = /*#__PURE__*/function (_StubArray) { - _inheritsLoose(LegacyObservableArray, _StubArray); - - function LegacyObservableArray(initialValues, enhancer, name, owned) { - var _this; - - if (name === void 0) { - name = "ObservableArray@" + getNextId(); - } - - if (owned === void 0) { - owned = false; - } - - _this = _StubArray.call(this) || this; - var adm = new ObservableArrayAdministration(name, enhancer, owned, true); - adm.proxy_ = _assertThisInitialized(_this); - addHiddenFinalProp(_assertThisInitialized(_this), $mobx, adm); - - if (initialValues && initialValues.length) { - var prev = allowStateChangesStart(true); // @ts-ignore - - _this.spliceWithArray(0, 0, initialValues); - - allowStateChangesEnd(prev); - } - - return _this; - } - - var _proto = LegacyObservableArray.prototype; - - _proto.concat = function concat() { - this[$mobx].atom_.reportObserved(); - - for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) { - arrays[_key] = arguments[_key]; - } - - return Array.prototype.concat.apply(this.slice(), //@ts-ignore - arrays.map(function (a) { - return isObservableArray(a) ? a.slice() : a; - })); - }; - - _proto[Symbol.iterator] = function () { - var self = this; - var nextIndex = 0; - return makeIterable({ - next: function next() { - // @ts-ignore - return nextIndex < self.length ? { - value: self[nextIndex++], - done: false - } : { - done: true, - value: undefined - }; - } - }); - }; - - _createClass(LegacyObservableArray, [{ - key: "length", - get: function get() { - return this[$mobx].getArrayLength_(); - }, - set: function set(newLength) { - this[$mobx].setArrayLength_(newLength); - } - }, { - key: Symbol.toStringTag, - get: function get() { - return "Array"; - } - }]); - - return LegacyObservableArray; -}(StubArray); - -Object.entries(arrayExtensions).forEach(function (_ref) { - var prop = _ref[0], - fn = _ref[1]; - if (prop !== "concat") addHiddenProp(LegacyObservableArray.prototype, prop, fn); -}); - -function createArrayEntryDescriptor(index) { - return { - enumerable: false, - configurable: true, - get: function get() { - return this[$mobx].get_(index); - }, - set: function set(value) { - this[$mobx].set_(index, value); - } - }; -} - -function createArrayBufferItem(index) { - defineProperty(LegacyObservableArray.prototype, "" + index, createArrayEntryDescriptor(index)); -} - -function reserveArrayBuffer(max) { - if (max > OBSERVABLE_ARRAY_BUFFER_SIZE) { - for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max + 100; index++) { - createArrayBufferItem(index); - } - - OBSERVABLE_ARRAY_BUFFER_SIZE = max; - } -} -reserveArrayBuffer(1000); -function createLegacyArray(initialValues, enhancer, name) { - return new LegacyObservableArray(initialValues, enhancer, name); -} - -function getAtom(thing, property) { - if (typeof thing === "object" && thing !== null) { - if (isObservableArray(thing)) { - if (property !== undefined) die(23); - return thing[$mobx].atom_; - } - - if (isObservableSet(thing)) { - return thing[$mobx]; - } - - if (isObservableMap(thing)) { - if (property === undefined) return thing.keysAtom_; - var observable = thing.data_.get(property) || thing.hasMap_.get(property); - if (!observable) die(25, property, getDebugName(thing)); - return observable; - } - - if (isObservableObject(thing)) { - if (!property) return die(26); - - var _observable = thing[$mobx].values_.get(property); - - if (!_observable) die(27, property, getDebugName(thing)); - return _observable; - } - - if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) { - return thing; - } - } else if (isFunction(thing)) { - if (isReaction(thing[$mobx])) { - // disposer function - return thing[$mobx]; - } - } - - die(28); -} -function getAdministration(thing, property) { - if (!thing) die(29); - if (property !== undefined) return getAdministration(getAtom(thing, property)); - if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) return thing; - if (isObservableMap(thing) || isObservableSet(thing)) return thing; - if (thing[$mobx]) return thing[$mobx]; - die(24, thing); -} -function getDebugName(thing, property) { - var named; - if (property !== undefined) named = getAtom(thing, property);else if (isObservableObject(thing) || isObservableMap(thing) || isObservableSet(thing)) named = getAdministration(thing);else named = getAtom(thing); // valid for arrays as well - - return named.name_; -} - -var toString = objectPrototype.toString; -function deepEqual(a, b, depth) { - if (depth === void 0) { - depth = -1; - } - - return eq(a, b, depth); -} // Copied from https://github.com/jashkenas/underscore/blob/5c237a7c682fb68fd5378203f0bf22dce1624854/underscore.js#L1186-L1289 -// Internal recursive comparison function for `isEqual`. - -function eq(a, b, depth, aStack, bStack) { - // Identical objects are equal. `0 === -0`, but they aren't identical. - // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). - if (a === b) return a !== 0 || 1 / a === 1 / b; // `null` or `undefined` only equal to itself (strict comparison). - - if (a == null || b == null) return false; // `NaN`s are equivalent, but non-reflexive. - - if (a !== a) return b !== b; // Exhaust primitive checks - - var type = typeof a; - if (!isFunction(type) && type !== "object" && typeof b != "object") return false; // Compare `[[Class]]` names. - - var className = toString.call(a); - if (className !== toString.call(b)) return false; - - switch (className) { - // Strings, numbers, regular expressions, dates, and booleans are compared by value. - case "[object RegExp]": // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') - - case "[object String]": - // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is - // equivalent to `new String("5")`. - return "" + a === "" + b; - - case "[object Number]": - // `NaN`s are equivalent, but non-reflexive. - // Object(NaN) is equivalent to NaN. - if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. - - return +a === 0 ? 1 / +a === 1 / b : +a === +b; - - case "[object Date]": - case "[object Boolean]": - // Coerce dates and booleans to numeric primitive values. Dates are compared by their - // millisecond representations. Note that invalid dates with millisecond representations - // of `NaN` are not equivalent. - return +a === +b; - - case "[object Symbol]": - return typeof Symbol !== "undefined" && Symbol.valueOf.call(a) === Symbol.valueOf.call(b); - - case "[object Map]": - case "[object Set]": - // Maps and Sets are unwrapped to arrays of entry-pairs, adding an incidental level. - // Hide this extra level by increasing the depth. - if (depth >= 0) { - depth++; - } - - break; - } // Unwrap any wrapped objects. - - - a = unwrap(a); - b = unwrap(b); - var areArrays = className === "[object Array]"; - - if (!areArrays) { - if (typeof a != "object" || typeof b != "object") return false; // Objects with different constructors are not equivalent, but `Object`s or `Array`s - // from different frames are. - - var aCtor = a.constructor, - bCtor = b.constructor; - - if (aCtor !== bCtor && !(isFunction(aCtor) && aCtor instanceof aCtor && isFunction(bCtor) && bCtor instanceof bCtor) && "constructor" in a && "constructor" in b) { - return false; - } - } - - if (depth === 0) { - return false; - } else if (depth < 0) { - depth = -1; - } // Assume equality for cyclic structures. The algorithm for detecting cyclic - // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. - // Initializing stack of traversed objects. - // It's done here since we only need them for objects and arrays comparison. - - - aStack = aStack || []; - bStack = bStack || []; - var length = aStack.length; - - while (length--) { - // Linear search. Performance is inversely proportional to the number of - // unique nested structures. - if (aStack[length] === a) return bStack[length] === b; - } // Add the first object to the stack of traversed objects. - - - aStack.push(a); - bStack.push(b); // Recursively compare objects and arrays. - - if (areArrays) { - // Compare array lengths to determine if a deep comparison is necessary. - length = a.length; - if (length !== b.length) return false; // Deep compare the contents, ignoring non-numeric properties. - - while (length--) { - if (!eq(a[length], b[length], depth - 1, aStack, bStack)) return false; - } - } else { - // Deep compare objects. - var keys = Object.keys(a); - var key; - length = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. - - if (Object.keys(b).length !== length) return false; - - while (length--) { - // Deep compare each member - key = keys[length]; - if (!(hasProp(b, key) && eq(a[key], b[key], depth - 1, aStack, bStack))) return false; - } - } // Remove the first object from the stack of traversed objects. - - - aStack.pop(); - bStack.pop(); - return true; -} - -function unwrap(a) { - if (isObservableArray(a)) return a.slice(); - if (isES6Map(a) || isObservableMap(a)) return Array.from(a.entries()); - if (isES6Set(a) || isObservableSet(a)) return Array.from(a.entries()); - return a; -} - -function makeIterable(iterator) { - iterator[Symbol.iterator] = getSelf; - return iterator; -} - -function getSelf() { - return this; -} - -/** - * (c) Michel Weststrate 2015 - 2020 - * MIT Licensed - * - * Welcome to the mobx sources! To get an global overview of how MobX internally works, - * this is a good place to start: - * https://medium.com/@mweststrate/becoming-fully-reactive-an-in-depth-explanation-of-mobservable-55995262a254#.xvbh6qd74 - * - * Source folders: - * =============== - * - * - api/ Most of the public static methods exposed by the module can be found here. - * - core/ Implementation of the MobX algorithm; atoms, derivations, reactions, dependency trees, optimizations. Cool stuff can be found here. - * - types/ All the magic that is need to have observable objects, arrays and values is in this folder. Including the modifiers like `asFlat`. - * - utils/ Utility stuff. - * - */ -["Symbol", "Map", "Set", "Symbol"].forEach(function (m) { - var g = getGlobal(); - - if (typeof g[m] === "undefined") { - die("MobX requires global '" + m + "' to be available or polyfilled"); - } -}); - -if (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === "object") { - // See: https://github.com/andykog/mobx-devtools/ - __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({ - spy: spy, - extras: { - getDebugName: getDebugName - }, - $mobx: $mobx - }); -} - - - - -/***/ }), - -/***/ 3608: -/*!**************************************************************!*\ - !*** ../../node_modules/nanoid/index.browser.js + 1 modules ***! - \**************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -// ESM COMPAT FLAG -__webpack_require__.r(__webpack_exports__); - -// EXPORTS -__webpack_require__.d(__webpack_exports__, { - "customAlphabet": () => (/* binding */ customAlphabet), - "customRandom": () => (/* binding */ customRandom), - "nanoid": () => (/* binding */ nanoid), - "random": () => (/* binding */ random), - "urlAlphabet": () => (/* reexport */ urlAlphabet) -}); - -;// CONCATENATED MODULE: ../../node_modules/nanoid/url-alphabet/index.js -// This alphabet uses `A-Za-z0-9_-` symbols. The genetic algorithm helped -// optimize the gzip compression for this alphabet. -let urlAlphabet = - 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW' - - - -;// CONCATENATED MODULE: ../../node_modules/nanoid/index.browser.js -// This file replaces `index.js` in bundlers like webpack or Rollup, -// according to `browser` config in `package.json`. - - - -if (false) {} - -let random = bytes => crypto.getRandomValues(new Uint8Array(bytes)) - -let customRandom = (alphabet, size, getRandom) => { - // First, a bitmask is necessary to generate the ID. The bitmask makes bytes - // values closer to the alphabet size. The bitmask calculates the closest - // `2^31 - 1` number, which exceeds the alphabet size. - // For example, the bitmask for the alphabet size 30 is 31 (00011111). - // `Math.clz32` is not used, because it is not available in browsers. - let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 - // Though, the bitmask solution is not perfect since the bytes exceeding - // the alphabet size are refused. Therefore, to reliably generate the ID, - // the random bytes redundancy has to be satisfied. - - // Note: every hardware random generator call is performance expensive, - // because the system call for entropy collection takes a lot of time. - // So, to avoid additional system calls, extra bytes are requested in advance. - - // Next, a step determines how many random bytes to generate. - // The number of random bytes gets decided upon the ID size, mask, - // alphabet size, and magic number 1.6 (using 1.6 peaks at performance - // according to benchmarks). - - // `-~f => Math.ceil(f)` if f is a float - // `-~i => i + 1` if i is an integer - let step = -~((1.6 * mask * size) / alphabet.length) - - return () => { - let id = '' - while (true) { - let bytes = getRandom(step) - // A compact alternative for `for (var i = 0; i < step; i++)`. - let j = step - while (j--) { - // Adding `|| ''` refuses a random byte that exceeds the alphabet size. - id += alphabet[bytes[j] & mask] || '' - // `id.length + 1 === size` is a more compact option. - if (id.length === +size) return id - } - } - } -} - -let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random) - -let nanoid = (size = 21) => { - let id = '' - let bytes = crypto.getRandomValues(new Uint8Array(size)) - - // A compact alternative for `for (var i = 0; i < step; i++)`. - while (size--) { - // It is incorrect to use bytes exceeding the alphabet size. - // The following mask reduces the random byte in the 0-255 value - // range to the 0-63 value range. Therefore, adding hacks, such - // as empty string fallback or magic numbers, is unneccessary because - // the bitmask trims bytes down to the alphabet size. - let byte = bytes[size] & 63 - if (byte < 36) { - // `0-9a-z` - id += byte.toString(36) - } else if (byte < 62) { - // `A-Z` - id += (byte - 26).toString(36).toUpperCase() - } else if (byte < 63) { - id += '_' - } else { - id += '-' - } - } - return id -} - - - - -/***/ }), - -/***/ 5006: -/*!****************************************************************!*\ - !*** ../../node_modules/webextension-polyfill-ts/lib/index.js ***! - \****************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -// if not in a browser, assume we're in a test, return a dummy -if (typeof window === "undefined") exports.browser = {}; -else exports.browser = __webpack_require__(/*! webextension-polyfill */ 1105); - - -/***/ }), - -/***/ 1105: -/*!*************************************************************************!*\ - !*** ../../node_modules/webextension-polyfill/dist/browser-polyfill.js ***! - \*************************************************************************/ -/***/ (function(module, exports) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (global, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [module], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else { var mod; } -})(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (module) { - /* webextension-polyfill - v0.6.0 - Mon Dec 23 2019 12:32:53 */ - - /* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ - - /* vim: set sts=2 sw=2 et tw=80: */ - - /* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - "use strict"; - - if (typeof browser === "undefined" || Object.getPrototypeOf(browser) !== Object.prototype) { - const CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE = "The message port closed before a response was received."; - const SEND_RESPONSE_DEPRECATION_WARNING = "Returning a Promise is the preferred way to send a reply from an onMessage/onMessageExternal listener, as the sendResponse will be removed from the specs (See https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage)"; // Wrapping the bulk of this polyfill in a one-time-use function is a minor - // optimization for Firefox. Since Spidermonkey does not fully parse the - // contents of a function until the first time it's called, and since it will - // never actually need to be called, this allows the polyfill to be included - // in Firefox nearly for free. - - const wrapAPIs = extensionAPIs => { - // NOTE: apiMetadata is associated to the content of the api-metadata.json file - // at build time by replacing the following "include" with the content of the - // JSON file. - const apiMetadata = { - "alarms": { - "clear": { - "minArgs": 0, - "maxArgs": 1 - }, - "clearAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "get": { - "minArgs": 0, - "maxArgs": 1 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "bookmarks": { - "create": { - "minArgs": 1, - "maxArgs": 1 - }, - "get": { - "minArgs": 1, - "maxArgs": 1 - }, - "getChildren": { - "minArgs": 1, - "maxArgs": 1 - }, - "getRecent": { - "minArgs": 1, - "maxArgs": 1 - }, - "getSubTree": { - "minArgs": 1, - "maxArgs": 1 - }, - "getTree": { - "minArgs": 0, - "maxArgs": 0 - }, - "move": { - "minArgs": 2, - "maxArgs": 2 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeTree": { - "minArgs": 1, - "maxArgs": 1 - }, - "search": { - "minArgs": 1, - "maxArgs": 1 - }, - "update": { - "minArgs": 2, - "maxArgs": 2 - } - }, - "browserAction": { - "disable": { - "minArgs": 0, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "enable": { - "minArgs": 0, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "getBadgeBackgroundColor": { - "minArgs": 1, - "maxArgs": 1 - }, - "getBadgeText": { - "minArgs": 1, - "maxArgs": 1 - }, - "getPopup": { - "minArgs": 1, - "maxArgs": 1 - }, - "getTitle": { - "minArgs": 1, - "maxArgs": 1 - }, - "openPopup": { - "minArgs": 0, - "maxArgs": 0 - }, - "setBadgeBackgroundColor": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setBadgeText": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setIcon": { - "minArgs": 1, - "maxArgs": 1 - }, - "setPopup": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setTitle": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - } - }, - "browsingData": { - "remove": { - "minArgs": 2, - "maxArgs": 2 - }, - "removeCache": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeCookies": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeDownloads": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeFormData": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeHistory": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeLocalStorage": { - "minArgs": 1, - "maxArgs": 1 - }, - "removePasswords": { - "minArgs": 1, - "maxArgs": 1 - }, - "removePluginData": { - "minArgs": 1, - "maxArgs": 1 - }, - "settings": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "commands": { - "getAll": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "contextMenus": { - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "update": { - "minArgs": 2, - "maxArgs": 2 - } - }, - "cookies": { - "get": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAll": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAllCookieStores": { - "minArgs": 0, - "maxArgs": 0 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "set": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "devtools": { - "inspectedWindow": { - "eval": { - "minArgs": 1, - "maxArgs": 2, - "singleCallbackArg": false - } - }, - "panels": { - "create": { - "minArgs": 3, - "maxArgs": 3, - "singleCallbackArg": true - } - } - }, - "downloads": { - "cancel": { - "minArgs": 1, - "maxArgs": 1 - }, - "download": { - "minArgs": 1, - "maxArgs": 1 - }, - "erase": { - "minArgs": 1, - "maxArgs": 1 - }, - "getFileIcon": { - "minArgs": 1, - "maxArgs": 2 - }, - "open": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "pause": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeFile": { - "minArgs": 1, - "maxArgs": 1 - }, - "resume": { - "minArgs": 1, - "maxArgs": 1 - }, - "search": { - "minArgs": 1, - "maxArgs": 1 - }, - "show": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - } - }, - "extension": { - "isAllowedFileSchemeAccess": { - "minArgs": 0, - "maxArgs": 0 - }, - "isAllowedIncognitoAccess": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "history": { - "addUrl": { - "minArgs": 1, - "maxArgs": 1 - }, - "deleteAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "deleteRange": { - "minArgs": 1, - "maxArgs": 1 - }, - "deleteUrl": { - "minArgs": 1, - "maxArgs": 1 - }, - "getVisits": { - "minArgs": 1, - "maxArgs": 1 - }, - "search": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "i18n": { - "detectLanguage": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAcceptLanguages": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "identity": { - "launchWebAuthFlow": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "idle": { - "queryState": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "management": { - "get": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "getSelf": { - "minArgs": 0, - "maxArgs": 0 - }, - "setEnabled": { - "minArgs": 2, - "maxArgs": 2 - }, - "uninstallSelf": { - "minArgs": 0, - "maxArgs": 1 - } - }, - "notifications": { - "clear": { - "minArgs": 1, - "maxArgs": 1 - }, - "create": { - "minArgs": 1, - "maxArgs": 2 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "getPermissionLevel": { - "minArgs": 0, - "maxArgs": 0 - }, - "update": { - "minArgs": 2, - "maxArgs": 2 - } - }, - "pageAction": { - "getPopup": { - "minArgs": 1, - "maxArgs": 1 - }, - "getTitle": { - "minArgs": 1, - "maxArgs": 1 - }, - "hide": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setIcon": { - "minArgs": 1, - "maxArgs": 1 - }, - "setPopup": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "setTitle": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - }, - "show": { - "minArgs": 1, - "maxArgs": 1, - "fallbackToNoCallback": true - } - }, - "permissions": { - "contains": { - "minArgs": 1, - "maxArgs": 1 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 0 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "request": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "runtime": { - "getBackgroundPage": { - "minArgs": 0, - "maxArgs": 0 - }, - "getPlatformInfo": { - "minArgs": 0, - "maxArgs": 0 - }, - "openOptionsPage": { - "minArgs": 0, - "maxArgs": 0 - }, - "requestUpdateCheck": { - "minArgs": 0, - "maxArgs": 0 - }, - "sendMessage": { - "minArgs": 1, - "maxArgs": 3 - }, - "sendNativeMessage": { - "minArgs": 2, - "maxArgs": 2 - }, - "setUninstallURL": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "sessions": { - "getDevices": { - "minArgs": 0, - "maxArgs": 1 - }, - "getRecentlyClosed": { - "minArgs": 0, - "maxArgs": 1 - }, - "restore": { - "minArgs": 0, - "maxArgs": 1 - } - }, - "storage": { - "local": { - "clear": { - "minArgs": 0, - "maxArgs": 0 - }, - "get": { - "minArgs": 0, - "maxArgs": 1 - }, - "getBytesInUse": { - "minArgs": 0, - "maxArgs": 1 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "set": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "managed": { - "get": { - "minArgs": 0, - "maxArgs": 1 - }, - "getBytesInUse": { - "minArgs": 0, - "maxArgs": 1 - } - }, - "sync": { - "clear": { - "minArgs": 0, - "maxArgs": 0 - }, - "get": { - "minArgs": 0, - "maxArgs": 1 - }, - "getBytesInUse": { - "minArgs": 0, - "maxArgs": 1 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "set": { - "minArgs": 1, - "maxArgs": 1 - } - } - }, - "tabs": { - "captureVisibleTab": { - "minArgs": 0, - "maxArgs": 2 - }, - "create": { - "minArgs": 1, - "maxArgs": 1 - }, - "detectLanguage": { - "minArgs": 0, - "maxArgs": 1 - }, - "discard": { - "minArgs": 0, - "maxArgs": 1 - }, - "duplicate": { - "minArgs": 1, - "maxArgs": 1 - }, - "executeScript": { - "minArgs": 1, - "maxArgs": 2 - }, - "get": { - "minArgs": 1, - "maxArgs": 1 - }, - "getCurrent": { - "minArgs": 0, - "maxArgs": 0 - }, - "getZoom": { - "minArgs": 0, - "maxArgs": 1 - }, - "getZoomSettings": { - "minArgs": 0, - "maxArgs": 1 - }, - "highlight": { - "minArgs": 1, - "maxArgs": 1 - }, - "insertCSS": { - "minArgs": 1, - "maxArgs": 2 - }, - "move": { - "minArgs": 2, - "maxArgs": 2 - }, - "query": { - "minArgs": 1, - "maxArgs": 1 - }, - "reload": { - "minArgs": 0, - "maxArgs": 2 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "removeCSS": { - "minArgs": 1, - "maxArgs": 2 - }, - "sendMessage": { - "minArgs": 2, - "maxArgs": 3 - }, - "setZoom": { - "minArgs": 1, - "maxArgs": 2 - }, - "setZoomSettings": { - "minArgs": 1, - "maxArgs": 2 - }, - "update": { - "minArgs": 1, - "maxArgs": 2 - } - }, - "topSites": { - "get": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "webNavigation": { - "getAllFrames": { - "minArgs": 1, - "maxArgs": 1 - }, - "getFrame": { - "minArgs": 1, - "maxArgs": 1 - } - }, - "webRequest": { - "handlerBehaviorChanged": { - "minArgs": 0, - "maxArgs": 0 - } - }, - "windows": { - "create": { - "minArgs": 0, - "maxArgs": 1 - }, - "get": { - "minArgs": 1, - "maxArgs": 2 - }, - "getAll": { - "minArgs": 0, - "maxArgs": 1 - }, - "getCurrent": { - "minArgs": 0, - "maxArgs": 1 - }, - "getLastFocused": { - "minArgs": 0, - "maxArgs": 1 - }, - "remove": { - "minArgs": 1, - "maxArgs": 1 - }, - "update": { - "minArgs": 2, - "maxArgs": 2 - } - } - }; - - if (Object.keys(apiMetadata).length === 0) { - throw new Error("api-metadata.json has not been included in browser-polyfill"); - } - /** - * A WeakMap subclass which creates and stores a value for any key which does - * not exist when accessed, but behaves exactly as an ordinary WeakMap - * otherwise. - * - * @param {function} createItem - * A function which will be called in order to create the value for any - * key which does not exist, the first time it is accessed. The - * function receives, as its only argument, the key being created. - */ - - - class DefaultWeakMap extends WeakMap { - constructor(createItem, items = undefined) { - super(items); - this.createItem = createItem; - } - - get(key) { - if (!this.has(key)) { - this.set(key, this.createItem(key)); - } - - return super.get(key); - } - - } - /** - * Returns true if the given object is an object with a `then` method, and can - * therefore be assumed to behave as a Promise. - * - * @param {*} value The value to test. - * @returns {boolean} True if the value is thenable. - */ - - - const isThenable = value => { - return value && typeof value === "object" && typeof value.then === "function"; - }; - /** - * Creates and returns a function which, when called, will resolve or reject - * the given promise based on how it is called: - * - * - If, when called, `chrome.runtime.lastError` contains a non-null object, - * the promise is rejected with that value. - * - If the function is called with exactly one argument, the promise is - * resolved to that value. - * - Otherwise, the promise is resolved to an array containing all of the - * function's arguments. - * - * @param {object} promise - * An object containing the resolution and rejection functions of a - * promise. - * @param {function} promise.resolve - * The promise's resolution function. - * @param {function} promise.rejection - * The promise's rejection function. - * @param {object} metadata - * Metadata about the wrapped method which has created the callback. - * @param {integer} metadata.maxResolvedArgs - * The maximum number of arguments which may be passed to the - * callback created by the wrapped async function. - * - * @returns {function} - * The generated callback function. - */ - - - const makeCallback = (promise, metadata) => { - return (...callbackArgs) => { - if (extensionAPIs.runtime.lastError) { - promise.reject(extensionAPIs.runtime.lastError); - } else if (metadata.singleCallbackArg || callbackArgs.length <= 1 && metadata.singleCallbackArg !== false) { - promise.resolve(callbackArgs[0]); - } else { - promise.resolve(callbackArgs); - } - }; - }; - - const pluralizeArguments = numArgs => numArgs == 1 ? "argument" : "arguments"; - /** - * Creates a wrapper function for a method with the given name and metadata. - * - * @param {string} name - * The name of the method which is being wrapped. - * @param {object} metadata - * Metadata about the method being wrapped. - * @param {integer} metadata.minArgs - * The minimum number of arguments which must be passed to the - * function. If called with fewer than this number of arguments, the - * wrapper will raise an exception. - * @param {integer} metadata.maxArgs - * The maximum number of arguments which may be passed to the - * function. If called with more than this number of arguments, the - * wrapper will raise an exception. - * @param {integer} metadata.maxResolvedArgs - * The maximum number of arguments which may be passed to the - * callback created by the wrapped async function. - * - * @returns {function(object, ...*)} - * The generated wrapper function. - */ - - - const wrapAsyncFunction = (name, metadata) => { - return function asyncFunctionWrapper(target, ...args) { - if (args.length < metadata.minArgs) { - throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`); - } - - if (args.length > metadata.maxArgs) { - throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`); - } - - return new Promise((resolve, reject) => { - if (metadata.fallbackToNoCallback) { - // This API method has currently no callback on Chrome, but it return a promise on Firefox, - // and so the polyfill will try to call it with a callback first, and it will fallback - // to not passing the callback if the first call fails. - try { - target[name](...args, makeCallback({ - resolve, - reject - }, metadata)); - } catch (cbError) { - console.warn(`${name} API method doesn't seem to support the callback parameter, ` + "falling back to call it without a callback: ", cbError); - target[name](...args); // Update the API method metadata, so that the next API calls will not try to - // use the unsupported callback anymore. - - metadata.fallbackToNoCallback = false; - metadata.noCallback = true; - resolve(); - } - } else if (metadata.noCallback) { - target[name](...args); - resolve(); - } else { - target[name](...args, makeCallback({ - resolve, - reject - }, metadata)); - } - }); - }; - }; - /** - * Wraps an existing method of the target object, so that calls to it are - * intercepted by the given wrapper function. The wrapper function receives, - * as its first argument, the original `target` object, followed by each of - * the arguments passed to the original method. - * - * @param {object} target - * The original target object that the wrapped method belongs to. - * @param {function} method - * The method being wrapped. This is used as the target of the Proxy - * object which is created to wrap the method. - * @param {function} wrapper - * The wrapper function which is called in place of a direct invocation - * of the wrapped method. - * - * @returns {Proxy} - * A Proxy object for the given method, which invokes the given wrapper - * method in its place. - */ - - - const wrapMethod = (target, method, wrapper) => { - return new Proxy(method, { - apply(targetMethod, thisObj, args) { - return wrapper.call(thisObj, target, ...args); - } - - }); - }; - - let hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty); - /** - * Wraps an object in a Proxy which intercepts and wraps certain methods - * based on the given `wrappers` and `metadata` objects. - * - * @param {object} target - * The target object to wrap. - * - * @param {object} [wrappers = {}] - * An object tree containing wrapper functions for special cases. Any - * function present in this object tree is called in place of the - * method in the same location in the `target` object tree. These - * wrapper methods are invoked as described in {@see wrapMethod}. - * - * @param {object} [metadata = {}] - * An object tree containing metadata used to automatically generate - * Promise-based wrapper functions for asynchronous. Any function in - * the `target` object tree which has a corresponding metadata object - * in the same location in the `metadata` tree is replaced with an - * automatically-generated wrapper function, as described in - * {@see wrapAsyncFunction} - * - * @returns {Proxy} - */ - - const wrapObject = (target, wrappers = {}, metadata = {}) => { - let cache = Object.create(null); - let handlers = { - has(proxyTarget, prop) { - return prop in target || prop in cache; - }, - - get(proxyTarget, prop, receiver) { - if (prop in cache) { - return cache[prop]; - } - - if (!(prop in target)) { - return undefined; - } - - let value = target[prop]; - - if (typeof value === "function") { - // This is a method on the underlying object. Check if we need to do - // any wrapping. - if (typeof wrappers[prop] === "function") { - // We have a special-case wrapper for this method. - value = wrapMethod(target, target[prop], wrappers[prop]); - } else if (hasOwnProperty(metadata, prop)) { - // This is an async method that we have metadata for. Create a - // Promise wrapper for it. - let wrapper = wrapAsyncFunction(prop, metadata[prop]); - value = wrapMethod(target, target[prop], wrapper); - } else { - // This is a method that we don't know or care about. Return the - // original method, bound to the underlying object. - value = value.bind(target); - } - } else if (typeof value === "object" && value !== null && (hasOwnProperty(wrappers, prop) || hasOwnProperty(metadata, prop))) { - // This is an object that we need to do some wrapping for the children - // of. Create a sub-object wrapper for it with the appropriate child - // metadata. - value = wrapObject(value, wrappers[prop], metadata[prop]); - } else if (hasOwnProperty(metadata, "*")) { - // Wrap all properties in * namespace. - value = wrapObject(value, wrappers[prop], metadata["*"]); - } else { - // We don't need to do any wrapping for this property, - // so just forward all access to the underlying object. - Object.defineProperty(cache, prop, { - configurable: true, - enumerable: true, - - get() { - return target[prop]; - }, - - set(value) { - target[prop] = value; - } - - }); - return value; - } - - cache[prop] = value; - return value; - }, - - set(proxyTarget, prop, value, receiver) { - if (prop in cache) { - cache[prop] = value; - } else { - target[prop] = value; - } - - return true; - }, - - defineProperty(proxyTarget, prop, desc) { - return Reflect.defineProperty(cache, prop, desc); - }, - - deleteProperty(proxyTarget, prop) { - return Reflect.deleteProperty(cache, prop); - } - - }; // Per contract of the Proxy API, the "get" proxy handler must return the - // original value of the target if that value is declared read-only and - // non-configurable. For this reason, we create an object with the - // prototype set to `target` instead of using `target` directly. - // Otherwise we cannot return a custom object for APIs that - // are declared read-only and non-configurable, such as `chrome.devtools`. - // - // The proxy handlers themselves will still use the original `target` - // instead of the `proxyTarget`, so that the methods and properties are - // dereferenced via the original targets. - - let proxyTarget = Object.create(target); - return new Proxy(proxyTarget, handlers); - }; - /** - * Creates a set of wrapper functions for an event object, which handles - * wrapping of listener functions that those messages are passed. - * - * A single wrapper is created for each listener function, and stored in a - * map. Subsequent calls to `addListener`, `hasListener`, or `removeListener` - * retrieve the original wrapper, so that attempts to remove a - * previously-added listener work as expected. - * - * @param {DefaultWeakMap} wrapperMap - * A DefaultWeakMap object which will create the appropriate wrapper - * for a given listener function when one does not exist, and retrieve - * an existing one when it does. - * - * @returns {object} - */ - - - const wrapEvent = wrapperMap => ({ - addListener(target, listener, ...args) { - target.addListener(wrapperMap.get(listener), ...args); - }, - - hasListener(target, listener) { - return target.hasListener(wrapperMap.get(listener)); - }, - - removeListener(target, listener) { - target.removeListener(wrapperMap.get(listener)); - } - - }); // Keep track if the deprecation warning has been logged at least once. - - - let loggedSendResponseDeprecationWarning = false; - const onMessageWrappers = new DefaultWeakMap(listener => { - if (typeof listener !== "function") { - return listener; - } - /** - * Wraps a message listener function so that it may send responses based on - * its return value, rather than by returning a sentinel value and calling a - * callback. If the listener function returns a Promise, the response is - * sent when the promise either resolves or rejects. - * - * @param {*} message - * The message sent by the other end of the channel. - * @param {object} sender - * Details about the sender of the message. - * @param {function(*)} sendResponse - * A callback which, when called with an arbitrary argument, sends - * that value as a response. - * @returns {boolean} - * True if the wrapped listener returned a Promise, which will later - * yield a response. False otherwise. - */ - - - return function onMessage(message, sender, sendResponse) { - let didCallSendResponse = false; - let wrappedSendResponse; - let sendResponsePromise = new Promise(resolve => { - wrappedSendResponse = function (response) { - if (!loggedSendResponseDeprecationWarning) { - console.warn(SEND_RESPONSE_DEPRECATION_WARNING, new Error().stack); - loggedSendResponseDeprecationWarning = true; - } - - didCallSendResponse = true; - resolve(response); - }; - }); - let result; - - try { - result = listener(message, sender, wrappedSendResponse); - } catch (err) { - result = Promise.reject(err); - } - - const isResultThenable = result !== true && isThenable(result); // If the listener didn't returned true or a Promise, or called - // wrappedSendResponse synchronously, we can exit earlier - // because there will be no response sent from this listener. - - if (result !== true && !isResultThenable && !didCallSendResponse) { - return false; - } // A small helper to send the message if the promise resolves - // and an error if the promise rejects (a wrapped sendMessage has - // to translate the message into a resolved promise or a rejected - // promise). - - - const sendPromisedResult = promise => { - promise.then(msg => { - // send the message value. - sendResponse(msg); - }, error => { - // Send a JSON representation of the error if the rejected value - // is an instance of error, or the object itself otherwise. - let message; - - if (error && (error instanceof Error || typeof error.message === "string")) { - message = error.message; - } else { - message = "An unexpected error occurred"; - } - - sendResponse({ - __mozWebExtensionPolyfillReject__: true, - message - }); - }).catch(err => { - // Print an error on the console if unable to send the response. - console.error("Failed to send onMessage rejected reply", err); - }); - }; // If the listener returned a Promise, send the resolved value as a - // result, otherwise wait the promise related to the wrappedSendResponse - // callback to resolve and send it as a response. - - - if (isResultThenable) { - sendPromisedResult(result); - } else { - sendPromisedResult(sendResponsePromise); - } // Let Chrome know that the listener is replying. - - - return true; - }; - }); - - const wrappedSendMessageCallback = ({ - reject, - resolve - }, reply) => { - if (extensionAPIs.runtime.lastError) { - // Detect when none of the listeners replied to the sendMessage call and resolve - // the promise to undefined as in Firefox. - // See https://github.com/mozilla/webextension-polyfill/issues/130 - if (extensionAPIs.runtime.lastError.message === CHROME_SEND_MESSAGE_CALLBACK_NO_RESPONSE_MESSAGE) { - resolve(); - } else { - reject(extensionAPIs.runtime.lastError); - } - } else if (reply && reply.__mozWebExtensionPolyfillReject__) { - // Convert back the JSON representation of the error into - // an Error instance. - reject(new Error(reply.message)); - } else { - resolve(reply); - } - }; - - const wrappedSendMessage = (name, metadata, apiNamespaceObj, ...args) => { - if (args.length < metadata.minArgs) { - throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`); - } - - if (args.length > metadata.maxArgs) { - throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`); - } - - return new Promise((resolve, reject) => { - const wrappedCb = wrappedSendMessageCallback.bind(null, { - resolve, - reject - }); - args.push(wrappedCb); - apiNamespaceObj.sendMessage(...args); - }); - }; - - const staticWrappers = { - runtime: { - onMessage: wrapEvent(onMessageWrappers), - onMessageExternal: wrapEvent(onMessageWrappers), - sendMessage: wrappedSendMessage.bind(null, "sendMessage", { - minArgs: 1, - maxArgs: 3 - }) - }, - tabs: { - sendMessage: wrappedSendMessage.bind(null, "sendMessage", { - minArgs: 2, - maxArgs: 3 - }) - } - }; - const settingMetadata = { - clear: { - minArgs: 1, - maxArgs: 1 - }, - get: { - minArgs: 1, - maxArgs: 1 - }, - set: { - minArgs: 1, - maxArgs: 1 - } - }; - apiMetadata.privacy = { - network: { - "*": settingMetadata - }, - services: { - "*": settingMetadata - }, - websites: { - "*": settingMetadata - } - }; - return wrapObject(extensionAPIs, staticWrappers, apiMetadata); - }; - - if (typeof chrome != "object" || !chrome || !chrome.runtime || !chrome.runtime.id) { - throw new Error("This script should only be loaded in a browser extension."); - } // The build process adds a UMD wrapper around this file, which makes the - // `module` variable available. - - - module.exports = wrapAPIs(chrome); - } else { - module.exports = browser; - } -}); - - -/***/ }), - -/***/ 7843: -/*!****************************!*\ - !*** ../core/ts/config.ts ***! - \****************************/ -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.config = void 0; -const developmentBuild = "production" !== "production"; -exports.config = { - bergamotRestApiUrl: "http://127.0.0.1:8787", - useBergamotRestApi: "0" === "1", - sentryDsn: "https://@.ingest.sentry.io/", - bergamotModelsBaseUrl: developmentBuild - ? "http://0.0.0.0:4000/models" - : "https://storage.googleapis.com/bergamot-models-sandbox/0.2.2", - wasmBinariesBaseUrl: developmentBuild - ? "http://0.0.0.0:4000/wasm" - : "https://storage.googleapis.com/bergamot-models-sandbox/wasm/1", - telemetryAppId: "org-mozilla-bergamot", - telemetryDebugMode: developmentBuild, - extensionBuildId: `${"v0.4.3"}-${"local"}#${"HEAD"}`, - supportedLanguagePairs: [ - // "German, French, Spanish, Polish, Czech, and Estonian in and out of English" - // ISO 639-1 codes - // Language pairs that are not available are commented out - // ["de","en"], - // ["fr","en"], - ["es", "en"], - // ["pl","en"], - ["cs", "en"], - ["et", "en"], - ["en", "de"], - // ["en","fr"], - ["en", "es"], - // ["en","pl"], - ["en", "cs"], - ["en", "et"], - ["ru", "en"], - ], - privacyNoticeUrl: "https://example.com/privacy-notice", - feedbackSurveyUrl: "https://qsurvey.mozilla.com/s3/bergamot-translate-product-feedback", -}; - - -/***/ }), - -/***/ 9009: -/*!*****************************************************!*\ - !*** ../core/ts/shared-resources/ErrorReporting.ts ***! - \*****************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Sentry = exports.captureExceptionWithExtras = exports.initErrorReportingInContentScript = exports.initErrorReportingInBackgroundScript = exports.toggleErrorReportingBasedAsPerExtensionPreferences = void 0; -const Sentry = __importStar(__webpack_require__(/*! @sentry/browser */ 1346)); -exports.Sentry = Sentry; -const config_1 = __webpack_require__(/*! ../config */ 7843); -const subscribeToExtensionPreferenceChanges_1 = __webpack_require__(/*! ./state-management/subscribeToExtensionPreferenceChanges */ 14); -const flat_1 = __webpack_require__(/*! flat */ 3229); -// Initialize Sentry SDK if we have a non-placeholder DSN configured -let sentryIntialized = false; -if (!config_1.config.sentryDsn.includes("")) { - Sentry.init({ dsn: config_1.config.sentryDsn }); - sentryIntialized = true; -} -const enableErrorReporting = () => sentryIntialized && - (Sentry.getCurrentHub() - .getClient() - .getOptions().enabled = true); -const disableErrorReporting = () => sentryIntialized && - (Sentry.getCurrentHub() - .getClient() - .getOptions().enabled = false); -// Start with Sentry disabled -disableErrorReporting(); -const toggleErrorReportingBasedAsPerExtensionPreferences = (extensionPreferences) => { - if (extensionPreferences.enableErrorReporting) { - enableErrorReporting(); - Sentry.configureScope(function (scope) { - scope.setTag("extension.version", extensionPreferences.extensionVersion); - scope.setUser({ - id: extensionPreferences.extensionInstallationErrorReportingId, - }); - }); - console.info("Enabled error reporting"); - } - else { - disableErrorReporting(); - console.info("Disabled error reporting"); - } -}; -exports.toggleErrorReportingBasedAsPerExtensionPreferences = toggleErrorReportingBasedAsPerExtensionPreferences; -const initErrorReportingInBackgroundScript = (store, portNames) => __awaiter(void 0, void 0, void 0, function* () { - console.info(`Inquiring about error reporting preference in background script`); - yield subscribeToExtensionPreferenceChanges_1.subscribeToExtensionPreferenceChangesInBackgroundScript(store, exports.toggleErrorReportingBasedAsPerExtensionPreferences); - // Set up the port listeners that initErrorReportingInContentScript() - // expects to be available - return subscribeToExtensionPreferenceChanges_1.communicateExtensionPreferenceChangesToContentScripts(store, portNames); -}); -exports.initErrorReportingInBackgroundScript = initErrorReportingInBackgroundScript; -const initErrorReportingInContentScript = (portName) => __awaiter(void 0, void 0, void 0, function* () { - console.info(`Inquiring about error reporting preference in "${portName}"`); - yield subscribeToExtensionPreferenceChanges_1.subscribeToExtensionPreferenceChangesInContentScript(portName, exports.toggleErrorReportingBasedAsPerExtensionPreferences); -}); -exports.initErrorReportingInContentScript = initErrorReportingInContentScript; -const captureExceptionWithExtras = (exception, extras = null, level = null) => { - Sentry.withScope(scope => { - if (extras !== null) { - scope.setExtras(flat_1.flatten(extras)); - } - if (level !== null) { - scope.setLevel(level); - } - Sentry.captureException(exception); - }); -}; -exports.captureExceptionWithExtras = captureExceptionWithExtras; -Sentry.configureScope(scope => { - scope.addEventProcessor((event) => __awaiter(void 0, void 0, void 0, function* () { - // console.log("Unprocessed sentry event", Object.assign({}, { event })); - const normalizeUrl = url => { - return url.replace(/(webpack_require__@)?(moz|chrome)-extension:\/\/[^\/]+\//, "~/"); - }; - if (event.exception && - event.exception.values && - event.exception.values[0]) { - // Required for Sentry to map web extension sourcemap paths properly - if (event.culprit) { - event.culprit = normalizeUrl(event.culprit); - } - if (event.exception.values[0].stacktrace && - event.exception.values[0].stacktrace.frames) { - event.exception.values[0].stacktrace.frames = event.exception.values[0].stacktrace.frames.map(frame => { - frame.filename = normalizeUrl(frame.filename); - return frame; - }); - } - // console.log("Processed sentry event", { event }); - return event; - } - return null; - })); -}); - - -/***/ }), - -/***/ 3872: -/*!******************************************************!*\ - !*** ../core/ts/shared-resources/LanguageSupport.ts ***! - \******************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.LanguageSupport = void 0; -const webextension_polyfill_ts_1 = __webpack_require__(/*! webextension-polyfill-ts */ 5006); -const config_1 = __webpack_require__(/*! ../config */ 7843); -class LanguageSupport { - constructor() { - this.getAcceptedTargetLanguages = () => __awaiter(this, void 0, void 0, function* () { - return [ - ...new Set([ - webextension_polyfill_ts_1.browser.i18n.getUILanguage(), - ...(yield webextension_polyfill_ts_1.browser.i18n.getAcceptLanguages()), - ].map(localeCode => localeCode.split("-")[0])), - ]; - }); - this.getSupportedSourceLanguages = () => { - return [...new Set(config_1.config.supportedLanguagePairs.map(lp => lp[0]))]; - }; - this.getSupportedTargetLanguagesGivenASourceLanguage = (translateFrom) => { - return [ - ...new Set(config_1.config.supportedLanguagePairs - .filter(lp => lp[0] === translateFrom) - .map(lp => lp[1])), - ]; - }; - this.getAllPossiblySupportedTargetLanguages = () => { - return [...new Set(config_1.config.supportedLanguagePairs.map(lp => lp[1]))]; - }; - this.getDefaultSourceLanguage = (translateFrom, detectedLanguage) => { - return translateFrom || detectedLanguage; - }; - this.getDefaultTargetLanguage = (translateFrom, acceptedTargetLanguages) => { - const supportedTargetLanguages = translateFrom - ? this.getSupportedTargetLanguagesGivenASourceLanguage(translateFrom) - : this.getAllPossiblySupportedTargetLanguages(); - const possibleDefaultTargetLanguages = acceptedTargetLanguages.filter(languageCode => supportedTargetLanguages.includes(languageCode)); - if (possibleDefaultTargetLanguages.length) { - return possibleDefaultTargetLanguages[0]; - } - return null; - }; - this.summarizeLanguageSupport = (detectedLanguageResults) => __awaiter(this, void 0, void 0, function* () { - const acceptedTargetLanguages = yield this.getAcceptedTargetLanguages(); - const defaultSourceLanguage = this.getDefaultSourceLanguage(null, detectedLanguageResults === null || detectedLanguageResults === void 0 ? void 0 : detectedLanguageResults.language); - const defaultTargetLanguage = this.getDefaultTargetLanguage(defaultSourceLanguage, acceptedTargetLanguages); - const supportedSourceLanguages = this.getSupportedSourceLanguages(); - const supportedTargetLanguagesGivenDefaultSourceLanguage = this.getSupportedTargetLanguagesGivenASourceLanguage(defaultSourceLanguage); - const allPossiblySupportedTargetLanguages = this.getAllPossiblySupportedTargetLanguages(); - return { - acceptedTargetLanguages, - defaultSourceLanguage, - defaultTargetLanguage, - supportedSourceLanguages, - supportedTargetLanguagesGivenDefaultSourceLanguage, - allPossiblySupportedTargetLanguages, - }; - }); - } -} -exports.LanguageSupport = LanguageSupport; - - -/***/ }), - -/***/ 9359: -/*!******************************************************************!*\ - !*** ../core/ts/shared-resources/models/BaseTranslationState.ts ***! - \******************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BaseTranslationState = exports.TranslationStatus = void 0; -const mobx_keystone_1 = __webpack_require__(/*! mobx-keystone */ 4380); -const mobx_1 = __webpack_require__(/*! mobx */ 5412); -const webextension_polyfill_ts_1 = __webpack_require__(/*! webextension-polyfill-ts */ 5006); -/* eslint-disable no-unused-vars, no-shadow */ -// TODO: update typescript-eslint when support for this kind of declaration is supported -var TranslationStatus; -(function (TranslationStatus) { - TranslationStatus["UNKNOWN"] = "UNKNOWN"; - TranslationStatus["UNAVAILABLE"] = "UNAVAILABLE"; - TranslationStatus["DETECTING_LANGUAGE"] = "DETECTING_LANGUAGE"; - TranslationStatus["LANGUAGE_NOT_DETECTED"] = "LANGUAGE_NOT_DETECTED"; - TranslationStatus["SOURCE_LANGUAGE_UNDERSTOOD"] = "SOURCE_LANGUAGE_UNDERSTOOD"; - TranslationStatus["TRANSLATION_UNSUPPORTED"] = "TRANSLATION_UNSUPPORTED"; - TranslationStatus["OFFER"] = "OFFER"; - TranslationStatus["TRANSLATING"] = "TRANSLATING"; - TranslationStatus["TRANSLATED"] = "TRANSLATED"; - TranslationStatus["ERROR"] = "ERROR"; -})(TranslationStatus = exports.TranslationStatus || (exports.TranslationStatus = {})); -/* eslint-enable no-unused-vars, no-shadow */ -let BaseTranslationState = class BaseTranslationState extends mobx_keystone_1.Model({ - isVisible: mobx_keystone_1.prop({ setterAction: true }), - displayQualityEstimation: mobx_keystone_1.prop({ setterAction: true }), - translationRequested: mobx_keystone_1.prop({ setterAction: true }), - cancellationRequested: mobx_keystone_1.prop({ setterAction: true }), - detectedLanguageResults: mobx_keystone_1.prop(() => null, { - setterAction: true, - }), - translateFrom: mobx_keystone_1.prop({ setterAction: true }), - translateTo: mobx_keystone_1.prop({ setterAction: true }), - translationStatus: mobx_keystone_1.prop(TranslationStatus.UNKNOWN, { - setterAction: true, - }), - tabId: mobx_keystone_1.prop(), - wordCount: mobx_keystone_1.prop(), - wordCountVisible: mobx_keystone_1.prop(), - wordCountVisibleInViewport: mobx_keystone_1.prop(), - translationInitiationTimestamp: mobx_keystone_1.prop(), - totalModelLoadWallTimeMs: mobx_keystone_1.prop(), - totalTranslationWallTimeMs: mobx_keystone_1.prop(), - totalTranslationEngineRequestCount: mobx_keystone_1.prop(), - queuedTranslationEngineRequestCount: mobx_keystone_1.prop(), - modelLoadNecessary: mobx_keystone_1.prop(), - modelDownloadNecessary: mobx_keystone_1.prop(), - modelDownloading: mobx_keystone_1.prop(), - modelDownloadProgress: mobx_keystone_1.prop(), - modelLoading: mobx_keystone_1.prop(), - modelLoaded: mobx_keystone_1.prop(), - translationFinished: mobx_keystone_1.prop(), - modelLoadErrorOccurred: mobx_keystone_1.prop(), - modelDownloadErrorOccurred: mobx_keystone_1.prop(), - translationErrorOccurred: mobx_keystone_1.prop(), - otherErrorOccurred: mobx_keystone_1.prop(), -}) { - get effectiveTranslateFrom() { - var _a; - return this.translateFrom || ((_a = this.detectedLanguageResults) === null || _a === void 0 ? void 0 : _a.language); - } - get effectiveTranslateTo() { - const browserUiLanguageCode = webextension_polyfill_ts_1.browser.i18n.getUILanguage().split("-")[0]; - return this.translateTo || browserUiLanguageCode; - } -}; -__decorate([ - mobx_1.computed -], BaseTranslationState.prototype, "effectiveTranslateFrom", null); -__decorate([ - mobx_1.computed -], BaseTranslationState.prototype, "effectiveTranslateTo", null); -BaseTranslationState = __decorate([ - mobx_keystone_1.model("bergamotTranslate/BaseTranslationState") -], BaseTranslationState); -exports.BaseTranslationState = BaseTranslationState; - - -/***/ }), - -/***/ 1120: -/*!**********************************************************************!*\ - !*** ../core/ts/shared-resources/models/DocumentTranslationState.ts ***! - \**********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DocumentTranslationState = void 0; -const mobx_keystone_1 = __webpack_require__(/*! mobx-keystone */ 4380); -const TabTranslationState_1 = __webpack_require__(/*! ./TabTranslationState */ 6777); -let DocumentTranslationState = class DocumentTranslationState extends mobx_keystone_1.ExtendedModel(TabTranslationState_1.TabTranslationState, { - frameId: mobx_keystone_1.prop(), -}) { -}; -DocumentTranslationState = __decorate([ - mobx_keystone_1.model("bergamotTranslate/DocumentTranslationState") -], DocumentTranslationState); -exports.DocumentTranslationState = DocumentTranslationState; - - -/***/ }), - -/***/ 7516: -/*!************************************************************!*\ - !*** ../core/ts/shared-resources/models/ExtensionState.ts ***! - \************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ExtensionState = exports.translateOwnTextTranslationStateMapKey = exports.documentTranslationStateMapKey = void 0; -const mobx_keystone_1 = __webpack_require__(/*! mobx-keystone */ 4380); -const mobx_1 = __webpack_require__(/*! mobx */ 5412); -const TabTranslationState_1 = __webpack_require__(/*! ./TabTranslationState */ 6777); -const BaseTranslationState_1 = __webpack_require__(/*! ./BaseTranslationState */ 9359); -const documentTranslationStateMapKey = (frameInfo) => `${frameInfo.tabId}-${frameInfo.frameId}`; -exports.documentTranslationStateMapKey = documentTranslationStateMapKey; -const translateOwnTextTranslationStateMapKey = (totts) => `${totts.tabId}`; -exports.translateOwnTextTranslationStateMapKey = translateOwnTextTranslationStateMapKey; -let ExtensionState = class ExtensionState extends mobx_keystone_1.Model({ - documentTranslationStates: mobx_keystone_1.prop_mapObject(() => new Map()), - fragmentTranslationStates: mobx_keystone_1.prop_mapObject(() => new Map()), - translateOwnTextTranslationStates: mobx_keystone_1.prop_mapObject(() => new Map()), -}) { - setDocumentTranslationState(documentTranslationState) { - this.documentTranslationStates.set(exports.documentTranslationStateMapKey(documentTranslationState), documentTranslationState); - } - patchDocumentTranslationStateByFrameInfo(frameInfo, patches) { - const key = exports.documentTranslationStateMapKey(frameInfo); - const dts = this.documentTranslationStates.get(key); - mobx_keystone_1.applyPatches(dts, patches); - this.documentTranslationStates.set(key, dts); - } - deleteDocumentTranslationStateByFrameInfo(frameInfo) { - this.documentTranslationStates.delete(exports.documentTranslationStateMapKey(frameInfo)); - } - setTranslateOwnTextTranslationState(translateOwnTextTranslationState) { - this.translateOwnTextTranslationStates.set(exports.translateOwnTextTranslationStateMapKey(translateOwnTextTranslationState), translateOwnTextTranslationState); - } - deleteTranslateOwnTextTranslationState(translateOwnTextTranslationState) { - this.translateOwnTextTranslationStates.delete(exports.translateOwnTextTranslationStateMapKey(translateOwnTextTranslationState)); - } - get documentTranslationStatesByTabId() { - const map = new Map(); - this.documentTranslationStates.forEach((documentTranslationState) => { - if (map.has(documentTranslationState.tabId)) { - map.set(documentTranslationState.tabId, [ - ...map.get(documentTranslationState.tabId), - documentTranslationState, - ]); - } - else { - map.set(documentTranslationState.tabId, [documentTranslationState]); - } - }); - return map; - } - get tabTranslationStates() { - const map = new Map(); - this.documentTranslationStatesByTabId.forEach((documentTranslationStates, tabId) => { - const tabTopFrameState = documentTranslationStates.find((dts) => dts.frameId === 0); - // If the top frame state is unavailable (may happen during the early stages of a - // document translation state model instance), return an equally uninformative tab translation state - if (!tabTopFrameState) { - const tabTranslationState = new TabTranslationState_1.TabTranslationState(Object.assign({ tabId }, mobx_keystone_1.getSnapshot(documentTranslationStates[0]))); - map.set(tabId, tabTranslationState); - return; - } - // Use top frame state attributes to represent most of the tab state if available - const { isVisible, displayQualityEstimation, translationRequested, cancellationRequested, detectedLanguageResults, translateFrom, translateTo, windowId, showOriginal, url, } = mobx_keystone_1.getSnapshot(tabTopFrameState); - // For most translation-related attributes, we are only interested in the frames that existed when - // the translation was requested, or else we will not get attributes that represent the state of the - // web page at that time - const translationRelevantDocumentTranslationStates = documentTranslationStates.filter(dts => dts.translationRequested || - dts.translationStatus === BaseTranslationState_1.TranslationStatus.TRANSLATING || - dts.translationFinished); - const isNotUndefined = val => val !== undefined; - // Sum some state attributes - const wordCount = translationRelevantDocumentTranslationStates - .map(dts => dts.wordCount) - .filter(isNotUndefined) - .reduce((a, b) => a + b, 0); - const wordCountVisible = translationRelevantDocumentTranslationStates - .map(dts => dts.wordCountVisible) - .filter(isNotUndefined) - .reduce((a, b) => a + b, 0); - const wordCountVisibleInViewport = translationRelevantDocumentTranslationStates - .map(dts => dts.wordCountVisibleInViewport) - .filter(isNotUndefined) - .reduce((a, b) => a + b, 0); - const totalModelLoadWallTimeMs = translationRelevantDocumentTranslationStates - .map(dts => dts.totalModelLoadWallTimeMs) - .filter(isNotUndefined) - .reduce((a, b) => a + b, 0); - const totalTranslationWallTimeMs = translationRelevantDocumentTranslationStates - .map(dts => dts.totalTranslationWallTimeMs) - .filter(isNotUndefined) - .reduce((a, b) => a + b, 0); - const totalTranslationEngineRequestCount = translationRelevantDocumentTranslationStates - .map(dts => dts.totalTranslationEngineRequestCount) - .filter(isNotUndefined) - .reduce((a, b) => a + b, 0); - const queuedTranslationEngineRequestCount = translationRelevantDocumentTranslationStates - .map(dts => dts.queuedTranslationEngineRequestCount) - .filter(isNotUndefined) - .reduce((a, b) => a + b, 0); - // Merge translation-progress-related booleans as per src/core/ts/shared-resources/state-management/DocumentTranslationStateCommunicator.ts - const translationInitiationTimestamps = translationRelevantDocumentTranslationStates - .map((dts) => dts.translationInitiationTimestamp) - .filter(isNotUndefined); - const translationInitiationTimestamp = Math.min(...translationInitiationTimestamps); - const modelLoadNecessary = !!translationRelevantDocumentTranslationStates.filter((dts) => dts.modelLoadNecessary).length; - const modelDownloadNecessary = !!translationRelevantDocumentTranslationStates.filter((dts) => dts.modelDownloadNecessary).length; - const modelDownloading = !!translationRelevantDocumentTranslationStates.filter((dts) => dts.modelDownloading).length; - const modelLoading = modelLoadNecessary - ? !!translationRelevantDocumentTranslationStates.find((dts) => dts.modelLoading) - : undefined; - const modelLoaded = modelLoadNecessary - ? !!translationRelevantDocumentTranslationStates.find((dts) => !dts.modelLoaded) - : undefined; - const translationFinished = translationRelevantDocumentTranslationStates.filter((dts) => !dts.translationFinished).length === 0; - // Merge model download progress as per src/core/ts/shared-resources/state-management/DocumentTranslationStateCommunicator.ts - const emptyDownloadProgress = { - bytesDownloaded: 0, - bytesToDownload: 0, - startTs: undefined, - durationMs: 0, - endTs: undefined, - }; - const modelDownloadProgress = translationRelevantDocumentTranslationStates - .map((dts) => mobx_keystone_1.getSnapshot(dts.modelDownloadProgress)) - .filter((mdp) => mdp) - .reduce((a, b) => { - const startTs = a.startTs && a.startTs <= b.startTs ? a.startTs : b.startTs; - const endTs = a.endTs && a.endTs >= b.endTs ? a.endTs : b.endTs; - return { - bytesDownloaded: a.bytesDownloaded + b.bytesDownloaded, - bytesToDownload: a.bytesToDownload + b.bytesToDownload, - startTs, - durationMs: endTs ? endTs - startTs : Date.now() - startTs, - endTs, - }; - }, emptyDownloadProgress); - // Merge errorOccurred attributes - const modelLoadErrorOccurred = !!translationRelevantDocumentTranslationStates.filter((dts) => dts.modelLoadErrorOccurred).length; - const modelDownloadErrorOccurred = !!translationRelevantDocumentTranslationStates.filter((dts) => dts.modelDownloadErrorOccurred).length; - const translationErrorOccurred = !!translationRelevantDocumentTranslationStates.filter((dts) => dts.translationErrorOccurred).length; - const otherErrorOccurred = !!translationRelevantDocumentTranslationStates.filter((dts) => dts.otherErrorOccurred).length; - // Special merging of translation status - const anyFrameHasTranslationStatus = (translationStatus) => documentTranslationStates.find(dts => dts.translationStatus === translationStatus); - const anyFrameThatExistedWhenTranslationWasRequestedHasTranslationStatus = (translationStatus) => translationRelevantDocumentTranslationStates.find(dts => dts.translationStatus === translationStatus); - const tabTranslationStatus = () => { - // Since we only use some attributes from the top frame, we should only consider - // top frame when considering the related statuses - if ([ - BaseTranslationState_1.TranslationStatus.DETECTING_LANGUAGE, - BaseTranslationState_1.TranslationStatus.OFFER, - ].includes(tabTopFrameState.translationStatus)) { - return tabTopFrameState.translationStatus; - } - // Translation is ongoing - only consider frames that were available when - // the translation was requested, or else new frames injected in the document - // will cause unexpected status changes - if (anyFrameThatExistedWhenTranslationWasRequestedHasTranslationStatus(BaseTranslationState_1.TranslationStatus.TRANSLATING)) { - return BaseTranslationState_1.TranslationStatus.TRANSLATING; - } - // An error in any frame makes gets promoted to tab-level - if (anyFrameHasTranslationStatus(BaseTranslationState_1.TranslationStatus.ERROR)) { - return BaseTranslationState_1.TranslationStatus.ERROR; - } - // Fallback on top frame status as the canonical status - return tabTopFrameState.translationStatus; - }; - const translationStatus = tabTranslationStatus(); - const tabTranslationStateData = { - isVisible, - displayQualityEstimation, - translationRequested, - cancellationRequested, - detectedLanguageResults, - translateFrom, - translateTo, - translationStatus, - tabId, - windowId, - showOriginal, - url, - wordCount, - wordCountVisible, - wordCountVisibleInViewport, - translationInitiationTimestamp, - totalModelLoadWallTimeMs, - totalTranslationWallTimeMs, - totalTranslationEngineRequestCount, - queuedTranslationEngineRequestCount, - modelLoadNecessary, - modelDownloadNecessary, - modelDownloading, - modelDownloadProgress, - modelLoading, - modelLoaded, - translationFinished, - modelLoadErrorOccurred, - modelDownloadErrorOccurred, - translationErrorOccurred, - otherErrorOccurred, - }; - const tabTranslationState = new TabTranslationState_1.TabTranslationState(tabTranslationStateData); - map.set(tabId, tabTranslationState); - }); - return map; - } - tabSpecificDocumentTranslationStates(tabId) { - const result = []; - this.documentTranslationStates.forEach((documentTranslationState) => { - if (documentTranslationState.tabId === tabId) { - result.push(documentTranslationState); - } - }); - return result; - } - requestTranslationOfAllFramesInTab(tabId, from, to) { - // Request translation of all frames in a specific tab - this.tabSpecificDocumentTranslationStates(tabId).forEach((dts) => { - this.patchDocumentTranslationStateByFrameInfo(dts, [ - { - op: "replace", - path: ["translateFrom"], - value: from, - }, - { - op: "replace", - path: ["translateTo"], - value: to, - }, - { - op: "replace", - path: ["translationRequested"], - value: true, - }, - { - op: "replace", - path: ["translationStatus"], - value: BaseTranslationState_1.TranslationStatus.TRANSLATING, - }, - ]); - }); - } - showOriginalInTab(tabId) { - this.tabSpecificDocumentTranslationStates(tabId).forEach((dts) => { - this.patchDocumentTranslationStateByFrameInfo(dts, [ - { - op: "replace", - path: ["showOriginal"], - value: true, - }, - ]); - }); - } - hideOriginalInTab(tabId) { - this.tabSpecificDocumentTranslationStates(tabId).forEach((dts) => { - this.patchDocumentTranslationStateByFrameInfo(dts, [ - { - op: "replace", - path: ["showOriginal"], - value: false, - }, - ]); - }); - } -}; -__decorate([ - mobx_keystone_1.modelAction -], ExtensionState.prototype, "setDocumentTranslationState", null); -__decorate([ - mobx_keystone_1.modelAction -], ExtensionState.prototype, "patchDocumentTranslationStateByFrameInfo", null); -__decorate([ - mobx_keystone_1.modelAction -], ExtensionState.prototype, "deleteDocumentTranslationStateByFrameInfo", null); -__decorate([ - mobx_keystone_1.modelAction -], ExtensionState.prototype, "setTranslateOwnTextTranslationState", null); -__decorate([ - mobx_keystone_1.modelAction -], ExtensionState.prototype, "deleteTranslateOwnTextTranslationState", null); -__decorate([ - mobx_1.computed -], ExtensionState.prototype, "documentTranslationStatesByTabId", null); -__decorate([ - mobx_1.computed -], ExtensionState.prototype, "tabTranslationStates", null); -ExtensionState = __decorate([ - mobx_keystone_1.model("bergamotTranslate/ExtensionState") -], ExtensionState); -exports.ExtensionState = ExtensionState; - - -/***/ }), - -/***/ 6777: -/*!*****************************************************************!*\ - !*** ../core/ts/shared-resources/models/TabTranslationState.ts ***! - \*****************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TabTranslationState = void 0; -const mobx_keystone_1 = __webpack_require__(/*! mobx-keystone */ 4380); -const BaseTranslationState_1 = __webpack_require__(/*! ./BaseTranslationState */ 9359); -let TabTranslationState = class TabTranslationState extends mobx_keystone_1.ExtendedModel(BaseTranslationState_1.BaseTranslationState, { - windowId: mobx_keystone_1.prop(), - showOriginal: mobx_keystone_1.prop({ setterAction: true }), - url: mobx_keystone_1.prop(), -}) { -}; -TabTranslationState = __decorate([ - mobx_keystone_1.model("bergamotTranslate/TabTranslationState") -], TabTranslationState); -exports.TabTranslationState = TabTranslationState; - - -/***/ }), - -/***/ 6745: -/*!******************************************************************************!*\ - !*** ../core/ts/shared-resources/models/TranslateOwnTextTranslationState.ts ***! - \******************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TranslateOwnTextTranslationState = void 0; -const mobx_keystone_1 = __webpack_require__(/*! mobx-keystone */ 4380); -const BaseTranslationState_1 = __webpack_require__(/*! ./BaseTranslationState */ 9359); -let TranslateOwnTextTranslationState = class TranslateOwnTextTranslationState extends mobx_keystone_1.ExtendedModel(BaseTranslationState_1.BaseTranslationState, { - translateAutomatically: mobx_keystone_1.prop(true), -}) { -}; -TranslateOwnTextTranslationState = __decorate([ - mobx_keystone_1.model("bergamotTranslate/TranslateOwnTextTranslationState") -], TranslateOwnTextTranslationState); -exports.TranslateOwnTextTranslationState = TranslateOwnTextTranslationState; - - -/***/ }), - -/***/ 14: -/*!*********************************************************************************************!*\ - !*** ../core/ts/shared-resources/state-management/subscribeToExtensionPreferenceChanges.ts ***! - \*********************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - -"use strict"; - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.communicateExtensionPreferenceChangesToContentScripts = exports.subscribeToExtensionPreferenceChangesInContentScript = exports.subscribeToExtensionPreferenceChangesInBackgroundScript = void 0; -const webextension_polyfill_ts_1 = __webpack_require__(/*! webextension-polyfill-ts */ 5006); -const subscribeToExtensionPreferenceChangesInBackgroundScript = (store, callback) => __awaiter(void 0, void 0, void 0, function* () { - const extensionPreferences = yield store.getExtensionPreferences(); - callback(extensionPreferences); - const originalSetExtensionPreferences = store.setExtensionPreferences.bind(store); - store.setExtensionPreferences = ($extensionPreferences) => __awaiter(void 0, void 0, void 0, function* () { - yield originalSetExtensionPreferences($extensionPreferences); - callback(yield store.getExtensionPreferences()); - }); -}); -exports.subscribeToExtensionPreferenceChangesInBackgroundScript = subscribeToExtensionPreferenceChangesInBackgroundScript; -const subscribeToExtensionPreferenceChangesInContentScript = (portName, callback) => __awaiter(void 0, void 0, void 0, function* () { - const port = webextension_polyfill_ts_1.browser.runtime.connect(webextension_polyfill_ts_1.browser.runtime.id, { - name: portName, - }); - return new Promise((resolve, reject) => { - port.postMessage({ - requestExtensionPreferences: true, - }); - port.onMessage.addListener((m) => __awaiter(void 0, void 0, void 0, function* () { - if (m.extensionPreferences) { - const { extensionPreferences } = m; - callback(extensionPreferences); - resolve(); - } - reject("Unexpected message"); - })); - }); -}); -exports.subscribeToExtensionPreferenceChangesInContentScript = subscribeToExtensionPreferenceChangesInContentScript; -/** - * Set up communication channels with content scripts so that they - * can subscribe to changes in extension preferences - * @param store - * @param portNames - */ -const communicateExtensionPreferenceChangesToContentScripts = (store, portNames) => __awaiter(void 0, void 0, void 0, function* () { - const connectedPorts = {}; - // Broadcast updates to extension preferences - const originalSetExtensionPreferences = store.setExtensionPreferences.bind(store); - store.setExtensionPreferences = (extensionPreferences) => __awaiter(void 0, void 0, void 0, function* () { - yield originalSetExtensionPreferences(extensionPreferences); - Object.keys(connectedPorts).forEach((portName) => __awaiter(void 0, void 0, void 0, function* () { - const port = connectedPorts[portName]; - port.postMessage({ - extensionPreferences: yield store.getExtensionPreferences(), - }); - })); - }); - const extensionPreferencesContentScriptPortListener = (port) => { - if (!portNames.includes(port.name)) { - return; - } - port.onMessage.addListener(function (m) { - return __awaiter(this, void 0, void 0, function* () { - connectedPorts[port.name] = port; - // console.debug(`Message from port "${port.name}"`, { m }); - if (m.requestExtensionPreferences) { - port.postMessage({ - extensionPreferences: yield store.getExtensionPreferences(), - }); - } - if (m.saveExtensionPreferences) { - const { updatedExtensionPreferences } = m.saveExtensionPreferences; - yield store.setExtensionPreferences(updatedExtensionPreferences); - port.postMessage({ - extensionPreferences: yield store.getExtensionPreferences(), - }); - } - }); - }); - port.onDisconnect.addListener(($port) => { - delete connectedPorts[$port.name]; - }); - }; - webextension_polyfill_ts_1.browser.runtime.onConnect.addListener(extensionPreferencesContentScriptPortListener); - return extensionPreferencesContentScriptPortListener; -}); -exports.communicateExtensionPreferenceChangesToContentScripts = communicateExtensionPreferenceChangesToContentScripts; - - -/***/ }) - -}]); -//# sourceMappingURL=commons.js.map \ No newline at end of file diff --git a/browser/extensions/translations/extension/dom-translation-content-script.js b/browser/extensions/translations/extension/dom-translation-content-script.js deleted file mode 100644 index 8b53b9d124e5..000000000000 --- a/browser/extensions/translations/extension/dom-translation-content-script.js +++ /dev/null @@ -1,2824 +0,0 @@ -/******/ (() => { // webpackBootstrap -/******/ "use strict"; -/******/ var __webpack_modules__ = ({ - -/***/ 3550: -/*!*********************************************************************************************!*\ - !*** ../core/ts/content-scripts/dom-translation-content-script.js/DomTranslationManager.ts ***! - \*********************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this file, - * You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DomTranslationManager = void 0; -const TranslationDocument_1 = __webpack_require__(/*! ./TranslationDocument */ 3451); -const BergamotDomTranslator_1 = __webpack_require__(/*! ./dom-translators/BergamotDomTranslator */ 7668); -const ContentScriptLanguageDetectorProxy_1 = __webpack_require__(/*! ../../shared-resources/ContentScriptLanguageDetectorProxy */ 8341); -const BaseTranslationState_1 = __webpack_require__(/*! ../../shared-resources/models/BaseTranslationState */ 9359); -const LanguageSupport_1 = __webpack_require__(/*! ../../shared-resources/LanguageSupport */ 3872); -class DomTranslationManager { - constructor(documentTranslationStateCommunicator, document, contentWindow) { - this.documentTranslationStateCommunicator = documentTranslationStateCommunicator; - this.document = document; - this.contentWindow = contentWindow; - this.languageDetector = new ContentScriptLanguageDetectorProxy_1.ContentScriptLanguageDetectorProxy(); - } - getTranslationDocument() { - // If a TranslationDocument already exists for this document, it should - // be used instead of creating a new one so that we can use the original - // content of the page for the new translation instead of the newly - // translated text. - return (this.contentWindow.translationDocument || - new TranslationDocument_1.TranslationDocument(this.document)); - } - attemptToDetectLanguage() { - return __awaiter(this, void 0, void 0, function* () { - console.debug("Attempting to detect language"); - const url = String(this.document.location); - if (!url.startsWith("http://") && !url.startsWith("https://")) { - console.debug("Not a HTTP(S) url, translation unavailable", { url }); - this.documentTranslationStateCommunicator.broadcastUpdatedTranslationStatus(BaseTranslationState_1.TranslationStatus.UNAVAILABLE); - return; - } - console.debug("Setting status to reflect detection of language ongoing"); - this.documentTranslationStateCommunicator.broadcastUpdatedTranslationStatus(BaseTranslationState_1.TranslationStatus.DETECTING_LANGUAGE); - // Extract translation roots from the document - necessary for grabbing a sample for language detection - const startGetTranslationNodes = performance.now(); - const translationRoots = this.getTranslationDocument() - .translationRoots; - const endGetTranslationNodes = performance.now(); - console.info(`Extracting translation nodes from the document took ${(endGetTranslationNodes - - startGetTranslationNodes) / - 1000} seconds`); - // Grab a 60k sample of text from the page. - // (The CLD2 library used by the language detector is capable of - // analyzing raw HTML. Unfortunately, that takes much more memory, - // and since it's hosted by emscripten, and therefore can't shrink - // its heap after it's grown, it has a performance cost. - // So we send plain text instead.) - const startGrabSample = performance.now(); - const grabTranslationNodesSample = ($translationRoots, maxLength) => { - let totalLength = 0; - const textContents = []; - $translationRoots.some(translationItem => { - const textContent = translationItem.nodeRef.textContent; - textContents.push(textContent); - totalLength += textContent.length; - return totalLength >= maxLength; - }); - return textContents.join("\n").substr(0, maxLength); - }; - const string = grabTranslationNodesSample(translationRoots, 60 * 1024); - const endGrabSample = performance.now(); - console.info(`Grabbing a DOM sample for language detection took ${(endGrabSample - - startGrabSample) / - 1000} seconds`); - // console.debug("DOM sample for language detection:", { string }); - // Language detection isn't reliable on very short strings. - if (string.length < 100) { - console.debug("Language detection isn't reliable on very short strings. Skipping language detection", { string }); - this.documentTranslationStateCommunicator.broadcastUpdatedTranslationStatus(BaseTranslationState_1.TranslationStatus.LANGUAGE_NOT_DETECTED); - return; - } - const detectedLanguageResults = yield this.languageDetector.detectLanguage(string); - console.debug("Language detection results are in", { - detectedLanguageResults, - }); - // The window might be gone by now. - if (!this.contentWindow) { - console.info("Content window reference invalid, deleting document translation state"); - this.documentTranslationStateCommunicator.clear(); - return; - } - // Save results in extension state - this.documentTranslationStateCommunicator.updatedDetectedLanguageResults(detectedLanguageResults); - if (!detectedLanguageResults.confident) { - console.debug("Language detection results not confident enough, bailing.", { string }); - this.documentTranslationStateCommunicator.broadcastUpdatedTranslationStatus(BaseTranslationState_1.TranslationStatus.LANGUAGE_NOT_DETECTED); - return; - } - console.debug("Updating state to reflect that language has been detected"); - yield this.checkLanguageSupport(detectedLanguageResults); - }); - } - checkLanguageSupport(detectedLanguageResults) { - return __awaiter(this, void 0, void 0, function* () { - const { summarizeLanguageSupport } = new LanguageSupport_1.LanguageSupport(); - const detectedLanguage = detectedLanguageResults.language; - const { acceptedTargetLanguages, - // defaultSourceLanguage, - defaultTargetLanguage, supportedSourceLanguages, supportedTargetLanguagesGivenDefaultSourceLanguage, allPossiblySupportedTargetLanguages, } = yield summarizeLanguageSupport(detectedLanguageResults); - if (acceptedTargetLanguages.includes(detectedLanguage)) { - // Detected language is the same as the user's accepted target languages. - console.info("Detected language is in one of the user's accepted target languages.", { - acceptedTargetLanguages, - }); - this.documentTranslationStateCommunicator.broadcastUpdatedTranslationStatus(BaseTranslationState_1.TranslationStatus.SOURCE_LANGUAGE_UNDERSTOOD); - return; - } - if (!supportedSourceLanguages.includes(detectedLanguage)) { - // Detected language is not part of the supported source languages. - console.info("Detected language is not part of the supported source languages.", { detectedLanguage, supportedSourceLanguages }); - this.documentTranslationStateCommunicator.broadcastUpdatedTranslationStatus(BaseTranslationState_1.TranslationStatus.TRANSLATION_UNSUPPORTED); - return; - } - if (!allPossiblySupportedTargetLanguages.includes(defaultTargetLanguage)) { - // Detected language is not part of the supported source languages. - console.info("Default target language is not part of the supported target languages.", { - acceptedTargetLanguages, - defaultTargetLanguage, - allPossiblySupportedTargetLanguages, - }); - this.documentTranslationStateCommunicator.broadcastUpdatedTranslationStatus(BaseTranslationState_1.TranslationStatus.TRANSLATION_UNSUPPORTED); - return; - } - if (!defaultTargetLanguage || - !supportedTargetLanguagesGivenDefaultSourceLanguage.includes(defaultTargetLanguage)) { - // Combination of source and target languages unsupported - console.info("Combination of source and target languages unsupported.", { - acceptedTargetLanguages, - defaultTargetLanguage, - supportedTargetLanguagesGivenDefaultSourceLanguage, - }); - this.documentTranslationStateCommunicator.broadcastUpdatedTranslationStatus(BaseTranslationState_1.TranslationStatus.TRANSLATION_UNSUPPORTED); - return; - } - this.documentTranslationStateCommunicator.broadcastUpdatedTranslationStatus(BaseTranslationState_1.TranslationStatus.OFFER); - }); - } - doTranslation(from, to) { - return __awaiter(this, void 0, void 0, function* () { - const translationDocument = this.getTranslationDocument(); - console.info("Translating web page"); - const domTranslator = new BergamotDomTranslator_1.BergamotDomTranslator(translationDocument, from, to); - this.contentWindow.translationDocument = translationDocument; - translationDocument.translatedFrom = from; - translationDocument.translatedTo = to; - translationDocument.translationError = false; - try { - console.info(`About to translate web page document (${translationDocument.translationRoots.length} translation items)`, { from, to }); - // TODO: Timeout here to be able to abort UI in case translation hangs - yield domTranslator.translate((frameTranslationProgress) => { - this.documentTranslationStateCommunicator.broadcastUpdatedFrameTranslationProgress(frameTranslationProgress); - }); - console.info(`Translation of web page document completed (translated ${translationDocument.translationRoots.filter(translationRoot => translationRoot.currentDisplayMode === "translation").length} out of ${translationDocument.translationRoots.length} translation items)`, { from, to }); - console.info("Translated web page"); - } - catch (err) { - console.warn("Translation error occurred: ", err); - translationDocument.translationError = true; - } - finally { - // Positioned in finally-clause so that it gets communicated whether the - // translation attempt resulted in some translated content or not - this.documentTranslationStateCommunicator.broadcastTranslationAttemptConcluded(translationDocument.translationError, domTranslator.derivedTranslationDocumentData); - // Communicate that errors occurred - domTranslator.errorsEncountered.forEach((error) => { - if (error.name === "BergamotTranslatorAPIModelLoadError") { - this.documentTranslationStateCommunicator.broadcastUpdatedAttributeValue("modelLoadErrorOccurred", true); - } - else if (error.name === "BergamotTranslatorAPIModelDownloadError") { - this.documentTranslationStateCommunicator.broadcastUpdatedAttributeValue("modelDownloadErrorOccurred", true); - } - else if (error.name === "BergamotTranslatorAPITranslationError") { - this.documentTranslationStateCommunicator.broadcastUpdatedAttributeValue("translationErrorOccurred", true); - } - else { - this.documentTranslationStateCommunicator.broadcastUpdatedAttributeValue("otherErrorOccurred", true); - } - }); - } - }); - } -} -exports.DomTranslationManager = DomTranslationManager; - - -/***/ }), - -/***/ 3451: -/*!*******************************************************************************************!*\ - !*** ../core/ts/content-scripts/dom-translation-content-script.js/TranslationDocument.ts ***! - \*******************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.generateMarkupToTranslateForItem = exports.TranslationDocument = void 0; -const getTranslationNodes_1 = __webpack_require__(/*! ./getTranslationNodes */ 2542); -const TranslationItem_1 = __webpack_require__(/*! ./TranslationItem */ 664); -/** - * This class represents a document that is being translated, - * and it is responsible for parsing the document, - * generating the data structures translation (the list of - * translation items and roots), and managing the original - * and translated texts on the translation items. - * - * @param document The document to be translated - */ -class TranslationDocument { - constructor(document) { - this.translatedFrom = ""; - this.translatedTo = ""; - this.translationError = false; - this.originalShown = true; - this.qualityEstimationShown = true; - // Set temporarily to true during development to visually inspect which nodes have been processed and in which way - this.paintProcessedNodes = false; - this.nodeTranslationItemsMap = new Map(); - this.translationRoots = []; - this._init(document); - } - /** - * Initializes the object and populates - * the translation roots lists. - * - * @param document The document to be translated - */ - _init(document) { - // Get all the translation nodes in the document's body: - // a translation node is a node from the document which - // contains useful content for translation, and therefore - // must be included in the translation process. - const translationNodes = getTranslationNodes_1.getTranslationNodes(document.body); - console.info(`The document has a total of ${translationNodes.length} translation nodes, of which ${translationNodes.filter(tn => tn.isTranslationRoot).length} are translation roots`); - translationNodes.forEach((translationNode, index) => { - const { content, isTranslationRoot } = translationNode; - if (this.paintProcessedNodes) { - content.style.backgroundColor = "darkorange"; - } - // Create a TranslationItem object for this node. - // This function will also add it to the this.translationRoots array. - this._createItemForNode(content, index, isTranslationRoot); - }); - // At first all translation roots are stored in the translation roots list, and only after - // the process has finished we're able to determine which translation roots are - // simple, and which ones are not. - // A simple root is defined by a translation root with no children items, which - // basically represents an element from a page with only text content - // inside. - // This distinction is useful for optimization purposes: we treat a - // simple root as plain-text in the translation process and with that - // we are able to reduce their data payload sent to the translation service. - for (const translationRoot of this.translationRoots) { - if (!translationRoot.children.length && - translationRoot.nodeRef instanceof Element && - translationRoot.nodeRef.childElementCount === 0) { - translationRoot.isSimleTranslationRoot = true; - if (this.paintProcessedNodes) { - translationRoot.nodeRef.style.backgroundColor = "orange"; - } - } - } - } - /** - * Creates a TranslationItem object, which should be called - * for each node returned by getTranslationNodes. - * - * @param node The DOM node for this item. - * @param id A unique, numeric id for this item. - * @param isTranslationRoot A boolean saying whether this item is a translation root. - * - * @returns A TranslationItem object. - */ - _createItemForNode(node, id, isTranslationRoot) { - if (this.nodeTranslationItemsMap.has(node)) { - return this.nodeTranslationItemsMap.get(node); - } - const item = new TranslationItem_1.TranslationItem(node, id, isTranslationRoot); - if (isTranslationRoot) { - // Translation root items do not have a parent item. - this.translationRoots.push(item); - } - else { - // Other translation nodes have at least one ancestor which is a translation root - let ancestorTranslationItem; - for (let ancestor = node.parentNode; ancestor; ancestor = ancestor.parentNode) { - ancestorTranslationItem = this.nodeTranslationItemsMap.get(ancestor); - if (ancestorTranslationItem) { - ancestorTranslationItem.children.push(item); - break; - } - else { - // make intermediate ancestors link to the descendent translation item - // so that it gets picked up on in generateOriginalStructureElements - this.nodeTranslationItemsMap.set(ancestor, item); - } - } - } - this.nodeTranslationItemsMap.set(node, item); - return item; - } - /** - * Generate the markup that represents a TranslationItem object. - * Besides generating the markup, it also stores a fuller representation - * of the TranslationItem in the "original" field of the TranslationItem object, - * which needs to be stored for later to be used in the "Show Original" functionality. - * If this function had already been called for the given item (determined - * by the presence of the "original" array in the item), the markup will - * be regenerated from the "original" data instead of from the related - * DOM nodes (because the nodes might contain translated data). - * - * @param item A TranslationItem object - * - * @returns A markup representation of the TranslationItem. - */ - generateMarkupToTranslate(item) { - if (!item.original) { - item.original = this.generateOriginalStructureElements(item); - } - return regenerateMarkupToTranslateFromOriginal(item); - } - /** - * Generates a fuller representation of the TranslationItem - * @param item - */ - generateOriginalStructureElements(item) { - const original = []; - if (item.isSimleTranslationRoot) { - const text = item.nodeRef.firstChild.nodeValue.trim(); - original.push(text); - return original; - } - let wasLastItemPlaceholder = false; - for (const child of Array.from(item.nodeRef.childNodes)) { - if (child.nodeType === child.TEXT_NODE) { - const x = child.nodeValue; - const hasLeadingWhitespace = x.length !== x.trimStart().length; - const hasTrailingWhitespace = x.length !== x.trimEnd().length; - if (x.trim() !== "") { - const xWithNormalizedWhitespace = `${hasLeadingWhitespace ? " " : ""}${x.trim()}${hasTrailingWhitespace ? " " : ""}`; - original.push(xWithNormalizedWhitespace); - wasLastItemPlaceholder = false; - } - continue; - } - const objInMap = this.nodeTranslationItemsMap.get(child); - if (objInMap && !objInMap.isTranslationRoot) { - // If this childNode is present in the nodeTranslationItemsMap, it means - // it's a translation node: it has useful content for translation. - // In this case, we need to stringify this node. - // However, if this item is a translation root, we should skip it here in this - // object's child list (and just add a placeholder for it), because - // it will be stringified separately for being a translation root. - original.push(objInMap); - objInMap.original = this.generateOriginalStructureElements(objInMap); - wasLastItemPlaceholder = false; - } - else if (!wasLastItemPlaceholder) { - // Otherwise, if this node doesn't contain any useful content, - // or if it is a translation root itself, we can replace it with a placeholder node. - // We can't simply eliminate this node from our string representation - // because that could change the HTML structure (e.g., it would - // probably merge two separate text nodes). - // It's not necessary to add more than one placeholder in sequence; - // we can optimize them away. - original.push(new TranslationItem_1.TranslationItem_NodePlaceholder()); - wasLastItemPlaceholder = true; - } - } - return original; - } - /** - * Changes the document to display its translated - * content. - */ - showTranslation() { - this.originalShown = false; - this.qualityEstimationShown = false; - this._swapDocumentContent("translation"); - } - /** - * Changes the document to display its original - * content. - */ - showOriginal() { - this.originalShown = true; - this.qualityEstimationShown = false; - this._swapDocumentContent("original"); - // TranslationTelemetry.recordShowOriginalContent(); - } - /** - * Changes the document to display the translation with quality estimation metadata - * content. - */ - showQualityEstimation() { - this.originalShown = false; - this.qualityEstimationShown = true; - this._swapDocumentContent("qeAnnotatedTranslation"); - } - /** - * Swap the document with the resulting translation, - * or back with the original content. - */ - _swapDocumentContent(target) { - (() => __awaiter(this, void 0, void 0, function* () { - this.translationRoots - .filter(translationRoot => translationRoot.currentDisplayMode !== target) - .forEach(translationRoot => translationRoot.swapText(target, this.paintProcessedNodes)); - // TODO: Make sure that the above does not lock the main event loop - /* - // Let the event loop breath on every 100 nodes - // that are replaced. - const YIELD_INTERVAL = 100; - await Async.yieldingForEach( - this.roots, - root => root.swapText(target, this.paintProcessedNodes), - YIELD_INTERVAL - ); - */ - }))(); - } - determineVisibilityOfTranslationRoots() { - return __awaiter(this, void 0, void 0, function* () { - const { translationRoots } = this; - // Short-circuit this process in case the document is empty, or else - // it will hang, waiting for any visible elements - if (translationRoots.length === 0) { - return { - translationRoots: [], - translationRootsVisible: [], - translationRootsVisibleInViewport: [], - }; - } - const elements = translationRoots.map(translationRoot => translationRoot.nodeRef); - const elementsVisibleInViewport = yield getElementsVisibleInViewport(elements); - const translationRootsVisible = []; - const translationRootsVisibleInViewport = []; - for (let i = 0; i < translationRoots.length; i++) { - const translationRoot = translationRoots[i]; - const visible = isElementVisible(translationRoot.nodeRef); - if (visible) { - translationRootsVisible.push(translationRoot); - } - const visibleInViewport = isElementVisibleInViewport(elementsVisibleInViewport, translationRoot.nodeRef); - if (visibleInViewport) { - translationRootsVisibleInViewport.push(translationRoot); - } - } - if (this.paintProcessedNodes) { - translationRootsVisible.forEach(translationRoot => { - translationRoot.nodeRef.style.color = "purple"; - }); - translationRootsVisibleInViewport.forEach(translationRoot => { - translationRoot.nodeRef.style.color = "maroon"; - }); - } - return { - translationRoots, - translationRootsVisible, - translationRootsVisibleInViewport, - }; - }); - } -} -exports.TranslationDocument = TranslationDocument; -/** - * Generate the translation markup for a given item. - * - * @param item A TranslationItem object. - * @param content The inner content for this item. - * @returns string The outer HTML needed for translation - * of this item. - */ -function generateMarkupToTranslateForItem(item, content) { - const localName = item.isTranslationRoot ? "div" : "b"; - return ("<" + localName + " id=n" + item.id + ">" + content + ""); -} -exports.generateMarkupToTranslateForItem = generateMarkupToTranslateForItem; -/** - * Regenerate the markup that represents a TranslationItem object, - * with data from its "original" array. The array must have already - * been created by TranslationDocument.generateMarkupToTranslate(). - * - * @param item A TranslationItem object - * - * @returns A markup representation of the TranslationItem. - */ -function regenerateMarkupToTranslateFromOriginal(item) { - if (item.isSimleTranslationRoot) { - return item.original[0]; - } - let str = ""; - for (const child of item.original) { - if (child instanceof TranslationItem_1.TranslationItem) { - str += regenerateMarkupToTranslateFromOriginal(child); - } - else if (child instanceof TranslationItem_1.TranslationItem_NodePlaceholder) { - str += "
"; - } - else { - str += child; - } - } - return generateMarkupToTranslateForItem(item, str); -} -const isElementVisible = (el) => { - const rect = el.getBoundingClientRect(); - // Elements that are not visible will have a zero width/height bounding client rect - return rect.width > 0 && rect.height > 0; -}; -const isElementVisibleInViewport = (elementsVisibleInViewport, el) => { - return !!elementsVisibleInViewport.filter($el => $el === el).length; -}; -const getElementsVisibleInViewport = (elements) => __awaiter(void 0, void 0, void 0, function* () { - return new Promise(resolve => { - const options = { - threshold: 0.0, - }; - const callback = (entries, $observer) => { - // console.debug("InteractionObserver callback", entries.length, entries); - const elementsInViewport = entries - .filter(entry => entry.isIntersecting) - .map(entry => entry.target); - $observer.disconnect(); - resolve(elementsInViewport); - }; - const observer = new IntersectionObserver(callback, options); - elements.forEach(el => observer.observe(el)); - }); -}); - - -/***/ }), - -/***/ 664: -/*!***************************************************************************************!*\ - !*** ../core/ts/content-scripts/dom-translation-content-script.js/TranslationItem.ts ***! - \***************************************************************************************/ -/***/ ((__unused_webpack_module, exports) => { - - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.TranslationItem_NodePlaceholder = exports.TranslationItem = void 0; -/** - * This class represents an item for translation. It's basically our - * wrapper class around a node returned by getTranslationNode, with - * more data and structural information on it. - * - * At the end of the translation process, besides the properties below, - * a TranslationItem will contain two other properties: one called "original" - * and one called "translation". They are twin objects, one which reflect - * the structure of that node in its original state, and the other in its - * translated state. - * - * The "original" array is generated in the - * TranslationDocument.generateMarkupToTranslate function, - * and the "translation" array is generated when the translation results - * are parsed. - * - * They are both arrays, which contain a mix of strings and references to - * child TranslationItems. The references in both arrays point to the * same * - * TranslationItem object, but they might appear in different orders between the - * "original" and "translation" arrays. - * - * An example: - * - * English:
Welcome to Mozilla's website
- * Portuguese:
Bem vindo a pagina da Mozilla
- * - * TranslationItem n1 = { - * id: 1, - * original: ["Welcome to", ptr to n2, "website"] - * translation: ["Bem vindo a pagina", ptr to n2] - * } - * - * TranslationItem n2 = { - * id: 2, - * original: ["Mozilla's"], - * translation: ["da Mozilla"] - * } - */ -class TranslationItem { - constructor(node, id, isTranslationRoot) { - this.isTranslationRoot = false; - this.isSimleTranslationRoot = false; - this.children = []; - this.nodeRef = node; - this.id = id; - this.isTranslationRoot = isTranslationRoot; - } - toString() { - let rootType = ""; - if (this.isTranslationRoot) { - if (this.isSimleTranslationRoot) { - rootType = " (simple root)"; - } - else { - rootType = " (non simple root)"; - } - } - return ("[object TranslationItem: <" + - this.nodeRef.toString() + - ">" + - rootType + - "]"); - } - /** - * This function will parse the result of the translation of one translation - * item. If this item was a simple root, all we sent was a plain-text version - * of it, so the result is also straightforward text. - * - * For non-simple roots, we sent a simplified HTML representation of that - * node, and we'll first parse that into an HTML doc and then call the - * parseResultNode helper function to parse it. - * - * While parsing, the result is stored in the "translation" field of the - * TranslationItem, which will be used to display the final translation when - * all items are finished. It remains stored too to allow back-and-forth - * switching between the "Show Original" and "Show Translation" functions. - * - * @param translatedMarkup A string with the textual result received from the translation engine, - * which can be plain-text or a serialized HTML doc. - */ - parseTranslationResult(translatedMarkup) { - this.translatedMarkup = translatedMarkup; - if (this.isSimleTranslationRoot) { - // If translation contains HTML entities, we need to convert them. - // It is because simple roots expect a plain text result. - if (this.isSimleTranslationRoot && - translatedMarkup.match(/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});/gi)) { - const doc = new DOMParser().parseFromString(translatedMarkup, "text/html"); - translatedMarkup = doc.body.firstChild.nodeValue; - } - this.translation = [translatedMarkup]; - return; - } - const domParser = new DOMParser(); - const doc = domParser.parseFromString(translatedMarkup, "text/html"); - this.translation = []; - parseResultNode(this, doc.body.firstChild, "translation"); - } - /** - * Note: QE-annotated translation results are never plain text nodes, despite that - * the original translation item may be a simple translation root. - * This wreaks havoc. - * @param qeAnnotatedTranslatedMarkup - */ - parseQeAnnotatedTranslationResult(qeAnnotatedTranslatedMarkup) { - const domParser = new DOMParser(); - const doc = domParser.parseFromString(qeAnnotatedTranslatedMarkup, "text/html"); - this.qeAnnotatedTranslation = []; - parseResultNode(this, doc.body.firstChild, "qeAnnotatedTranslation"); - } - /** - * This function finds a child TranslationItem - * with the given id. - * @param id The id to look for, in the format "n#" - * @returns A TranslationItem with the given id, or null if - * it was not found. - */ - getChildById(id) { - for (const child of this.children) { - const childId = "n" + child.id; - if (childId === id) { - return child; - } - } - return null; - } - /** - * Swap the text of this TranslationItem between - * its original and translated states. - */ - swapText(target, paintProcessedNodes) { - swapTextForItem(this, target, paintProcessedNodes); - } -} -exports.TranslationItem = TranslationItem; -/** - * This object represents a placeholder item for translation. It's similar to - * the TranslationItem class, but it represents nodes that have no meaningful - * content for translation. These nodes will be replaced by "
" in a - * translation request. It's necessary to keep them to use it as a mark - * for correct positioning and splitting of text nodes. - */ -class TranslationItem_NodePlaceholder { - static toString() { - return "[object TranslationItem_NodePlaceholder]"; - } -} -exports.TranslationItem_NodePlaceholder = TranslationItem_NodePlaceholder; -/** - * Helper function to parse a HTML doc result. - * How it works: - * - * An example result string is: - * - *
Hello World of Mozilla.
- * - * For an element node, we look at its id and find the corresponding - * TranslationItem that was associated with this node, and then we - * walk down it repeating the process. - * - * For text nodes we simply add it as a string. - */ -function parseResultNode(item, node, target) { - try { - const into = item[target]; - // @ts-ignore - for (const child of node.childNodes) { - if (child.nodeType === Node.TEXT_NODE) { - into.push(child.nodeValue); - } - else if (child.localName === "br") { - into.push(new TranslationItem_NodePlaceholder()); - } - else if (child.dataset && - typeof child.dataset.translationQeScore !== "undefined") { - // handle the special case of quality estimate annotated nodes - into.push(child); - } - else { - const translationRootChild = item.getChildById(child.id); - if (translationRootChild) { - into.push(translationRootChild); - translationRootChild[target] = []; - parseResultNode(translationRootChild, child, target); - } - else { - console.warn(`Result node's (belonging to translation item with id ${item.id}) child node (child.id: ${child.id}) lacks an associated translation root child`, { item, node, child }); - } - } - } - } - catch (err) { - console.error(err); - throw err; - } -} -/* eslint-disable complexity */ -// TODO: Simplify swapTextForItem to avoid the following eslint error: -// Function 'swapTextForItem' has a complexity of 35. Maximum allowed is 34 complexity -/** - * Helper function to swap the text of a TranslationItem - * between its original and translated states. - * How it works: - * - * The function iterates through the target array (either the `original` or - * `translation` array from the TranslationItem), while also keeping a pointer - * to a current position in the child nodes from the actual DOM node that we - * are modifying. This pointer is moved forward after each item of the array - * is translated. If, at any given time, the pointer doesn't match the expected - * node that was supposed to be seen, it means that the original and translated - * contents have a different ordering, and thus we need to adjust that. - * - * A full example of the reordering process, swapping from Original to - * Translation: - * - * Original (en):
I miss you
- * - * Translation (fr):
Tu me manques
- * - * Step 1: - * pointer points to firstChild of the DOM node, textnode "I " - * first item in item.translation is [object TranslationItem ] - * - * pointer does not match the expected element, . So let's move to the - * pointer position. - * - * Current state of the DOM: - *
youI miss
- * - * Step 2: - * pointer moves forward to nextSibling, textnode "I " again. - * second item in item.translation is the string " me " - * - * pointer points to a text node, and we were expecting a text node. Match! - * just replace the text content. - * - * Current state of the DOM: - *
you me miss
- * - * Step 3: - * pointer moves forward to nextSibling, miss - * third item in item.translation is [object TranslationItem ] - * - * pointer points to the expected node. Match! Nothing to do. - * - * Step 4: - * all items in this item.translation were transformed. The remaining - * text nodes are cleared to "", and domNode.normalize() removes them. - * - * Current state of the DOM: - *
you me miss
- * - * Further steps: - * After that, the function will visit the child items (from the visitStack), - * and the text inside the and nodes will be swapped as well, - * yielding the final result: - * - *
Tu me manques
- */ -function swapTextForItem(item, target, paintProcessedNodes) { - // visitStack is the stack of items that we still need to visit. - // Let's start the process by adding the translation root item. - const visitStack = [item]; - if (paintProcessedNodes) { - item.nodeRef.style.border = "1px solid maroon"; - } - while (visitStack.length) { - const curItem = visitStack.shift(); - if (paintProcessedNodes) { - item.nodeRef.style.border = "1px solid yellow"; - } - const domNode = curItem.nodeRef; - if (!domNode) { - // Skipping this item due to a missing node. - continue; - } - if (!curItem[target]) { - // Translation not found for this item. This could be due to - // the translation not yet being available from the translation engine - // For example, if a translation was broken in various - // chunks, and not all of them has completed, the items from that - // chunk will be missing its "translation" field. - if (paintProcessedNodes) { - curItem.nodeRef.style.border = "1px solid red"; - } - continue; - } - domNode.normalize(); - if (paintProcessedNodes) { - curItem.nodeRef.style.border = "1px solid green"; - } - // curNode points to the child nodes of the DOM node that we are - // modifying. During most of the process, while the target array is - // being iterated (in the for loop below), it should walk together with - // the array and be pointing to the correct node that needs to modified. - // If it's not pointing to it, that means some sort of node reordering - // will be necessary to produce the correct translation. - // Note that text nodes don't need to be reordered, as we can just replace - // the content of one text node with another. - // - // curNode starts in the firstChild... - let curNode = domNode.firstChild; - if (paintProcessedNodes && curNode instanceof HTMLElement) { - curNode.style.border = "1px solid blue"; - } - // ... actually, let's make curNode start at the first useful node (either - // a non-blank text node or something else). This is not strictly necessary, - // as the reordering algorithm would correctly handle this case. However, - // this better aligns the resulting translation with the DOM content of the - // page, avoiding cases that would need to be unnecessarily reordered. - // - // An example of how this helps: - // - // ---- Original:
Hello world.
- // ^textnode 1 ^item 1 ^textnode 2 - // - // - Translation:
Hallo Welt.
- // - // Transformation process without this optimization: - // 1 - start pointer at textnode 1 - // 2 - move item 1 to first position inside the
- // - // Node now looks like:
Hello [ ][ world.]
- // textnode 1^ ^textnode 2 - // - // 3 - replace textnode 1 with " Welt." - // 4 - clear remaining text nodes (in this case, textnode 2) - // - // Transformation process with this optimization: - // 1 - start pointer at item 1 - // 2 - item 1 is already in position - // 3 - replace textnode 2 with " Welt." - // - // which completely avoids any node reordering, and requires only one - // text change instead of two (while also leaving the page closer to - // its original state). - while (curNode && - curNode.nodeType === Node.TEXT_NODE && - curNode.nodeValue.trim() === "") { - curNode = curNode.nextSibling; - } - // Now let's walk through all items in the `target` array of the - // TranslationItem. This means either the TranslationItem.original or - // TranslationItem.translation array. - for (const targetItem of curItem[target]) { - if (targetItem instanceof TranslationItem) { - // If the array element is another TranslationItem object, let's - // add it to the stack to be visited. - visitStack.push(targetItem); - const targetNode = targetItem.nodeRef; - // If the node is not in the expected position, let's reorder - // it into position... - if (curNode !== targetNode && - // ...unless the page has reparented this node under a totally - // different node (or removed it). In this case, all bets are off - // on being able to do anything correctly, so it's better not to - // bring back the node to this parent. - // @ts-ignore - targetNode.parentNode === domNode) { - // We don't need to null-check curNode because insertBefore(..., null) - // does what we need in that case: reorder this node to the end - // of child nodes. - domNode.insertBefore(targetNode, curNode); - curNode = targetNode; - } - // Move pointer forward. Since we do not add empty text nodes to the - // list of translation items, we must skip them here too while - // traversing the DOM in order to get better alignment between the - // text nodes and the translation items. - if (curNode) { - curNode = getNextSiblingSkippingEmptyTextNodes(curNode); - } - } - else if (targetItem instanceof TranslationItem_NodePlaceholder) { - // If the current item is a placeholder node, we need to move - // our pointer "past" it, jumping from one side of a block of - // elements + empty text nodes to the other side. Even if - // non-placeholder elements exists inside the jumped block, - // they will be pulled correctly later in the process when the - // targetItem for those nodes are handled. - while (curNode && - (curNode.nodeType !== Node.TEXT_NODE || - curNode.nodeValue.trim() === "")) { - curNode = curNode.nextSibling; - } - } - else { - // Finally, if it's a text item, we just need to find the next - // text node to use. Text nodes don't need to be reordered, so - // the first one found can be used. - while (curNode && curNode.nodeType !== Node.TEXT_NODE) { - curNode = curNode.nextSibling; - } - // If none was found and we reached the end of the child nodes, - // let's create a new one. - if (!curNode) { - // We don't know if the original content had a space or not, - // so the best bet is to create the text node with " " which - // will add one space at the beginning and one at the end. - curNode = domNode.appendChild(domNode.ownerDocument.createTextNode(" ")); - } - if (target === "translation") { - // A trailing and a leading space must be preserved because - // they are meaningful in HTML. - const preSpace = /^\s/.test(curNode.nodeValue) ? " " : ""; - const endSpace = /\s$/.test(curNode.nodeValue) ? " " : ""; - curNode.nodeValue = preSpace + targetItem + endSpace; - } - else { - curNode.nodeValue = targetItem; - } - if (["original", "translation"].includes(target)) { - // Workaround necessary when switching "back" from QE display - // since quality estimated annotated nodes - // replaced the simple text nodes of the original document - // @ts-ignore - for (const child of curNode.parentNode.childNodes) { - if (child.dataset && - typeof child.dataset.translationQeScore !== "undefined") { - // There should be only 1 such node. Remove the curNode from the - // parent's children and replace the qe-annotated node with it to - // maintain the right order in original DOM tree of the document. - curNode.remove(); - child.parentNode.replaceChild(curNode, child); - } - } - curNode = getNextSiblingSkippingEmptyTextNodes(curNode); - } - else if (target === "qeAnnotatedTranslation") { - const nextSibling = getNextSiblingSkippingEmptyTextNodes(curNode); - // Replace the text node with the qe-annotated node to maintain the - // right order in original DOM tree of the document. - curNode.parentNode.replaceChild(targetItem, curNode); - curNode = nextSibling; - } - } - } - // The translated version of a node might have less text nodes than its - // original version. If that's the case, let's clear the remaining nodes. - if (curNode) { - clearRemainingNonEmptyTextNodesFromElement(curNode); - } - // And remove any garbage "" nodes left after clearing. - domNode.normalize(); - // Mark the translation item as displayed in the requested target - curItem.currentDisplayMode = target; - if (paintProcessedNodes) { - curItem.nodeRef.style.border = "2px solid green"; - } - } -} -/* eslint-enable complexity */ -function getNextSiblingSkippingEmptyTextNodes(startSibling) { - let item = startSibling.nextSibling; - while (item && - item.nodeType === Node.TEXT_NODE && - item.nodeValue.trim() === "") { - item = item.nextSibling; - } - return item; -} -function clearRemainingNonEmptyTextNodesFromElement(startSibling) { - let item = startSibling; - while (item) { - if (item.nodeType === Node.TEXT_NODE && item.nodeValue !== "") { - item.nodeValue = ""; - } - item = item.nextSibling; - } -} - - -/***/ }), - -/***/ 1896: -/*!*********************************************************************************************************!*\ - !*** ../core/ts/content-scripts/dom-translation-content-script.js/dom-translators/BaseDomTranslator.ts ***! - \*********************************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BaseDomTranslator = exports.DomTranslatorError = void 0; -const MinimalDomTranslator_1 = __webpack_require__(/*! ./MinimalDomTranslator */ 3301); -const detagAndProject_1 = __webpack_require__(/*! ./detagAndProject */ 3770); -class DomTranslatorError extends Error { - constructor() { - super(...arguments); - this.name = "DomTranslatorError"; - } -} -exports.DomTranslatorError = DomTranslatorError; -/** - * Base class for DOM translators that splits the document into several chunks - * respecting the data limits of the backing API. - */ -class BaseDomTranslator extends MinimalDomTranslator_1.MinimalDomTranslator { - /** - * @param translationDocument The TranslationDocument object that represents - * the webpage to be translated - * @param sourceLanguage The source language of the document - * @param targetLanguage The target language for the translation - * @param translationApiClient - * @param parseChunkResult - * @param translationApiLimits - * @param domTranslatorRequestFactory - */ - constructor(translationDocument, sourceLanguage, targetLanguage, translationApiClient, parseChunkResult, translationApiLimits, domTranslatorRequestFactory) { - super(translationDocument, sourceLanguage, targetLanguage); - this.translatedCharacterCount = 0; - this.errorsEncountered = []; - this.partialSuccess = false; - this.translationApiClient = translationApiClient; - this.parseChunkResult = parseChunkResult; - this.translationApiLimits = translationApiLimits; - this.domTranslatorRequestFactory = domTranslatorRequestFactory; - } - /** - * Performs the translation, splitting the document into several chunks - * respecting the data limits of the API. - * - * @returns {Promise} A promise that will resolve when the translation - * task is finished. - */ - translate(frameTranslationProgressCallback) { - return __awaiter(this, void 0, void 0, function* () { - const chunksBeingProcessed = []; - const { MAX_REQUESTS } = this.translationApiLimits; - // Derive document translation data upfront - const startDeriveDocumentTranslationData = performance.now(); - this.derivedTranslationDocumentData = yield this.deriveDocumentTranslationData(); - console.log({ - derivedTranslationDocumentData: this.derivedTranslationDocumentData, - }); - const endDeriveDocumentTranslationData = performance.now(); - console.info(`Deriving document translation data took ${(endDeriveDocumentTranslationData - - startDeriveDocumentTranslationData) / - 1000} seconds`); - const { translationRoots, translationRootsVisible, translationRootsVisibleInViewport, } = this.derivedTranslationDocumentData; - this.translationRootsPickedUpForTranslation = []; - const progressOfIndividualTranslationRequests = new Map(); - // Split the document into various requests to be sent to the translation API - for (let currentRequestOrdinal = 0; currentRequestOrdinal < MAX_REQUESTS; currentRequestOrdinal++) { - // Determine the data for the next request. - const domTranslationChunk = this.generateNextDomTranslationChunk(translationRoots, translationRootsVisible, translationRootsVisibleInViewport); - // Break if there was nothing left to translate - if (domTranslationChunk.translationRoots.length === 0) { - break; - } - // Create a real request for the translation engine and add it to the pending requests list. - const translationRequestData = domTranslationChunk.translationRequestData; - const domTranslatorRequest = this.domTranslatorRequestFactory(translationRequestData, this.sourceLanguage, this.targetLanguage); - // Fire off the requests in parallel to existing requests - const chunkBeingProcessed = domTranslatorRequest.fireRequest(this.translationApiClient, (translationRequestProgress) => { - progressOfIndividualTranslationRequests.set(translationRequestProgress.requestId, translationRequestProgress); - frameTranslationProgressCallback({ - progressOfIndividualTranslationRequests, - }); - }); - chunksBeingProcessed.push(chunkBeingProcessed); - chunkBeingProcessed - .then((translationResponseData) => { - if (translationResponseData) { - this.chunkCompleted(translationResponseData, domTranslationChunk, domTranslatorRequest); - } - else { - throw new Error("The returned translationResponseData was false/empty"); - } - }) - .catch(err => { - this.errorsEncountered.push(err); - }); - console.info(`Fired off request with ${domTranslationChunk.translationRoots.length} translation roots to the translation backend`, { domTranslationChunk }); - if (domTranslationChunk.isLastChunk) { - break; - } - // Warn if we still have content left to translate but have reached the MAX_REQUESTS limit - if (!domTranslationChunk.isLastChunk && - currentRequestOrdinal === MAX_REQUESTS - 1) { - console.warn(`We have reached the MAX_REQUESTS limit of ${MAX_REQUESTS} requests. Remaining parts of the page will be left untranslated`); - } - } - // Return early with a noop if there is nothing to translate - if (chunksBeingProcessed.length === 0) { - console.info("Found nothing to translate"); - return { characterCount: 0 }; - } - console.info(`Fired off ${chunksBeingProcessed.length} requests to the translation backend`); - // Wait for all requests to settle - yield Promise.allSettled(chunksBeingProcessed); - // Surface encountered errors - if (this.errorsEncountered.length) { - console.warn("Errors were encountered during translation", this.errorsEncountered); - } - // If at least one chunk was successful, the - // translation should be displayed, albeit incomplete. - // Otherwise, the "Error" state will appear. - if (!this.partialSuccess) { - throw new DomTranslatorError("No content was translated"); - } - return { - characterCount: this.translatedCharacterCount, - }; - }); - } - deriveDocumentTranslationData() { - return __awaiter(this, void 0, void 0, function* () { - const { translationRoots, translationRootsVisible, translationRootsVisibleInViewport, } = yield this.translationDocument.determineVisibilityOfTranslationRoots(); - const generateOriginalMarkupToTranslate = translationRoot => this.translationDocument.generateMarkupToTranslate(translationRoot); - const removeTags = originalString => { - const detaggedString = detagAndProject_1.detag(originalString); - return detaggedString.plainString; - }; - const texts = translationRoots - .map(generateOriginalMarkupToTranslate) - .map(removeTags); - const textsVisible = translationRootsVisible - .map(generateOriginalMarkupToTranslate) - .map(removeTags); - const textsVisibleInViewport = translationRootsVisibleInViewport - .map(generateOriginalMarkupToTranslate) - .map(removeTags); - const wordCount = texts.join(" ").split(" ").length; - const wordCountVisible = textsVisible.join(" ").split(" ").length; - const wordCountVisibleInViewport = textsVisibleInViewport - .join(" ") - .split(" ").length; - const translationRootsCount = translationRoots.length; - const simpleTranslationRootsCount = translationRoots.filter(translationRoot => translationRoot.isSimleTranslationRoot).length; - return { - translationRoots, - translationRootsVisible, - translationRootsVisibleInViewport, - translationRootsCount, - simpleTranslationRootsCount, - texts, - textsVisible, - textsVisibleInViewport, - wordCount, - wordCountVisible, - wordCountVisibleInViewport, - }; - }); - } - /** - * Function called when a request sent to the translation engine completed successfully. - * This function handles calling the function to parse the result and the - * function to resolve the promise returned by the public `translate()` - * method when there's no pending request left. - */ - chunkCompleted(translationResponseData, domTranslationChunk, domTranslatorRequest) { - if (this.parseChunkResult(translationResponseData, domTranslationChunk)) { - this.partialSuccess = true; - // Count the number of characters successfully translated. - this.translatedCharacterCount += domTranslatorRequest.characterCount; - // Show translated chunks as they arrive - console.info("Part of the web page document translated. Showing translations that have completed so far..."); - this.translationDocument.showTranslation(); - } - } - /** - * This function will determine what is the data to be used for - * the Nth request we are generating, based on the input params. - */ - generateNextDomTranslationChunk(translationRoots, translationRootsVisible, translationRootsVisibleInViewport) { - let currentDataSize = 0; - let currentChunks = 0; - const translationRequestData = { - markupsToTranslate: [], - }; - const chunkTranslationRoots = []; - const { MAX_REQUEST_DATA, MAX_REQUEST_TEXTS } = this.translationApiLimits; - let translationRootsToConsider; - // Don't consider translation roots that are already picked up for translation - const notYetPickedUp = ($translationRoots) => $translationRoots.filter(value => !this.translationRootsPickedUpForTranslation.includes(value)); - // Prioritize the translation roots visible in viewport - translationRootsToConsider = notYetPickedUp(translationRootsVisibleInViewport); - // Then prioritize the translation roots that are visible - if (translationRootsToConsider.length === 0) { - translationRootsToConsider = notYetPickedUp(translationRootsVisible); - } - // Then prioritize the remaining translation roots - if (translationRootsToConsider.length === 0) { - translationRootsToConsider = notYetPickedUp(translationRoots); - } - for (let i = 0; i < translationRootsToConsider.length; i++) { - const translationRoot = translationRootsToConsider[i]; - const markupToTranslate = this.translationDocument.generateMarkupToTranslate(translationRoot); - const newCurSize = currentDataSize + markupToTranslate.length; - const newChunks = currentChunks + 1; - if (newCurSize > MAX_REQUEST_DATA || newChunks > MAX_REQUEST_TEXTS) { - // If we've reached the API limits, let's stop accumulating data - // for this request and return. We return information useful for - // the caller to pass back on the next call, so that the function - // can keep working from where it stopped. - console.info("We have reached the specified translation API limits and will process remaining translation roots in a separate request", { - newCurSize, - newChunks, - translationApiLimits: this.translationApiLimits, - }); - return { - translationRequestData, - translationRoots: chunkTranslationRoots, - isLastChunk: false, - }; - } - currentDataSize = newCurSize; - currentChunks = newChunks; - chunkTranslationRoots.push(translationRoot); - this.translationRootsPickedUpForTranslation.push(translationRoot); - translationRequestData.markupsToTranslate.push(markupToTranslate); - } - const remainingTranslationRoots = notYetPickedUp(translationRoots); - const isLastChunk = remainingTranslationRoots.length === 0; - return { - translationRequestData, - translationRoots: chunkTranslationRoots, - isLastChunk, - }; - } -} -exports.BaseDomTranslator = BaseDomTranslator; - - -/***/ }), - -/***/ 7668: -/*!*************************************************************************************************************!*\ - !*** ../core/ts/content-scripts/dom-translation-content-script.js/dom-translators/BergamotDomTranslator.ts ***! - \*************************************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BergamotDomTranslator = exports.MAX_REQUESTS = exports.MAX_REQUEST_TEXTS = exports.MAX_REQUEST_DATA = void 0; -const ContentScriptBergamotApiClient_1 = __webpack_require__(/*! ../../../shared-resources/ContentScriptBergamotApiClient */ 5971); -const TranslationDocument_1 = __webpack_require__(/*! ../TranslationDocument */ 3451); -const BaseDomTranslator_1 = __webpack_require__(/*! ./BaseDomTranslator */ 1896); -const BergamotDomTranslatorRequest_1 = __webpack_require__(/*! ./BergamotDomTranslatorRequest */ 3535); -// The maximum amount of net data allowed per request on Bergamot's API. -exports.MAX_REQUEST_DATA = 10 * 500; // About 500-1000 words per request -// The maximum number of texts allowed to be translated in a single request. -// Currently set to 5000 sentences per request, which should cover -// any ordinary request with max 500-1000 words per request -exports.MAX_REQUEST_TEXTS = 5000; -// Self-imposed limit of requests. This means that a page that would need -// to be broken in more than this amount of requests won't be fully translated. -// Currently set to 1000, which implies that any document with less -// than 0.5-1 million words will be translated - eventually. -exports.MAX_REQUESTS = 1000; -/** - * Translates a webpage using Bergamot's Translation backend. - */ -class BergamotDomTranslator extends BaseDomTranslator_1.BaseDomTranslator { - /** - * @param translationDocument The TranslationDocument object that represents - * the webpage to be translated - * @param sourceLanguage The source language of the document - * @param targetLanguage The target language for the translation - */ - constructor(translationDocument, sourceLanguage, targetLanguage) { - super(translationDocument, sourceLanguage, targetLanguage, new ContentScriptBergamotApiClient_1.ContentScriptBergamotApiClient(), parseChunkResult, { MAX_REQUEST_DATA: exports.MAX_REQUEST_DATA, MAX_REQUEST_TEXTS: exports.MAX_REQUEST_TEXTS, MAX_REQUESTS: exports.MAX_REQUESTS }, (translationRequestData, $sourceLanguage, $targetLanguage) => new BergamotDomTranslatorRequest_1.BergamotDomTranslatorRequest(translationRequestData, $sourceLanguage, $targetLanguage)); - } -} -exports.BergamotDomTranslator = BergamotDomTranslator; -/** - * This function parses the result returned by Bergamot's Translation API for - * the translated text in the target language. - * - * @returns boolean True if parsing of this chunk was successful. - */ -function parseChunkResult(translationResponseData, domTranslationChunk) { - const len = translationResponseData.translatedMarkups.length; - if (len === 0) { - throw new Error("Translation response data has no translated strings"); - } - if (len !== domTranslationChunk.translationRoots.length) { - // This should never happen, but if the service returns a different number - // of items (from the number of items submitted), we can't use this chunk - // because all items would be paired incorrectly. - throw new Error("Translation response data has a different number of items (from the number of items submitted)"); - } - console.info(`Parsing translation chunk result with ${len} translation entries`); - let errorOccurred = false; - domTranslationChunk.translationRoots.forEach((translationRoot, index) => { - try { - const translatedMarkup = translationResponseData.translatedMarkups[index]; - translationRoot.parseTranslationResult(translatedMarkup); - if (translationResponseData.qeAnnotatedTranslatedMarkups) { - let qeAnnotatedTranslatedMarkup = translationResponseData.qeAnnotatedTranslatedMarkups[index]; - qeAnnotatedTranslatedMarkup = TranslationDocument_1.generateMarkupToTranslateForItem(translationRoot, qeAnnotatedTranslatedMarkup); - translationRoot.parseQeAnnotatedTranslationResult(qeAnnotatedTranslatedMarkup); - } - } - catch (e) { - errorOccurred = true; - console.error("Translation error: ", e); - } - }); - console.info(`Parsed translation chunk result with ${len} translation entries`, { errorOccurred }); - return !errorOccurred; -} - - -/***/ }), - -/***/ 3535: -/*!********************************************************************************************************************!*\ - !*** ../core/ts/content-scripts/dom-translation-content-script.js/dom-translators/BergamotDomTranslatorRequest.ts ***! - \********************************************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.BergamotDomTranslatorRequest = void 0; -const detagAndProject_1 = __webpack_require__(/*! ./detagAndProject */ 3770); -/** - * Represents a request (for 1 chunk) sent off to Bergamot's translation backend. - * - * @params translationRequestData The data to be used for this translation. - * @param sourceLanguage The source language of the document. - * @param targetLanguage The target language for the translation. - * @param characterCount A counter for tracking the amount of characters translated. - * - */ -class BergamotDomTranslatorRequest { - constructor(translationRequestData, sourceLanguage, targetLanguage) { - this.translationRequestData = translationRequestData; - this.sourceLanguage = sourceLanguage; - this.targetLanguage = targetLanguage; - this.translationRequestData.markupsToTranslate.forEach(text => { - this.characterCount += text.length; - }); - } - /** - * Initiates the request - */ - fireRequest(bergamotApiClient, translationRequestProgressCallback) { - return __awaiter(this, void 0, void 0, function* () { - // The server can only deal with pure text, so we detag the strings to - // translate and later project the tags back into the result - const detaggedStrings = this.translationRequestData.markupsToTranslate.map(detagAndProject_1.detag); - const plainStringsToTranslate = detaggedStrings.map(detaggedString => detaggedString.plainString); - const results = yield bergamotApiClient.sendTranslationRequest(plainStringsToTranslate, this.sourceLanguage, this.targetLanguage, translationRequestProgressCallback); - return Object.assign(Object.assign({}, this.parseResults(results, detaggedStrings)), { plainStringsToTranslate }); - }); - } - parseResults(results, detaggedStrings) { - const len = results.translatedTexts.length; - if (len !== this.translationRequestData.markupsToTranslate.length) { - // This should never happen, but if the service returns a different number - // of items (from the number of items submitted), we can't use this chunk - // because all items would be paired incorrectly. - throw new Error("Translation backend returned a different number of results (from the number of strings to translate)"); - } - const translatedMarkups = []; - const translatedPlainTextStrings = []; - const qeAnnotatedTranslatedMarkups = results.qeAnnotatedTranslatedTexts; - // The 'text' field of results is a list of 'Paragraph'. Parse each 'Paragraph' entry - results.translatedTexts.forEach((translatedPlainTextString, index) => { - const detaggedString = detaggedStrings[index]; - // Work around issue with doubled periods returned at the end of the translated string - const originalEndedWithASinglePeriod = /([^\.])\.(\s+)?$/gm.exec(detaggedString.plainString); - const translationEndsWithTwoPeriods = /([^\.])\.\.(\s+)?$/gm.exec(translatedPlainTextString); - if (originalEndedWithASinglePeriod && translationEndsWithTwoPeriods) { - translatedPlainTextString = translatedPlainTextString.replace(/([^\.])\.\.(\s+)?$/gm, "$1.$2"); - } - let translatedMarkup; - // Use original rather than an empty or obviously invalid translation - // TODO: Address this upstream - if (["", "*", "* ()"].includes(translatedPlainTextString)) { - translatedMarkup = this.translationRequestData.markupsToTranslate[index]; - } - else { - // Project original tags/markup onto translated plain text string - // TODO: Use alignment info returned from the translation engine when it becomes available - translatedMarkup = detagAndProject_1.project(detaggedString, translatedPlainTextString); - } - translatedMarkups.push(translatedMarkup); - translatedPlainTextStrings.push(translatedPlainTextString); - }); - return { - translatedMarkups, - translatedPlainTextStrings, - qeAnnotatedTranslatedMarkups, - }; - } -} -exports.BergamotDomTranslatorRequest = BergamotDomTranslatorRequest; - - -/***/ }), - -/***/ 3301: -/*!************************************************************************************************************!*\ - !*** ../core/ts/content-scripts/dom-translation-content-script.js/dom-translators/MinimalDomTranslator.ts ***! - \************************************************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.MinimalDomTranslator = void 0; -class MinimalDomTranslator { - /** - * @param translationDocument The TranslationDocument object that represents - * the webpage to be translated - * @param sourceLanguage The source language of the document - * @param targetLanguage The target language for the translation - */ - constructor(translationDocument, sourceLanguage, targetLanguage) { - this.translationDocument = translationDocument; - this.sourceLanguage = sourceLanguage; - this.targetLanguage = targetLanguage; - } - translate(_translationProgressCallback) { - return __awaiter(this, void 0, void 0, function* () { - return { characterCount: -1 }; - }); - } -} -exports.MinimalDomTranslator = MinimalDomTranslator; - - -/***/ }), - -/***/ 3770: -/*!*******************************************************************************************************!*\ - !*** ../core/ts/content-scripts/dom-translation-content-script.js/dom-translators/detagAndProject.ts ***! - \*******************************************************************************************************/ -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.project = exports.detag = void 0; -const isTagTokenWithImpliedWhitespace = (token) => { - return token.type === "tag" && token.tagName === "br"; -}; -const detag = (originalString) => { - // console.info("detag", { originalString }); - const originalStringDoc = new DOMParser().parseFromString(originalString, "text/html"); - // console.debug("originalStringDoc.body", originalStringDoc.body); - const tokens = serializeNodeIntoTokens(originalStringDoc.body); - // console.debug({ tokens }); - const plainString = tokens - .map(token => { - if (token.type === "tag") { - return isTagTokenWithImpliedWhitespace(token) ? " " : ""; - } - return token.textRepresentation; - }) - .join(""); - return { - originalString, - tokens, - plainString, - }; -}; -exports.detag = detag; -function serializeNodeIntoTokens(node) { - const tokens = []; - try { - // @ts-ignore - for (const child of node.childNodes) { - if (child.nodeType === Node.TEXT_NODE) { - const textChunk = child.nodeValue.trim(); - // If this is only whitespace, only add such a token and then visit the next node - if (textChunk === "") { - tokens.push({ - type: "whitespace", - textRepresentation: " ", - }); - continue; - } - // Otherwise, parse the text content and add whitespace + word tokens as necessary - const leadingSpace = /^\s+/.exec(child.nodeValue); - const trailingSpace = /\s+$/.exec(child.nodeValue); - if (leadingSpace !== null) { - tokens.push({ - type: "whitespace", - textRepresentation: leadingSpace[0], - }); - } - const words = textChunk.split(" "); - words.forEach((word, wordIndex) => { - // Don't add empty words - if (word !== "") { - tokens.push({ - type: "word", - textRepresentation: word, - }); - } - // Add whitespace tokens for spaces in between words, eg not after the last word - if (wordIndex !== words.length - 1) { - tokens.push({ - type: "whitespace", - textRepresentation: " ", - }); - } - }); - if (trailingSpace !== null) { - tokens.push({ - type: "whitespace", - textRepresentation: trailingSpace[0], - }); - } - } - else { - const startTagMatch = /^<[^>]*>/gm.exec(child.outerHTML); - const endTagMatch = /<\/[^>]*>$/gm.exec(child.outerHTML); - const tagName = child.tagName.toLowerCase(); - tokens.push({ - type: "tag", - tagName, - textRepresentation: startTagMatch[0], - }); - const childTokens = serializeNodeIntoTokens(child); - tokens.push(...childTokens); - if (endTagMatch) { - tokens.push({ - type: "tag", - tagName, - textRepresentation: endTagMatch[0], - }); - } - } - } - } - catch (err) { - console.error(err); - throw err; - } - return tokens; -} -const project = (detaggedString, translatedString) => { - // console.info("project", { detaggedString, translatedString }); - // Return the translated string as is if there were no tokens in the original string - if (detaggedString.tokens.filter(token => token.type === "tag").length === 0) { - return translatedString; - } - // If the last token is a tag, we pop it off the token array and re-add it - // last so that the last tag gets any additional translation content injected into it - const lastToken = detaggedString.tokens.slice(-1)[0]; - if (lastToken.type === "tag") { - detaggedString.tokens.pop(); - } - // Inject the tags naively in the translated string assuming a 1:1 - // relationship between original text nodes and words in the translated string - const translatedStringWords = translatedString.split(" "); - const remainingTranslatedStringWords = [...translatedStringWords]; - let whitespaceHaveBeenInjectedSinceTheLastWordWasInjected = true; - const projectedStringParts = detaggedString.tokens.map((token) => { - const determineProjectedStringPart = () => { - if (token.type === "word") { - const correspondingTranslatedWord = remainingTranslatedStringWords.shift(); - // If we have run out of translated words, don't attempt to add to the projected string - if (correspondingTranslatedWord === undefined) { - return ""; - } - // Otherwise, inject the translated word - // ... possibly with a space injected in case none has been injected since the last word - const $projectedStringPart = `${whitespaceHaveBeenInjectedSinceTheLastWordWasInjected ? "" : " "}${correspondingTranslatedWord}`; - whitespaceHaveBeenInjectedSinceTheLastWordWasInjected = false; - return $projectedStringPart; - } - else if (token.type === "whitespace") { - // Don't pad whitespace onto each other when there are no more words - if (remainingTranslatedStringWords.length === 0) { - return ""; - } - whitespaceHaveBeenInjectedSinceTheLastWordWasInjected = true; - return token.textRepresentation; - } - else if (token.type === "tag") { - if (isTagTokenWithImpliedWhitespace(token)) { - whitespaceHaveBeenInjectedSinceTheLastWordWasInjected = true; - } - return token.textRepresentation; - } - throw new Error(`Unexpected token type: ${token.type}`); - }; - const projectedStringPart = determineProjectedStringPart(); - return projectedStringPart; - }); - let projectedString = projectedStringParts.join(""); - // Add any remaining translated words to the end - if (remainingTranslatedStringWords.length) { - // Add a whitespace to the end first in case there was none, or else two words will be joined together - if (lastToken.type !== "whitespace") { - projectedString += " "; - } - projectedString += remainingTranslatedStringWords.join(" "); - } - // If the last token is a tag, see above - if (lastToken.type === "tag") { - projectedString += lastToken.textRepresentation; - } - // console.debug({translatedStringWords, projectedString}); - return projectedString; -}; -exports.project = project; - - -/***/ }), - -/***/ 2542: -/*!*******************************************************************************************!*\ - !*** ../core/ts/content-scripts/dom-translation-content-script.js/getTranslationNodes.ts ***! - \*******************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getTranslationNodes = void 0; -const hasTextForTranslation_1 = __webpack_require__(/*! ./hasTextForTranslation */ 895); -const isBlockFrameOrSubclass = (element) => { - // TODO: Make this generalize like the corresponding C code invoked by: - /* - nsIFrame* frame = childElement->GetPrimaryFrame(); - frame->IsBlockFrameOrSubclass(); - */ - const nodeTagName = element.tagName.toLowerCase(); - const blockLevelElementTagNames = [ - "address", - "article", - "aside", - "blockquote", - "canvas", - "dd", - "div", - "dl", - "dt", - "fieldset", - "figcaption", - "figure", - "footer", - "form", - "h1", - "h2", - "h3", - "h4", - "h5", - "h6", - "header", - "hr", - "li", - "main", - "nav", - "noscript", - "ol", - "p", - "pre", - "section", - "table", - "tfoot", - "ul", - "video", - ]; - const result = (blockLevelElementTagNames.includes(nodeTagName) || - element.style.display === "block") && - element.style.display !== "inline"; - return result; -}; -const getTranslationNodes = (rootElement, seenTranslationNodes = [], limit = 15000) => { - const translationNodes = []; - // Query child elements in order to explicitly skip the root element from being classified as a translation node - const childElements = rootElement.children; - for (let i = 0; i < limit && i < childElements.length; i++) { - const childElement = childElements[i]; - const tagName = childElement.tagName.toLowerCase(); - const isTextNode = childElement.nodeType === Node.TEXT_NODE; - if (isTextNode) { - console.warn(`We are not supposed to run into text nodes here. childElement.textContent: "${childElement.textContent}"`); - continue; - } - // Skip elements that usually contain non-translatable text content. - if ([ - "script", - "iframe", - "frameset", - "frame", - "code", - "noscript", - "style", - "svg", - "math", - ].includes(tagName)) { - continue; - } - const nodeHasTextForTranslation = hasTextForTranslation_1.hasTextForTranslation(childElement.textContent); - // Only empty or non-translatable content in this part of the tree - if (!nodeHasTextForTranslation) { - continue; - } - // An element is a translation node if it contains - // at least one text node that has meaningful data - // for translation - const childChildTextNodes = Array.from(childElement.childNodes).filter((childChildNode) => childChildNode.nodeType === Node.TEXT_NODE); - const childChildTextNodesWithTextForTranslation = childChildTextNodes - .map(textNode => textNode.textContent) - .filter(hasTextForTranslation_1.hasTextForTranslation); - const isTranslationNode = !!childChildTextNodesWithTextForTranslation.length; - if (isTranslationNode) { - // At this point, we know we have a translation node at hand, but we need - // to figure out it the node is a translation root or not - let isTranslationRoot; - // Block elements are translation roots - isTranslationRoot = isBlockFrameOrSubclass(childElement); - // If an element is not a block element, it still - // can be considered a translation root if all ancestors - // of this element are not translation nodes - seenTranslationNodes.push(childElement); - if (!isTranslationRoot) { - // Walk up tree and check if an ancestor was a translation node - let ancestorWasATranslationNode = false; - for (let ancestor = childElement.parentNode; ancestor; ancestor = ancestor.parentNode) { - if (seenTranslationNodes.includes(ancestor)) { - ancestorWasATranslationNode = true; - break; - } - } - isTranslationRoot = !ancestorWasATranslationNode; - } - const translationNode = { - content: childElement, - isTranslationRoot, - }; - translationNodes.push(translationNode); - } - // Now traverse any element children to find nested translation nodes - if (childElement.firstElementChild) { - const childTranslationNodes = exports.getTranslationNodes(childElement, seenTranslationNodes, limit - translationNodes.length); - translationNodes.push(...childTranslationNodes); - } - } - return translationNodes; -}; -exports.getTranslationNodes = getTranslationNodes; - - -/***/ }), - -/***/ 895: -/*!*********************************************************************************************!*\ - !*** ../core/ts/content-scripts/dom-translation-content-script.js/hasTextForTranslation.ts ***! - \*********************************************************************************************/ -/***/ ((__unused_webpack_module, exports) => { - - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.hasTextForTranslation = void 0; -const hasTextForTranslation = text => { - const trimmed = text.trim(); - if (trimmed === "") { - return false; - } - /* tslint:disable:no-empty-character-class */ - // https://github.com/buzinas/tslint-eslint-rules/issues/289 - return /\p{L}/gu.test(trimmed); -}; -exports.hasTextForTranslation = hasTextForTranslation; - - -/***/ }), - -/***/ 2380: -/*!*****************************************************************************!*\ - !*** ../core/ts/content-scripts/dom-translation-content-script.js/index.ts ***! - \*****************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const mobx_keystone_1 = __webpack_require__(/*! mobx-keystone */ 4380); -const DomTranslationManager_1 = __webpack_require__(/*! ./DomTranslationManager */ 3550); -const subscribeToExtensionState_1 = __webpack_require__(/*! ../../shared-resources/state-management/subscribeToExtensionState */ 1429); -const DocumentTranslationStateCommunicator_1 = __webpack_require__(/*! ../../shared-resources/state-management/DocumentTranslationStateCommunicator */ 7994); -const ContentScriptFrameInfo_1 = __webpack_require__(/*! ../../shared-resources/ContentScriptFrameInfo */ 6528); -const ExtensionState_1 = __webpack_require__(/*! ../../shared-resources/models/ExtensionState */ 7516); -const BaseTranslationState_1 = __webpack_require__(/*! ../../shared-resources/models/BaseTranslationState */ 9359); -const TranslateOwnTextTranslationState_1 = __webpack_require__(/*! ../../shared-resources/models/TranslateOwnTextTranslationState */ 6745); -const DocumentTranslationState_1 = __webpack_require__(/*! ../../shared-resources/models/DocumentTranslationState */ 1120); -// Workaround for https://github.com/xaviergonz/mobx-keystone/issues/183 -// We need to import some models explicitly lest they fail to be registered by mobx -new ExtensionState_1.ExtensionState({}); -new TranslateOwnTextTranslationState_1.TranslateOwnTextTranslationState({}); -/** - * Note this content script runs at "document_idle" ie after the DOM is complete - */ -const init = () => __awaiter(void 0, void 0, void 0, function* () { - /* - await initErrorReportingInContentScript( - "port-from-dom-translation-content-script:index", - ); - */ - const contentScriptFrameInfo = new ContentScriptFrameInfo_1.ContentScriptFrameInfo(); - // Get window, tab and frame id - const frameInfo = yield contentScriptFrameInfo.getCurrentFrameInfo(); - const tabFrameReference = `${frameInfo.tabId}-${frameInfo.frameId}`; - const extensionState = yield subscribeToExtensionState_1.subscribeToExtensionState(); - const documentTranslationStateCommunicator = new DocumentTranslationStateCommunicator_1.DocumentTranslationStateCommunicator(frameInfo, extensionState); - const domTranslationManager = new DomTranslationManager_1.DomTranslationManager(documentTranslationStateCommunicator, document, window); - // TODO: Prevent multiple translations from occurring simultaneously + enable cancellations of existing translation jobs - // Any subsequent actions are determined by document translation state changes - mobx_keystone_1.onSnapshot(extensionState.$.documentTranslationStates, (documentTranslationStates, previousDocumentTranslationStates) => __awaiter(void 0, void 0, void 0, function* () { - // console.debug("dom-translation-content-script.js - documentTranslationStates snapshot HAS CHANGED", {documentTranslationStates}); - var _a, _b; - const currentTabFrameDocumentTranslationState = documentTranslationStates[tabFrameReference]; - const previousTabFrameDocumentTranslationState = previousDocumentTranslationStates[tabFrameReference]; - // console.log({ currentTabFrameDocumentTranslationState }); - // TODO: Possibly react to no current state in some other way - if (!currentTabFrameDocumentTranslationState) { - return; - } - const hasChanged = property => { - return (!previousTabFrameDocumentTranslationState || - currentTabFrameDocumentTranslationState[property] !== - previousTabFrameDocumentTranslationState[property]); - }; - if (hasChanged("translationRequested")) { - if (currentTabFrameDocumentTranslationState.translationRequested) { - /* TODO: Do not translate if already translated - if ( - domTranslationManager?.contentWindow?.translationDocument && - currentTabFrameDocumentTranslationState.translateFrom !== - domTranslationManager.contentWindow.translationDocument.sourceLanguage - ) { - */ - const translationPromise = domTranslationManager.doTranslation(currentTabFrameDocumentTranslationState.translateFrom, currentTabFrameDocumentTranslationState.translateTo); - extensionState.patchDocumentTranslationStateByFrameInfo(frameInfo, [ - { - op: "replace", - path: ["translationRequested"], - value: false, - }, - ]); - yield translationPromise; - } - } - if (hasChanged("translationStatus")) { - if (currentTabFrameDocumentTranslationState.translationStatus === - BaseTranslationState_1.TranslationStatus.UNKNOWN && - // Only attempt to detect language in top frames - frameInfo.frameId === 0) { - yield domTranslationManager.attemptToDetectLanguage(); - } - if (currentTabFrameDocumentTranslationState.translationStatus === - BaseTranslationState_1.TranslationStatus.TRANSLATING) { - if (currentTabFrameDocumentTranslationState.cancellationRequested) { - console.debug("Cancellation requested"); - console.debug("TODO: Implement"); - } - } - } - if ((_a = domTranslationManager === null || domTranslationManager === void 0 ? void 0 : domTranslationManager.contentWindow) === null || _a === void 0 ? void 0 : _a.translationDocument) { - const translationDocument = (_b = domTranslationManager === null || domTranslationManager === void 0 ? void 0 : domTranslationManager.contentWindow) === null || _b === void 0 ? void 0 : _b.translationDocument; - if (hasChanged("showOriginal")) { - if (currentTabFrameDocumentTranslationState.showOriginal !== - translationDocument.originalShown) { - if (translationDocument.originalShown) { - translationDocument.showTranslation(); - } - else { - translationDocument.showOriginal(); - } - } - } - if (hasChanged("displayQualityEstimation")) { - if (currentTabFrameDocumentTranslationState.displayQualityEstimation !== - translationDocument.qualityEstimationShown) { - if (translationDocument.qualityEstimationShown) { - translationDocument.showTranslation(); - } - else { - translationDocument.showQualityEstimation(); - } - } - } - } - })); - // Add an initial document translation state - try { - extensionState.setDocumentTranslationState(new DocumentTranslationState_1.DocumentTranslationState(Object.assign(Object.assign({}, frameInfo), { translationStatus: BaseTranslationState_1.TranslationStatus.UNKNOWN, url: window.location.href }))); - // Schedule removal of this document translation state when the document is closed - const onBeforeunloadEventListener = function (e) { - extensionState.deleteDocumentTranslationStateByFrameInfo(frameInfo); - // the absence of a returnValue property on the event will guarantee the browser unload happens - delete e.returnValue; - // balanced-listeners - window.removeEventListener("beforeunload", onBeforeunloadEventListener); - }; - window.addEventListener("beforeunload", onBeforeunloadEventListener); - } - catch (err) { - console.error("Instantiate DocumentTranslationState error", err); - } -}); -// noinspection JSIgnoredPromiseFromCall -init(); - - -/***/ }), - -/***/ 5971: -/*!*********************************************************************!*\ - !*** ../core/ts/shared-resources/ContentScriptBergamotApiClient.ts ***! - \*********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ContentScriptBergamotApiClient = void 0; -const webextension_polyfill_ts_1 = __webpack_require__(/*! webextension-polyfill-ts */ 5006); -const nanoid_1 = __webpack_require__(/*! nanoid */ 3608); -const ErrorReporting_1 = __webpack_require__(/*! ./ErrorReporting */ 9009); -class ContentScriptBergamotApiClient { - constructor() { - // console.debug("ContentScriptBergamotApiClient: Connecting to the background script"); - this.backgroundContextPort = webextension_polyfill_ts_1.browser.runtime.connect(webextension_polyfill_ts_1.browser.runtime.id, { - name: "port-from-content-script-bergamot-api-client", - }); - } - sendTranslationRequest(texts, from, to, translationRequestProgressCallback) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - const requestId = nanoid_1.nanoid(); - const resultsMessageListener = (m) => __awaiter(this, void 0, void 0, function* () { - if (m.translationRequestUpdate) { - const { translationRequestUpdate } = m; - if (translationRequestUpdate.requestId !== requestId) { - return; - } - // console.debug("ContentScriptBergamotApiClient received translationRequestUpdate", { translationRequestUpdate }); - const { results, translationRequestProgress, error, } = translationRequestUpdate; - if (translationRequestProgress) { - translationRequestProgressCallback(translationRequestProgress); - return; - } - if (results) { - this.backgroundContextPort.onMessage.removeListener(resultsMessageListener); - resolve(translationRequestUpdate.results); - return; - } - if (error) { - this.backgroundContextPort.onMessage.removeListener(resultsMessageListener); - reject(error); - return; - } - } - ErrorReporting_1.captureExceptionWithExtras(new Error("Unexpected message structure"), { - m, - }); - console.error("Unexpected message structure", { m }); - reject({ m }); - }); - this.backgroundContextPort.onMessage.addListener(resultsMessageListener); - // console.debug("ContentScriptBergamotApiClient: Sending translation request", {texts}); - this.backgroundContextPort.postMessage({ - texts, - from, - to, - requestId, - }); - }); - }); - } -} -exports.ContentScriptBergamotApiClient = ContentScriptBergamotApiClient; - - -/***/ }), - -/***/ 6528: -/*!*************************************************************!*\ - !*** ../core/ts/shared-resources/ContentScriptFrameInfo.ts ***! - \*************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ContentScriptFrameInfo = void 0; -const webextension_polyfill_ts_1 = __webpack_require__(/*! webextension-polyfill-ts */ 5006); -const ErrorReporting_1 = __webpack_require__(/*! ./ErrorReporting */ 9009); -const nanoid_1 = __webpack_require__(/*! nanoid */ 3608); -class ContentScriptFrameInfo { - constructor() { - // console.debug("ContentScriptFrameInfo: Connecting to the background script"); - this.backgroundContextPort = webextension_polyfill_ts_1.browser.runtime.connect(webextension_polyfill_ts_1.browser.runtime.id, { - name: "port-from-content-script-frame-info", - }); - } - getCurrentFrameInfo() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - const requestId = nanoid_1.nanoid(); - const resultsMessageListener = (m) => __awaiter(this, void 0, void 0, function* () { - if (m.frameInfo) { - const { frameInfo } = m; - if (m.requestId !== requestId) { - return; - } - // console.debug("ContentScriptFrameInfo received results", {frameInfo}); - this.backgroundContextPort.onMessage.removeListener(resultsMessageListener); - resolve(frameInfo); - return; - } - ErrorReporting_1.captureExceptionWithExtras(new Error("Unexpected message"), { m }); - console.error("Unexpected message", { m }); - reject({ m }); - }); - this.backgroundContextPort.onMessage.addListener(resultsMessageListener); - this.backgroundContextPort.postMessage({ - requestId, - }); - }); - }); - } -} -exports.ContentScriptFrameInfo = ContentScriptFrameInfo; - - -/***/ }), - -/***/ 8341: -/*!*************************************************************************!*\ - !*** ../core/ts/shared-resources/ContentScriptLanguageDetectorProxy.ts ***! - \*************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ContentScriptLanguageDetectorProxy = void 0; -const webextension_polyfill_ts_1 = __webpack_require__(/*! webextension-polyfill-ts */ 5006); -const ErrorReporting_1 = __webpack_require__(/*! ./ErrorReporting */ 9009); -const nanoid_1 = __webpack_require__(/*! nanoid */ 3608); -class ContentScriptLanguageDetectorProxy { - constructor() { - // console.debug("ContentScriptLanguageDetectorProxy: Connecting to the background script"); - this.backgroundContextPort = webextension_polyfill_ts_1.browser.runtime.connect(webextension_polyfill_ts_1.browser.runtime.id, { - name: "port-from-content-script-language-detector-proxy", - }); - } - detectLanguage(str) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - const requestId = nanoid_1.nanoid(); - const resultsMessageListener = (m) => __awaiter(this, void 0, void 0, function* () { - if (m.languageDetectorResults) { - const { languageDetectorResults } = m; - if (languageDetectorResults.requestId !== requestId) { - return; - } - // console.debug("ContentScriptLanguageDetectorProxy received language detector results", {languageDetectorResults}); - this.backgroundContextPort.onMessage.removeListener(resultsMessageListener); - resolve(languageDetectorResults.results); - return; - } - ErrorReporting_1.captureExceptionWithExtras(new Error("Unexpected message"), { m }); - console.error("Unexpected message", { m }); - reject({ m }); - }); - this.backgroundContextPort.onMessage.addListener(resultsMessageListener); - // console.debug("Attempting detectLanguage via content script proxy", {str}); - this.backgroundContextPort.postMessage({ - str, - requestId, - }); - }); - }); - } -} -exports.ContentScriptLanguageDetectorProxy = ContentScriptLanguageDetectorProxy; - - -/***/ }), - -/***/ 7994: -/*!********************************************************************************************!*\ - !*** ../core/ts/shared-resources/state-management/DocumentTranslationStateCommunicator.ts ***! - \********************************************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DocumentTranslationStateCommunicator = void 0; -const BaseTranslationState_1 = __webpack_require__(/*! ../models/BaseTranslationState */ 9359); -/** - * Helper class to communicate updated document translation states. - * - * State patching code is wrapped in setTimeout to prevent - * automatic (by mobx) batching of updates which leads to much less frequent - * state updates communicated to subscribers. No state updates during a translation - * session is not useful since we want to communicate the translation progress) - */ -class DocumentTranslationStateCommunicator { - constructor(frameInfo, extensionState) { - this.frameInfo = frameInfo; - this.extensionState = extensionState; - } - patchDocumentTranslationState(patches) { - setTimeout(() => { - this.extensionState.patchDocumentTranslationStateByFrameInfo(this.frameInfo, patches); - }, 0); - } - broadcastUpdatedAttributeValue(attribute, value) { - this.patchDocumentTranslationState([ - { - op: "replace", - path: [attribute], - value, - }, - ]); - } - broadcastUpdatedTranslationStatus(translationStatus) { - this.broadcastUpdatedAttributeValue("translationStatus", translationStatus); - } - broadcastTranslationAttemptConcluded(translationError, derivedTranslationDocumentData) { - const { wordCount, wordCountVisible, wordCountVisibleInViewport, } = derivedTranslationDocumentData; - this.patchDocumentTranslationState([ - { - op: "replace", - path: ["translationStatus"], - value: translationError - ? BaseTranslationState_1.TranslationStatus.ERROR - : BaseTranslationState_1.TranslationStatus.TRANSLATED, - }, - { - op: "replace", - path: ["wordCount"], - value: wordCount, - }, - { - op: "replace", - path: ["wordCountVisible"], - value: wordCountVisible, - }, - { - op: "replace", - path: ["wordCountVisibleInViewport"], - value: wordCountVisibleInViewport, - }, - ]); - } - /** - * This method was chosen as the place to sum up the progress of individual translation - * requests into the similar translation progress attributes present at the frame level - * in document translation state objects (totalTranslationWallTimeMs, totalTranslationEngineRequestCount etc). - * - * Another natural place to do this conversion would be as computed properties in the mobx models - * but it proved problematic to maintain/patch/sync map attributes (such as progressOfIndividualTranslationRequests) - * in document translation state objects, so reduction to simpler attributes is done here instead. - * - * @param frameTranslationProgress - */ - broadcastUpdatedFrameTranslationProgress(frameTranslationProgress) { - const { progressOfIndividualTranslationRequests, } = frameTranslationProgress; - const translationRequestProgressEntries = Array.from(progressOfIndividualTranslationRequests).map(([, translationRequestProgress]) => translationRequestProgress); - const translationInitiationTimestamps = translationRequestProgressEntries.map((trp) => trp.initiationTimestamp); - const translationInitiationTimestamp = Math.min(...translationInitiationTimestamps); - const totalModelLoadWallTimeMs = translationRequestProgressEntries - .map((trp) => trp.modelLoadWallTimeMs || 0) - .reduce((a, b) => a + b, 0); - const totalTranslationWallTimeMs = translationRequestProgressEntries - .map((trp) => trp.translationWallTimeMs || 0) - .reduce((a, b) => a + b, 0); - const totalTranslationEngineRequestCount = translationRequestProgressEntries.length; - const queuedTranslationEngineRequestCount = translationRequestProgressEntries.filter((trp) => trp.queued).length; - // Merge translation-progress-related booleans - const modelLoadNecessary = !!translationRequestProgressEntries.filter((trp) => trp.modelLoadNecessary).length; - const modelDownloadNecessary = !!translationRequestProgressEntries.filter((trp) => trp.modelDownloadNecessary).length; - const modelDownloading = !!translationRequestProgressEntries.filter((trp) => trp.modelDownloading).length; - const modelLoading = modelLoadNecessary - ? !!translationRequestProgressEntries.find((trp) => trp.modelLoading) - : undefined; - const modelLoaded = modelLoadNecessary - ? !!translationRequestProgressEntries - .filter((trp) => trp.modelLoadNecessary) - .find((trp) => trp.modelLoaded) - : undefined; - const translationFinished = translationRequestProgressEntries.filter((trp) => !trp.translationFinished).length === 0; - // Merge model download progress - const emptyDownloadProgress = { - bytesDownloaded: 0, - bytesToDownload: 0, - startTs: undefined, - durationMs: 0, - endTs: undefined, - }; - const modelDownloadProgress = translationRequestProgressEntries - .map((trp) => trp.modelDownloadProgress) - .filter((mdp) => mdp) - .reduce((a, b) => { - const startTs = a.startTs && a.startTs <= b.startTs ? a.startTs : b.startTs; - const endTs = a.endTs && a.endTs >= b.endTs ? a.endTs : b.endTs; - return { - bytesDownloaded: a.bytesDownloaded + b.bytesDownloaded, - bytesToDownload: a.bytesToDownload + b.bytesToDownload, - startTs, - durationMs: endTs ? endTs - startTs : Date.now() - startTs, - endTs, - }; - }, emptyDownloadProgress); - this.patchDocumentTranslationState([ - { - op: "replace", - path: ["translationInitiationTimestamp"], - value: translationInitiationTimestamp, - }, - { - op: "replace", - path: ["totalModelLoadWallTimeMs"], - value: totalModelLoadWallTimeMs, - }, - { - op: "replace", - path: ["modelDownloadNecessary"], - value: modelDownloadNecessary, - }, - { - op: "replace", - path: ["modelDownloading"], - value: modelDownloading, - }, - { - op: "replace", - path: ["modelDownloadProgress"], - value: modelDownloadProgress, - }, - { - op: "replace", - path: ["totalTranslationWallTimeMs"], - value: totalTranslationWallTimeMs, - }, - { - op: "replace", - path: ["totalTranslationEngineRequestCount"], - value: totalTranslationEngineRequestCount, - }, - { - op: "replace", - path: ["queuedTranslationEngineRequestCount"], - value: queuedTranslationEngineRequestCount, - }, - { - op: "replace", - path: ["modelLoadNecessary"], - value: modelLoadNecessary, - }, - { - op: "replace", - path: ["modelLoading"], - value: modelLoading, - }, - { - op: "replace", - path: ["modelLoaded"], - value: modelLoaded, - }, - { - op: "replace", - path: ["translationFinished"], - value: translationFinished, - }, - ]); - } - clear() { - setTimeout(() => { - this.extensionState.deleteDocumentTranslationStateByFrameInfo(this.frameInfo); - }, 0); - } - updatedDetectedLanguageResults(detectedLanguageResults) { - this.broadcastUpdatedAttributeValue("detectedLanguageResults", detectedLanguageResults); - } -} -exports.DocumentTranslationStateCommunicator = DocumentTranslationStateCommunicator; - - -/***/ }), - -/***/ 1429: -/*!*********************************************************************************!*\ - !*** ../core/ts/shared-resources/state-management/subscribeToExtensionState.ts ***! - \*********************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.subscribeToExtensionState = void 0; -const mobx_keystone_1 = __webpack_require__(/*! mobx-keystone */ 4380); -const webextension_polyfill_ts_1 = __webpack_require__(/*! webextension-polyfill-ts */ 5006); -const ErrorReporting_1 = __webpack_require__(/*! ../ErrorReporting */ 9009); -const nanoid_1 = __webpack_require__(/*! nanoid */ 3608); -// disable runtime data checking (we rely on TypeScript at compile time so that our model definitions can be cleaner) -mobx_keystone_1.setGlobalConfig({ - modelAutoTypeChecking: mobx_keystone_1.ModelAutoTypeCheckingMode.AlwaysOff, -}); -class MobxKeystoneProxy { - constructor(msgListeners) { - this.msgListeners = []; - this.msgListeners = msgListeners; - // console.debug("MobxKeystoneProxy: Connecting to the background script"); - this.backgroundContextPort = webextension_polyfill_ts_1.browser.runtime.connect(webextension_polyfill_ts_1.browser.runtime.id, { - name: "port-from-mobx-keystone-proxy", - }); - // listen to updates from host - const actionCallResultsMessageListener = (m) => __awaiter(this, void 0, void 0, function* () { - if (m.serializedActionCallToReplicate) { - const { serializedActionCallToReplicate } = m; - // console.log("MobxKeystoneProxy received applyActionResult", {serializedActionCallToReplicate}); - this.msgListeners.forEach(listener => listener(serializedActionCallToReplicate)); - return; - } - if (m.initialState) { - // handled in another listener, do nothing here - return; - } - ErrorReporting_1.captureExceptionWithExtras(new Error("Unexpected message"), { m }); - console.error("Unexpected message", { m }); - }); - this.backgroundContextPort.onMessage.addListener(actionCallResultsMessageListener); - } - requestInitialState() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - const requestId = nanoid_1.nanoid(); - const resultsMessageListener = (m) => __awaiter(this, void 0, void 0, function* () { - if (m.initialState) { - const { initialState } = m; - if (m.requestId !== requestId) { - return; - } - // console.debug("MobxKeystoneProxy received initialState", {initialState}); - this.backgroundContextPort.onMessage.removeListener(resultsMessageListener); - resolve(initialState); - return; - } - if (m.serializedActionCallToReplicate) { - // handled in another listener, do nothing here - return; - } - ErrorReporting_1.captureExceptionWithExtras(new Error("Unexpected message"), { m }); - console.error("Unexpected message", { m }); - reject({ m }); - }); - this.backgroundContextPort.onMessage.addListener(resultsMessageListener); - // console.debug("requestInitialState via content script mobx keystone proxy", {}); - this.backgroundContextPort.postMessage({ - requestInitialState: true, - requestId, - }); - }); - }); - } - actionCall(actionCall) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, _reject) => { - const requestId = nanoid_1.nanoid(); - // console.debug("MobxKeystoneProxy (Content Script Context): actionCall via content script mobx keystone proxy", { actionCall }); - this.backgroundContextPort.postMessage({ - actionCall, - requestId, - }); - resolve(); - }); - }); - } -} -class BackgroundContextCommunicator { - constructor() { - this.msgListeners = []; - this.mobxKeystoneProxy = new MobxKeystoneProxy(this.msgListeners); - } - requestInitialState() { - return __awaiter(this, void 0, void 0, function* () { - return this.mobxKeystoneProxy.requestInitialState(); - }); - } - onMessage(listener) { - this.msgListeners.push(listener); - } - sendMessage(actionCall) { - // send the action to be taken to the host - this.mobxKeystoneProxy.actionCall(actionCall); - } -} -const server = new BackgroundContextCommunicator(); -function subscribeToExtensionState() { - return __awaiter(this, void 0, void 0, function* () { - // we get the snapshot from the server, which is a serializable object - const rootStoreSnapshot = yield server.requestInitialState(); - // and hydrate it into a proper object - const rootStore = mobx_keystone_1.fromSnapshot(rootStoreSnapshot); - let serverAction = false; - const runServerActionLocally = (actionCall) => { - const wasServerAction = serverAction; - serverAction = true; - try { - // in clients we use the sync new model ids version to make sure that - // any model ids that were generated in the server side end up being - // the same in the client side - mobx_keystone_1.applySerializedActionAndSyncNewModelIds(rootStore, actionCall); - } - finally { - serverAction = wasServerAction; - } - }; - // listen to action messages to be replicated into the local root store - server.onMessage(actionCall => { - runServerActionLocally(actionCall); - }); - // also listen to local actions, cancel them and send them to the server (background context) - mobx_keystone_1.onActionMiddleware(rootStore, { - onStart(actionCall, ctx) { - if (!serverAction) { - // if the action does not come from the server (background context) cancel it silently - // and send it to the server (background context) - // it will then be replicated by the server (background context) and properly executed - server.sendMessage(mobx_keystone_1.serializeActionCall(actionCall, rootStore)); - ctx.data.cancelled = true; // just for logging purposes - // "cancel" the action by returning undefined - return { - result: mobx_keystone_1.ActionTrackingResult.Return, - value: undefined, - }; - } - // run actions that comes from the server (background context) unmodified - /* eslint-disable consistent-return */ - return undefined; - /* eslint-enable consistent-return */ - }, - }); - // recommended by mobx-keystone (allows the model hook `onAttachedToRootStore` to work) - mobx_keystone_1.registerRootStore(rootStore); - return rootStore; - }); -} -exports.subscribeToExtensionState = subscribeToExtensionState; - - -/***/ }) - -/******/ }); -/************************************************************************/ -/******/ // The module cache -/******/ var __webpack_module_cache__ = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ // Check if module is in cache -/******/ if(__webpack_module_cache__[moduleId]) { -/******/ return __webpack_module_cache__[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = __webpack_module_cache__[moduleId] = { -/******/ id: moduleId, -/******/ loaded: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.loaded = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = __webpack_modules__; -/******/ -/******/ // the startup function -/******/ // It's empty as some runtime module handles the default behavior -/******/ __webpack_require__.x = x => {}; -/************************************************************************/ -/******/ /* webpack/runtime/compat get default export */ -/******/ (() => { -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = (module) => { -/******/ var getter = module && module.__esModule ? -/******/ () => (module['default']) : -/******/ () => (module); -/******/ __webpack_require__.d(getter, { a: getter }); -/******/ return getter; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/define property getters */ -/******/ (() => { -/******/ // define getter functions for harmony exports -/******/ __webpack_require__.d = (exports, definition) => { -/******/ for(var key in definition) { -/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { -/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); -/******/ } -/******/ } -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/global */ -/******/ (() => { -/******/ __webpack_require__.g = (function() { -/******/ if (typeof globalThis === 'object') return globalThis; -/******/ try { -/******/ return this || new Function('return this')(); -/******/ } catch (e) { -/******/ if (typeof window === 'object') return window; -/******/ } -/******/ })(); -/******/ })(); -/******/ -/******/ /* webpack/runtime/harmony module decorator */ -/******/ (() => { -/******/ __webpack_require__.hmd = (module) => { -/******/ module = Object.create(module); -/******/ if (!module.children) module.children = []; -/******/ Object.defineProperty(module, 'exports', { -/******/ enumerable: true, -/******/ set: () => { -/******/ throw new Error('ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ' + module.id); -/******/ } -/******/ }); -/******/ return module; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/hasOwnProperty shorthand */ -/******/ (() => { -/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -/******/ })(); -/******/ -/******/ /* webpack/runtime/make namespace object */ -/******/ (() => { -/******/ // define __esModule on exports -/******/ __webpack_require__.r = (exports) => { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/jsonp chunk loading */ -/******/ (() => { -/******/ // no baseURI -/******/ -/******/ // object to store loaded and loading chunks -/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched -/******/ // Promise = chunk loading, 0 = chunk loaded -/******/ var installedChunks = { -/******/ 840: 0 -/******/ }; -/******/ -/******/ var deferredModules = [ -/******/ [2380,351] -/******/ ]; -/******/ // no chunk on demand loading -/******/ -/******/ // no prefetching -/******/ -/******/ // no preloaded -/******/ -/******/ // no HMR -/******/ -/******/ // no HMR manifest -/******/ -/******/ var checkDeferredModules = x => {}; -/******/ -/******/ // install a JSONP callback for chunk loading -/******/ var webpackJsonpCallback = (parentChunkLoadingFunction, data) => { -/******/ var [chunkIds, moreModules, runtime, executeModules] = data; -/******/ // add "moreModules" to the modules object, -/******/ // then flag all "chunkIds" as loaded and fire callback -/******/ var moduleId, chunkId, i = 0, resolves = []; -/******/ for(;i < chunkIds.length; i++) { -/******/ chunkId = chunkIds[i]; -/******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) { -/******/ resolves.push(installedChunks[chunkId][0]); -/******/ } -/******/ installedChunks[chunkId] = 0; -/******/ } -/******/ for(moduleId in moreModules) { -/******/ if(__webpack_require__.o(moreModules, moduleId)) { -/******/ __webpack_require__.m[moduleId] = moreModules[moduleId]; -/******/ } -/******/ } -/******/ if(runtime) runtime(__webpack_require__); -/******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data); -/******/ while(resolves.length) { -/******/ resolves.shift()(); -/******/ } -/******/ -/******/ // add entry modules from loaded chunk to deferred list -/******/ if(executeModules) deferredModules.push.apply(deferredModules, executeModules); -/******/ -/******/ // run deferred modules when all chunks ready -/******/ return checkDeferredModules(); -/******/ } -/******/ -/******/ var chunkLoadingGlobal = self["webpackChunkfirefox_infobar_ui"] = self["webpackChunkfirefox_infobar_ui"] || []; -/******/ chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0)); -/******/ chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal)); -/******/ -/******/ function checkDeferredModulesImpl() { -/******/ var result; -/******/ for(var i = 0; i < deferredModules.length; i++) { -/******/ var deferredModule = deferredModules[i]; -/******/ var fulfilled = true; -/******/ for(var j = 1; j < deferredModule.length; j++) { -/******/ var depId = deferredModule[j]; -/******/ if(installedChunks[depId] !== 0) fulfilled = false; -/******/ } -/******/ if(fulfilled) { -/******/ deferredModules.splice(i--, 1); -/******/ result = __webpack_require__(__webpack_require__.s = deferredModule[0]); -/******/ } -/******/ } -/******/ if(deferredModules.length === 0) { -/******/ __webpack_require__.x(); -/******/ __webpack_require__.x = x => {}; -/******/ } -/******/ return result; -/******/ } -/******/ var startup = __webpack_require__.x; -/******/ __webpack_require__.x = () => { -/******/ // reset startup function so it can be called again when more startup code is added -/******/ __webpack_require__.x = startup || (x => {}); -/******/ return (checkDeferredModules = checkDeferredModulesImpl)(); -/******/ }; -/******/ })(); -/******/ -/************************************************************************/ -/******/ -/******/ // run startup -/******/ var __webpack_exports__ = __webpack_require__.x(); -/******/ -/******/ })() -; -//# sourceMappingURL=dom-translation-content-script.js.map \ No newline at end of file diff --git a/browser/extensions/translations/extension/experiment-apis/extensionPreferences/api.js b/browser/extensions/translations/extension/experiment-apis/extensionPreferences/api.js deleted file mode 100644 index f6d98817ccca..000000000000 --- a/browser/extensions/translations/extension/experiment-apis/extensionPreferences/api.js +++ /dev/null @@ -1,44 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* global ExtensionAPI, ExtensionCommon, Services */ - -"use strict"; - -this.extensionPreferences = class extends ExtensionAPI { - getAPI() { - const { Preferences } = ChromeUtils.import( - "resource://gre/modules/Preferences.jsm", - {}, - ); - const { ExtensionUtils } = ChromeUtils.import( - "resource://gre/modules/ExtensionUtils.jsm", - {}, - ); - const { ExtensionError } = ExtensionUtils; - const telemetryInactivityThresholdInSecondsOverridePrefName = `extensions.translations.telemetryInactivityThresholdInSecondsOverride`; - return { - experiments: { - extensionPreferences: { - async getTelemetryInactivityThresholdInSecondsOverridePref() { - try { - const value = Preferences.get( - telemetryInactivityThresholdInSecondsOverridePrefName, - false, - ); - if (!value) { - return false; - } - return parseFloat(value); - } catch (error) { - // Surface otherwise silent or obscurely reported errors - console.error(error.message, error.stack); - throw new ExtensionError(error.message); - } - }, - }, - }, - }; - } -}; diff --git a/browser/extensions/translations/extension/experiment-apis/extensionPreferences/schema.json b/browser/extensions/translations/extension/experiment-apis/extensionPreferences/schema.json deleted file mode 100644 index c58a4b16d75c..000000000000 --- a/browser/extensions/translations/extension/experiment-apis/extensionPreferences/schema.json +++ /dev/null @@ -1,15 +0,0 @@ -[ - { - "namespace": "experiments.extensionPreferences", - "description": "Enables read-only access to specific Extensions-related about:config preferences", - "functions": [ - { - "name": "getTelemetryInactivityThresholdInSecondsOverridePref", - "type": "function", - "description": "Get the `extensions.translations.telemetryInactivityThresholdInSecondsOverride` preference's value", - "parameters": [], - "async": true - } - ] - } -] diff --git a/browser/extensions/translations/extension/experiment-apis/languageDetector/api.js b/browser/extensions/translations/extension/experiment-apis/languageDetector/api.js deleted file mode 100644 index d573dae41880..000000000000 --- a/browser/extensions/translations/extension/experiment-apis/languageDetector/api.js +++ /dev/null @@ -1,40 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* global ExtensionAPI */ - -"use strict"; - -this.languageDetector = class extends ExtensionAPI { - getAPI() { - const { LanguageDetector } = ChromeUtils.import( - "resource:///modules/translation/LanguageDetector.jsm", - {}, - ); - - const { ExtensionUtils } = ChromeUtils.import( - "resource://gre/modules/ExtensionUtils.jsm", - {}, - ); - const { ExtensionError } = ExtensionUtils; - - return { - experiments: { - languageDetector: { - /* Detect language */ - detectLanguage: async function detectLanguage(str) { - try { - // console.log("Called detectLanguage(str)", str); - return LanguageDetector.detectLanguage(str); - } catch (error) { - // Surface otherwise silent or obscurely reported errors - console.error(error.message, error.stack); - throw new ExtensionError(error.message); - } - }, - }, - }, - }; - } -}; diff --git a/browser/extensions/translations/extension/experiment-apis/languageDetector/schema.json b/browser/extensions/translations/extension/experiment-apis/languageDetector/schema.json deleted file mode 100644 index 8cdabecad8a2..000000000000 --- a/browser/extensions/translations/extension/experiment-apis/languageDetector/schema.json +++ /dev/null @@ -1,20 +0,0 @@ -[ - { - "namespace": "experiments.languageDetector", - "description": "Provides access to the language detector that resides in tree", - "functions": [ - { - "name": "detectLanguage", - "type": "function", - "async": true, - "description": "Detect language", - "parameters": [ - { - "name": "params", - "type": "any" - } - ] - } - ] - } -] diff --git a/browser/extensions/translations/extension/experiment-apis/telemetryEnvironment/api.js b/browser/extensions/translations/extension/experiment-apis/telemetryEnvironment/api.js deleted file mode 100644 index a3c302e9bcfd..000000000000 --- a/browser/extensions/translations/extension/experiment-apis/telemetryEnvironment/api.js +++ /dev/null @@ -1,58 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* global ExtensionAPI, ExtensionCommon, Services */ - -"use strict"; - -this.telemetryEnvironment = class extends ExtensionAPI { - getAPI(context) { - const { TelemetryController } = ChromeUtils.import( - "resource://gre/modules/TelemetryController.jsm", - {}, - ); - const { TelemetryEnvironment } = ChromeUtils.import( - "resource://gre/modules/TelemetryEnvironment.jsm", - {}, - ); - - /** - * These attributes are already sent as part of the telemetry ping envelope - * @returns {{}} - */ - const collectTelemetryEnvironmentBasedAttributes = () => { - const environment = TelemetryEnvironment.currentEnvironment; - // console.debug("TelemetryEnvironment.currentEnvironment", environment); - - return { - systemMemoryMb: environment.system.memoryMB, - systemCpuCount: environment.system.cpu.count, - systemCpuCores: environment.system.cpu.cores, - systemCpuVendor: environment.system.cpu.vendor, - systemCpuFamily: environment.system.cpu.family, - systemCpuModel: environment.system.cpu.model, - systemCpuStepping: environment.system.cpu.stepping, - systemCpuL2cacheKB: environment.system.cpu.l2cacheKB, - systemCpuL3cacheKB: environment.system.cpu.l3cacheKB, - systemCpuSpeedMhz: environment.system.cpu.speedMHz, - systemCpuExtensions: environment.system.cpu.extensions, - }; - }; - - return { - experiments: { - telemetryEnvironment: { - async getTranslationRelevantFxTelemetryMetrics() { - await TelemetryController.promiseInitialized(); - const telemetryEnvironmentBasedAttributes = collectTelemetryEnvironmentBasedAttributes(); - // console.debug("telemetryEnvironmentBasedAttributes", telemetryEnvironmentBasedAttributes); - return { - ...telemetryEnvironmentBasedAttributes, - }; - }, - }, - }, - }; - } -}; diff --git a/browser/extensions/translations/extension/experiment-apis/telemetryEnvironment/schema.json b/browser/extensions/translations/extension/experiment-apis/telemetryEnvironment/schema.json deleted file mode 100644 index d31d43a39b4f..000000000000 --- a/browser/extensions/translations/extension/experiment-apis/telemetryEnvironment/schema.json +++ /dev/null @@ -1,15 +0,0 @@ -[ - { - "namespace": "experiments.telemetryEnvironment", - "description": "Enables read-only access to the translation-relevant info from the current telemetry environment", - "functions": [ - { - "name": "getTranslationRelevantFxTelemetryMetrics", - "type": "function", - "description": "Get the translation-relevant info from the current telemetry environment", - "parameters": [], - "async": true - } - ] - } -] diff --git a/browser/extensions/translations/extension/experiment-apis/telemetryPreferences/api.js b/browser/extensions/translations/extension/experiment-apis/telemetryPreferences/api.js deleted file mode 100644 index 8baa57902515..000000000000 --- a/browser/extensions/translations/extension/experiment-apis/telemetryPreferences/api.js +++ /dev/null @@ -1,57 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* global ExtensionAPI, ExtensionCommon, Services */ - -"use strict"; - -this.telemetryPreferences = class extends ExtensionAPI { - getAPI(context) { - const EventManager = ExtensionCommon.EventManager; - const uploadEnabledPrefName = `datareporting.healthreport.uploadEnabled`; - const cachedClientIDPrefName = `toolkit.telemetry.cachedClientID`; - - return { - experiments: { - telemetryPreferences: { - onUploadEnabledPrefChange: new EventManager({ - context, - name: "telemetryPreferences.onUploadEnabledPrefChange", - register: fire => { - const callback = () => { - fire.async().catch(() => {}); // ignore Message Manager disconnects - }; - Services.prefs.addObserver(uploadEnabledPrefName, callback); - return () => { - Services.prefs.removeObserver(uploadEnabledPrefName, callback); - }; - }, - }).api(), - async getUploadEnabledPref() { - return Services.prefs.getBoolPref(uploadEnabledPrefName, undefined); - }, - onCachedClientIDPrefChange: new EventManager({ - context, - name: "telemetryPreferences.onCachedClientIDPrefChange", - register: fire => { - const callback = () => { - fire.async().catch(() => {}); // ignore Message Manager disconnects - }; - Services.prefs.addObserver(cachedClientIDPrefName, callback); - return () => { - Services.prefs.removeObserver(cachedClientIDPrefName, callback); - }; - }, - }).api(), - async getCachedClientIDPref() { - return Services.prefs.getStringPref( - cachedClientIDPrefName, - undefined, - ); - }, - }, - }, - }; - } -}; diff --git a/browser/extensions/translations/extension/experiment-apis/telemetryPreferences/schema.json b/browser/extensions/translations/extension/experiment-apis/telemetryPreferences/schema.json deleted file mode 100644 index e508dcfe116c..000000000000 --- a/browser/extensions/translations/extension/experiment-apis/telemetryPreferences/schema.json +++ /dev/null @@ -1,34 +0,0 @@ -[ - { - "namespace": "experiments.telemetryPreferences", - "description": "Enables read-only access to specific Telemetry-related about:config preferences", - "events": [ - { - "name": "onUploadEnabledPrefChange", - "type": "function", - "parameters": [] - }, - { - "name": "onCachedClientIDPrefChange", - "type": "function", - "parameters": [] - } - ], - "functions": [ - { - "name": "getUploadEnabledPref", - "type": "function", - "description": "Get the uploadEnabled preference's value", - "parameters": [], - "async": true - }, - { - "name": "getCachedClientIDPref", - "type": "function", - "description": "Get the cachedClientID preference's value", - "parameters": [], - "async": true - } - ] - } -] diff --git a/browser/extensions/translations/extension/experiment-apis/translateUi/TranslationBrowserChromeUi.js b/browser/extensions/translations/extension/experiment-apis/translateUi/TranslationBrowserChromeUi.js deleted file mode 100644 index 6a98841bfaf6..000000000000 --- a/browser/extensions/translations/extension/experiment-apis/translateUi/TranslationBrowserChromeUi.js +++ /dev/null @@ -1,320 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* global TranslationBrowserChromeUiNotificationManager */ -/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "(TranslationBrowserChromeUi)" }]*/ - -const { setTimeout, clearTimeout } = ChromeUtils.import( - "resource://gre/modules/Timer.jsm", - {}, -); - -const TranslationInfoBarStates = { - STATE_OFFER: 0, - STATE_TRANSLATING: 1, - STATE_TRANSLATED: 2, - STATE_ERROR: 3, - STATE_UNAVAILABLE: 4, -}; - -class TranslationBrowserChromeUi { - constructor(Services, browser, context, apiEventEmitter, tabId) { - this.Services = Services; - this.uiState = null; - this.browser = browser; - this.context = context; - this.translationInfoBarShown = false; - this.shouldShowTranslationProgressTimer = undefined; - this.importTranslationNotification(); - - // The manager instance is injected into the translation notification bar and handles events from therein - this.translationBrowserChromeUiNotificationManager = new TranslationBrowserChromeUiNotificationManager( - browser, - apiEventEmitter, - tabId, - TranslationInfoBarStates, - ); - } - - get notificationBox() { - return this.browser.ownerGlobal.gBrowser.getNotificationBox(this.browser); - } - - importTranslationNotification() { - const chromeWin = this.browser.ownerGlobal; - - // As a workaround to be able to load updates for the translation notification on extension reload - // we use the current unix timestamp as part of the element id. - // TODO: Restrict use of Date.now() as cachebuster to development mode only - chromeWin.now = Date.now(); - - try { - chromeWin.customElements.setElementCreationCallback( - `translation-notification-${chromeWin.now}`, - () => { - this.Services.scriptloader.loadSubScript( - this.context.extension.getURL( - "experiment-apis/translateUi/content/translation-notification.js", - ) + - "?cachebuster=" + - chromeWin.now, - chromeWin, - ); - }, - ); - } catch (e) { - console.log( - "Error occurred when attempting to load the translation notification script, but we continue nevertheless", - e, - ); - } - } - - onUiStateUpdate(uiState) { - // Set all values before showing a new translation infobar. - this.translationBrowserChromeUiNotificationManager.uiState = uiState; - this.setInfobarState(uiState.infobarState); - this.updateTranslationProgress(uiState); - const showInfoBar = this.shouldShowInfoBar(this.browser.contentPrincipal); - if (showInfoBar) { - this.showTranslationInfoBarIfNotAlreadyShown(); - } else { - this.hideTranslationInfoBarIfShown(); - } - // Always show the url bar icon - this.showURLBarIcon(showInfoBar); - } - - /** - * Syncs infobarState with the inner infobar state variable of the infobar - * @param val - */ - setInfobarState(val) { - const notif = this.notificationBox.getNotificationWithValue("translation"); - if (notif) { - notif.state = val; - } - } - - /** - * Informs the infobar element of the current translation progress - */ - updateTranslationProgress(uiState) { - // Don't bother updating translation progress if not currently translating - if ( - this.translationBrowserChromeUiNotificationManager.uiState - .infobarState !== TranslationInfoBarStates.STATE_TRANSLATING - ) { - return; - } - const notif = this.notificationBox.getNotificationWithValue("translation"); - if (notif) { - const { - modelDownloading, - translationDurationMs, - localizedTranslationProgressText, - } = uiState; - - // Always cancel ongoing timers so that we start from a clean state - if (this.shouldShowTranslationProgressTimer) { - clearTimeout(this.shouldShowTranslationProgressTimer); - } - - // Only show progress if translation has been going on for at least 3 seconds - // or we are currently downloading a model - let shouldShowTranslationProgress; - const thresholdMsAfterWhichToShouldTranslationProgress = 3000; - if ( - translationDurationMs >= - thresholdMsAfterWhichToShouldTranslationProgress || - modelDownloading - ) { - shouldShowTranslationProgress = true; - } else { - // Use a timer to show the translation progress after the threshold - this.shouldShowTranslationProgressTimer = setTimeout(() => { - notif.updateTranslationProgress( - true, - localizedTranslationProgressText, - ); - clearTimeout(this.shouldShowTranslationProgressTimer); - }, thresholdMsAfterWhichToShouldTranslationProgress - translationDurationMs); - // Don't show until then - shouldShowTranslationProgress = false; - } - notif.updateTranslationProgress( - shouldShowTranslationProgress, - localizedTranslationProgressText, - ); - } - } - - shouldShowInfoBar(principal) { - if ( - ![ - TranslationInfoBarStates.STATE_OFFER, - TranslationInfoBarStates.STATE_TRANSLATING, - TranslationInfoBarStates.STATE_TRANSLATED, - TranslationInfoBarStates.STATE_ERROR, - ].includes( - this.translationBrowserChromeUiNotificationManager.uiState.infobarState, - ) - ) { - return false; - } - - // Don't show the infobar if we have no language detection results yet - if ( - !this.translationBrowserChromeUiNotificationManager.uiState - .detectedLanguageResults - ) { - return false; - } - - // Don't show the infobar if we couldn't confidently detect the language - if ( - !this.translationBrowserChromeUiNotificationManager.uiState - .detectedLanguageResults.confident - ) { - return false; - } - - // Check if we should never show the infobar for this language. - const neverForLangs = this.Services.prefs.getCharPref( - "browser.translation.neverForLanguages", - ); - if ( - neverForLangs - .split(",") - .includes( - this.translationBrowserChromeUiNotificationManager.uiState - .detectedLanguageResults.language, - ) - ) { - // TranslationTelemetry.recordAutoRejectedTranslationOffer(); - return false; - } - - // or if we should never show the infobar for this domain. - const perms = this.Services.perms; - if ( - perms.testExactPermissionFromPrincipal(principal, "translate") === - perms.DENY_ACTION - ) { - // TranslationTelemetry.recordAutoRejectedTranslationOffer(); - return false; - } - - return true; - } - - hideURLBarIcon() { - const chromeWin = this.browser.ownerGlobal; - const PopupNotifications = chromeWin.PopupNotifications; - const removeId = this.translationBrowserChromeUiNotificationManager.uiState - .originalShown - ? "translated" - : "translate"; - const notification = PopupNotifications.getNotification( - removeId, - this.browser, - ); - if (notification) { - PopupNotifications.remove(notification); - } - } - - showURLBarIcon(showInfoBar) { - const chromeWin = this.browser.ownerGlobal; - const PopupNotifications = chromeWin.PopupNotifications; - const inactive = - !showInfoBar || - this.translationBrowserChromeUiNotificationManager.uiState.originalShown; - - // Remove existing url bar icon - ["translated", "translate"].forEach(id => { - const notification = PopupNotifications.getNotification(id, this.browser); - if (notification) { - PopupNotifications.remove(notification); - } - }); - - const onClickCallback = (topic /* , aNewBrowser */) => { - if (topic === "swapping") { - const infoBarVisible = this.notificationBox.getNotificationWithValue( - "translation", - ); - if (infoBarVisible) { - this.showTranslationInfoBar(); - } - return true; - } - - if (topic !== "showing") { - return false; - } - const translationNotification = this.notificationBox.getNotificationWithValue( - "translation", - ); - if (translationNotification) { - translationNotification.close(); - } else { - this.showTranslationInfoBar(); - } - return true; - }; - - const addId = inactive ? "translate" : "translated"; - - PopupNotifications.show( - this.browser, - addId, - null, - addId + "-notification-icon", - null, - null, - { dismissed: true, eventCallback: onClickCallback }, - ); - } - - showTranslationInfoBarIfNotAlreadyShown() { - const translationNotification = this.notificationBox.getNotificationWithValue( - "translation", - ); - if (!translationNotification && !this.translationInfoBarShown) { - this.showTranslationInfoBar(); - } - } - - hideTranslationInfoBarIfShown() { - const translationNotification = this.notificationBox.getNotificationWithValue( - "translation", - ); - if (translationNotification) { - translationNotification.close(); - } - this.translationInfoBarShown = false; - } - - showTranslationInfoBar() { - console.debug("showTranslationInfoBar"); - this.translationInfoBarShown = true; - const notificationBox = this.notificationBox; - const chromeWin = this.browser.ownerGlobal; - const notif = notificationBox.appendNotification( - "translation", - { - label: "", - priority: notificationBox.PRIORITY_INFO_HIGH, - is: `translation-notification-${chromeWin.now}`, - } - ); - notif.init(this.translationBrowserChromeUiNotificationManager); - this.translationBrowserChromeUiNotificationManager.infobarDisplayed( - notif._getSourceLang(), - notif._getTargetLang(), - ); - return notif; - } -} diff --git a/browser/extensions/translations/extension/experiment-apis/translateUi/TranslationBrowserChromeUiManager.js b/browser/extensions/translations/extension/experiment-apis/translateUi/TranslationBrowserChromeUiManager.js deleted file mode 100644 index fa4bdb96fbf4..000000000000 --- a/browser/extensions/translations/extension/experiment-apis/translateUi/TranslationBrowserChromeUiManager.js +++ /dev/null @@ -1,80 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "(TranslationBrowserChromeUiNotificationManager)" }]*/ - -class TranslationBrowserChromeUiNotificationManager { - constructor(browser, apiEventEmitter, tabId, TranslationInfoBarStates) { - this.uiState = null; - this.TranslationInfoBarStates = TranslationInfoBarStates; - this.apiEventEmitter = apiEventEmitter; - this.tabId = tabId; - this.browser = browser; - } - - infobarDisplayed(from, to) { - console.log("infobarDisplayed", { from, to }); - this.apiEventEmitter.emit("onInfoBarDisplayed", this.tabId, from, to); - } - - toLanguageChanged(from, newTo) { - console.log("toLanguageChanged", { from, newTo }); - this.apiEventEmitter.emit("onSelectTranslateTo", this.tabId, from, newTo); - } - - fromLanguageChanged(newFrom, to) { - console.log("fromLanguageChanged", { newFrom, to }); - this.apiEventEmitter.emit("onSelectTranslateFrom", this.tabId, newFrom, to); - } - - infobarClosed(from, to) { - console.log("infobarClosed", { from, to }); - this.apiEventEmitter.emit("onInfoBarClosed", this.tabId, from, to); - } - - neverForLanguage(from, to) { - console.log("neverForLanguage", { from, to }); - this.apiEventEmitter.emit( - "onNeverTranslateSelectedLanguage", - this.tabId, - from, - to, - ); - } - - neverForSite(from, to) { - console.log("neverForSite", { from, to }); - this.apiEventEmitter.emit("onNeverTranslateThisSite", this.tabId, from, to); - } - - showOriginalContent(from, to) { - console.log("showOriginalContent", { from, to }); - this.apiEventEmitter.emit( - "onShowOriginalButtonPressed", - this.tabId, - from, - to, - ); - } - - showTranslatedContent(from, to) { - console.log("showTranslatedContent", { from, to }); - this.apiEventEmitter.emit( - "onShowTranslatedButtonPressed", - this.tabId, - from, - to, - ); - } - - translate(from, to) { - console.log("translate", { from, to }); - this.apiEventEmitter.emit("onTranslateButtonPressed", this.tabId, from, to); - } - - notNow(from, to) { - console.log("notNow", { from, to }); - this.apiEventEmitter.emit("onNotNowButtonPressed", this.tabId, from, to); - } -} diff --git a/browser/extensions/translations/extension/experiment-apis/translateUi/api.js b/browser/extensions/translations/extension/experiment-apis/translateUi/api.js deleted file mode 100644 index 21c81c3a11c4..000000000000 --- a/browser/extensions/translations/extension/experiment-apis/translateUi/api.js +++ /dev/null @@ -1,177 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* global ExtensionAPI */ - -"use strict"; - -this.translateUi = class extends ExtensionAPI { - getAPI(context) { - const { Services } = ChromeUtils.import( - "resource://gre/modules/Services.jsm", - {}, - ); - - const now = Date.now(); - - /* global TranslationBrowserChromeUiManager */ - Services.scriptloader.loadSubScript( - context.extension.getURL( - "experiment-apis/translateUi/TranslationBrowserChromeUiManager.js", - ) + - "?cachebuster=" + - now, - ); - /* global TranslationBrowserChromeUi */ - Services.scriptloader.loadSubScript( - context.extension.getURL( - "experiment-apis/translateUi/TranslationBrowserChromeUi.js", - ) + - "?cachebuster=" + - now, - ); - - const { ExtensionCommon } = ChromeUtils.import( - "resource://gre/modules/ExtensionCommon.jsm", - {}, - ); - - const { EventManager, EventEmitter } = ExtensionCommon; - - const apiEventEmitter = new EventEmitter(); - - const { ExtensionUtils } = ChromeUtils.import( - "resource://gre/modules/ExtensionUtils.jsm", - {}, - ); - const { ExtensionError } = ExtensionUtils; - - /** - * Boilerplate-reducing factory method translating between - * apiEventEmitter.emit("translateUi.onFoo", ...args) - * and the actual web extension event being emitted - * - * @param {string} eventRef the event reference, eg "onFoo" - * @returns {void} - */ - const eventManagerFactory = eventRef => { - const eventId = `translateUi.${eventRef}`; - return new EventManager({ - context, - name: eventId, - register: fire => { - const listener = (event, ...args) => fire.async(...args); - apiEventEmitter.on(eventRef, listener); - return () => { - apiEventEmitter.off(eventRef, listener); - }; - }, - }); - }; - - const { tabManager } = context.extension; - const translationBrowserChromeUiInstancesByTabId = new Map(); - const getTranslationBrowserChromeUiInstanceByTabId = tabId => { - if (translationBrowserChromeUiInstancesByTabId.has(tabId)) { - return translationBrowserChromeUiInstancesByTabId.get(tabId); - } - const tab = tabManager.get(tabId); - const { browser } = tab; - const translationBrowserChromeUi = new TranslationBrowserChromeUi( - Services, - browser, - context, - apiEventEmitter, - tabId, - ); - translationBrowserChromeUiInstancesByTabId.set( - tabId, - translationBrowserChromeUi, - ); - return translationBrowserChromeUi; - }; - - return { - experiments: { - translateUi: { - /* Start reacting to translation state updates */ - start: async function start() { - try { - console.log("Called start()"); - - console.log( - "Inactivating legacy built-in translation feature (by setting browser.translation.ui.show and browser.translation.detectLanguage to false)", - ); - Services.prefs.setBoolPref(`browser.translation.ui.show`, false); - Services.prefs.setBoolPref( - `browser.translation.detectLanguage`, - false, - ); - - return undefined; - } catch (error) { - // Surface otherwise silent or obscurely reported errors - console.error(error.message, error.stack); - throw new ExtensionError(error.message); - } - }, - - /* Set current ui state */ - setUiState: async function setUiState(tabId, uiState) { - try { - // console.log("Called setUiState(tabId, uiState)", {tabId,uiState}); - const translationBrowserChromeUi = getTranslationBrowserChromeUiInstanceByTabId( - tabId, - ); - translationBrowserChromeUi.onUiStateUpdate(uiState); - return undefined; - } catch (error) { - // Surface otherwise silent or obscurely reported errors - console.error(error.message, error.stack); - throw new ExtensionError(error.message); - } - }, - - /* Stop reacting to translation state updates */ - stop: async function stop() { - try { - console.log("Called stop()"); - return undefined; - } catch (error) { - // Surface otherwise silent or obscurely reported errors - console.error(error.message, error.stack); - throw new ExtensionError(error.message); - } - }, - - /* Event boilerplate with listeners that forwards all but the first argument to the web extension event */ - onInfoBarDisplayed: eventManagerFactory("onInfoBarDisplayed").api(), - onSelectTranslateTo: eventManagerFactory("onSelectTranslateTo").api(), - onSelectTranslateFrom: eventManagerFactory( - "onSelectTranslateFrom", - ).api(), - onInfoBarClosed: eventManagerFactory("onInfoBarClosed").api(), - onNeverTranslateSelectedLanguage: eventManagerFactory( - "onNeverTranslateSelectedLanguage", - ).api(), - onNeverTranslateThisSite: eventManagerFactory( - "onNeverTranslateThisSite", - ).api(), - onShowOriginalButtonPressed: eventManagerFactory( - "onShowOriginalButtonPressed", - ).api(), - onShowTranslatedButtonPressed: eventManagerFactory( - "onShowTranslatedButtonPressed", - ).api(), - onTranslateButtonPressed: eventManagerFactory( - "onTranslateButtonPressed", - ).api(), - onNotNowButtonPressed: eventManagerFactory( - "onNotNowButtonPressed", - ).api(), - }, - }, - }; - } -}; diff --git a/browser/extensions/translations/extension/experiment-apis/translateUi/content/translation-notification.js b/browser/extensions/translations/extension/experiment-apis/translateUi/content/translation-notification.js deleted file mode 100644 index 1ee416e32329..000000000000 --- a/browser/extensions/translations/extension/experiment-apis/translateUi/content/translation-notification.js +++ /dev/null @@ -1,443 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -/* global MozElements */ - -"use strict"; - -window.MozTranslationNotification = class extends MozElements.Notification { - static get markup() { - return ` - - - - - - - - - - - `; - } - - static get entities() { - return [ - "chrome://global/locale/notification.dtd", - "chrome://browser/locale/translation.dtd", - ]; - } - - connectedCallback() { - this.appendChild(this.constructor.fragment); - - for (const [propertyName, selector] of [ - ["details", "[anonid=details]"], - ["messageImage", ".messageImage"], - ["spacer", "[anonid=spacer]"], - ]) { - this[propertyName] = this.querySelector(selector); - } - } - - async updateTranslationProgress( - shouldShowTranslationProgress, - localizedTranslationProgressText, - ) { - const progressLabelValue = shouldShowTranslationProgress - ? localizedTranslationProgressText - : ""; - this._getAnonElt("progress-label").setAttribute( - "value", - progressLabelValue, - ); - } - - set state(val) { - const deck = this._getAnonElt("translationStates"); - - const activeElt = document.activeElement; - if (activeElt && deck.contains(activeElt)) { - activeElt.blur(); - } - - let stateName; - for (const name of ["OFFER", "TRANSLATING", "TRANSLATED", "ERROR"]) { - if (Translation["STATE_" + name] === val) { - stateName = name.toLowerCase(); - break; - } - } - this.setAttribute("state", stateName); - - if (val === this.translation.TranslationInfoBarStates.STATE_TRANSLATED) { - this._handleButtonHiding(); - } - - deck.selectedIndex = val; - } - - get state() { - return this._getAnonElt("translationStates").selectedIndex; - } - - init(translationBrowserChromeUiNotificationManager) { - this.translation = translationBrowserChromeUiNotificationManager; - - this.localizedLanguagesByCode = {}; - - const sortByLocalizedName = function(list) { - const names = Services.intl.getLanguageDisplayNames(undefined, list); - return list - .map((code, i) => [code, names[i]]) - .sort((a, b) => a[1].localeCompare(b[1])); - }; - - // Fill the lists of supported source languages. - const detectedLanguage = this._getAnonElt("detectedLanguage"); - const sourceLanguages = sortByLocalizedName( - this.translation.uiState.supportedSourceLanguages, - ); - for (const [code, name] of sourceLanguages) { - detectedLanguage.appendItem(name, code); - this.localizedLanguagesByCode[code] = name; - } - detectedLanguage.value = this.translation.uiState.detectedLanguageResults.language; - - // translatedFrom is only set if we have already translated this page. - const fromLanguage = this._getAnonElt("fromLanguage"); - if (translationBrowserChromeUiNotificationManager.uiState.translatedFrom) { - for (const [code, name] of sourceLanguages) { - detectedLanguage.appendItem(name, code); - } - fromLanguage.setAttribute( - "value", - this.localizedLanguagesByCode[ - translationBrowserChromeUiNotificationManager.uiState.translatedFrom - ], - ); - } - - // Fill the list of supported target languages. - const toLanguage = this._getAnonElt("toLanguage"); - const targetLanguages = sortByLocalizedName( - this.translation.uiState.supportedTargetLanguages, - ); - for (const [code, name] of targetLanguages) { - this.localizedLanguagesByCode[code] = name; - } - - if (translationBrowserChromeUiNotificationManager.uiState.translatedTo) { - toLanguage.setAttribute( - "value", - this.localizedLanguagesByCode[ - translationBrowserChromeUiNotificationManager.uiState.translatedTo - ], - ); - } - - if (translationBrowserChromeUiNotificationManager.uiState.infobarState) { - this.state = - translationBrowserChromeUiNotificationManager.uiState.infobarState; - } - - /* - // The welcome popup/notification is currently disabled - const kWelcomePref = "browser.translation.ui.welcomeMessageShown"; - if ( - Services.prefs.prefHasUserValue(kWelcomePref) || - this.translation.browser !== gBrowser.selectedBrowser - ) { - return; - } - - this.addEventListener( - "transitionend", - function() { - // These strings are hardcoded because they need to reach beta - // without riding the trains. - const localizedStrings = { - en: [ - "Hey look! It's something new!", - "Now the Web is even more accessible with our new in-page translation feature. Click the translate button to try it!", - "Learn more.", - "Thanks", - ], - "es-AR": [ - "\xA1Mir\xE1! \xA1Hay algo nuevo!", - "Ahora la web es a\xFAn m\xE1s accesible con nuestra nueva funcionalidad de traducci\xF3n integrada. \xA1Hac\xE9 clic en el bot\xF3n traducir para probarla!", - "Conoc\xE9 m\xE1s.", - "Gracias", - ], - "es-ES": [ - "\xA1Mira! \xA1Hay algo nuevo!", - "Con la nueva funcionalidad de traducci\xF3n integrada, ahora la Web es a\xFAn m\xE1s accesible. \xA1Pulsa el bot\xF3n Traducir y pru\xE9bala!", - "M\xE1s informaci\xF3n.", - "Gracias", - ], - pl: [ - "Sp\xF3jrz tutaj! To co\u015B nowego!", - "Sie\u0107 sta\u0142a si\u0119 w\u0142a\u015Bnie jeszcze bardziej dost\u0119pna dzi\u0119ki opcji bezpo\u015Bredniego t\u0142umaczenia stron. Kliknij przycisk t\u0142umaczenia, aby spr\xF3bowa\u0107!", - "Dowiedz si\u0119 wi\u0119cej", - "Dzi\u0119kuj\u0119", - ], - tr: [ - "Bak\u0131n, burada yeni bir \u015Fey var!", - "Yeni sayfa i\xE7i \xE7eviri \xF6zelli\u011Fimiz sayesinde Web art\u0131k \xE7ok daha anla\u015F\u0131l\u0131r olacak. Denemek i\xE7in \xC7evir d\xFC\u011Fmesine t\u0131klay\u0131n!", - "Daha fazla bilgi al\u0131n.", - "Te\u015Fekk\xFCrler", - ], - vi: [ - "Nh\xECn n\xE0y! \u0110\u1ED3 m\u1EDBi!", - "Gi\u1EDD \u0111\xE2y ch\xFAng ta c\xF3 th\u1EC3 ti\u1EBFp c\u1EADn web d\u1EC5 d\xE0ng h\u01A1n n\u1EEFa v\u1EDBi t\xEDnh n\u0103ng d\u1ECBch ngay trong trang. Hay nh\u1EA5n n\xFAt d\u1ECBch \u0111\u1EC3 th\u1EED!", - "T\xECm hi\u1EC3u th\xEAm.", - "C\u1EA3m \u01A1n", - ], - }; - - let locale = Services.locale.appLocaleAsBCP47; - if (!(locale in localizedStrings)) { - locale = "en"; - } - const strings = localizedStrings[locale]; - - this._getAnonElt("welcomeHeadline").setAttribute("value", strings[0]); - this._getAnonElt("welcomeBody").textContent = strings[1]; - this._getAnonElt("learnMore").setAttribute("value", strings[2]); - this._getAnonElt("thanksButton").setAttribute("label", strings[3]); - - // TODO: Figure out why this shows a strangely rendered popup at the corner of the window instead next to the URL bar - const panel = this._getAnonElt("welcomePanel"); - panel.openPopup( - this._getAnonElt("messageImage"), - "bottomcenter topleft", - ); - - Services.prefs.setBoolPref(kWelcomePref, true); - }, - { once: true }, - ); - */ - } - - _getAnonElt(anonId) { - return this.querySelector("[anonid=" + anonId + "]"); - } - - fromLanguageChanged() { - this.translation.fromLanguageChanged( - this._getSourceLang(), - this._getTargetLang(), - ); - this.translate(); - } - - toLanguageChanged() { - this.translation.toLanguageChanged( - this._getSourceLang(), - this._getTargetLang(), - ); - this.translate(); - } - - translate() { - const from = this._getSourceLang(); - const to = this._getTargetLang(); - - // Initiate translation - this.translation.translate(from, to); - - // Store the values used in the translation in the from and to inputs - if ( - this.translation.uiState.infobarState === - this.translation.TranslationInfoBarStates.STATE_OFFER - ) { - this._getAnonElt("fromLanguage").setAttribute( - "value", - this.localizedLanguagesByCode[from], - ); - this._getAnonElt("toLanguage").setAttribute( - "value", - this.localizedLanguagesByCode[to], - ); - } - } - - /** - * To be called when the infobar should be closed per user's wish (e.g. - * by clicking the notification's close button, the not now button or choosing never to translate) - */ - closeCommand() { - const from = this._getSourceLang(); - const to = this._getTargetLang(); - this.close(); - this.translation.infobarClosed(from, to); - } - - /** - * To be called when the infobar should be closed per user's wish - * by clicking the Not now button - */ - notNow() { - this.translation.notNow(this._getSourceLang(), this._getTargetLang()); - this.closeCommand(); - } - - _handleButtonHiding() { - const originalShown = this.translation.uiState.originalShown; - this._getAnonElt("showOriginal").hidden = originalShown; - this._getAnonElt("showTranslation").hidden = !originalShown; - } - - showOriginal() { - this.translation.showOriginalContent( - this._getSourceLang(), - this._getTargetLang(), - ); - this._handleButtonHiding(); - } - - showTranslation() { - this.translation.showTranslatedContent( - this._getSourceLang(), - this._getTargetLang(), - ); - this._handleButtonHiding(); - } - - _getSourceLang() { - const lang = this._getAnonElt("detectedLanguage").value; - if (!lang) { - throw new Error("Source language is not defined"); - } - return lang; - } - - _getTargetLang() { - return this.translation.uiState.defaultTargetLanguage; - } - - optionsShowing() { - const lang = this._getSourceLang(); - - // Get the source language name. - const langName = Services.intl.getLanguageDisplayNames(undefined, [ - lang, - ])[0]; - - // Set the label and accesskey on the menuitem. - const bundle = Services.strings.createBundle( - "chrome://browser/locale/translation.properties", - ); - let item = this._getAnonElt("neverForLanguage"); - const kStrId = "translation.options.neverForLanguage"; - item.setAttribute( - "label", - bundle.formatStringFromName(kStrId + ".label", [langName]), - ); - item.setAttribute( - "accesskey", - bundle.GetStringFromName(kStrId + ".accesskey"), - ); - - // We may need to disable the menuitems if they have already been used. - // Check if translation is already disabled for this language: - const neverForLangs = Services.prefs.getCharPref( - "browser.translation.neverForLanguages", - ); - item.disabled = neverForLangs.split(",").includes(lang); - - // Check if translation is disabled for the domain: - const principal = this.translation.browser.contentPrincipal; - const perms = Services.perms; - item = this._getAnonElt("neverForSite"); - item.disabled = - perms.testExactPermissionFromPrincipal(principal, "translate") === - perms.DENY_ACTION; - } - - neverForLanguage() { - const kPrefName = "browser.translation.neverForLanguages"; - const sourceLang = this._getSourceLang(); - - let val = Services.prefs.getCharPref(kPrefName); - if (val) { - val += ","; - } - val += sourceLang; - - Services.prefs.setCharPref(kPrefName, val); - - this.translation.neverForLanguage( - this._getSourceLang(), - this._getTargetLang(), - ); - this.closeCommand(); - } - - neverForSite() { - const principal = this.translation.browser.contentPrincipal; - const perms = Services.perms; - perms.addFromPrincipal(principal, "translate", perms.DENY_ACTION); - - this.translation.neverForSite(this._getSourceLang(), this._getTargetLang()); - this.closeCommand(); - } -}; - -customElements.define( - `translation-notification-${window.now}`, - window.MozTranslationNotification, - { - extends: "notification", - }, -); diff --git a/browser/extensions/translations/extension/experiment-apis/translateUi/schema.json b/browser/extensions/translations/extension/experiment-apis/translateUi/schema.json deleted file mode 100644 index 508126b4c7e9..000000000000 --- a/browser/extensions/translations/extension/experiment-apis/translateUi/schema.json +++ /dev/null @@ -1,100 +0,0 @@ -[ - { - "namespace": "experiments.translateUi", - "description": "Provides browser chrome UI that reacts to translation states and fires events on user interaction", - "functions": [ - { - "name": "start", - "type": "function", - "async": true, - "description": "Start reacting to translation state updates", - "parameters": [] - }, - { - "name": "setUiState", - "type": "function", - "async": true, - "description": "Set current ui state", - "parameters": [ - { - "name": "tabId", - "type": "number" - }, - { - "name": "uiState", - "type": "any" - } - ] - }, - { - "name": "stop", - "type": "function", - "async": true, - "description": "Stop reacting to translation state updates", - "parameters": [] - } - ], - "events": [ - { - "name": "onInfoBarDisplayed", - "type": "function", - "description": "Foo", - "parameters": [] - }, - { - "name": "onSelectTranslateTo", - "type": "function", - "description": "Foo", - "parameters": [] - }, - { - "name": "onSelectTranslateFrom", - "type": "function", - "description": "Foo", - "parameters": [] - }, - { - "name": "onInfoBarClosed", - "type": "function", - "description": "Foo", - "parameters": [] - }, - { - "name": "onNeverTranslateSelectedLanguage", - "type": "function", - "description": "Foo", - "parameters": [] - }, - { - "name": "onNeverTranslateThisSite", - "type": "function", - "description": "Foo", - "parameters": [] - }, - { - "name": "onShowOriginalButtonPressed", - "type": "function", - "description": "Foo", - "parameters": [] - }, - { - "name": "onShowTranslatedButtonPressed", - "type": "function", - "description": "Foo", - "parameters": [] - }, - { - "name": "onTranslateButtonPressed", - "type": "function", - "description": "Foo", - "parameters": [] - }, - { - "name": "onNotNowButtonPressed", - "type": "function", - "description": "Foo", - "parameters": [] - } - ] - } -] diff --git a/browser/extensions/translations/extension/icons/translation.16x16.png b/browser/extensions/translations/extension/icons/translation.16x16.png deleted file mode 100644 index bc843397f45a..000000000000 Binary files a/browser/extensions/translations/extension/icons/translation.16x16.png and /dev/null differ diff --git a/browser/extensions/translations/extension/icons/translation.32x32.png b/browser/extensions/translations/extension/icons/translation.32x32.png deleted file mode 100644 index 5f862a730dc3..000000000000 Binary files a/browser/extensions/translations/extension/icons/translation.32x32.png and /dev/null differ diff --git a/browser/extensions/translations/extension/manifest.json b/browser/extensions/translations/extension/manifest.json deleted file mode 100644 index 0f0c3f9e1033..000000000000 --- a/browser/extensions/translations/extension/manifest.json +++ /dev/null @@ -1,136 +0,0 @@ -{ - "manifest_version": 2, - "name": "Firefox Translations", - "description": "__MSG_extensionDescription__", - "version": "0.4.3", - "incognito": "spanning", - "default_locale": "en_US", - "background": { - "scripts": [ - "commons.js", - "background.js" - ] - }, - "content_scripts": [ - { - "js": [ - "commons.js" - ], - "matches": [ - "" - ], - "all_frames": true, - "run_at": "document_idle", - "match_about_blank": false - }, - { - "js": [ - "dom-translation-content-script.js" - ], - "matches": [ - "" - ], - "all_frames": true, - "run_at": "document_idle", - "match_about_blank": false - } - ], - "permissions": [ - "", - "storage" - ], - "web_accessible_resources": [ - "commons.js.map", - "background.js.map", - "dom-translation-content-script.js.map", - "translation-worker.js.map" - ], - "icons": { - "16": "icons/translation.16x16.png", - "32": "icons/translation.32x32.png" - }, - "hidden": false, - "experiment_apis": { - "extensionPreferences": { - "schema": "./experiment-apis/extensionPreferences/schema.json", - "parent": { - "scopes": [ - "addon_parent" - ], - "script": "./experiment-apis/extensionPreferences/api.js", - "paths": [ - [ - "experiments", - "extensionPreferences" - ] - ] - } - }, - "languageDetector": { - "schema": "./experiment-apis/languageDetector/schema.json", - "parent": { - "scopes": [ - "addon_parent" - ], - "script": "./experiment-apis/languageDetector/api.js", - "paths": [ - [ - "experiments", - "languageDetector" - ] - ] - } - }, - "telemetryEnvironment": { - "schema": "./experiment-apis/telemetryEnvironment/schema.json", - "parent": { - "scopes": [ - "addon_parent" - ], - "script": "./experiment-apis/telemetryEnvironment/api.js", - "paths": [ - [ - "experiments", - "telemetryEnvironment" - ] - ] - } - }, - "telemetryPreferences": { - "schema": "./experiment-apis/telemetryPreferences/schema.json", - "parent": { - "scopes": [ - "addon_parent" - ], - "script": "./experiment-apis/telemetryPreferences/api.js", - "paths": [ - [ - "experiments", - "telemetryPreferences" - ] - ] - } - }, - "translateUi": { - "schema": "./experiment-apis/translateUi/schema.json", - "parent": { - "scopes": [ - "addon_parent" - ], - "script": "./experiment-apis/translateUi/api.js", - "paths": [ - [ - "experiments", - "translateUi" - ] - ] - } - } - }, - "applications": { - "gecko": { - "id": "firefox-translations@mozilla.org", - "strict_min_version": "90.0a1" - } - } -} \ No newline at end of file diff --git a/browser/extensions/translations/extension/translation-worker.js b/browser/extensions/translations/extension/translation-worker.js deleted file mode 100644 index d380ebf1665d..000000000000 --- a/browser/extensions/translations/extension/translation-worker.js +++ /dev/null @@ -1,8737 +0,0 @@ -/******/ (() => { // webpackBootstrap -/******/ "use strict"; -/******/ var __webpack_modules__ = ({ - -/***/ 7843: -/*!****************************!*\ - !*** ../core/ts/config.ts ***! - \****************************/ -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.config = void 0; -const developmentBuild = "production" !== "production"; -exports.config = { - bergamotRestApiUrl: "http://127.0.0.1:8787", - useBergamotRestApi: "0" === "1", - sentryDsn: "https://@.ingest.sentry.io/", - bergamotModelsBaseUrl: developmentBuild - ? "http://0.0.0.0:4000/models" - : "https://storage.googleapis.com/bergamot-models-sandbox/0.2.2", - wasmBinariesBaseUrl: developmentBuild - ? "http://0.0.0.0:4000/wasm" - : "https://storage.googleapis.com/bergamot-models-sandbox/wasm/1", - telemetryAppId: "org-mozilla-bergamot", - telemetryDebugMode: developmentBuild, - extensionBuildId: `${"v0.4.3"}-${"local"}#${"HEAD"}`, - supportedLanguagePairs: [ - // "German, French, Spanish, Polish, Czech, and Estonian in and out of English" - // ISO 639-1 codes - // Language pairs that are not available are commented out - // ["de","en"], - // ["fr","en"], - ["es", "en"], - // ["pl","en"], - ["cs", "en"], - ["et", "en"], - ["en", "de"], - // ["en","fr"], - ["en", "es"], - // ["en","pl"], - ["en", "cs"], - ["en", "et"], - ["ru", "en"], - ], - privacyNoticeUrl: "https://example.com/privacy-notice", - feedbackSurveyUrl: "https://qsurvey.mozilla.com/s3/bergamot-translate-product-feedback", -}; - - -/***/ }), - -/***/ 2050: -/*!***********************************!*\ - !*** ../core/ts/modelRegistry.ts ***! - \***********************************/ -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.modelRegistry = void 0; -exports.modelRegistry = { - ruen: { - vocab: { - name: "vocab.ruen.spm", - size: 911389, - estimatedCompressedSize: 433000, - expectedSha256Hash: "d52b077fd1a2633f8a833b5f50ec0a1d1775d1d82edf5f92fcae9be50cbee1a5", - }, - lex: { - name: "lex.50.50.ruen.s2t.bin", - size: 4020736, - estimatedCompressedSize: 2131338, - expectedSha256Hash: "f34d96729e9c7ccd060109d9add03705b4f012ea5783ba3ad9c24ba57fe1813d", - }, - model: { - name: "model.ruen.intgemm.alphas.bin", - size: 17140836, - estimatedCompressedSize: 13170690, - expectedSha256Hash: "5dd27f1c7c0872f1d544aa285828b5bcf71bfd923d07d1e493e354fb1d743655", - }, - }, - csen: { - vocab: { - name: "vocab.csen.spm", - size: 769763, - estimatedCompressedSize: 366392, - expectedSha256Hash: "f71cc5d045e479607078e079884f44032f5a0b82547fb96eefa29cd1eb47c6f3", - }, - lex: { - name: "lex.50.50.csen.s2t.bin", - size: 4535788, - estimatedCompressedSize: 2418488, - expectedSha256Hash: "8228a3c3f7887759a62b7d7c674a7bef9b70161913f9b0939ab58f71186835c2", - }, - model: { - name: "model.csen.intgemm.alphas.bin", - size: 17140756, - estimatedCompressedSize: 13045032, - expectedSha256Hash: "5b16661e2864dc50b2f4091a16bdd4ec8d8283e04271e602159ba348df5d6e2d", - }, - }, - encs: { - vocab: { - name: "vocab.csen.spm", - size: 769763, - estimatedCompressedSize: 366392, - expectedSha256Hash: "f71cc5d045e479607078e079884f44032f5a0b82547fb96eefa29cd1eb47c6f3", - }, - lex: { - name: "lex.50.50.encs.s2t.bin", - size: 3556124, - estimatedCompressedSize: 1913246, - expectedSha256Hash: "e19c77231bf977988e31ff8db15fe79966b5170564bd3e10613f239e7f461d97", - }, - model: { - name: "model.encs.intgemm.alphas.bin", - size: 17140756, - estimatedCompressedSize: 12630325, - expectedSha256Hash: "9a2fe0588bd972accfc801e2f31c945de0557804a91666ae5ab43b94fb74ac4b", - }, - }, - ende: { - vocab: { - name: "vocab.deen.spm", - size: 797501, - estimatedCompressedSize: 412505, - expectedSha256Hash: "bc8f8229933d8294c727f3eab12f6f064e7082b929f2d29494c8a1e619ba174c", - }, - lex: { - name: "lex.50.50.ende.s2t.bin", - size: 3062492, - estimatedCompressedSize: 1575385, - expectedSha256Hash: "764797d075f0642c0b079cce6547348d65fe4e92ac69fa6a8605cd8b53dacb3f", - }, - model: { - name: "model.ende.intgemm.alphas.bin", - size: 17140498, - estimatedCompressedSize: 13207068, - expectedSha256Hash: "f0946515c6645304f0706fa66a051c3b7b7c507f12d0c850f276c18165a10c14", - }, - }, - enes: { - vocab: { - name: "vocab.esen.spm", - size: 825463, - estimatedCompressedSize: 414566, - expectedSha256Hash: "909b1eea1face0d7f90a474fe29a8c0fef8d104b6e41e65616f864c964ba8845", - }, - lex: { - name: "lex.50.50.enes.s2t.bin", - size: 3347104, - estimatedCompressedSize: 1720700, - expectedSha256Hash: "3a113d713dec3cf1d12bba5b138ae616e28bba4bbc7fe7fd39ba145e26b86d7f", - }, - model: { - name: "model.enes.intgemm.alphas.bin", - size: 17140755, - estimatedCompressedSize: 12602853, - expectedSha256Hash: "fa7460037a3163e03fe1d23602f964bff2331da6ee813637e092ddf37156ef53", - }, - }, - enet: { - vocab: { - name: "vocab.eten.spm", - size: 828426, - estimatedCompressedSize: 416995, - expectedSha256Hash: "e3b66bc141f6123cd40746e2fb9b8ee4f89cbf324ab27d6bbf3782e52f15fa2d", - }, - lex: { - name: "lex.50.50.enet.s2t.bin", - size: 2700780, - estimatedCompressedSize: 1336443, - expectedSha256Hash: "3d1b40ff43ebef82cf98d416a88a1ea19eb325a85785eef102f59878a63a829d", - }, - model: { - name: "model.enet.intgemm.alphas.bin", - size: 17140754, - estimatedCompressedSize: 12543318, - expectedSha256Hash: "a28874a8b702a519a14dc71bcee726a5cb4b539eeaada2d06492f751469a1fd6", - }, - }, - esen: { - vocab: { - name: "vocab.esen.spm", - size: 825463, - estimatedCompressedSize: 414566, - expectedSha256Hash: "909b1eea1face0d7f90a474fe29a8c0fef8d104b6e41e65616f864c964ba8845", - }, - lex: { - name: "lex.50.50.esen.s2t.bin", - size: 3860888, - estimatedCompressedSize: 1978538, - expectedSha256Hash: "f11a2c23ef85ab1fee1c412b908d69bc20d66fd59faa8f7da5a5f0347eddf969", - }, - model: { - name: "model.esen.intgemm.alphas.bin", - size: 17140755, - estimatedCompressedSize: 13215960, - expectedSha256Hash: "4b6b7f451094aaa447d012658af158ffc708fc8842dde2f871a58404f5457fe0", - }, - }, - eten: { - vocab: { - name: "vocab.eten.spm", - size: 828426, - estimatedCompressedSize: 416995, - expectedSha256Hash: "e3b66bc141f6123cd40746e2fb9b8ee4f89cbf324ab27d6bbf3782e52f15fa2d", - }, - lex: { - name: "lex.50.50.eten.s2t.bin", - size: 3974944, - estimatedCompressedSize: 1920655, - expectedSha256Hash: "6992bedc590e60e610a28129c80746fe5f33144a4520e2c5508d87db14ca54f8", - }, - model: { - name: "model.eten.intgemm.alphas.bin", - size: 17140754, - estimatedCompressedSize: 12222624, - expectedSha256Hash: "aac98a2371e216ee2d4843cbe896c617f6687501e17225ac83482eba52fd0028", - }, - }, -}; - - -/***/ }), - -/***/ 31: -/*!*****************************************************************************************!*\ - !*** ../core/ts/web-worker-scripts/translation-worker.js/bergamot-translator-worker.ts ***! - \*****************************************************************************************/ -/***/ ((__unused_webpack_module, exports) => { - - -// @ts-nocheck -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.loadEmscriptenGlueCode = void 0; -// Note: The source code in this file is imported from bergamot-translator via -// the import-bergamot-translator.sh script in the root of this repo. -// Changes will be overwritten on each import! -function loadEmscriptenGlueCode(Module) { - var BERGAMOT_VERSION_FULL = "v0.3.1+d264450"; - function GROWABLE_HEAP_I8() { - if (wasmMemory.buffer != buffer) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAP8; - } - function GROWABLE_HEAP_U8() { - if (wasmMemory.buffer != buffer) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAPU8; - } - function GROWABLE_HEAP_I16() { - if (wasmMemory.buffer != buffer) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAP16; - } - function GROWABLE_HEAP_U16() { - if (wasmMemory.buffer != buffer) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAPU16; - } - function GROWABLE_HEAP_I32() { - if (wasmMemory.buffer != buffer) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAP32; - } - function GROWABLE_HEAP_U32() { - if (wasmMemory.buffer != buffer) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAPU32; - } - function GROWABLE_HEAP_F32() { - if (wasmMemory.buffer != buffer) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAPF32; - } - function GROWABLE_HEAP_F64() { - if (wasmMemory.buffer != buffer) { - updateGlobalBufferAndViews(wasmMemory.buffer); - } - return HEAPF64; - } - var Module = typeof Module !== "undefined" ? Module : {}; - var moduleOverrides = {}; - var key; - for (key in Module) { - if (Module.hasOwnProperty(key)) { - moduleOverrides[key] = Module[key]; - } - } - var arguments_ = []; - var thisProgram = "./this.program"; - var quit_ = function (status, toThrow) { - throw toThrow; - }; - var ENVIRONMENT_IS_WEB = false; - var ENVIRONMENT_IS_WORKER = false; - var ENVIRONMENT_IS_NODE = false; - var ENVIRONMENT_IS_SHELL = false; - ENVIRONMENT_IS_WEB = typeof window === "object"; - ENVIRONMENT_IS_WORKER = typeof importScripts === "function"; - ENVIRONMENT_IS_NODE = - typeof process === "object" && - typeof process.versions === "object" && - typeof process.versions.node === "string"; - ENVIRONMENT_IS_SHELL = - !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER; - var ENVIRONMENT_IS_PTHREAD = Module["ENVIRONMENT_IS_PTHREAD"] || false; - if (ENVIRONMENT_IS_PTHREAD) { - buffer = Module["buffer"]; - } - var _scriptDir = typeof document !== "undefined" && document.currentScript - ? document.currentScript.src - : undefined; - if (ENVIRONMENT_IS_WORKER) { - _scriptDir = self.location.href; - } - var scriptDirectory = ""; - function locateFile(path) { - if (Module["locateFile"]) { - return Module["locateFile"](path, scriptDirectory); - } - return scriptDirectory + path; - } - var read_, readAsync, readBinary, setWindowTitle; - if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { - if (ENVIRONMENT_IS_WORKER) { - scriptDirectory = self.location.href; - } - else if (typeof document !== "undefined" && document.currentScript) { - scriptDirectory = document.currentScript.src; - } - if (scriptDirectory.indexOf("blob:") !== 0) { - scriptDirectory = scriptDirectory.substr(0, scriptDirectory.lastIndexOf("/") + 1); - } - else { - scriptDirectory = ""; - } - { - read_ = function shell_read(url) { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, false); - xhr.send(null); - return xhr.responseText; - }; - if (ENVIRONMENT_IS_WORKER) { - readBinary = function readBinary(url) { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, false); - xhr.responseType = "arraybuffer"; - xhr.send(null); - return new Uint8Array(xhr.response); - }; - } - readAsync = function readAsync(url, onload, onerror) { - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, true); - xhr.responseType = "arraybuffer"; - xhr.onload = function xhr_onload() { - if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { - onload(xhr.response); - return; - } - onerror(); - }; - xhr.onerror = onerror; - xhr.send(null); - }; - } - setWindowTitle = function (title) { - document.title = title; - }; - } - else { - } - var out = Module["print"] || console.log.bind(console); - var err = Module["printErr"] || console.warn.bind(console); - for (key in moduleOverrides) { - if (moduleOverrides.hasOwnProperty(key)) { - Module[key] = moduleOverrides[key]; - } - } - moduleOverrides = null; - if (Module["arguments"]) - arguments_ = Module["arguments"]; - if (Module["thisProgram"]) - thisProgram = Module["thisProgram"]; - if (Module["quit"]) - quit_ = Module["quit"]; - var STACK_ALIGN = 16; - function alignMemory(size, factor) { - if (!factor) - factor = STACK_ALIGN; - return Math.ceil(size / factor) * factor; - } - function warnOnce(text) { - if (!warnOnce.shown) - warnOnce.shown = {}; - if (!warnOnce.shown[text]) { - warnOnce.shown[text] = 1; - err(text); - } - } - function convertJsFunctionToWasm(func, sig) { - if (typeof WebAssembly.Function === "function") { - var typeNames = { - i: "i32", - j: "i64", - f: "f32", - d: "f64", - }; - var type = { - parameters: [], - results: sig[0] == "v" ? [] : [typeNames[sig[0]]], - }; - for (var i = 1; i < sig.length; ++i) { - type.parameters.push(typeNames[sig[i]]); - } - return new WebAssembly.Function(type, func); - } - var typeSection = [1, 0, 1, 96]; - var sigRet = sig.slice(0, 1); - var sigParam = sig.slice(1); - var typeCodes = { - i: 127, - j: 126, - f: 125, - d: 124, - }; - typeSection.push(sigParam.length); - for (var i = 0; i < sigParam.length; ++i) { - typeSection.push(typeCodes[sigParam[i]]); - } - if (sigRet == "v") { - typeSection.push(0); - } - else { - typeSection = typeSection.concat([1, typeCodes[sigRet]]); - } - typeSection[1] = typeSection.length - 2; - var bytes = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0].concat(typeSection, [ - 2, - 7, - 1, - 1, - 101, - 1, - 102, - 0, - 0, - 7, - 5, - 1, - 1, - 102, - 0, - 0, - ])); - var module = new WebAssembly.Module(bytes, { simdWormhole: true }); - var instance = new WebAssembly.Instance(module, { - e: { - f: func, - }, - }); - var wrappedFunc = instance.exports["f"]; - return wrappedFunc; - } - var freeTableIndexes = []; - var functionsInTableMap; - function getEmptyTableSlot() { - if (freeTableIndexes.length) { - return freeTableIndexes.pop(); - } - try { - wasmTable.grow(1); - } - catch (err) { - if (!(err instanceof RangeError)) { - throw err; - } - throw "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."; - } - return wasmTable.length - 1; - } - function addFunctionWasm(func, sig) { - if (!functionsInTableMap) { - functionsInTableMap = new WeakMap(); - for (var i = 0; i < wasmTable.length; i++) { - var item = wasmTable.get(i); - if (item) { - functionsInTableMap.set(item, i); - } - } - } - if (functionsInTableMap.has(func)) { - return functionsInTableMap.get(func); - } - var ret = getEmptyTableSlot(); - try { - wasmTable.set(ret, func); - } - catch (err) { - if (!(err instanceof TypeError)) { - throw err; - } - var wrapped = convertJsFunctionToWasm(func, sig); - wasmTable.set(ret, wrapped); - } - functionsInTableMap.set(func, ret); - return ret; - } - var tempRet0 = 0; - var setTempRet0 = function (value) { - tempRet0 = value; - }; - var Atomics_load = Atomics.load; - var Atomics_store = Atomics.store; - var Atomics_compareExchange = Atomics.compareExchange; - var wasmBinary; - if (Module["wasmBinary"]) - wasmBinary = Module["wasmBinary"]; - var noExitRuntime; - if (Module["noExitRuntime"]) - noExitRuntime = Module["noExitRuntime"]; - if (typeof WebAssembly !== "object") { - abort("no native wasm support detected"); - } - var wasmMemory; - var wasmModule; - var threadInfoStruct = 0; - var selfThreadId = 0; - var ABORT = false; - var EXITSTATUS = 0; - function assert(condition, text) { - if (!condition) { - abort("Assertion failed: " + text); - } - } - function getCFunc(ident) { - var func = Module["_" + ident]; - assert(func, "Cannot call unknown function " + ident + ", make sure it is exported"); - return func; - } - function ccall(ident, returnType, argTypes, args, opts) { - var toC = { - string: function (str) { - var ret = 0; - if (str !== null && str !== undefined && str !== 0) { - var len = (str.length << 2) + 1; - ret = stackAlloc(len); - stringToUTF8(str, ret, len); - } - return ret; - }, - array: function (arr) { - var ret = stackAlloc(arr.length); - writeArrayToMemory(arr, ret); - return ret; - }, - }; - function convertReturnValue(ret) { - if (returnType === "string") - return UTF8ToString(ret); - if (returnType === "boolean") - return Boolean(ret); - return ret; - } - var func = getCFunc(ident); - var cArgs = []; - var stack = 0; - if (args) { - for (var i = 0; i < args.length; i++) { - var converter = toC[argTypes[i]]; - if (converter) { - if (stack === 0) - stack = stackSave(); - cArgs[i] = converter(args[i]); - } - else { - cArgs[i] = args[i]; - } - } - } - var ret = func.apply(null, cArgs); - ret = convertReturnValue(ret); - if (stack !== 0) - stackRestore(stack); - return ret; - } - var ALLOC_STACK = 1; - function UTF8ArrayToString(heap, idx, maxBytesToRead) { - var endIdx = idx + maxBytesToRead; - var str = ""; - while (!(idx >= endIdx)) { - var u0 = heap[idx++]; - if (!u0) - return str; - if (!(u0 & 128)) { - str += String.fromCharCode(u0); - continue; - } - var u1 = heap[idx++] & 63; - if ((u0 & 224) == 192) { - str += String.fromCharCode(((u0 & 31) << 6) | u1); - continue; - } - var u2 = heap[idx++] & 63; - if ((u0 & 240) == 224) { - u0 = ((u0 & 15) << 12) | (u1 << 6) | u2; - } - else { - u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heap[idx++] & 63); - } - if (u0 < 65536) { - str += String.fromCharCode(u0); - } - else { - var ch = u0 - 65536; - str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023)); - } - } - return str; - } - function UTF8ToString(ptr, maxBytesToRead) { - return ptr - ? UTF8ArrayToString(GROWABLE_HEAP_U8(), ptr, maxBytesToRead) - : ""; - } - function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) { - if (!(maxBytesToWrite > 0)) - return 0; - var startIdx = outIdx; - var endIdx = outIdx + maxBytesToWrite - 1; - for (var i = 0; i < str.length; ++i) { - var u = str.charCodeAt(i); - if (u >= 55296 && u <= 57343) { - var u1 = str.charCodeAt(++i); - u = (65536 + ((u & 1023) << 10)) | (u1 & 1023); - } - if (u <= 127) { - if (outIdx >= endIdx) - break; - heap[outIdx++] = u; - } - else if (u <= 2047) { - if (outIdx + 1 >= endIdx) - break; - heap[outIdx++] = 192 | (u >> 6); - heap[outIdx++] = 128 | (u & 63); - } - else if (u <= 65535) { - if (outIdx + 2 >= endIdx) - break; - heap[outIdx++] = 224 | (u >> 12); - heap[outIdx++] = 128 | ((u >> 6) & 63); - heap[outIdx++] = 128 | (u & 63); - } - else { - if (outIdx + 3 >= endIdx) - break; - heap[outIdx++] = 240 | (u >> 18); - heap[outIdx++] = 128 | ((u >> 12) & 63); - heap[outIdx++] = 128 | ((u >> 6) & 63); - heap[outIdx++] = 128 | (u & 63); - } - } - heap[outIdx] = 0; - return outIdx - startIdx; - } - function stringToUTF8(str, outPtr, maxBytesToWrite) { - return stringToUTF8Array(str, GROWABLE_HEAP_U8(), outPtr, maxBytesToWrite); - } - function lengthBytesUTF8(str) { - var len = 0; - for (var i = 0; i < str.length; ++i) { - var u = str.charCodeAt(i); - if (u >= 55296 && u <= 57343) - u = (65536 + ((u & 1023) << 10)) | (str.charCodeAt(++i) & 1023); - if (u <= 127) - ++len; - else if (u <= 2047) - len += 2; - else if (u <= 65535) - len += 3; - else - len += 4; - } - return len; - } - function UTF16ToString(ptr, maxBytesToRead) { - var str = ""; - for (var i = 0; !(i >= maxBytesToRead / 2); ++i) { - var codeUnit = GROWABLE_HEAP_I16()[(ptr + i * 2) >> 1]; - if (codeUnit == 0) - break; - str += String.fromCharCode(codeUnit); - } - return str; - } - function stringToUTF16(str, outPtr, maxBytesToWrite) { - if (maxBytesToWrite === undefined) { - maxBytesToWrite = 2147483647; - } - if (maxBytesToWrite < 2) - return 0; - maxBytesToWrite -= 2; - var startPtr = outPtr; - var numCharsToWrite = maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length; - for (var i = 0; i < numCharsToWrite; ++i) { - var codeUnit = str.charCodeAt(i); - GROWABLE_HEAP_I16()[outPtr >> 1] = codeUnit; - outPtr += 2; - } - GROWABLE_HEAP_I16()[outPtr >> 1] = 0; - return outPtr - startPtr; - } - function lengthBytesUTF16(str) { - return str.length * 2; - } - function UTF32ToString(ptr, maxBytesToRead) { - var i = 0; - var str = ""; - while (!(i >= maxBytesToRead / 4)) { - var utf32 = GROWABLE_HEAP_I32()[(ptr + i * 4) >> 2]; - if (utf32 == 0) - break; - ++i; - if (utf32 >= 65536) { - var ch = utf32 - 65536; - str += String.fromCharCode(55296 | (ch >> 10), 56320 | (ch & 1023)); - } - else { - str += String.fromCharCode(utf32); - } - } - return str; - } - function stringToUTF32(str, outPtr, maxBytesToWrite) { - if (maxBytesToWrite === undefined) { - maxBytesToWrite = 2147483647; - } - if (maxBytesToWrite < 4) - return 0; - var startPtr = outPtr; - var endPtr = startPtr + maxBytesToWrite - 4; - for (var i = 0; i < str.length; ++i) { - var codeUnit = str.charCodeAt(i); - if (codeUnit >= 55296 && codeUnit <= 57343) { - var trailSurrogate = str.charCodeAt(++i); - codeUnit = - (65536 + ((codeUnit & 1023) << 10)) | (trailSurrogate & 1023); - } - GROWABLE_HEAP_I32()[outPtr >> 2] = codeUnit; - outPtr += 4; - if (outPtr + 4 > endPtr) - break; - } - GROWABLE_HEAP_I32()[outPtr >> 2] = 0; - return outPtr - startPtr; - } - function lengthBytesUTF32(str) { - var len = 0; - for (var i = 0; i < str.length; ++i) { - var codeUnit = str.charCodeAt(i); - if (codeUnit >= 55296 && codeUnit <= 57343) - ++i; - len += 4; - } - return len; - } - function allocateUTF8(str) { - var size = lengthBytesUTF8(str) + 1; - var ret = _malloc(size); - if (ret) - stringToUTF8Array(str, GROWABLE_HEAP_I8(), ret, size); - return ret; - } - function writeArrayToMemory(array, buffer) { - GROWABLE_HEAP_I8().set(array, buffer); - } - function writeAsciiToMemory(str, buffer, dontAddNull) { - for (var i = 0; i < str.length; ++i) { - GROWABLE_HEAP_I8()[buffer++ >> 0] = str.charCodeAt(i); - } - if (!dontAddNull) - GROWABLE_HEAP_I8()[buffer >> 0] = 0; - } - function alignUp(x, multiple) { - if (x % multiple > 0) { - x += multiple - (x % multiple); - } - return x; - } - var buffer, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64; - function updateGlobalBufferAndViews(buf) { - buffer = buf; - Module["HEAP8"] = HEAP8 = new Int8Array(buf); - Module["HEAP16"] = HEAP16 = new Int16Array(buf); - Module["HEAP32"] = HEAP32 = new Int32Array(buf); - Module["HEAPU8"] = HEAPU8 = new Uint8Array(buf); - Module["HEAPU16"] = HEAPU16 = new Uint16Array(buf); - Module["HEAPU32"] = HEAPU32 = new Uint32Array(buf); - Module["HEAPF32"] = HEAPF32 = new Float32Array(buf); - Module["HEAPF64"] = HEAPF64 = new Float64Array(buf); - } - var INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 16777216; - if (ENVIRONMENT_IS_PTHREAD) { - wasmMemory = Module["wasmMemory"]; - buffer = Module["buffer"]; - } - else { - if (Module["wasmMemory"]) { - wasmMemory = Module["wasmMemory"]; - } - else { - wasmMemory = new WebAssembly.Memory({ - initial: INITIAL_MEMORY / 65536, - maximum: 2147483648 / 65536, - shared: true, - }); - if (!(wasmMemory.buffer instanceof SharedArrayBuffer)) { - err("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"); - if (ENVIRONMENT_IS_NODE) { - console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"); - } - throw Error("bad memory"); - } - } - } - if (wasmMemory) { - buffer = wasmMemory.buffer; - } - INITIAL_MEMORY = buffer.byteLength; - updateGlobalBufferAndViews(buffer); - var wasmTable; - var __ATPRERUN__ = []; - var __ATINIT__ = []; - var __ATMAIN__ = []; - var __ATEXIT__ = []; - var __ATPOSTRUN__ = []; - var runtimeInitialized = false; - var runtimeExited = false; - if (ENVIRONMENT_IS_PTHREAD) - runtimeInitialized = true; - function preRun() { - if (ENVIRONMENT_IS_PTHREAD) - return; - if (Module["preRun"]) { - if (typeof Module["preRun"] == "function") - Module["preRun"] = [Module["preRun"]]; - while (Module["preRun"].length) { - addOnPreRun(Module["preRun"].shift()); - } - } - callRuntimeCallbacks(__ATPRERUN__); - } - function initRuntime() { - runtimeInitialized = true; - if (!Module["noFSInit"] && !FS.init.initialized) - FS.init(); - TTY.init(); - callRuntimeCallbacks(__ATINIT__); - } - function preMain() { - if (ENVIRONMENT_IS_PTHREAD) - return; - FS.ignorePermissions = false; - callRuntimeCallbacks(__ATMAIN__); - } - function exitRuntime() { - if (ENVIRONMENT_IS_PTHREAD) - return; - runtimeExited = true; - } - function postRun() { - if (ENVIRONMENT_IS_PTHREAD) - return; - if (Module["postRun"]) { - if (typeof Module["postRun"] == "function") - Module["postRun"] = [Module["postRun"]]; - while (Module["postRun"].length) { - addOnPostRun(Module["postRun"].shift()); - } - } - callRuntimeCallbacks(__ATPOSTRUN__); - } - function addOnPreRun(cb) { - __ATPRERUN__.unshift(cb); - } - function addOnPreMain(cb) { - __ATMAIN__.unshift(cb); - } - function addOnPostRun(cb) { - __ATPOSTRUN__.unshift(cb); - } - var runDependencies = 0; - var runDependencyWatcher = null; - var dependenciesFulfilled = null; - function getUniqueRunDependency(id) { - return id; - } - function addRunDependency(id) { - assert(!ENVIRONMENT_IS_PTHREAD, "addRunDependency cannot be used in a pthread worker"); - runDependencies++; - if (Module["monitorRunDependencies"]) { - Module["monitorRunDependencies"](runDependencies); - } - } - function removeRunDependency(id) { - runDependencies--; - if (Module["monitorRunDependencies"]) { - Module["monitorRunDependencies"](runDependencies); - } - if (runDependencies == 0) { - if (runDependencyWatcher !== null) { - clearInterval(runDependencyWatcher); - runDependencyWatcher = null; - } - if (dependenciesFulfilled) { - var callback = dependenciesFulfilled; - dependenciesFulfilled = null; - callback(); - } - } - } - Module["preloadedImages"] = {}; - Module["preloadedAudios"] = {}; - function abort(what) { - if (Module["onAbort"]) { - Module["onAbort"](what); - } - if (ENVIRONMENT_IS_PTHREAD) - console.error("Pthread aborting at " + new Error().stack); - what += ""; - err(what); - ABORT = true; - EXITSTATUS = 1; - what = "abort(" + what + "). Build with -s ASSERTIONS=1 for more info."; - var e = new WebAssembly.RuntimeError(what); - throw e; - } - function hasPrefix(str, prefix) { - return String.prototype.startsWith - ? str.startsWith(prefix) - : str.indexOf(prefix) === 0; - } - var dataURIPrefix = "data:application/octet-stream;base64,"; - function isDataURI(filename) { - return hasPrefix(filename, dataURIPrefix); - } - var fileURIPrefix = "file://"; - var wasmBinaryFile = "wasm/bergamot-translator-worker.wasm"; - if (!isDataURI(wasmBinaryFile)) { - wasmBinaryFile = locateFile(wasmBinaryFile); - } - function getBinary() { - try { - if (wasmBinary) { - return new Uint8Array(wasmBinary); - } - if (readBinary) { - return readBinary(wasmBinaryFile); - } - else { - throw "both async and sync fetching of the wasm failed"; - } - } - catch (err) { - abort(err); - } - } - function getBinaryPromise() { - if (!wasmBinary && - (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) && - typeof fetch === "function") { - return fetch(wasmBinaryFile, { - credentials: "same-origin", - }) - .then(function (response) { - if (!response["ok"]) { - throw "failed to load wasm binary file at '" + wasmBinaryFile + "'"; - } - return response["arrayBuffer"](); - }) - .catch(function () { - return getBinary(); - }); - } - return Promise.resolve().then(getBinary); - } - function createWasm() { - var info = { - env: asmLibraryArg, - wasi_snapshot_preview1: asmLibraryArg, - }; - function receiveInstance(instance, module) { - var exports = instance.exports; - Module["asm"] = exports; - wasmTable = Module["asm"]["__indirect_function_table"]; - wasmModule = module; - if (!ENVIRONMENT_IS_PTHREAD) { - removeRunDependency("wasm-instantiate"); - } - } - if (!ENVIRONMENT_IS_PTHREAD) { - addRunDependency("wasm-instantiate"); - } - function receiveInstantiatedSource(output) { - receiveInstance(output["instance"], output["module"]); - } - function instantiateArrayBuffer(receiver) { - return getBinaryPromise() - .then(function (binary) { - return WebAssembly.instantiate(binary, info, { simdWormhole: true }); - }) - .then(receiver, function (reason) { - err("failed to asynchronously prepare wasm: " + reason); - abort(reason); - }); - } - function instantiateAsync() { - if (!wasmBinary && - typeof WebAssembly.instantiateStreaming === "function" && - !isDataURI(wasmBinaryFile) && - typeof fetch === "function") { - return fetch(wasmBinaryFile, { - credentials: "same-origin", - }).then(function (response) { - var result = WebAssembly.instantiateStreaming(response, info, { - simdWormhole: true, - }); - return result.then(receiveInstantiatedSource, function (reason) { - err("wasm streaming compile failed: " + reason); - err("falling back to ArrayBuffer instantiation"); - return instantiateArrayBuffer(receiveInstantiatedSource); - }); - }); - } - else { - return instantiateArrayBuffer(receiveInstantiatedSource); - } - } - if (Module["instantiateWasm"]) { - try { - var exports = Module["instantiateWasm"](info, receiveInstance); - return exports; - } - catch (e) { - err("Module.instantiateWasm callback failed with error: " + e); - return false; - } - } - instantiateAsync(); - return {}; - } - var tempDouble; - var tempI64; - var ASM_CONSTS = { - 1466288: function () { - throw "Canceled!"; - }, - 1466510: function ($0, $1) { - setTimeout(function () { - _do_emscripten_dispatch_to_thread($0, $1); - }, 0); - }, - }; - function initPthreadsJS() { - PThread.initRuntime(); - } - function callRuntimeCallbacks(callbacks) { - while (callbacks.length > 0) { - var callback = callbacks.shift(); - if (typeof callback == "function") { - callback(Module); - continue; - } - var func = callback.func; - if (typeof func === "number") { - if (callback.arg === undefined) { - wasmTable.get(func)(); - } - else { - wasmTable.get(func)(callback.arg); - } - } - else { - func(callback.arg === undefined ? null : callback.arg); - } - } - } - function demangle(func) { - return func; - } - function demangleAll(text) { - var regex = /\b_Z[\w\d_]+/g; - return text.replace(regex, function (x) { - var y = demangle(x); - return x === y ? x : y + " [" + x + "]"; - }); - } - function dynCallLegacy(sig, ptr, args) { - if (args && args.length) { - return Module["dynCall_" + sig].apply(null, [ptr].concat(args)); - } - return Module["dynCall_" + sig].call(null, ptr); - } - function dynCall(sig, ptr, args) { - if (sig.indexOf("j") != -1) { - return dynCallLegacy(sig, ptr, args); - } - return wasmTable.get(ptr).apply(null, args); - } - Module["dynCall"] = dynCall; - var __pthread_ptr = 0; - var __pthread_is_main_runtime_thread = 0; - var __pthread_is_main_browser_thread = 0; - function registerPthreadPtr(pthreadPtr, isMainBrowserThread, isMainRuntimeThread) { - pthreadPtr = pthreadPtr | 0; - isMainBrowserThread = isMainBrowserThread | 0; - isMainRuntimeThread = isMainRuntimeThread | 0; - __pthread_ptr = pthreadPtr; - __pthread_is_main_browser_thread = isMainBrowserThread; - __pthread_is_main_runtime_thread = isMainRuntimeThread; - } - Module["registerPthreadPtr"] = registerPthreadPtr; - var ERRNO_CODES = { - EPERM: 63, - ENOENT: 44, - ESRCH: 71, - EINTR: 27, - EIO: 29, - ENXIO: 60, - E2BIG: 1, - ENOEXEC: 45, - EBADF: 8, - ECHILD: 12, - EAGAIN: 6, - EWOULDBLOCK: 6, - ENOMEM: 48, - EACCES: 2, - EFAULT: 21, - ENOTBLK: 105, - EBUSY: 10, - EEXIST: 20, - EXDEV: 75, - ENODEV: 43, - ENOTDIR: 54, - EISDIR: 31, - EINVAL: 28, - ENFILE: 41, - EMFILE: 33, - ENOTTY: 59, - ETXTBSY: 74, - EFBIG: 22, - ENOSPC: 51, - ESPIPE: 70, - EROFS: 69, - EMLINK: 34, - EPIPE: 64, - EDOM: 18, - ERANGE: 68, - ENOMSG: 49, - EIDRM: 24, - ECHRNG: 106, - EL2NSYNC: 156, - EL3HLT: 107, - EL3RST: 108, - ELNRNG: 109, - EUNATCH: 110, - ENOCSI: 111, - EL2HLT: 112, - EDEADLK: 16, - ENOLCK: 46, - EBADE: 113, - EBADR: 114, - EXFULL: 115, - ENOANO: 104, - EBADRQC: 103, - EBADSLT: 102, - EDEADLOCK: 16, - EBFONT: 101, - ENOSTR: 100, - ENODATA: 116, - ETIME: 117, - ENOSR: 118, - ENONET: 119, - ENOPKG: 120, - EREMOTE: 121, - ENOLINK: 47, - EADV: 122, - ESRMNT: 123, - ECOMM: 124, - EPROTO: 65, - EMULTIHOP: 36, - EDOTDOT: 125, - EBADMSG: 9, - ENOTUNIQ: 126, - EBADFD: 127, - EREMCHG: 128, - ELIBACC: 129, - ELIBBAD: 130, - ELIBSCN: 131, - ELIBMAX: 132, - ELIBEXEC: 133, - ENOSYS: 52, - ENOTEMPTY: 55, - ENAMETOOLONG: 37, - ELOOP: 32, - EOPNOTSUPP: 138, - EPFNOSUPPORT: 139, - ECONNRESET: 15, - ENOBUFS: 42, - EAFNOSUPPORT: 5, - EPROTOTYPE: 67, - ENOTSOCK: 57, - ENOPROTOOPT: 50, - ESHUTDOWN: 140, - ECONNREFUSED: 14, - EADDRINUSE: 3, - ECONNABORTED: 13, - ENETUNREACH: 40, - ENETDOWN: 38, - ETIMEDOUT: 73, - EHOSTDOWN: 142, - EHOSTUNREACH: 23, - EINPROGRESS: 26, - EALREADY: 7, - EDESTADDRREQ: 17, - EMSGSIZE: 35, - EPROTONOSUPPORT: 66, - ESOCKTNOSUPPORT: 137, - EADDRNOTAVAIL: 4, - ENETRESET: 39, - EISCONN: 30, - ENOTCONN: 53, - ETOOMANYREFS: 141, - EUSERS: 136, - EDQUOT: 19, - ESTALE: 72, - ENOTSUP: 138, - ENOMEDIUM: 148, - EILSEQ: 25, - EOVERFLOW: 61, - ECANCELED: 11, - ENOTRECOVERABLE: 56, - EOWNERDEAD: 62, - ESTRPIPE: 135, - }; - function _emscripten_futex_wake(addr, count) { - if (addr <= 0 || - addr > GROWABLE_HEAP_I8().length || - addr & (3 != 0) || - count < 0) - return -28; - if (count == 0) - return 0; - if (count >= 2147483647) - count = Infinity; - var mainThreadWaitAddress = Atomics.load(GROWABLE_HEAP_I32(), PThread.mainThreadFutex >> 2); - var mainThreadWoken = 0; - if (mainThreadWaitAddress == addr) { - var loadedAddr = Atomics.compareExchange(GROWABLE_HEAP_I32(), PThread.mainThreadFutex >> 2, mainThreadWaitAddress, 0); - if (loadedAddr == mainThreadWaitAddress) { - --count; - mainThreadWoken = 1; - if (count <= 0) - return 1; - } - } - var ret = Atomics.notify(GROWABLE_HEAP_I32(), addr >> 2, count); - if (ret >= 0) - return ret + mainThreadWoken; - throw "Atomics.notify returned an unexpected value " + ret; - } - Module["_emscripten_futex_wake"] = _emscripten_futex_wake; - function killThread(pthread_ptr) { - if (ENVIRONMENT_IS_PTHREAD) - throw "Internal Error! killThread() can only ever be called from main application thread!"; - if (!pthread_ptr) - throw "Internal Error! Null pthread_ptr in killThread!"; - GROWABLE_HEAP_I32()[(pthread_ptr + 12) >> 2] = 0; - var pthread = PThread.pthreads[pthread_ptr]; - pthread.worker.terminate(); - PThread.freeThreadData(pthread); - PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(pthread.worker), 1); - pthread.worker.pthread = undefined; - } - function cancelThread(pthread_ptr) { - if (ENVIRONMENT_IS_PTHREAD) - throw "Internal Error! cancelThread() can only ever be called from main application thread!"; - if (!pthread_ptr) - throw "Internal Error! Null pthread_ptr in cancelThread!"; - var pthread = PThread.pthreads[pthread_ptr]; - pthread.worker.postMessage({ - cmd: "cancel", - }); - } - function cleanupThread(pthread_ptr) { - if (ENVIRONMENT_IS_PTHREAD) - throw "Internal Error! cleanupThread() can only ever be called from main application thread!"; - if (!pthread_ptr) - throw "Internal Error! Null pthread_ptr in cleanupThread!"; - GROWABLE_HEAP_I32()[(pthread_ptr + 12) >> 2] = 0; - var pthread = PThread.pthreads[pthread_ptr]; - if (pthread) { - var worker = pthread.worker; - PThread.returnWorkerToPool(worker); - } - } - var PThread = { - MAIN_THREAD_ID: 1, - mainThreadInfo: { - schedPolicy: 0, - schedPrio: 0, - }, - unusedWorkers: [], - runningWorkers: [], - initMainThreadBlock: function () { }, - initRuntime: function () { - PThread.mainThreadBlock = _malloc(232); - for (var i = 0; i < 232 / 4; ++i) - GROWABLE_HEAP_U32()[PThread.mainThreadBlock / 4 + i] = 0; - GROWABLE_HEAP_I32()[(PThread.mainThreadBlock + 12) >> 2] = - PThread.mainThreadBlock; - var headPtr = PThread.mainThreadBlock + 156; - GROWABLE_HEAP_I32()[headPtr >> 2] = headPtr; - var tlsMemory = _malloc(512); - for (var i = 0; i < 128; ++i) - GROWABLE_HEAP_U32()[tlsMemory / 4 + i] = 0; - Atomics.store(GROWABLE_HEAP_U32(), (PThread.mainThreadBlock + 104) >> 2, tlsMemory); - Atomics.store(GROWABLE_HEAP_U32(), (PThread.mainThreadBlock + 40) >> 2, PThread.mainThreadBlock); - Atomics.store(GROWABLE_HEAP_U32(), (PThread.mainThreadBlock + 44) >> 2, 42); - PThread.initShared(); - registerPthreadPtr(PThread.mainThreadBlock, !ENVIRONMENT_IS_WORKER, 1); - _emscripten_register_main_browser_thread_id(PThread.mainThreadBlock); - }, - initWorker: function () { - PThread.initShared(); - }, - initShared: function () { - PThread.mainThreadFutex = _main_thread_futex; - }, - pthreads: {}, - threadExitHandlers: [], - setThreadStatus: function () { }, - runExitHandlers: function () { - while (PThread.threadExitHandlers.length > 0) { - PThread.threadExitHandlers.pop()(); - } - if (ENVIRONMENT_IS_PTHREAD && threadInfoStruct) - ___pthread_tsd_run_dtors(); - }, - threadExit: function (exitCode) { - var tb = _pthread_self(); - if (tb) { - Atomics.store(GROWABLE_HEAP_U32(), (tb + 4) >> 2, exitCode); - Atomics.store(GROWABLE_HEAP_U32(), (tb + 0) >> 2, 1); - Atomics.store(GROWABLE_HEAP_U32(), (tb + 60) >> 2, 1); - Atomics.store(GROWABLE_HEAP_U32(), (tb + 64) >> 2, 0); - PThread.runExitHandlers(); - _emscripten_futex_wake(tb + 0, 2147483647); - registerPthreadPtr(0, 0, 0); - threadInfoStruct = 0; - if (ENVIRONMENT_IS_PTHREAD) { - postMessage({ - cmd: "exit", - }); - } - } - }, - threadCancel: function () { - PThread.runExitHandlers(); - Atomics.store(GROWABLE_HEAP_U32(), (threadInfoStruct + 4) >> 2, -1); - Atomics.store(GROWABLE_HEAP_U32(), (threadInfoStruct + 0) >> 2, 1); - _emscripten_futex_wake(threadInfoStruct + 0, 2147483647); - threadInfoStruct = selfThreadId = 0; - registerPthreadPtr(0, 0, 0); - postMessage({ - cmd: "cancelDone", - }); - }, - terminateAllThreads: function () { - for (var t in PThread.pthreads) { - var pthread = PThread.pthreads[t]; - if (pthread && pthread.worker) { - PThread.returnWorkerToPool(pthread.worker); - } - } - PThread.pthreads = {}; - for (var i = 0; i < PThread.unusedWorkers.length; ++i) { - var worker = PThread.unusedWorkers[i]; - worker.terminate(); - } - PThread.unusedWorkers = []; - for (var i = 0; i < PThread.runningWorkers.length; ++i) { - var worker = PThread.runningWorkers[i]; - var pthread = worker.pthread; - PThread.freeThreadData(pthread); - worker.terminate(); - } - PThread.runningWorkers = []; - }, - freeThreadData: function (pthread) { - if (!pthread) - return; - if (pthread.threadInfoStruct) { - var tlsMemory = GROWABLE_HEAP_I32()[(pthread.threadInfoStruct + 104) >> 2]; - GROWABLE_HEAP_I32()[(pthread.threadInfoStruct + 104) >> 2] = 0; - _free(tlsMemory); - _free(pthread.threadInfoStruct); - } - pthread.threadInfoStruct = 0; - if (pthread.allocatedOwnStack && pthread.stackBase) - _free(pthread.stackBase); - pthread.stackBase = 0; - if (pthread.worker) - pthread.worker.pthread = null; - }, - returnWorkerToPool: function (worker) { - delete PThread.pthreads[worker.pthread.thread]; - PThread.unusedWorkers.push(worker); - PThread.runningWorkers.splice(PThread.runningWorkers.indexOf(worker), 1); - PThread.freeThreadData(worker.pthread); - worker.pthread = undefined; - }, - receiveObjectTransfer: function (data) { }, - loadWasmModuleToWorker: function (worker, onFinishedLoading) { - worker.onmessage = function (e) { - var d = e["data"]; - var cmd = d["cmd"]; - if (worker.pthread) - PThread.currentProxiedOperationCallerThread = - worker.pthread.threadInfoStruct; - if (d["targetThread"] && d["targetThread"] != _pthread_self()) { - var thread = PThread.pthreads[d.targetThread]; - if (thread) { - thread.worker.postMessage(e.data, d["transferList"]); - } - else { - console.error('Internal error! Worker sent a message "' + - cmd + - '" to target pthread ' + - d["targetThread"] + - ", but that thread no longer exists!"); - } - PThread.currentProxiedOperationCallerThread = undefined; - return; - } - if (cmd === "processQueuedMainThreadWork") { - _emscripten_main_thread_process_queued_calls(); - } - else if (cmd === "spawnThread") { - spawnThread(e.data); - } - else if (cmd === "cleanupThread") { - cleanupThread(d["thread"]); - } - else if (cmd === "killThread") { - killThread(d["thread"]); - } - else if (cmd === "cancelThread") { - cancelThread(d["thread"]); - } - else if (cmd === "loaded") { - worker.loaded = true; - if (onFinishedLoading) - onFinishedLoading(worker); - if (worker.runPthread) { - worker.runPthread(); - delete worker.runPthread; - } - } - else if (cmd === "print") { - out("Thread " + d["threadId"] + ": " + d["text"]); - } - else if (cmd === "printErr") { - err("Thread " + d["threadId"] + ": " + d["text"]); - } - else if (cmd === "alert") { - alert("Thread " + d["threadId"] + ": " + d["text"]); - } - else if (cmd === "exit") { - var detached = worker.pthread && - Atomics.load(GROWABLE_HEAP_U32(), (worker.pthread.thread + 68) >> 2); - if (detached) { - PThread.returnWorkerToPool(worker); - } - } - else if (cmd === "cancelDone") { - PThread.returnWorkerToPool(worker); - } - else if (cmd === "objectTransfer") { - PThread.receiveObjectTransfer(e.data); - } - else if (e.data.target === "setimmediate") { - worker.postMessage(e.data); - } - else { - err("worker sent an unknown command " + cmd); - } - PThread.currentProxiedOperationCallerThread = undefined; - }; - worker.onerror = function (e) { - err("pthread sent an error! " + - e.filename + - ":" + - e.lineno + - ": " + - e.message); - }; - worker.postMessage({ - cmd: "load", - urlOrBlob: Module["mainScriptUrlOrBlob"] || _scriptDir, - wasmMemory: wasmMemory, - wasmModule: wasmModule, - }); - }, - allocateUnusedWorker: function () { - var pthreadMainJs = locateFile("bergamot-translator-worker.worker.js"); - PThread.unusedWorkers.push(new Worker(pthreadMainJs)); - }, - getNewWorker: function () { - if (PThread.unusedWorkers.length == 0) { - PThread.allocateUnusedWorker(); - PThread.loadWasmModuleToWorker(PThread.unusedWorkers[0]); - } - if (PThread.unusedWorkers.length > 0) - return PThread.unusedWorkers.pop(); - else - return null; - }, - busySpinWait: function (msecs) { - var t = performance.now() + msecs; - while (performance.now() < t) { } - }, - }; - function establishStackSpace(stackTop, stackMax) { - _emscripten_stack_set_limits(stackTop, stackMax); - stackRestore(stackTop); - } - Module["establishStackSpace"] = establishStackSpace; - function getNoExitRuntime() { - return noExitRuntime; - } - Module["getNoExitRuntime"] = getNoExitRuntime; - function jsStackTrace() { - var error = new Error(); - if (!error.stack) { - try { - throw new Error(); - } - catch (e) { - error = e; - } - if (!error.stack) { - return "(no stack trace available)"; - } - } - return error.stack.toString(); - } - function ___assert_fail(condition, filename, line, func) { - abort("Assertion failed: " + - UTF8ToString(condition) + - ", at: " + - [ - filename ? UTF8ToString(filename) : "unknown filename", - line, - func ? UTF8ToString(func) : "unknown function", - ]); - } - var _emscripten_get_now; - if (ENVIRONMENT_IS_PTHREAD) { - _emscripten_get_now = function () { - return performance.now() - Module["__performance_now_clock_drift"]; - }; - } - else - _emscripten_get_now = function () { - return performance.now(); - }; - var _emscripten_get_now_is_monotonic = true; - function setErrNo(value) { - GROWABLE_HEAP_I32()[___errno_location() >> 2] = value; - return value; - } - function _clock_gettime(clk_id, tp) { - var now; - if (clk_id === 0) { - now = Date.now(); - } - else if ((clk_id === 1 || clk_id === 4) && - _emscripten_get_now_is_monotonic) { - now = _emscripten_get_now(); - } - else { - setErrNo(28); - return -1; - } - GROWABLE_HEAP_I32()[tp >> 2] = (now / 1e3) | 0; - GROWABLE_HEAP_I32()[(tp + 4) >> 2] = ((now % 1e3) * 1e3 * 1e3) | 0; - return 0; - } - function ___clock_gettime(a0, a1) { - return _clock_gettime(a0, a1); - } - var ExceptionInfoAttrs = { - DESTRUCTOR_OFFSET: 0, - REFCOUNT_OFFSET: 4, - TYPE_OFFSET: 8, - CAUGHT_OFFSET: 12, - RETHROWN_OFFSET: 13, - SIZE: 16, - }; - function ___cxa_allocate_exception(size) { - return _malloc(size + ExceptionInfoAttrs.SIZE) + ExceptionInfoAttrs.SIZE; - } - function _atexit(func, arg) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(1, 1, func, arg); - } - function ___cxa_atexit(a0, a1) { - return _atexit(a0, a1); - } - function _pthread_cleanup_push(routine, arg) { - PThread.threadExitHandlers.push(function () { - wasmTable.get(routine)(arg); - }); - } - function ___cxa_thread_atexit(a0, a1) { - return _pthread_cleanup_push(a0, a1); - } - function ExceptionInfo(excPtr) { - this.excPtr = excPtr; - this.ptr = excPtr - ExceptionInfoAttrs.SIZE; - this.set_type = function (type) { - GROWABLE_HEAP_I32()[(this.ptr + ExceptionInfoAttrs.TYPE_OFFSET) >> 2] = type; - }; - this.get_type = function () { - return GROWABLE_HEAP_I32()[(this.ptr + ExceptionInfoAttrs.TYPE_OFFSET) >> 2]; - }; - this.set_destructor = function (destructor) { - GROWABLE_HEAP_I32()[(this.ptr + ExceptionInfoAttrs.DESTRUCTOR_OFFSET) >> 2] = destructor; - }; - this.get_destructor = function () { - return GROWABLE_HEAP_I32()[(this.ptr + ExceptionInfoAttrs.DESTRUCTOR_OFFSET) >> 2]; - }; - this.set_refcount = function (refcount) { - GROWABLE_HEAP_I32()[(this.ptr + ExceptionInfoAttrs.REFCOUNT_OFFSET) >> 2] = refcount; - }; - this.set_caught = function (caught) { - caught = caught ? 1 : 0; - GROWABLE_HEAP_I8()[(this.ptr + ExceptionInfoAttrs.CAUGHT_OFFSET) >> 0] = caught; - }; - this.get_caught = function () { - return (GROWABLE_HEAP_I8()[(this.ptr + ExceptionInfoAttrs.CAUGHT_OFFSET) >> 0] != 0); - }; - this.set_rethrown = function (rethrown) { - rethrown = rethrown ? 1 : 0; - GROWABLE_HEAP_I8()[(this.ptr + ExceptionInfoAttrs.RETHROWN_OFFSET) >> 0] = rethrown; - }; - this.get_rethrown = function () { - return (GROWABLE_HEAP_I8()[(this.ptr + ExceptionInfoAttrs.RETHROWN_OFFSET) >> 0] != 0); - }; - this.init = function (type, destructor) { - this.set_type(type); - this.set_destructor(destructor); - this.set_refcount(0); - this.set_caught(false); - this.set_rethrown(false); - }; - this.add_ref = function () { - Atomics.add(GROWABLE_HEAP_I32(), (this.ptr + ExceptionInfoAttrs.REFCOUNT_OFFSET) >> 2, 1); - }; - this.release_ref = function () { - var prev = Atomics.sub(GROWABLE_HEAP_I32(), (this.ptr + ExceptionInfoAttrs.REFCOUNT_OFFSET) >> 2, 1); - return prev === 1; - }; - } - var exceptionLast = 0; - var uncaughtExceptionCount = 0; - function ___cxa_throw(ptr, type, destructor) { - var info = new ExceptionInfo(ptr); - info.init(type, destructor); - exceptionLast = ptr; - uncaughtExceptionCount++; - throw ptr; - } - var PATH = { - splitPath: function (filename) { - var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; - return splitPathRe.exec(filename).slice(1); - }, - normalizeArray: function (parts, allowAboveRoot) { - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === ".") { - parts.splice(i, 1); - } - else if (last === "..") { - parts.splice(i, 1); - up++; - } - else if (up) { - parts.splice(i, 1); - up--; - } - } - if (allowAboveRoot) { - for (; up; up--) { - parts.unshift(".."); - } - } - return parts; - }, - normalize: function (path) { - var isAbsolute = path.charAt(0) === "/", trailingSlash = path.substr(-1) === "/"; - path = PATH.normalizeArray(path.split("/").filter(function (p) { - return !!p; - }), !isAbsolute).join("/"); - if (!path && !isAbsolute) { - path = "."; - } - if (path && trailingSlash) { - path += "/"; - } - return (isAbsolute ? "/" : "") + path; - }, - dirname: function (path) { - var result = PATH.splitPath(path), root = result[0], dir = result[1]; - if (!root && !dir) { - return "."; - } - if (dir) { - dir = dir.substr(0, dir.length - 1); - } - return root + dir; - }, - basename: function (path) { - if (path === "/") - return "/"; - path = PATH.normalize(path); - path = path.replace(/\/$/, ""); - var lastSlash = path.lastIndexOf("/"); - if (lastSlash === -1) - return path; - return path.substr(lastSlash + 1); - }, - extname: function (path) { - return PATH.splitPath(path)[3]; - }, - join: function () { - var paths = Array.prototype.slice.call(arguments, 0); - return PATH.normalize(paths.join("/")); - }, - join2: function (l, r) { - return PATH.normalize(l + "/" + r); - }, - }; - function getRandomDevice() { - if (typeof crypto === "object" && - typeof crypto["getRandomValues"] === "function") { - var randomBuffer = new Uint8Array(1); - return function () { - crypto.getRandomValues(randomBuffer); - return randomBuffer[0]; - }; - } - else - return function () { - abort("randomDevice"); - }; - } - var PATH_FS = { - resolve: function () { - var resolvedPath = "", resolvedAbsolute = false; - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = i >= 0 ? arguments[i] : FS.cwd(); - if (typeof path !== "string") { - throw new TypeError("Arguments to path.resolve must be strings"); - } - else if (!path) { - return ""; - } - resolvedPath = path + "/" + resolvedPath; - resolvedAbsolute = path.charAt(0) === "/"; - } - resolvedPath = PATH.normalizeArray(resolvedPath.split("/").filter(function (p) { - return !!p; - }), !resolvedAbsolute).join("/"); - return (resolvedAbsolute ? "/" : "") + resolvedPath || "."; - }, - relative: function (from, to) { - from = PATH_FS.resolve(from).substr(1); - to = PATH_FS.resolve(to).substr(1); - function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== "") - break; - } - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== "") - break; - } - if (start > end) - return []; - return arr.slice(start, end - start + 1); - } - var fromParts = trim(from.split("/")); - var toParts = trim(to.split("/")); - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push(".."); - } - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - return outputParts.join("/"); - }, - }; - var TTY = { - ttys: [], - init: function () { }, - shutdown: function () { }, - register: function (dev, ops) { - TTY.ttys[dev] = { - input: [], - output: [], - ops: ops, - }; - FS.registerDevice(dev, TTY.stream_ops); - }, - stream_ops: { - open: function (stream) { - var tty = TTY.ttys[stream.node.rdev]; - if (!tty) { - throw new FS.ErrnoError(43); - } - stream.tty = tty; - stream.seekable = false; - }, - close: function (stream) { - stream.tty.ops.flush(stream.tty); - }, - flush: function (stream) { - stream.tty.ops.flush(stream.tty); - }, - read: function (stream, buffer, offset, length, pos) { - if (!stream.tty || !stream.tty.ops.get_char) { - throw new FS.ErrnoError(60); - } - var bytesRead = 0; - for (var i = 0; i < length; i++) { - var result; - try { - result = stream.tty.ops.get_char(stream.tty); - } - catch (e) { - throw new FS.ErrnoError(29); - } - if (result === undefined && bytesRead === 0) { - throw new FS.ErrnoError(6); - } - if (result === null || result === undefined) - break; - bytesRead++; - buffer[offset + i] = result; - } - if (bytesRead) { - stream.node.timestamp = Date.now(); - } - return bytesRead; - }, - write: function (stream, buffer, offset, length, pos) { - if (!stream.tty || !stream.tty.ops.put_char) { - throw new FS.ErrnoError(60); - } - try { - for (var i = 0; i < length; i++) { - stream.tty.ops.put_char(stream.tty, buffer[offset + i]); - } - } - catch (e) { - throw new FS.ErrnoError(29); - } - if (length) { - stream.node.timestamp = Date.now(); - } - return i; - }, - }, - default_tty_ops: { - get_char: function (tty) { - if (!tty.input.length) { - var result = null; - if (typeof window != "undefined" && - typeof window.prompt == "function") { - result = window.prompt("Input: "); - if (result !== null) { - result += "\n"; - } - } - else if (typeof readline == "function") { - result = readline(); - if (result !== null) { - result += "\n"; - } - } - if (!result) { - return null; - } - tty.input = intArrayFromString(result, true); - } - return tty.input.shift(); - }, - put_char: function (tty, val) { - if (val === null || val === 10) { - out(UTF8ArrayToString(tty.output, 0)); - tty.output = []; - } - else { - if (val != 0) - tty.output.push(val); - } - }, - flush: function (tty) { - if (tty.output && tty.output.length > 0) { - out(UTF8ArrayToString(tty.output, 0)); - tty.output = []; - } - }, - }, - default_tty1_ops: { - put_char: function (tty, val) { - if (val === null || val === 10) { - err(UTF8ArrayToString(tty.output, 0)); - tty.output = []; - } - else { - if (val != 0) - tty.output.push(val); - } - }, - flush: function (tty) { - if (tty.output && tty.output.length > 0) { - err(UTF8ArrayToString(tty.output, 0)); - tty.output = []; - } - }, - }, - }; - function mmapAlloc(size) { - var alignedSize = alignMemory(size, 16384); - var ptr = _malloc(alignedSize); - while (size < alignedSize) - GROWABLE_HEAP_I8()[ptr + size++] = 0; - return ptr; - } - var MEMFS = { - ops_table: null, - mount: function (mount) { - return MEMFS.createNode(null, "/", 16384 | 511, 0); - }, - createNode: function (parent, name, mode, dev) { - if (FS.isBlkdev(mode) || FS.isFIFO(mode)) { - throw new FS.ErrnoError(63); - } - if (!MEMFS.ops_table) { - MEMFS.ops_table = { - dir: { - node: { - getattr: MEMFS.node_ops.getattr, - setattr: MEMFS.node_ops.setattr, - lookup: MEMFS.node_ops.lookup, - mknod: MEMFS.node_ops.mknod, - rename: MEMFS.node_ops.rename, - unlink: MEMFS.node_ops.unlink, - rmdir: MEMFS.node_ops.rmdir, - readdir: MEMFS.node_ops.readdir, - symlink: MEMFS.node_ops.symlink, - }, - stream: { - llseek: MEMFS.stream_ops.llseek, - }, - }, - file: { - node: { - getattr: MEMFS.node_ops.getattr, - setattr: MEMFS.node_ops.setattr, - }, - stream: { - llseek: MEMFS.stream_ops.llseek, - read: MEMFS.stream_ops.read, - write: MEMFS.stream_ops.write, - allocate: MEMFS.stream_ops.allocate, - mmap: MEMFS.stream_ops.mmap, - msync: MEMFS.stream_ops.msync, - }, - }, - link: { - node: { - getattr: MEMFS.node_ops.getattr, - setattr: MEMFS.node_ops.setattr, - readlink: MEMFS.node_ops.readlink, - }, - stream: {}, - }, - chrdev: { - node: { - getattr: MEMFS.node_ops.getattr, - setattr: MEMFS.node_ops.setattr, - }, - stream: FS.chrdev_stream_ops, - }, - }; - } - var node = FS.createNode(parent, name, mode, dev); - if (FS.isDir(node.mode)) { - node.node_ops = MEMFS.ops_table.dir.node; - node.stream_ops = MEMFS.ops_table.dir.stream; - node.contents = {}; - } - else if (FS.isFile(node.mode)) { - node.node_ops = MEMFS.ops_table.file.node; - node.stream_ops = MEMFS.ops_table.file.stream; - node.usedBytes = 0; - node.contents = null; - } - else if (FS.isLink(node.mode)) { - node.node_ops = MEMFS.ops_table.link.node; - node.stream_ops = MEMFS.ops_table.link.stream; - } - else if (FS.isChrdev(node.mode)) { - node.node_ops = MEMFS.ops_table.chrdev.node; - node.stream_ops = MEMFS.ops_table.chrdev.stream; - } - node.timestamp = Date.now(); - if (parent) { - parent.contents[name] = node; - } - return node; - }, - getFileDataAsRegularArray: function (node) { - if (node.contents && node.contents.subarray) { - var arr = []; - for (var i = 0; i < node.usedBytes; ++i) - arr.push(node.contents[i]); - return arr; - } - return node.contents; - }, - getFileDataAsTypedArray: function (node) { - if (!node.contents) - return new Uint8Array(0); - if (node.contents.subarray) - return node.contents.subarray(0, node.usedBytes); - return new Uint8Array(node.contents); - }, - expandFileStorage: function (node, newCapacity) { - var prevCapacity = node.contents ? node.contents.length : 0; - if (prevCapacity >= newCapacity) - return; - var CAPACITY_DOUBLING_MAX = 1024 * 1024; - newCapacity = Math.max(newCapacity, (prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125)) >>> - 0); - if (prevCapacity != 0) - newCapacity = Math.max(newCapacity, 256); - var oldContents = node.contents; - node.contents = new Uint8Array(newCapacity); - if (node.usedBytes > 0) - node.contents.set(oldContents.subarray(0, node.usedBytes), 0); - return; - }, - resizeFileStorage: function (node, newSize) { - if (node.usedBytes == newSize) - return; - if (newSize == 0) { - node.contents = null; - node.usedBytes = 0; - return; - } - if (!node.contents || node.contents.subarray) { - var oldContents = node.contents; - node.contents = new Uint8Array(newSize); - if (oldContents) { - node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes))); - } - node.usedBytes = newSize; - return; - } - if (!node.contents) - node.contents = []; - if (node.contents.length > newSize) - node.contents.length = newSize; - else - while (node.contents.length < newSize) - node.contents.push(0); - node.usedBytes = newSize; - }, - node_ops: { - getattr: function (node) { - var attr = {}; - attr.dev = FS.isChrdev(node.mode) ? node.id : 1; - attr.ino = node.id; - attr.mode = node.mode; - attr.nlink = 1; - attr.uid = 0; - attr.gid = 0; - attr.rdev = node.rdev; - if (FS.isDir(node.mode)) { - attr.size = 4096; - } - else if (FS.isFile(node.mode)) { - attr.size = node.usedBytes; - } - else if (FS.isLink(node.mode)) { - attr.size = node.link.length; - } - else { - attr.size = 0; - } - attr.atime = new Date(node.timestamp); - attr.mtime = new Date(node.timestamp); - attr.ctime = new Date(node.timestamp); - attr.blksize = 4096; - attr.blocks = Math.ceil(attr.size / attr.blksize); - return attr; - }, - setattr: function (node, attr) { - if (attr.mode !== undefined) { - node.mode = attr.mode; - } - if (attr.timestamp !== undefined) { - node.timestamp = attr.timestamp; - } - if (attr.size !== undefined) { - MEMFS.resizeFileStorage(node, attr.size); - } - }, - lookup: function (parent, name) { - throw FS.genericErrors[44]; - }, - mknod: function (parent, name, mode, dev) { - return MEMFS.createNode(parent, name, mode, dev); - }, - rename: function (old_node, new_dir, new_name) { - if (FS.isDir(old_node.mode)) { - var new_node; - try { - new_node = FS.lookupNode(new_dir, new_name); - } - catch (e) { } - if (new_node) { - for (var i in new_node.contents) { - throw new FS.ErrnoError(55); - } - } - } - delete old_node.parent.contents[old_node.name]; - old_node.name = new_name; - new_dir.contents[new_name] = old_node; - old_node.parent = new_dir; - }, - unlink: function (parent, name) { - delete parent.contents[name]; - }, - rmdir: function (parent, name) { - var node = FS.lookupNode(parent, name); - for (var i in node.contents) { - throw new FS.ErrnoError(55); - } - delete parent.contents[name]; - }, - readdir: function (node) { - var entries = [".", ".."]; - for (var key in node.contents) { - if (!node.contents.hasOwnProperty(key)) { - continue; - } - entries.push(key); - } - return entries; - }, - symlink: function (parent, newname, oldpath) { - var node = MEMFS.createNode(parent, newname, 511 | 40960, 0); - node.link = oldpath; - return node; - }, - readlink: function (node) { - if (!FS.isLink(node.mode)) { - throw new FS.ErrnoError(28); - } - return node.link; - }, - }, - stream_ops: { - read: function (stream, buffer, offset, length, position) { - var contents = stream.node.contents; - if (position >= stream.node.usedBytes) - return 0; - var size = Math.min(stream.node.usedBytes - position, length); - if (size > 8 && contents.subarray) { - buffer.set(contents.subarray(position, position + size), offset); - } - else { - for (var i = 0; i < size; i++) - buffer[offset + i] = contents[position + i]; - } - return size; - }, - write: function (stream, buffer, offset, length, position, canOwn) { - if (buffer.buffer === GROWABLE_HEAP_I8().buffer) { - canOwn = false; - } - if (!length) - return 0; - var node = stream.node; - node.timestamp = Date.now(); - if (buffer.subarray && (!node.contents || node.contents.subarray)) { - if (canOwn) { - node.contents = buffer.subarray(offset, offset + length); - node.usedBytes = length; - return length; - } - else if (node.usedBytes === 0 && position === 0) { - node.contents = buffer.slice(offset, offset + length); - node.usedBytes = length; - return length; - } - else if (position + length <= node.usedBytes) { - node.contents.set(buffer.subarray(offset, offset + length), position); - return length; - } - } - MEMFS.expandFileStorage(node, position + length); - if (node.contents.subarray && buffer.subarray) { - node.contents.set(buffer.subarray(offset, offset + length), position); - } - else { - for (var i = 0; i < length; i++) { - node.contents[position + i] = buffer[offset + i]; - } - } - node.usedBytes = Math.max(node.usedBytes, position + length); - return length; - }, - llseek: function (stream, offset, whence) { - var position = offset; - if (whence === 1) { - position += stream.position; - } - else if (whence === 2) { - if (FS.isFile(stream.node.mode)) { - position += stream.node.usedBytes; - } - } - if (position < 0) { - throw new FS.ErrnoError(28); - } - return position; - }, - allocate: function (stream, offset, length) { - MEMFS.expandFileStorage(stream.node, offset + length); - stream.node.usedBytes = Math.max(stream.node.usedBytes, offset + length); - }, - mmap: function (stream, address, length, position, prot, flags) { - assert(address === 0); - if (!FS.isFile(stream.node.mode)) { - throw new FS.ErrnoError(43); - } - var ptr; - var allocated; - var contents = stream.node.contents; - if (!(flags & 2) && contents.buffer === buffer) { - allocated = false; - ptr = contents.byteOffset; - } - else { - if (position > 0 || position + length < contents.length) { - if (contents.subarray) { - contents = contents.subarray(position, position + length); - } - else { - contents = Array.prototype.slice.call(contents, position, position + length); - } - } - allocated = true; - ptr = mmapAlloc(length); - if (!ptr) { - throw new FS.ErrnoError(48); - } - GROWABLE_HEAP_I8().set(contents, ptr); - } - return { - ptr: ptr, - allocated: allocated, - }; - }, - msync: function (stream, buffer, offset, length, mmapFlags) { - if (!FS.isFile(stream.node.mode)) { - throw new FS.ErrnoError(43); - } - if (mmapFlags & 2) { - return 0; - } - var bytesWritten = MEMFS.stream_ops.write(stream, buffer, 0, length, offset, false); - return 0; - }, - }, - }; - var FS = { - root: null, - mounts: [], - devices: {}, - streams: [], - nextInode: 1, - nameTable: null, - currentPath: "/", - initialized: false, - ignorePermissions: true, - trackingDelegate: {}, - tracking: { - openFlags: { - READ: 1, - WRITE: 2, - }, - }, - ErrnoError: null, - genericErrors: {}, - filesystems: null, - syncFSRequests: 0, - lookupPath: function (path, opts) { - path = PATH_FS.resolve(FS.cwd(), path); - opts = opts || {}; - if (!path) - return { - path: "", - node: null, - }; - var defaults = { - follow_mount: true, - recurse_count: 0, - }; - for (var key in defaults) { - if (opts[key] === undefined) { - opts[key] = defaults[key]; - } - } - if (opts.recurse_count > 8) { - throw new FS.ErrnoError(32); - } - var parts = PATH.normalizeArray(path.split("/").filter(function (p) { - return !!p; - }), false); - var current = FS.root; - var current_path = "/"; - for (var i = 0; i < parts.length; i++) { - var islast = i === parts.length - 1; - if (islast && opts.parent) { - break; - } - current = FS.lookupNode(current, parts[i]); - current_path = PATH.join2(current_path, parts[i]); - if (FS.isMountpoint(current)) { - if (!islast || (islast && opts.follow_mount)) { - current = current.mounted.root; - } - } - if (!islast || opts.follow) { - var count = 0; - while (FS.isLink(current.mode)) { - var link = FS.readlink(current_path); - current_path = PATH_FS.resolve(PATH.dirname(current_path), link); - var lookup = FS.lookupPath(current_path, { - recurse_count: opts.recurse_count, - }); - current = lookup.node; - if (count++ > 40) { - throw new FS.ErrnoError(32); - } - } - } - } - return { - path: current_path, - node: current, - }; - }, - getPath: function (node) { - var path; - while (true) { - if (FS.isRoot(node)) { - var mount = node.mount.mountpoint; - if (!path) - return mount; - return mount[mount.length - 1] !== "/" - ? mount + "/" + path - : mount + path; - } - path = path ? node.name + "/" + path : node.name; - node = node.parent; - } - }, - hashName: function (parentid, name) { - var hash = 0; - for (var i = 0; i < name.length; i++) { - hash = ((hash << 5) - hash + name.charCodeAt(i)) | 0; - } - return ((parentid + hash) >>> 0) % FS.nameTable.length; - }, - hashAddNode: function (node) { - var hash = FS.hashName(node.parent.id, node.name); - node.name_next = FS.nameTable[hash]; - FS.nameTable[hash] = node; - }, - hashRemoveNode: function (node) { - var hash = FS.hashName(node.parent.id, node.name); - if (FS.nameTable[hash] === node) { - FS.nameTable[hash] = node.name_next; - } - else { - var current = FS.nameTable[hash]; - while (current) { - if (current.name_next === node) { - current.name_next = node.name_next; - break; - } - current = current.name_next; - } - } - }, - lookupNode: function (parent, name) { - var errCode = FS.mayLookup(parent); - if (errCode) { - throw new FS.ErrnoError(errCode, parent); - } - var hash = FS.hashName(parent.id, name); - for (var node = FS.nameTable[hash]; node; node = node.name_next) { - var nodeName = node.name; - if (node.parent.id === parent.id && nodeName === name) { - return node; - } - } - return FS.lookup(parent, name); - }, - createNode: function (parent, name, mode, rdev) { - var node = new FS.FSNode(parent, name, mode, rdev); - FS.hashAddNode(node); - return node; - }, - destroyNode: function (node) { - FS.hashRemoveNode(node); - }, - isRoot: function (node) { - return node === node.parent; - }, - isMountpoint: function (node) { - return !!node.mounted; - }, - isFile: function (mode) { - return (mode & 61440) === 32768; - }, - isDir: function (mode) { - return (mode & 61440) === 16384; - }, - isLink: function (mode) { - return (mode & 61440) === 40960; - }, - isChrdev: function (mode) { - return (mode & 61440) === 8192; - }, - isBlkdev: function (mode) { - return (mode & 61440) === 24576; - }, - isFIFO: function (mode) { - return (mode & 61440) === 4096; - }, - isSocket: function (mode) { - return (mode & 49152) === 49152; - }, - flagModes: { - r: 0, - "r+": 2, - w: 577, - "w+": 578, - a: 1089, - "a+": 1090, - }, - modeStringToFlags: function (str) { - var flags = FS.flagModes[str]; - if (typeof flags === "undefined") { - throw new Error("Unknown file open mode: " + str); - } - return flags; - }, - flagsToPermissionString: function (flag) { - var perms = ["r", "w", "rw"][flag & 3]; - if (flag & 512) { - perms += "w"; - } - return perms; - }, - nodePermissions: function (node, perms) { - if (FS.ignorePermissions) { - return 0; - } - if (perms.indexOf("r") !== -1 && !(node.mode & 292)) { - return 2; - } - else if (perms.indexOf("w") !== -1 && !(node.mode & 146)) { - return 2; - } - else if (perms.indexOf("x") !== -1 && !(node.mode & 73)) { - return 2; - } - return 0; - }, - mayLookup: function (dir) { - var errCode = FS.nodePermissions(dir, "x"); - if (errCode) - return errCode; - if (!dir.node_ops.lookup) - return 2; - return 0; - }, - mayCreate: function (dir, name) { - try { - var node = FS.lookupNode(dir, name); - return 20; - } - catch (e) { } - return FS.nodePermissions(dir, "wx"); - }, - mayDelete: function (dir, name, isdir) { - var node; - try { - node = FS.lookupNode(dir, name); - } - catch (e) { - return e.errno; - } - var errCode = FS.nodePermissions(dir, "wx"); - if (errCode) { - return errCode; - } - if (isdir) { - if (!FS.isDir(node.mode)) { - return 54; - } - if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) { - return 10; - } - } - else { - if (FS.isDir(node.mode)) { - return 31; - } - } - return 0; - }, - mayOpen: function (node, flags) { - if (!node) { - return 44; - } - if (FS.isLink(node.mode)) { - return 32; - } - else if (FS.isDir(node.mode)) { - if (FS.flagsToPermissionString(flags) !== "r" || flags & 512) { - return 31; - } - } - return FS.nodePermissions(node, FS.flagsToPermissionString(flags)); - }, - MAX_OPEN_FDS: 4096, - nextfd: function (fd_start, fd_end) { - fd_start = fd_start || 0; - fd_end = fd_end || FS.MAX_OPEN_FDS; - for (var fd = fd_start; fd <= fd_end; fd++) { - if (!FS.streams[fd]) { - return fd; - } - } - throw new FS.ErrnoError(33); - }, - getStream: function (fd) { - return FS.streams[fd]; - }, - createStream: function (stream, fd_start, fd_end) { - if (!FS.FSStream) { - FS.FSStream = function () { }; - FS.FSStream.prototype = { - object: { - get: function () { - return this.node; - }, - set: function (val) { - this.node = val; - }, - }, - isRead: { - get: function () { - return (this.flags & 2097155) !== 1; - }, - }, - isWrite: { - get: function () { - return (this.flags & 2097155) !== 0; - }, - }, - isAppend: { - get: function () { - return this.flags & 1024; - }, - }, - }; - } - var newStream = new FS.FSStream(); - for (var p in stream) { - newStream[p] = stream[p]; - } - stream = newStream; - var fd = FS.nextfd(fd_start, fd_end); - stream.fd = fd; - FS.streams[fd] = stream; - return stream; - }, - closeStream: function (fd) { - FS.streams[fd] = null; - }, - chrdev_stream_ops: { - open: function (stream) { - var device = FS.getDevice(stream.node.rdev); - stream.stream_ops = device.stream_ops; - if (stream.stream_ops.open) { - stream.stream_ops.open(stream); - } - }, - llseek: function () { - throw new FS.ErrnoError(70); - }, - }, - major: function (dev) { - return dev >> 8; - }, - minor: function (dev) { - return dev & 255; - }, - makedev: function (ma, mi) { - return (ma << 8) | mi; - }, - registerDevice: function (dev, ops) { - FS.devices[dev] = { - stream_ops: ops, - }; - }, - getDevice: function (dev) { - return FS.devices[dev]; - }, - getMounts: function (mount) { - var mounts = []; - var check = [mount]; - while (check.length) { - var m = check.pop(); - mounts.push(m); - check.push.apply(check, m.mounts); - } - return mounts; - }, - syncfs: function (populate, callback) { - if (typeof populate === "function") { - callback = populate; - populate = false; - } - FS.syncFSRequests++; - if (FS.syncFSRequests > 1) { - err("warning: " + - FS.syncFSRequests + - " FS.syncfs operations in flight at once, probably just doing extra work"); - } - var mounts = FS.getMounts(FS.root.mount); - var completed = 0; - function doCallback(errCode) { - FS.syncFSRequests--; - return callback(errCode); - } - function done(errCode) { - if (errCode) { - if (!done.errored) { - done.errored = true; - return doCallback(errCode); - } - return; - } - if (++completed >= mounts.length) { - doCallback(null); - } - } - mounts.forEach(function (mount) { - if (!mount.type.syncfs) { - return done(null); - } - mount.type.syncfs(mount, populate, done); - }); - }, - mount: function (type, opts, mountpoint) { - var root = mountpoint === "/"; - var pseudo = !mountpoint; - var node; - if (root && FS.root) { - throw new FS.ErrnoError(10); - } - else if (!root && !pseudo) { - var lookup = FS.lookupPath(mountpoint, { - follow_mount: false, - }); - mountpoint = lookup.path; - node = lookup.node; - if (FS.isMountpoint(node)) { - throw new FS.ErrnoError(10); - } - if (!FS.isDir(node.mode)) { - throw new FS.ErrnoError(54); - } - } - var mount = { - type: type, - opts: opts, - mountpoint: mountpoint, - mounts: [], - }; - var mountRoot = type.mount(mount); - mountRoot.mount = mount; - mount.root = mountRoot; - if (root) { - FS.root = mountRoot; - } - else if (node) { - node.mounted = mount; - if (node.mount) { - node.mount.mounts.push(mount); - } - } - return mountRoot; - }, - unmount: function (mountpoint) { - var lookup = FS.lookupPath(mountpoint, { - follow_mount: false, - }); - if (!FS.isMountpoint(lookup.node)) { - throw new FS.ErrnoError(28); - } - var node = lookup.node; - var mount = node.mounted; - var mounts = FS.getMounts(mount); - Object.keys(FS.nameTable).forEach(function (hash) { - var current = FS.nameTable[hash]; - while (current) { - var next = current.name_next; - if (mounts.indexOf(current.mount) !== -1) { - FS.destroyNode(current); - } - current = next; - } - }); - node.mounted = null; - var idx = node.mount.mounts.indexOf(mount); - node.mount.mounts.splice(idx, 1); - }, - lookup: function (parent, name) { - return parent.node_ops.lookup(parent, name); - }, - mknod: function (path, mode, dev) { - var lookup = FS.lookupPath(path, { - parent: true, - }); - var parent = lookup.node; - var name = PATH.basename(path); - if (!name || name === "." || name === "..") { - throw new FS.ErrnoError(28); - } - var errCode = FS.mayCreate(parent, name); - if (errCode) { - throw new FS.ErrnoError(errCode); - } - if (!parent.node_ops.mknod) { - throw new FS.ErrnoError(63); - } - return parent.node_ops.mknod(parent, name, mode, dev); - }, - create: function (path, mode) { - mode = mode !== undefined ? mode : 438; - mode &= 4095; - mode |= 32768; - return FS.mknod(path, mode, 0); - }, - mkdir: function (path, mode) { - mode = mode !== undefined ? mode : 511; - mode &= 511 | 512; - mode |= 16384; - return FS.mknod(path, mode, 0); - }, - mkdirTree: function (path, mode) { - var dirs = path.split("/"); - var d = ""; - for (var i = 0; i < dirs.length; ++i) { - if (!dirs[i]) - continue; - d += "/" + dirs[i]; - try { - FS.mkdir(d, mode); - } - catch (e) { - if (e.errno != 20) - throw e; - } - } - }, - mkdev: function (path, mode, dev) { - if (typeof dev === "undefined") { - dev = mode; - mode = 438; - } - mode |= 8192; - return FS.mknod(path, mode, dev); - }, - symlink: function (oldpath, newpath) { - if (!PATH_FS.resolve(oldpath)) { - throw new FS.ErrnoError(44); - } - var lookup = FS.lookupPath(newpath, { - parent: true, - }); - var parent = lookup.node; - if (!parent) { - throw new FS.ErrnoError(44); - } - var newname = PATH.basename(newpath); - var errCode = FS.mayCreate(parent, newname); - if (errCode) { - throw new FS.ErrnoError(errCode); - } - if (!parent.node_ops.symlink) { - throw new FS.ErrnoError(63); - } - return parent.node_ops.symlink(parent, newname, oldpath); - }, - rename: function (old_path, new_path) { - var old_dirname = PATH.dirname(old_path); - var new_dirname = PATH.dirname(new_path); - var old_name = PATH.basename(old_path); - var new_name = PATH.basename(new_path); - var lookup, old_dir, new_dir; - lookup = FS.lookupPath(old_path, { - parent: true, - }); - old_dir = lookup.node; - lookup = FS.lookupPath(new_path, { - parent: true, - }); - new_dir = lookup.node; - if (!old_dir || !new_dir) - throw new FS.ErrnoError(44); - if (old_dir.mount !== new_dir.mount) { - throw new FS.ErrnoError(75); - } - var old_node = FS.lookupNode(old_dir, old_name); - var relative = PATH_FS.relative(old_path, new_dirname); - if (relative.charAt(0) !== ".") { - throw new FS.ErrnoError(28); - } - relative = PATH_FS.relative(new_path, old_dirname); - if (relative.charAt(0) !== ".") { - throw new FS.ErrnoError(55); - } - var new_node; - try { - new_node = FS.lookupNode(new_dir, new_name); - } - catch (e) { } - if (old_node === new_node) { - return; - } - var isdir = FS.isDir(old_node.mode); - var errCode = FS.mayDelete(old_dir, old_name, isdir); - if (errCode) { - throw new FS.ErrnoError(errCode); - } - errCode = new_node - ? FS.mayDelete(new_dir, new_name, isdir) - : FS.mayCreate(new_dir, new_name); - if (errCode) { - throw new FS.ErrnoError(errCode); - } - if (!old_dir.node_ops.rename) { - throw new FS.ErrnoError(63); - } - if (FS.isMountpoint(old_node) || - (new_node && FS.isMountpoint(new_node))) { - throw new FS.ErrnoError(10); - } - if (new_dir !== old_dir) { - errCode = FS.nodePermissions(old_dir, "w"); - if (errCode) { - throw new FS.ErrnoError(errCode); - } - } - try { - if (FS.trackingDelegate["willMovePath"]) { - FS.trackingDelegate["willMovePath"](old_path, new_path); - } - } - catch (e) { - err("FS.trackingDelegate['willMovePath']('" + - old_path + - "', '" + - new_path + - "') threw an exception: " + - e.message); - } - FS.hashRemoveNode(old_node); - try { - old_dir.node_ops.rename(old_node, new_dir, new_name); - } - catch (e) { - throw e; - } - finally { - FS.hashAddNode(old_node); - } - try { - if (FS.trackingDelegate["onMovePath"]) - FS.trackingDelegate["onMovePath"](old_path, new_path); - } - catch (e) { - err("FS.trackingDelegate['onMovePath']('" + - old_path + - "', '" + - new_path + - "') threw an exception: " + - e.message); - } - }, - rmdir: function (path) { - var lookup = FS.lookupPath(path, { - parent: true, - }); - var parent = lookup.node; - var name = PATH.basename(path); - var node = FS.lookupNode(parent, name); - var errCode = FS.mayDelete(parent, name, true); - if (errCode) { - throw new FS.ErrnoError(errCode); - } - if (!parent.node_ops.rmdir) { - throw new FS.ErrnoError(63); - } - if (FS.isMountpoint(node)) { - throw new FS.ErrnoError(10); - } - try { - if (FS.trackingDelegate["willDeletePath"]) { - FS.trackingDelegate["willDeletePath"](path); - } - } - catch (e) { - err("FS.trackingDelegate['willDeletePath']('" + - path + - "') threw an exception: " + - e.message); - } - parent.node_ops.rmdir(parent, name); - FS.destroyNode(node); - try { - if (FS.trackingDelegate["onDeletePath"]) - FS.trackingDelegate["onDeletePath"](path); - } - catch (e) { - err("FS.trackingDelegate['onDeletePath']('" + - path + - "') threw an exception: " + - e.message); - } - }, - readdir: function (path) { - var lookup = FS.lookupPath(path, { - follow: true, - }); - var node = lookup.node; - if (!node.node_ops.readdir) { - throw new FS.ErrnoError(54); - } - return node.node_ops.readdir(node); - }, - unlink: function (path) { - var lookup = FS.lookupPath(path, { - parent: true, - }); - var parent = lookup.node; - var name = PATH.basename(path); - var node = FS.lookupNode(parent, name); - var errCode = FS.mayDelete(parent, name, false); - if (errCode) { - throw new FS.ErrnoError(errCode); - } - if (!parent.node_ops.unlink) { - throw new FS.ErrnoError(63); - } - if (FS.isMountpoint(node)) { - throw new FS.ErrnoError(10); - } - try { - if (FS.trackingDelegate["willDeletePath"]) { - FS.trackingDelegate["willDeletePath"](path); - } - } - catch (e) { - err("FS.trackingDelegate['willDeletePath']('" + - path + - "') threw an exception: " + - e.message); - } - parent.node_ops.unlink(parent, name); - FS.destroyNode(node); - try { - if (FS.trackingDelegate["onDeletePath"]) - FS.trackingDelegate["onDeletePath"](path); - } - catch (e) { - err("FS.trackingDelegate['onDeletePath']('" + - path + - "') threw an exception: " + - e.message); - } - }, - readlink: function (path) { - var lookup = FS.lookupPath(path); - var link = lookup.node; - if (!link) { - throw new FS.ErrnoError(44); - } - if (!link.node_ops.readlink) { - throw new FS.ErrnoError(28); - } - return PATH_FS.resolve(FS.getPath(link.parent), link.node_ops.readlink(link)); - }, - stat: function (path, dontFollow) { - var lookup = FS.lookupPath(path, { - follow: !dontFollow, - }); - var node = lookup.node; - if (!node) { - throw new FS.ErrnoError(44); - } - if (!node.node_ops.getattr) { - throw new FS.ErrnoError(63); - } - return node.node_ops.getattr(node); - }, - lstat: function (path) { - return FS.stat(path, true); - }, - chmod: function (path, mode, dontFollow) { - var node; - if (typeof path === "string") { - var lookup = FS.lookupPath(path, { - follow: !dontFollow, - }); - node = lookup.node; - } - else { - node = path; - } - if (!node.node_ops.setattr) { - throw new FS.ErrnoError(63); - } - node.node_ops.setattr(node, { - mode: (mode & 4095) | (node.mode & ~4095), - timestamp: Date.now(), - }); - }, - lchmod: function (path, mode) { - FS.chmod(path, mode, true); - }, - fchmod: function (fd, mode) { - var stream = FS.getStream(fd); - if (!stream) { - throw new FS.ErrnoError(8); - } - FS.chmod(stream.node, mode); - }, - chown: function (path, uid, gid, dontFollow) { - var node; - if (typeof path === "string") { - var lookup = FS.lookupPath(path, { - follow: !dontFollow, - }); - node = lookup.node; - } - else { - node = path; - } - if (!node.node_ops.setattr) { - throw new FS.ErrnoError(63); - } - node.node_ops.setattr(node, { - timestamp: Date.now(), - }); - }, - lchown: function (path, uid, gid) { - FS.chown(path, uid, gid, true); - }, - fchown: function (fd, uid, gid) { - var stream = FS.getStream(fd); - if (!stream) { - throw new FS.ErrnoError(8); - } - FS.chown(stream.node, uid, gid); - }, - truncate: function (path, len) { - if (len < 0) { - throw new FS.ErrnoError(28); - } - var node; - if (typeof path === "string") { - var lookup = FS.lookupPath(path, { - follow: true, - }); - node = lookup.node; - } - else { - node = path; - } - if (!node.node_ops.setattr) { - throw new FS.ErrnoError(63); - } - if (FS.isDir(node.mode)) { - throw new FS.ErrnoError(31); - } - if (!FS.isFile(node.mode)) { - throw new FS.ErrnoError(28); - } - var errCode = FS.nodePermissions(node, "w"); - if (errCode) { - throw new FS.ErrnoError(errCode); - } - node.node_ops.setattr(node, { - size: len, - timestamp: Date.now(), - }); - }, - ftruncate: function (fd, len) { - var stream = FS.getStream(fd); - if (!stream) { - throw new FS.ErrnoError(8); - } - if ((stream.flags & 2097155) === 0) { - throw new FS.ErrnoError(28); - } - FS.truncate(stream.node, len); - }, - utime: function (path, atime, mtime) { - var lookup = FS.lookupPath(path, { - follow: true, - }); - var node = lookup.node; - node.node_ops.setattr(node, { - timestamp: Math.max(atime, mtime), - }); - }, - open: function (path, flags, mode, fd_start, fd_end) { - if (path === "") { - throw new FS.ErrnoError(44); - } - flags = typeof flags === "string" ? FS.modeStringToFlags(flags) : flags; - mode = typeof mode === "undefined" ? 438 : mode; - if (flags & 64) { - mode = (mode & 4095) | 32768; - } - else { - mode = 0; - } - var node; - if (typeof path === "object") { - node = path; - } - else { - path = PATH.normalize(path); - try { - var lookup = FS.lookupPath(path, { - follow: !(flags & 131072), - }); - node = lookup.node; - } - catch (e) { } - } - var created = false; - if (flags & 64) { - if (node) { - if (flags & 128) { - throw new FS.ErrnoError(20); - } - } - else { - node = FS.mknod(path, mode, 0); - created = true; - } - } - if (!node) { - throw new FS.ErrnoError(44); - } - if (FS.isChrdev(node.mode)) { - flags &= ~512; - } - if (flags & 65536 && !FS.isDir(node.mode)) { - throw new FS.ErrnoError(54); - } - if (!created) { - var errCode = FS.mayOpen(node, flags); - if (errCode) { - throw new FS.ErrnoError(errCode); - } - } - if (flags & 512) { - FS.truncate(node, 0); - } - flags &= ~(128 | 512 | 131072); - var stream = FS.createStream({ - node: node, - path: FS.getPath(node), - flags: flags, - seekable: true, - position: 0, - stream_ops: node.stream_ops, - ungotten: [], - error: false, - }, fd_start, fd_end); - if (stream.stream_ops.open) { - stream.stream_ops.open(stream); - } - if (Module["logReadFiles"] && !(flags & 1)) { - if (!FS.readFiles) - FS.readFiles = {}; - if (!(path in FS.readFiles)) { - FS.readFiles[path] = 1; - err("FS.trackingDelegate error on read file: " + path); - } - } - try { - if (FS.trackingDelegate["onOpenFile"]) { - var trackingFlags = 0; - if ((flags & 2097155) !== 1) { - trackingFlags |= FS.tracking.openFlags.READ; - } - if ((flags & 2097155) !== 0) { - trackingFlags |= FS.tracking.openFlags.WRITE; - } - FS.trackingDelegate["onOpenFile"](path, trackingFlags); - } - } - catch (e) { - err("FS.trackingDelegate['onOpenFile']('" + - path + - "', flags) threw an exception: " + - e.message); - } - return stream; - }, - close: function (stream) { - if (FS.isClosed(stream)) { - throw new FS.ErrnoError(8); - } - if (stream.getdents) - stream.getdents = null; - try { - if (stream.stream_ops.close) { - stream.stream_ops.close(stream); - } - } - catch (e) { - throw e; - } - finally { - FS.closeStream(stream.fd); - } - stream.fd = null; - }, - isClosed: function (stream) { - return stream.fd === null; - }, - llseek: function (stream, offset, whence) { - if (FS.isClosed(stream)) { - throw new FS.ErrnoError(8); - } - if (!stream.seekable || !stream.stream_ops.llseek) { - throw new FS.ErrnoError(70); - } - if (whence != 0 && whence != 1 && whence != 2) { - throw new FS.ErrnoError(28); - } - stream.position = stream.stream_ops.llseek(stream, offset, whence); - stream.ungotten = []; - return stream.position; - }, - read: function (stream, buffer, offset, length, position) { - if (length < 0 || position < 0) { - throw new FS.ErrnoError(28); - } - if (FS.isClosed(stream)) { - throw new FS.ErrnoError(8); - } - if ((stream.flags & 2097155) === 1) { - throw new FS.ErrnoError(8); - } - if (FS.isDir(stream.node.mode)) { - throw new FS.ErrnoError(31); - } - if (!stream.stream_ops.read) { - throw new FS.ErrnoError(28); - } - var seeking = typeof position !== "undefined"; - if (!seeking) { - position = stream.position; - } - else if (!stream.seekable) { - throw new FS.ErrnoError(70); - } - var bytesRead = stream.stream_ops.read(stream, buffer, offset, length, position); - if (!seeking) - stream.position += bytesRead; - return bytesRead; - }, - write: function (stream, buffer, offset, length, position, canOwn) { - if (length < 0 || position < 0) { - throw new FS.ErrnoError(28); - } - if (FS.isClosed(stream)) { - throw new FS.ErrnoError(8); - } - if ((stream.flags & 2097155) === 0) { - throw new FS.ErrnoError(8); - } - if (FS.isDir(stream.node.mode)) { - throw new FS.ErrnoError(31); - } - if (!stream.stream_ops.write) { - throw new FS.ErrnoError(28); - } - if (stream.seekable && stream.flags & 1024) { - FS.llseek(stream, 0, 2); - } - var seeking = typeof position !== "undefined"; - if (!seeking) { - position = stream.position; - } - else if (!stream.seekable) { - throw new FS.ErrnoError(70); - } - var bytesWritten = stream.stream_ops.write(stream, buffer, offset, length, position, canOwn); - if (!seeking) - stream.position += bytesWritten; - try { - if (stream.path && FS.trackingDelegate["onWriteToFile"]) - FS.trackingDelegate["onWriteToFile"](stream.path); - } - catch (e) { - err("FS.trackingDelegate['onWriteToFile']('" + - stream.path + - "') threw an exception: " + - e.message); - } - return bytesWritten; - }, - allocate: function (stream, offset, length) { - if (FS.isClosed(stream)) { - throw new FS.ErrnoError(8); - } - if (offset < 0 || length <= 0) { - throw new FS.ErrnoError(28); - } - if ((stream.flags & 2097155) === 0) { - throw new FS.ErrnoError(8); - } - if (!FS.isFile(stream.node.mode) && !FS.isDir(stream.node.mode)) { - throw new FS.ErrnoError(43); - } - if (!stream.stream_ops.allocate) { - throw new FS.ErrnoError(138); - } - stream.stream_ops.allocate(stream, offset, length); - }, - mmap: function (stream, address, length, position, prot, flags) { - if ((prot & 2) !== 0 && - (flags & 2) === 0 && - (stream.flags & 2097155) !== 2) { - throw new FS.ErrnoError(2); - } - if ((stream.flags & 2097155) === 1) { - throw new FS.ErrnoError(2); - } - if (!stream.stream_ops.mmap) { - throw new FS.ErrnoError(43); - } - return stream.stream_ops.mmap(stream, address, length, position, prot, flags); - }, - msync: function (stream, buffer, offset, length, mmapFlags) { - if (!stream || !stream.stream_ops.msync) { - return 0; - } - return stream.stream_ops.msync(stream, buffer, offset, length, mmapFlags); - }, - munmap: function (stream) { - return 0; - }, - ioctl: function (stream, cmd, arg) { - if (!stream.stream_ops.ioctl) { - throw new FS.ErrnoError(59); - } - return stream.stream_ops.ioctl(stream, cmd, arg); - }, - readFile: function (path, opts) { - opts = opts || {}; - opts.flags = opts.flags || 0; - opts.encoding = opts.encoding || "binary"; - if (opts.encoding !== "utf8" && opts.encoding !== "binary") { - throw new Error('Invalid encoding type "' + opts.encoding + '"'); - } - var ret; - var stream = FS.open(path, opts.flags); - var stat = FS.stat(path); - var length = stat.size; - var buf = new Uint8Array(length); - FS.read(stream, buf, 0, length, 0); - if (opts.encoding === "utf8") { - ret = UTF8ArrayToString(buf, 0); - } - else if (opts.encoding === "binary") { - ret = buf; - } - FS.close(stream); - return ret; - }, - writeFile: function (path, data, opts) { - opts = opts || {}; - opts.flags = opts.flags || 577; - var stream = FS.open(path, opts.flags, opts.mode); - if (typeof data === "string") { - var buf = new Uint8Array(lengthBytesUTF8(data) + 1); - var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length); - FS.write(stream, buf, 0, actualNumBytes, undefined, opts.canOwn); - } - else if (ArrayBuffer.isView(data)) { - FS.write(stream, data, 0, data.byteLength, undefined, opts.canOwn); - } - else { - throw new Error("Unsupported data type"); - } - FS.close(stream); - }, - cwd: function () { - return FS.currentPath; - }, - chdir: function (path) { - var lookup = FS.lookupPath(path, { - follow: true, - }); - if (lookup.node === null) { - throw new FS.ErrnoError(44); - } - if (!FS.isDir(lookup.node.mode)) { - throw new FS.ErrnoError(54); - } - var errCode = FS.nodePermissions(lookup.node, "x"); - if (errCode) { - throw new FS.ErrnoError(errCode); - } - FS.currentPath = lookup.path; - }, - createDefaultDirectories: function () { - FS.mkdir("/tmp"); - FS.mkdir("/home"); - FS.mkdir("/home/web_user"); - }, - createDefaultDevices: function () { - FS.mkdir("/dev"); - FS.registerDevice(FS.makedev(1, 3), { - read: function () { - return 0; - }, - write: function (stream, buffer, offset, length, pos) { - return length; - }, - }); - FS.mkdev("/dev/null", FS.makedev(1, 3)); - TTY.register(FS.makedev(5, 0), TTY.default_tty_ops); - TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops); - FS.mkdev("/dev/tty", FS.makedev(5, 0)); - FS.mkdev("/dev/tty1", FS.makedev(6, 0)); - var random_device = getRandomDevice(); - FS.createDevice("/dev", "random", random_device); - FS.createDevice("/dev", "urandom", random_device); - FS.mkdir("/dev/shm"); - FS.mkdir("/dev/shm/tmp"); - }, - createSpecialDirectories: function () { - FS.mkdir("/proc"); - FS.mkdir("/proc/self"); - FS.mkdir("/proc/self/fd"); - FS.mount({ - mount: function () { - var node = FS.createNode("/proc/self", "fd", 16384 | 511, 73); - node.node_ops = { - lookup: function (parent, name) { - var fd = +name; - var stream = FS.getStream(fd); - if (!stream) - throw new FS.ErrnoError(8); - var ret = { - parent: null, - mount: { - mountpoint: "fake", - }, - node_ops: { - readlink: function () { - return stream.path; - }, - }, - }; - ret.parent = ret; - return ret; - }, - }; - return node; - }, - }, {}, "/proc/self/fd"); - }, - createStandardStreams: function () { - if (Module["stdin"]) { - FS.createDevice("/dev", "stdin", Module["stdin"]); - } - else { - FS.symlink("/dev/tty", "/dev/stdin"); - } - if (Module["stdout"]) { - FS.createDevice("/dev", "stdout", null, Module["stdout"]); - } - else { - FS.symlink("/dev/tty", "/dev/stdout"); - } - if (Module["stderr"]) { - FS.createDevice("/dev", "stderr", null, Module["stderr"]); - } - else { - FS.symlink("/dev/tty1", "/dev/stderr"); - } - var stdin = FS.open("/dev/stdin", 0); - var stdout = FS.open("/dev/stdout", 1); - var stderr = FS.open("/dev/stderr", 1); - }, - ensureErrnoError: function () { - if (FS.ErrnoError) - return; - FS.ErrnoError = function ErrnoError(errno, node) { - this.node = node; - this.setErrno = function (errno) { - this.errno = errno; - }; - this.setErrno(errno); - this.message = "FS error"; - }; - FS.ErrnoError.prototype = new Error(); - FS.ErrnoError.prototype.constructor = FS.ErrnoError; - [44].forEach(function (code) { - FS.genericErrors[code] = new FS.ErrnoError(code); - FS.genericErrors[code].stack = ""; - }); - }, - staticInit: function () { - FS.ensureErrnoError(); - FS.nameTable = new Array(4096); - FS.mount(MEMFS, {}, "/"); - FS.createDefaultDirectories(); - FS.createDefaultDevices(); - FS.createSpecialDirectories(); - FS.filesystems = { - MEMFS: MEMFS, - }; - }, - init: function (input, output, error) { - FS.init.initialized = true; - FS.ensureErrnoError(); - Module["stdin"] = input || Module["stdin"]; - Module["stdout"] = output || Module["stdout"]; - Module["stderr"] = error || Module["stderr"]; - FS.createStandardStreams(); - }, - quit: function () { - FS.init.initialized = false; - var fflush = Module["_fflush"]; - if (fflush) - fflush(0); - for (var i = 0; i < FS.streams.length; i++) { - var stream = FS.streams[i]; - if (!stream) { - continue; - } - FS.close(stream); - } - }, - getMode: function (canRead, canWrite) { - var mode = 0; - if (canRead) - mode |= 292 | 73; - if (canWrite) - mode |= 146; - return mode; - }, - findObject: function (path, dontResolveLastLink) { - var ret = FS.analyzePath(path, dontResolveLastLink); - if (ret.exists) { - return ret.object; - } - else { - return null; - } - }, - analyzePath: function (path, dontResolveLastLink) { - try { - var lookup = FS.lookupPath(path, { - follow: !dontResolveLastLink, - }); - path = lookup.path; - } - catch (e) { } - var ret = { - isRoot: false, - exists: false, - error: 0, - name: null, - path: null, - object: null, - parentExists: false, - parentPath: null, - parentObject: null, - }; - try { - var lookup = FS.lookupPath(path, { - parent: true, - }); - ret.parentExists = true; - ret.parentPath = lookup.path; - ret.parentObject = lookup.node; - ret.name = PATH.basename(path); - lookup = FS.lookupPath(path, { - follow: !dontResolveLastLink, - }); - ret.exists = true; - ret.path = lookup.path; - ret.object = lookup.node; - ret.name = lookup.node.name; - ret.isRoot = lookup.path === "/"; - } - catch (e) { - ret.error = e.errno; - } - return ret; - }, - createPath: function (parent, path, canRead, canWrite) { - parent = typeof parent === "string" ? parent : FS.getPath(parent); - var parts = path.split("/").reverse(); - while (parts.length) { - var part = parts.pop(); - if (!part) - continue; - var current = PATH.join2(parent, part); - try { - FS.mkdir(current); - } - catch (e) { } - parent = current; - } - return current; - }, - createFile: function (parent, name, properties, canRead, canWrite) { - var path = PATH.join2(typeof parent === "string" ? parent : FS.getPath(parent), name); - var mode = FS.getMode(canRead, canWrite); - return FS.create(path, mode); - }, - createDataFile: function (parent, name, data, canRead, canWrite, canOwn) { - var path = name - ? PATH.join2(typeof parent === "string" ? parent : FS.getPath(parent), name) - : parent; - var mode = FS.getMode(canRead, canWrite); - var node = FS.create(path, mode); - if (data) { - if (typeof data === "string") { - var arr = new Array(data.length); - for (var i = 0, len = data.length; i < len; ++i) - arr[i] = data.charCodeAt(i); - data = arr; - } - FS.chmod(node, mode | 146); - var stream = FS.open(node, 577); - FS.write(stream, data, 0, data.length, 0, canOwn); - FS.close(stream); - FS.chmod(node, mode); - } - return node; - }, - createDevice: function (parent, name, input, output) { - var path = PATH.join2(typeof parent === "string" ? parent : FS.getPath(parent), name); - var mode = FS.getMode(!!input, !!output); - if (!FS.createDevice.major) - FS.createDevice.major = 64; - var dev = FS.makedev(FS.createDevice.major++, 0); - FS.registerDevice(dev, { - open: function (stream) { - stream.seekable = false; - }, - close: function (stream) { - if (output && output.buffer && output.buffer.length) { - output(10); - } - }, - read: function (stream, buffer, offset, length, pos) { - var bytesRead = 0; - for (var i = 0; i < length; i++) { - var result; - try { - result = input(); - } - catch (e) { - throw new FS.ErrnoError(29); - } - if (result === undefined && bytesRead === 0) { - throw new FS.ErrnoError(6); - } - if (result === null || result === undefined) - break; - bytesRead++; - buffer[offset + i] = result; - } - if (bytesRead) { - stream.node.timestamp = Date.now(); - } - return bytesRead; - }, - write: function (stream, buffer, offset, length, pos) { - for (var i = 0; i < length; i++) { - try { - output(buffer[offset + i]); - } - catch (e) { - throw new FS.ErrnoError(29); - } - } - if (length) { - stream.node.timestamp = Date.now(); - } - return i; - }, - }); - return FS.mkdev(path, mode, dev); - }, - forceLoadFile: function (obj) { - if (obj.isDevice || obj.isFolder || obj.link || obj.contents) - return true; - if (typeof XMLHttpRequest !== "undefined") { - throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread."); - } - else if (read_) { - try { - obj.contents = intArrayFromString(read_(obj.url), true); - obj.usedBytes = obj.contents.length; - } - catch (e) { - throw new FS.ErrnoError(29); - } - } - else { - throw new Error("Cannot load without read() or XMLHttpRequest."); - } - }, - createLazyFile: function (parent, name, url, canRead, canWrite) { - function LazyUint8Array() { - this.lengthKnown = false; - this.chunks = []; - } - LazyUint8Array.prototype.get = function LazyUint8Array_get(idx) { - if (idx > this.length - 1 || idx < 0) { - return undefined; - } - var chunkOffset = idx % this.chunkSize; - var chunkNum = (idx / this.chunkSize) | 0; - return this.getter(chunkNum)[chunkOffset]; - }; - LazyUint8Array.prototype.setDataGetter = function LazyUint8Array_setDataGetter(getter) { - this.getter = getter; - }; - LazyUint8Array.prototype.cacheLength = function LazyUint8Array_cacheLength() { - var xhr = new XMLHttpRequest(); - xhr.open("HEAD", url, false); - xhr.send(null); - if (!((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304)) - throw new Error("Couldn't load " + url + ". Status: " + xhr.status); - var datalength = Number(xhr.getResponseHeader("Content-length")); - var header; - var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && - header === "bytes"; - var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && - header === "gzip"; - var chunkSize = 1024 * 1024; - if (!hasByteServing) - chunkSize = datalength; - var doXHR = function (from, to) { - if (from > to) - throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!"); - if (to > datalength - 1) - throw new Error("only " + datalength + " bytes available! programmer error!"); - var xhr = new XMLHttpRequest(); - xhr.open("GET", url, false); - if (datalength !== chunkSize) - xhr.setRequestHeader("Range", "bytes=" + from + "-" + to); - if (typeof Uint8Array != "undefined") - xhr.responseType = "arraybuffer"; - if (xhr.overrideMimeType) { - xhr.overrideMimeType("text/plain; charset=x-user-defined"); - } - xhr.send(null); - if (!((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304)) - throw new Error("Couldn't load " + url + ". Status: " + xhr.status); - if (xhr.response !== undefined) { - return new Uint8Array(xhr.response || []); - } - else { - return intArrayFromString(xhr.responseText || "", true); - } - }; - var lazyArray = this; - lazyArray.setDataGetter(function (chunkNum) { - var start = chunkNum * chunkSize; - var end = (chunkNum + 1) * chunkSize - 1; - end = Math.min(end, datalength - 1); - if (typeof lazyArray.chunks[chunkNum] === "undefined") { - lazyArray.chunks[chunkNum] = doXHR(start, end); - } - if (typeof lazyArray.chunks[chunkNum] === "undefined") - throw new Error("doXHR failed!"); - return lazyArray.chunks[chunkNum]; - }); - if (usesGzip || !datalength) { - chunkSize = datalength = 1; - datalength = this.getter(0).length; - chunkSize = datalength; - out("LazyFiles on gzip forces download of the whole file when length is accessed"); - } - this._length = datalength; - this._chunkSize = chunkSize; - this.lengthKnown = true; - }; - if (typeof XMLHttpRequest !== "undefined") { - if (!ENVIRONMENT_IS_WORKER) - throw "Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc"; - var lazyArray = new LazyUint8Array(); - Object.defineProperties(lazyArray, { - length: { - get: function () { - if (!this.lengthKnown) { - this.cacheLength(); - } - return this._length; - }, - }, - chunkSize: { - get: function () { - if (!this.lengthKnown) { - this.cacheLength(); - } - return this._chunkSize; - }, - }, - }); - var properties = { - isDevice: false, - contents: lazyArray, - }; - } - else { - var properties = { - isDevice: false, - url: url, - }; - } - var node = FS.createFile(parent, name, properties, canRead, canWrite); - if (properties.contents) { - node.contents = properties.contents; - } - else if (properties.url) { - node.contents = null; - node.url = properties.url; - } - Object.defineProperties(node, { - usedBytes: { - get: function () { - return this.contents.length; - }, - }, - }); - var stream_ops = {}; - var keys = Object.keys(node.stream_ops); - keys.forEach(function (key) { - var fn = node.stream_ops[key]; - stream_ops[key] = function forceLoadLazyFile() { - FS.forceLoadFile(node); - return fn.apply(null, arguments); - }; - }); - stream_ops.read = function stream_ops_read(stream, buffer, offset, length, position) { - FS.forceLoadFile(node); - var contents = stream.node.contents; - if (position >= contents.length) - return 0; - var size = Math.min(contents.length - position, length); - if (contents.slice) { - for (var i = 0; i < size; i++) { - buffer[offset + i] = contents[position + i]; - } - } - else { - for (var i = 0; i < size; i++) { - buffer[offset + i] = contents.get(position + i); - } - } - return size; - }; - node.stream_ops = stream_ops; - return node; - }, - createPreloadedFile: function (parent, name, url, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) { - Browser.init(); - var fullname = name ? PATH_FS.resolve(PATH.join2(parent, name)) : parent; - var dep = getUniqueRunDependency("cp " + fullname); - function processData(byteArray) { - function finish(byteArray) { - if (preFinish) - preFinish(); - if (!dontCreateFile) { - FS.createDataFile(parent, name, byteArray, canRead, canWrite, canOwn); - } - if (onload) - onload(); - removeRunDependency(dep); - } - var handled = false; - Module["preloadPlugins"].forEach(function (plugin) { - if (handled) - return; - if (plugin["canHandle"](fullname)) { - plugin["handle"](byteArray, fullname, finish, function () { - if (onerror) - onerror(); - removeRunDependency(dep); - }); - handled = true; - } - }); - if (!handled) - finish(byteArray); - } - addRunDependency(dep); - if (typeof url == "string") { - Browser.asyncLoad(url, function (byteArray) { - processData(byteArray); - }, onerror); - } - else { - processData(url); - } - }, - indexedDB: function () { - return (window.indexedDB || - window.mozIndexedDB || - window.webkitIndexedDB || - window.msIndexedDB); - }, - DB_NAME: function () { - return "EM_FS_" + window.location.pathname; - }, - DB_VERSION: 20, - DB_STORE_NAME: "FILE_DATA", - saveFilesToDB: function (paths, onload, onerror) { - onload = onload || function () { }; - onerror = onerror || function () { }; - var indexedDB = FS.indexedDB(); - try { - var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION); - } - catch (e) { - return onerror(e); - } - openRequest.onupgradeneeded = function openRequest_onupgradeneeded() { - out("creating db"); - var db = openRequest.result; - db.createObjectStore(FS.DB_STORE_NAME); - }; - openRequest.onsuccess = function openRequest_onsuccess() { - var db = openRequest.result; - var transaction = db.transaction([FS.DB_STORE_NAME], "readwrite"); - var files = transaction.objectStore(FS.DB_STORE_NAME); - var ok = 0, fail = 0, total = paths.length; - function finish() { - if (fail == 0) - onload(); - else - onerror(); - } - paths.forEach(function (path) { - var putRequest = files.put(FS.analyzePath(path).object.contents, path); - putRequest.onsuccess = function putRequest_onsuccess() { - ok++; - if (ok + fail == total) - finish(); - }; - putRequest.onerror = function putRequest_onerror() { - fail++; - if (ok + fail == total) - finish(); - }; - }); - transaction.onerror = onerror; - }; - openRequest.onerror = onerror; - }, - loadFilesFromDB: function (paths, onload, onerror) { - onload = onload || function () { }; - onerror = onerror || function () { }; - var indexedDB = FS.indexedDB(); - try { - var openRequest = indexedDB.open(FS.DB_NAME(), FS.DB_VERSION); - } - catch (e) { - return onerror(e); - } - openRequest.onupgradeneeded = onerror; - openRequest.onsuccess = function openRequest_onsuccess() { - var db = openRequest.result; - try { - var transaction = db.transaction([FS.DB_STORE_NAME], "readonly"); - } - catch (e) { - onerror(e); - return; - } - var files = transaction.objectStore(FS.DB_STORE_NAME); - var ok = 0, fail = 0, total = paths.length; - function finish() { - if (fail == 0) - onload(); - else - onerror(); - } - paths.forEach(function (path) { - var getRequest = files.get(path); - getRequest.onsuccess = function getRequest_onsuccess() { - if (FS.analyzePath(path).exists) { - FS.unlink(path); - } - FS.createDataFile(PATH.dirname(path), PATH.basename(path), getRequest.result, true, true, true); - ok++; - if (ok + fail == total) - finish(); - }; - getRequest.onerror = function getRequest_onerror() { - fail++; - if (ok + fail == total) - finish(); - }; - }); - transaction.onerror = onerror; - }; - openRequest.onerror = onerror; - }, - }; - var SYSCALLS = { - mappings: {}, - DEFAULT_POLLMASK: 5, - umask: 511, - calculateAt: function (dirfd, path) { - if (path[0] !== "/") { - var dir; - if (dirfd === -100) { - dir = FS.cwd(); - } - else { - var dirstream = FS.getStream(dirfd); - if (!dirstream) - throw new FS.ErrnoError(8); - dir = dirstream.path; - } - path = PATH.join2(dir, path); - } - return path; - }, - doStat: function (func, path, buf) { - try { - var stat = func(path); - } - catch (e) { - if (e && - e.node && - PATH.normalize(path) !== PATH.normalize(FS.getPath(e.node))) { - return -54; - } - throw e; - } - GROWABLE_HEAP_I32()[buf >> 2] = stat.dev; - GROWABLE_HEAP_I32()[(buf + 4) >> 2] = 0; - GROWABLE_HEAP_I32()[(buf + 8) >> 2] = stat.ino; - GROWABLE_HEAP_I32()[(buf + 12) >> 2] = stat.mode; - GROWABLE_HEAP_I32()[(buf + 16) >> 2] = stat.nlink; - GROWABLE_HEAP_I32()[(buf + 20) >> 2] = stat.uid; - GROWABLE_HEAP_I32()[(buf + 24) >> 2] = stat.gid; - GROWABLE_HEAP_I32()[(buf + 28) >> 2] = stat.rdev; - GROWABLE_HEAP_I32()[(buf + 32) >> 2] = 0; - (tempI64 = [ - stat.size >>> 0, - ((tempDouble = stat.size), - +Math.abs(tempDouble) >= 1 - ? tempDouble > 0 - ? (Math.min(+Math.floor(tempDouble / 4294967296), 4294967295) | - 0) >>> - 0 - : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 - : 0), - ]), - (GROWABLE_HEAP_I32()[(buf + 40) >> 2] = tempI64[0]), - (GROWABLE_HEAP_I32()[(buf + 44) >> 2] = tempI64[1]); - GROWABLE_HEAP_I32()[(buf + 48) >> 2] = 4096; - GROWABLE_HEAP_I32()[(buf + 52) >> 2] = stat.blocks; - GROWABLE_HEAP_I32()[(buf + 56) >> 2] = (stat.atime.getTime() / 1e3) | 0; - GROWABLE_HEAP_I32()[(buf + 60) >> 2] = 0; - GROWABLE_HEAP_I32()[(buf + 64) >> 2] = (stat.mtime.getTime() / 1e3) | 0; - GROWABLE_HEAP_I32()[(buf + 68) >> 2] = 0; - GROWABLE_HEAP_I32()[(buf + 72) >> 2] = (stat.ctime.getTime() / 1e3) | 0; - GROWABLE_HEAP_I32()[(buf + 76) >> 2] = 0; - (tempI64 = [ - stat.ino >>> 0, - ((tempDouble = stat.ino), - +Math.abs(tempDouble) >= 1 - ? tempDouble > 0 - ? (Math.min(+Math.floor(tempDouble / 4294967296), 4294967295) | - 0) >>> - 0 - : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 - : 0), - ]), - (GROWABLE_HEAP_I32()[(buf + 80) >> 2] = tempI64[0]), - (GROWABLE_HEAP_I32()[(buf + 84) >> 2] = tempI64[1]); - return 0; - }, - doMsync: function (addr, stream, len, flags, offset) { - var buffer = GROWABLE_HEAP_U8().slice(addr, addr + len); - FS.msync(stream, buffer, offset, len, flags); - }, - doMkdir: function (path, mode) { - path = PATH.normalize(path); - if (path[path.length - 1] === "/") - path = path.substr(0, path.length - 1); - FS.mkdir(path, mode, 0); - return 0; - }, - doMknod: function (path, mode, dev) { - switch (mode & 61440) { - case 32768: - case 8192: - case 24576: - case 4096: - case 49152: - break; - default: - return -28; - } - FS.mknod(path, mode, dev); - return 0; - }, - doReadlink: function (path, buf, bufsize) { - if (bufsize <= 0) - return -28; - var ret = FS.readlink(path); - var len = Math.min(bufsize, lengthBytesUTF8(ret)); - var endChar = GROWABLE_HEAP_I8()[buf + len]; - stringToUTF8(ret, buf, bufsize + 1); - GROWABLE_HEAP_I8()[buf + len] = endChar; - return len; - }, - doAccess: function (path, amode) { - if (amode & ~7) { - return -28; - } - var node; - var lookup = FS.lookupPath(path, { - follow: true, - }); - node = lookup.node; - if (!node) { - return -44; - } - var perms = ""; - if (amode & 4) - perms += "r"; - if (amode & 2) - perms += "w"; - if (amode & 1) - perms += "x"; - if (perms && FS.nodePermissions(node, perms)) { - return -2; - } - return 0; - }, - doDup: function (path, flags, suggestFD) { - var suggest = FS.getStream(suggestFD); - if (suggest) - FS.close(suggest); - return FS.open(path, flags, 0, suggestFD, suggestFD).fd; - }, - doReadv: function (stream, iov, iovcnt, offset) { - var ret = 0; - for (var i = 0; i < iovcnt; i++) { - var ptr = GROWABLE_HEAP_I32()[(iov + i * 8) >> 2]; - var len = GROWABLE_HEAP_I32()[(iov + (i * 8 + 4)) >> 2]; - var curr = FS.read(stream, GROWABLE_HEAP_I8(), ptr, len, offset); - if (curr < 0) - return -1; - ret += curr; - if (curr < len) - break; - } - return ret; - }, - doWritev: function (stream, iov, iovcnt, offset) { - var ret = 0; - for (var i = 0; i < iovcnt; i++) { - var ptr = GROWABLE_HEAP_I32()[(iov + i * 8) >> 2]; - var len = GROWABLE_HEAP_I32()[(iov + (i * 8 + 4)) >> 2]; - var curr = FS.write(stream, GROWABLE_HEAP_I8(), ptr, len, offset); - if (curr < 0) - return -1; - ret += curr; - } - return ret; - }, - varargs: undefined, - get: function () { - SYSCALLS.varargs += 4; - var ret = GROWABLE_HEAP_I32()[(SYSCALLS.varargs - 4) >> 2]; - return ret; - }, - getStr: function (ptr) { - var ret = UTF8ToString(ptr); - return ret; - }, - getStreamFromFD: function (fd) { - var stream = FS.getStream(fd); - if (!stream) - throw new FS.ErrnoError(8); - return stream; - }, - get64: function (low, high) { - return low; - }, - }; - function ___sys_access(path, amode) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(2, 1, path, amode); - try { - path = SYSCALLS.getStr(path); - return SYSCALLS.doAccess(path, amode); - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return -e.errno; - } - } - function ___sys_fcntl64(fd, cmd, varargs) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(3, 1, fd, cmd, varargs); - SYSCALLS.varargs = varargs; - try { - var stream = SYSCALLS.getStreamFromFD(fd); - switch (cmd) { - case 0: { - var arg = SYSCALLS.get(); - if (arg < 0) { - return -28; - } - var newStream; - newStream = FS.open(stream.path, stream.flags, 0, arg); - return newStream.fd; - } - case 1: - case 2: - return 0; - case 3: - return stream.flags; - case 4: { - var arg = SYSCALLS.get(); - stream.flags |= arg; - return 0; - } - case 12: { - var arg = SYSCALLS.get(); - var offset = 0; - GROWABLE_HEAP_I16()[(arg + offset) >> 1] = 2; - return 0; - } - case 13: - case 14: - return 0; - case 16: - case 8: - return -28; - case 9: - setErrNo(28); - return -1; - default: { - return -28; - } - } - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return -e.errno; - } - } - function ___sys_fstat64(fd, buf) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(4, 1, fd, buf); - try { - var stream = SYSCALLS.getStreamFromFD(fd); - return SYSCALLS.doStat(FS.stat, stream.path, buf); - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return -e.errno; - } - } - function ___sys_getcwd(buf, size) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(5, 1, buf, size); - try { - if (size === 0) - return -28; - var cwd = FS.cwd(); - var cwdLengthInBytes = lengthBytesUTF8(cwd); - if (size < cwdLengthInBytes + 1) - return -68; - stringToUTF8(cwd, buf, size); - return buf; - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return -e.errno; - } - } - function ___sys_ioctl(fd, op, varargs) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(6, 1, fd, op, varargs); - SYSCALLS.varargs = varargs; - try { - var stream = SYSCALLS.getStreamFromFD(fd); - switch (op) { - case 21509: - case 21505: { - if (!stream.tty) - return -59; - return 0; - } - case 21510: - case 21511: - case 21512: - case 21506: - case 21507: - case 21508: { - if (!stream.tty) - return -59; - return 0; - } - case 21519: { - if (!stream.tty) - return -59; - var argp = SYSCALLS.get(); - GROWABLE_HEAP_I32()[argp >> 2] = 0; - return 0; - } - case 21520: { - if (!stream.tty) - return -59; - return -28; - } - case 21531: { - var argp = SYSCALLS.get(); - return FS.ioctl(stream, op, argp); - } - case 21523: { - if (!stream.tty) - return -59; - return 0; - } - case 21524: { - if (!stream.tty) - return -59; - return 0; - } - default: - abort("bad ioctl syscall " + op); - } - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return -e.errno; - } - } - function syscallMmap2(addr, len, prot, flags, fd, off) { - off <<= 12; - var ptr; - var allocated = false; - if ((flags & 16) !== 0 && addr % 16384 !== 0) { - return -28; - } - if ((flags & 32) !== 0) { - ptr = _memalign(16384, len); - if (!ptr) - return -48; - _memset(ptr, 0, len); - allocated = true; - } - else { - var info = FS.getStream(fd); - if (!info) - return -8; - var res = FS.mmap(info, addr, len, off, prot, flags); - ptr = res.ptr; - allocated = res.allocated; - } - SYSCALLS.mappings[ptr] = { - malloc: ptr, - len: len, - allocated: allocated, - fd: fd, - prot: prot, - flags: flags, - offset: off, - }; - return ptr; - } - function ___sys_mmap2(addr, len, prot, flags, fd, off) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(7, 1, addr, len, prot, flags, fd, off); - try { - return syscallMmap2(addr, len, prot, flags, fd, off); - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return -e.errno; - } - } - function syscallMunmap(addr, len) { - if ((addr | 0) === -1 || len === 0) { - return -28; - } - var info = SYSCALLS.mappings[addr]; - if (!info) - return 0; - if (len === info.len) { - var stream = FS.getStream(info.fd); - if (info.prot & 2) { - SYSCALLS.doMsync(addr, stream, len, info.flags, info.offset); - } - FS.munmap(stream); - SYSCALLS.mappings[addr] = null; - if (info.allocated) { - _free(info.malloc); - } - } - return 0; - } - function ___sys_munmap(addr, len) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(8, 1, addr, len); - try { - return syscallMunmap(addr, len); - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return -e.errno; - } - } - function ___sys_open(path, flags, varargs) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(9, 1, path, flags, varargs); - SYSCALLS.varargs = varargs; - try { - var pathname = SYSCALLS.getStr(path); - var mode = SYSCALLS.get(); - var stream = FS.open(pathname, flags, mode); - return stream.fd; - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return -e.errno; - } - } - function ___sys_rename(old_path, new_path) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(10, 1, old_path, new_path); - try { - old_path = SYSCALLS.getStr(old_path); - new_path = SYSCALLS.getStr(new_path); - FS.rename(old_path, new_path); - return 0; - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return -e.errno; - } - } - function ___sys_rmdir(path) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(11, 1, path); - try { - path = SYSCALLS.getStr(path); - FS.rmdir(path); - return 0; - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return -e.errno; - } - } - function ___sys_stat64(path, buf) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(12, 1, path, buf); - try { - path = SYSCALLS.getStr(path); - return SYSCALLS.doStat(FS.stat, path, buf); - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return -e.errno; - } - } - function ___sys_unlink(path) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(13, 1, path); - try { - path = SYSCALLS.getStr(path); - FS.unlink(path); - return 0; - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return -e.errno; - } - } - function ___sys_wait4(pid, wstart, options, rusage) { - try { - abort("cannot wait on child processes"); - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return -e.errno; - } - } - function getShiftFromSize(size) { - switch (size) { - case 1: - return 0; - case 2: - return 1; - case 4: - return 2; - case 8: - return 3; - default: - throw new TypeError("Unknown type size: " + size); - } - } - function embind_init_charCodes() { - var codes = new Array(256); - for (var i = 0; i < 256; ++i) { - codes[i] = String.fromCharCode(i); - } - embind_charCodes = codes; - } - var embind_charCodes = undefined; - function readLatin1String(ptr) { - var ret = ""; - var c = ptr; - while (GROWABLE_HEAP_U8()[c]) { - ret += embind_charCodes[GROWABLE_HEAP_U8()[c++]]; - } - return ret; - } - var awaitingDependencies = {}; - var registeredTypes = {}; - var typeDependencies = {}; - var char_0 = 48; - var char_9 = 57; - function makeLegalFunctionName(name) { - if (undefined === name) { - return "_unknown"; - } - name = name.replace(/[^a-zA-Z0-9_]/g, "$"); - var f = name.charCodeAt(0); - if (f >= char_0 && f <= char_9) { - return "_" + name; - } - else { - return name; - } - } - function createNamedFunction(name, body) { - name = makeLegalFunctionName(name); - return function () { - "use strict"; - return body.apply(this, arguments); - }; - } - function extendError(baseErrorType, errorName) { - var errorClass = createNamedFunction(errorName, function (message) { - this.name = errorName; - this.message = message; - var stack = new Error(message).stack; - if (stack !== undefined) { - this.stack = - this.toString() + "\n" + stack.replace(/^Error(:[^\n]*)?\n/, ""); - } - }); - errorClass.prototype = Object.create(baseErrorType.prototype); - errorClass.prototype.constructor = errorClass; - errorClass.prototype.toString = function () { - if (this.message === undefined) { - return this.name; - } - else { - return this.name + ": " + this.message; - } - }; - return errorClass; - } - var BindingError = undefined; - function throwBindingError(message) { - throw new BindingError(message); - } - var InternalError = undefined; - function throwInternalError(message) { - throw new InternalError(message); - } - function whenDependentTypesAreResolved(myTypes, dependentTypes, getTypeConverters) { - myTypes.forEach(function (type) { - typeDependencies[type] = dependentTypes; - }); - function onComplete(typeConverters) { - var myTypeConverters = getTypeConverters(typeConverters); - if (myTypeConverters.length !== myTypes.length) { - throwInternalError("Mismatched type converter count"); - } - for (var i = 0; i < myTypes.length; ++i) { - registerType(myTypes[i], myTypeConverters[i]); - } - } - var typeConverters = new Array(dependentTypes.length); - var unregisteredTypes = []; - var registered = 0; - dependentTypes.forEach(function (dt, i) { - if (registeredTypes.hasOwnProperty(dt)) { - typeConverters[i] = registeredTypes[dt]; - } - else { - unregisteredTypes.push(dt); - if (!awaitingDependencies.hasOwnProperty(dt)) { - awaitingDependencies[dt] = []; - } - awaitingDependencies[dt].push(function () { - typeConverters[i] = registeredTypes[dt]; - ++registered; - if (registered === unregisteredTypes.length) { - onComplete(typeConverters); - } - }); - } - }); - if (0 === unregisteredTypes.length) { - onComplete(typeConverters); - } - } - function registerType(rawType, registeredInstance, options) { - options = options || {}; - if (!("argPackAdvance" in registeredInstance)) { - throw new TypeError("registerType registeredInstance requires argPackAdvance"); - } - var name = registeredInstance.name; - if (!rawType) { - throwBindingError('type "' + name + '" must have a positive integer typeid pointer'); - } - if (registeredTypes.hasOwnProperty(rawType)) { - if (options.ignoreDuplicateRegistrations) { - return; - } - else { - throwBindingError("Cannot register type '" + name + "' twice"); - } - } - registeredTypes[rawType] = registeredInstance; - delete typeDependencies[rawType]; - if (awaitingDependencies.hasOwnProperty(rawType)) { - var callbacks = awaitingDependencies[rawType]; - delete awaitingDependencies[rawType]; - callbacks.forEach(function (cb) { - cb(); - }); - } - } - function __embind_register_bool(rawType, name, size, trueValue, falseValue) { - var shift = getShiftFromSize(size); - name = readLatin1String(name); - registerType(rawType, { - name: name, - fromWireType: function (wt) { - return !!wt; - }, - toWireType: function (destructors, o) { - return o ? trueValue : falseValue; - }, - argPackAdvance: 8, - readValueFromPointer: function (pointer) { - var heap; - if (size === 1) { - heap = GROWABLE_HEAP_I8(); - } - else if (size === 2) { - heap = GROWABLE_HEAP_I16(); - } - else if (size === 4) { - heap = GROWABLE_HEAP_I32(); - } - else { - throw new TypeError("Unknown boolean type size: " + name); - } - return this["fromWireType"](heap[pointer >> shift]); - }, - destructorFunction: null, - }); - } - function ClassHandle_isAliasOf(other) { - if (!(this instanceof ClassHandle)) { - return false; - } - if (!(other instanceof ClassHandle)) { - return false; - } - var leftClass = this.$$.ptrType.registeredClass; - var left = this.$$.ptr; - var rightClass = other.$$.ptrType.registeredClass; - var right = other.$$.ptr; - while (leftClass.baseClass) { - left = leftClass.upcast(left); - leftClass = leftClass.baseClass; - } - while (rightClass.baseClass) { - right = rightClass.upcast(right); - rightClass = rightClass.baseClass; - } - return leftClass === rightClass && left === right; - } - function shallowCopyInternalPointer(o) { - return { - count: o.count, - deleteScheduled: o.deleteScheduled, - preservePointerOnDelete: o.preservePointerOnDelete, - ptr: o.ptr, - ptrType: o.ptrType, - smartPtr: o.smartPtr, - smartPtrType: o.smartPtrType, - }; - } - function throwInstanceAlreadyDeleted(obj) { - function getInstanceTypeName(handle) { - return handle.$$.ptrType.registeredClass.name; - } - throwBindingError(getInstanceTypeName(obj) + " instance already deleted"); - } - var finalizationGroup = false; - function detachFinalizer(handle) { } - function runDestructor($$) { - if ($$.smartPtr) { - $$.smartPtrType.rawDestructor($$.smartPtr); - } - else { - $$.ptrType.registeredClass.rawDestructor($$.ptr); - } - } - function releaseClassHandle($$) { - $$.count.value -= 1; - var toDelete = 0 === $$.count.value; - if (toDelete) { - runDestructor($$); - } - } - function attachFinalizer(handle) { - if ("undefined" === typeof FinalizationGroup) { - attachFinalizer = function (handle) { - return handle; - }; - return handle; - } - finalizationGroup = new FinalizationGroup(function (iter) { - for (var result = iter.next(); !result.done; result = iter.next()) { - var $$ = result.value; - if (!$$.ptr) { - console.warn("object already deleted: " + $$.ptr); - } - else { - releaseClassHandle($$); - } - } - }); - attachFinalizer = function (handle) { - finalizationGroup.register(handle, handle.$$, handle.$$); - return handle; - }; - detachFinalizer = function (handle) { - finalizationGroup.unregister(handle.$$); - }; - return attachFinalizer(handle); - } - function ClassHandle_clone() { - if (!this.$$.ptr) { - throwInstanceAlreadyDeleted(this); - } - if (this.$$.preservePointerOnDelete) { - this.$$.count.value += 1; - return this; - } - else { - var clone = attachFinalizer(Object.create(Object.getPrototypeOf(this), { - $$: { - value: shallowCopyInternalPointer(this.$$), - }, - })); - clone.$$.count.value += 1; - clone.$$.deleteScheduled = false; - return clone; - } - } - function ClassHandle_delete() { - if (!this.$$.ptr) { - throwInstanceAlreadyDeleted(this); - } - if (this.$$.deleteScheduled && !this.$$.preservePointerOnDelete) { - throwBindingError("Object already scheduled for deletion"); - } - detachFinalizer(this); - releaseClassHandle(this.$$); - if (!this.$$.preservePointerOnDelete) { - this.$$.smartPtr = undefined; - this.$$.ptr = undefined; - } - } - function ClassHandle_isDeleted() { - return !this.$$.ptr; - } - var delayFunction = undefined; - var deletionQueue = []; - function flushPendingDeletes() { - while (deletionQueue.length) { - var obj = deletionQueue.pop(); - obj.$$.deleteScheduled = false; - obj["delete"](); - } - } - function ClassHandle_deleteLater() { - if (!this.$$.ptr) { - throwInstanceAlreadyDeleted(this); - } - if (this.$$.deleteScheduled && !this.$$.preservePointerOnDelete) { - throwBindingError("Object already scheduled for deletion"); - } - deletionQueue.push(this); - if (deletionQueue.length === 1 && delayFunction) { - delayFunction(flushPendingDeletes); - } - this.$$.deleteScheduled = true; - return this; - } - function init_ClassHandle() { - ClassHandle.prototype["isAliasOf"] = ClassHandle_isAliasOf; - ClassHandle.prototype["clone"] = ClassHandle_clone; - ClassHandle.prototype["delete"] = ClassHandle_delete; - ClassHandle.prototype["isDeleted"] = ClassHandle_isDeleted; - ClassHandle.prototype["deleteLater"] = ClassHandle_deleteLater; - } - function ClassHandle() { } - var registeredPointers = {}; - function ensureOverloadTable(proto, methodName, humanName) { - if (undefined === proto[methodName].overloadTable) { - var prevFunc = proto[methodName]; - proto[methodName] = function () { - if (!proto[methodName].overloadTable.hasOwnProperty(arguments.length)) { - throwBindingError("Function '" + - humanName + - "' called with an invalid number of arguments (" + - arguments.length + - ") - expects one of (" + - proto[methodName].overloadTable + - ")!"); - } - return proto[methodName].overloadTable[arguments.length].apply(this, arguments); - }; - proto[methodName].overloadTable = []; - proto[methodName].overloadTable[prevFunc.argCount] = prevFunc; - } - } - function exposePublicSymbol(name, value, numArguments) { - if (Module.hasOwnProperty(name)) { - if (undefined === numArguments || - (undefined !== Module[name].overloadTable && - undefined !== Module[name].overloadTable[numArguments])) { - throwBindingError("Cannot register public name '" + name + "' twice"); - } - ensureOverloadTable(Module, name, name); - if (Module.hasOwnProperty(numArguments)) { - throwBindingError("Cannot register multiple overloads of a function with the same number of arguments (" + - numArguments + - ")!"); - } - Module[name].overloadTable[numArguments] = value; - } - else { - Module[name] = value; - if (undefined !== numArguments) { - Module[name].numArguments = numArguments; - } - } - } - function RegisteredClass(name, constructor, instancePrototype, rawDestructor, baseClass, getActualType, upcast, downcast) { - this.name = name; - this.constructor = constructor; - this.instancePrototype = instancePrototype; - this.rawDestructor = rawDestructor; - this.baseClass = baseClass; - this.getActualType = getActualType; - this.upcast = upcast; - this.downcast = downcast; - this.pureVirtualFunctions = []; - } - function upcastPointer(ptr, ptrClass, desiredClass) { - while (ptrClass !== desiredClass) { - if (!ptrClass.upcast) { - throwBindingError("Expected null or instance of " + - desiredClass.name + - ", got an instance of " + - ptrClass.name); - } - ptr = ptrClass.upcast(ptr); - ptrClass = ptrClass.baseClass; - } - return ptr; - } - function constNoSmartPtrRawPointerToWireType(destructors, handle) { - if (handle === null) { - if (this.isReference) { - throwBindingError("null is not a valid " + this.name); - } - return 0; - } - if (!handle.$$) { - throwBindingError('Cannot pass "' + _embind_repr(handle) + '" as a ' + this.name); - } - if (!handle.$$.ptr) { - throwBindingError("Cannot pass deleted object as a pointer of type " + this.name); - } - var handleClass = handle.$$.ptrType.registeredClass; - var ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass); - return ptr; - } - function genericPointerToWireType(destructors, handle) { - var ptr; - if (handle === null) { - if (this.isReference) { - throwBindingError("null is not a valid " + this.name); - } - if (this.isSmartPointer) { - ptr = this.rawConstructor(); - if (destructors !== null) { - destructors.push(this.rawDestructor, ptr); - } - return ptr; - } - else { - return 0; - } - } - if (!handle.$$) { - throwBindingError('Cannot pass "' + _embind_repr(handle) + '" as a ' + this.name); - } - if (!handle.$$.ptr) { - throwBindingError("Cannot pass deleted object as a pointer of type " + this.name); - } - if (!this.isConst && handle.$$.ptrType.isConst) { - throwBindingError("Cannot convert argument of type " + - (handle.$$.smartPtrType - ? handle.$$.smartPtrType.name - : handle.$$.ptrType.name) + - " to parameter type " + - this.name); - } - var handleClass = handle.$$.ptrType.registeredClass; - ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass); - if (this.isSmartPointer) { - if (undefined === handle.$$.smartPtr) { - throwBindingError("Passing raw pointer to smart pointer is illegal"); - } - switch (this.sharingPolicy) { - case 0: - if (handle.$$.smartPtrType === this) { - ptr = handle.$$.smartPtr; - } - else { - throwBindingError("Cannot convert argument of type " + - (handle.$$.smartPtrType - ? handle.$$.smartPtrType.name - : handle.$$.ptrType.name) + - " to parameter type " + - this.name); - } - break; - case 1: - ptr = handle.$$.smartPtr; - break; - case 2: - if (handle.$$.smartPtrType === this) { - ptr = handle.$$.smartPtr; - } - else { - var clonedHandle = handle["clone"](); - ptr = this.rawShare(ptr, __emval_register(function () { - clonedHandle["delete"](); - })); - if (destructors !== null) { - destructors.push(this.rawDestructor, ptr); - } - } - break; - default: - throwBindingError("Unsupporting sharing policy"); - } - } - return ptr; - } - function nonConstNoSmartPtrRawPointerToWireType(destructors, handle) { - if (handle === null) { - if (this.isReference) { - throwBindingError("null is not a valid " + this.name); - } - return 0; - } - if (!handle.$$) { - throwBindingError('Cannot pass "' + _embind_repr(handle) + '" as a ' + this.name); - } - if (!handle.$$.ptr) { - throwBindingError("Cannot pass deleted object as a pointer of type " + this.name); - } - if (handle.$$.ptrType.isConst) { - throwBindingError("Cannot convert argument of type " + - handle.$$.ptrType.name + - " to parameter type " + - this.name); - } - var handleClass = handle.$$.ptrType.registeredClass; - var ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass); - return ptr; - } - function simpleReadValueFromPointer(pointer) { - return this["fromWireType"](GROWABLE_HEAP_U32()[pointer >> 2]); - } - function RegisteredPointer_getPointee(ptr) { - if (this.rawGetPointee) { - ptr = this.rawGetPointee(ptr); - } - return ptr; - } - function RegisteredPointer_destructor(ptr) { - if (this.rawDestructor) { - this.rawDestructor(ptr); - } - } - function RegisteredPointer_deleteObject(handle) { - if (handle !== null) { - handle["delete"](); - } - } - function downcastPointer(ptr, ptrClass, desiredClass) { - if (ptrClass === desiredClass) { - return ptr; - } - if (undefined === desiredClass.baseClass) { - return null; - } - var rv = downcastPointer(ptr, ptrClass, desiredClass.baseClass); - if (rv === null) { - return null; - } - return desiredClass.downcast(rv); - } - function getInheritedInstanceCount() { - return Object.keys(registeredInstances).length; - } - function getLiveInheritedInstances() { - var rv = []; - for (var k in registeredInstances) { - if (registeredInstances.hasOwnProperty(k)) { - rv.push(registeredInstances[k]); - } - } - return rv; - } - function setDelayFunction(fn) { - delayFunction = fn; - if (deletionQueue.length && delayFunction) { - delayFunction(flushPendingDeletes); - } - } - function init_embind() { - Module["getInheritedInstanceCount"] = getInheritedInstanceCount; - Module["getLiveInheritedInstances"] = getLiveInheritedInstances; - Module["flushPendingDeletes"] = flushPendingDeletes; - Module["setDelayFunction"] = setDelayFunction; - } - var registeredInstances = {}; - function getBasestPointer(class_, ptr) { - if (ptr === undefined) { - throwBindingError("ptr should not be undefined"); - } - while (class_.baseClass) { - ptr = class_.upcast(ptr); - class_ = class_.baseClass; - } - return ptr; - } - function getInheritedInstance(class_, ptr) { - ptr = getBasestPointer(class_, ptr); - return registeredInstances[ptr]; - } - function makeClassHandle(prototype, record) { - if (!record.ptrType || !record.ptr) { - throwInternalError("makeClassHandle requires ptr and ptrType"); - } - var hasSmartPtrType = !!record.smartPtrType; - var hasSmartPtr = !!record.smartPtr; - if (hasSmartPtrType !== hasSmartPtr) { - throwInternalError("Both smartPtrType and smartPtr must be specified"); - } - record.count = { - value: 1, - }; - return attachFinalizer(Object.create(prototype, { - $$: { - value: record, - }, - })); - } - function RegisteredPointer_fromWireType(ptr) { - var rawPointer = this.getPointee(ptr); - if (!rawPointer) { - this.destructor(ptr); - return null; - } - var registeredInstance = getInheritedInstance(this.registeredClass, rawPointer); - if (undefined !== registeredInstance) { - if (0 === registeredInstance.$$.count.value) { - registeredInstance.$$.ptr = rawPointer; - registeredInstance.$$.smartPtr = ptr; - return registeredInstance["clone"](); - } - else { - var rv = registeredInstance["clone"](); - this.destructor(ptr); - return rv; - } - } - function makeDefaultHandle() { - if (this.isSmartPointer) { - return makeClassHandle(this.registeredClass.instancePrototype, { - ptrType: this.pointeeType, - ptr: rawPointer, - smartPtrType: this, - smartPtr: ptr, - }); - } - else { - return makeClassHandle(this.registeredClass.instancePrototype, { - ptrType: this, - ptr: ptr, - }); - } - } - var actualType = this.registeredClass.getActualType(rawPointer); - var registeredPointerRecord = registeredPointers[actualType]; - if (!registeredPointerRecord) { - return makeDefaultHandle.call(this); - } - var toType; - if (this.isConst) { - toType = registeredPointerRecord.constPointerType; - } - else { - toType = registeredPointerRecord.pointerType; - } - var dp = downcastPointer(rawPointer, this.registeredClass, toType.registeredClass); - if (dp === null) { - return makeDefaultHandle.call(this); - } - if (this.isSmartPointer) { - return makeClassHandle(toType.registeredClass.instancePrototype, { - ptrType: toType, - ptr: dp, - smartPtrType: this, - smartPtr: ptr, - }); - } - else { - return makeClassHandle(toType.registeredClass.instancePrototype, { - ptrType: toType, - ptr: dp, - }); - } - } - function init_RegisteredPointer() { - RegisteredPointer.prototype.getPointee = RegisteredPointer_getPointee; - RegisteredPointer.prototype.destructor = RegisteredPointer_destructor; - RegisteredPointer.prototype["argPackAdvance"] = 8; - RegisteredPointer.prototype["readValueFromPointer"] = simpleReadValueFromPointer; - RegisteredPointer.prototype["deleteObject"] = RegisteredPointer_deleteObject; - RegisteredPointer.prototype["fromWireType"] = RegisteredPointer_fromWireType; - } - function RegisteredPointer(name, registeredClass, isReference, isConst, isSmartPointer, pointeeType, sharingPolicy, rawGetPointee, rawConstructor, rawShare, rawDestructor) { - this.name = name; - this.registeredClass = registeredClass; - this.isReference = isReference; - this.isConst = isConst; - this.isSmartPointer = isSmartPointer; - this.pointeeType = pointeeType; - this.sharingPolicy = sharingPolicy; - this.rawGetPointee = rawGetPointee; - this.rawConstructor = rawConstructor; - this.rawShare = rawShare; - this.rawDestructor = rawDestructor; - if (!isSmartPointer && registeredClass.baseClass === undefined) { - if (isConst) { - this["toWireType"] = constNoSmartPtrRawPointerToWireType; - this.destructorFunction = null; - } - else { - this["toWireType"] = nonConstNoSmartPtrRawPointerToWireType; - this.destructorFunction = null; - } - } - else { - this["toWireType"] = genericPointerToWireType; - } - } - function replacePublicSymbol(name, value, numArguments) { - if (!Module.hasOwnProperty(name)) { - throwInternalError("Replacing nonexistant public symbol"); - } - if (undefined !== Module[name].overloadTable && - undefined !== numArguments) { - Module[name].overloadTable[numArguments] = value; - } - else { - Module[name] = value; - Module[name].argCount = numArguments; - } - } - function getDynCaller(sig, ptr) { - assert(sig.indexOf("j") >= 0, "getDynCaller should only be called with i64 sigs"); - var argCache = []; - return function () { - argCache.length = arguments.length; - for (var i = 0; i < arguments.length; i++) { - argCache[i] = arguments[i]; - } - return dynCall(sig, ptr, argCache); - }; - } - function embind__requireFunction(signature, rawFunction) { - signature = readLatin1String(signature); - function makeDynCaller() { - if (signature.indexOf("j") != -1) { - return getDynCaller(signature, rawFunction); - } - return wasmTable.get(rawFunction); - } - var fp = makeDynCaller(); - if (typeof fp !== "function") { - throwBindingError("unknown function pointer with signature " + - signature + - ": " + - rawFunction); - } - return fp; - } - var UnboundTypeError = undefined; - function getTypeName(type) { - var ptr = ___getTypeName(type); - var rv = readLatin1String(ptr); - _free(ptr); - return rv; - } - function throwUnboundTypeError(message, types) { - var unboundTypes = []; - var seen = {}; - function visit(type) { - if (seen[type]) { - return; - } - if (registeredTypes[type]) { - return; - } - if (typeDependencies[type]) { - typeDependencies[type].forEach(visit); - return; - } - unboundTypes.push(type); - seen[type] = true; - } - types.forEach(visit); - throw new UnboundTypeError(message + ": " + unboundTypes.map(getTypeName).join([", "])); - } - function __embind_register_class(rawType, rawPointerType, rawConstPointerType, baseClassRawType, getActualTypeSignature, getActualType, upcastSignature, upcast, downcastSignature, downcast, name, destructorSignature, rawDestructor) { - name = readLatin1String(name); - getActualType = embind__requireFunction(getActualTypeSignature, getActualType); - if (upcast) { - upcast = embind__requireFunction(upcastSignature, upcast); - } - if (downcast) { - downcast = embind__requireFunction(downcastSignature, downcast); - } - rawDestructor = embind__requireFunction(destructorSignature, rawDestructor); - var legalFunctionName = makeLegalFunctionName(name); - exposePublicSymbol(legalFunctionName, function () { - throwUnboundTypeError("Cannot construct " + name + " due to unbound types", [baseClassRawType]); - }); - whenDependentTypesAreResolved([rawType, rawPointerType, rawConstPointerType], baseClassRawType ? [baseClassRawType] : [], function (base) { - base = base[0]; - var baseClass; - var basePrototype; - if (baseClassRawType) { - baseClass = base.registeredClass; - basePrototype = baseClass.instancePrototype; - } - else { - basePrototype = ClassHandle.prototype; - } - var constructor = createNamedFunction(legalFunctionName, function () { - if (Object.getPrototypeOf(this) !== instancePrototype) { - throw new BindingError("Use 'new' to construct " + name); - } - if (undefined === registeredClass.constructor_body) { - throw new BindingError(name + " has no accessible constructor"); - } - var body = registeredClass.constructor_body[arguments.length]; - if (undefined === body) { - throw new BindingError("Tried to invoke ctor of " + - name + - " with invalid number of parameters (" + - arguments.length + - ") - expected (" + - Object.keys(registeredClass.constructor_body).toString() + - ") parameters instead!"); - } - return body.apply(this, arguments); - }); - var instancePrototype = Object.create(basePrototype, { - constructor: { - value: constructor, - }, - }); - constructor.prototype = instancePrototype; - var registeredClass = new RegisteredClass(name, constructor, instancePrototype, rawDestructor, baseClass, getActualType, upcast, downcast); - var referenceConverter = new RegisteredPointer(name, registeredClass, true, false, false); - var pointerConverter = new RegisteredPointer(name + "*", registeredClass, false, false, false); - var constPointerConverter = new RegisteredPointer(name + " const*", registeredClass, false, true, false); - registeredPointers[rawType] = { - pointerType: pointerConverter, - constPointerType: constPointerConverter, - }; - replacePublicSymbol(legalFunctionName, constructor); - return [referenceConverter, pointerConverter, constPointerConverter]; - }); - } - function heap32VectorToArray(count, firstElement) { - var array = []; - for (var i = 0; i < count; i++) { - array.push(GROWABLE_HEAP_I32()[(firstElement >> 2) + i]); - } - return array; - } - function runDestructors(destructors) { - while (destructors.length) { - var ptr = destructors.pop(); - var del = destructors.pop(); - del(ptr); - } - } - function __embind_register_class_constructor(rawClassType, argCount, rawArgTypesAddr, invokerSignature, invoker, rawConstructor) { - assert(argCount > 0); - var rawArgTypes = heap32VectorToArray(argCount, rawArgTypesAddr); - invoker = embind__requireFunction(invokerSignature, invoker); - var args = [rawConstructor]; - var destructors = []; - whenDependentTypesAreResolved([], [rawClassType], function (classType) { - classType = classType[0]; - var humanName = "constructor " + classType.name; - if (undefined === classType.registeredClass.constructor_body) { - classType.registeredClass.constructor_body = []; - } - if (undefined !== classType.registeredClass.constructor_body[argCount - 1]) { - throw new BindingError("Cannot register multiple constructors with identical number of parameters (" + - (argCount - 1) + - ") for class '" + - classType.name + - "'! Overload resolution is currently only performed using the parameter count, not actual type info!"); - } - classType.registeredClass.constructor_body[argCount - 1] = function unboundTypeHandler() { - throwUnboundTypeError("Cannot construct " + classType.name + " due to unbound types", rawArgTypes); - }; - whenDependentTypesAreResolved([], rawArgTypes, function (argTypes) { - classType.registeredClass.constructor_body[argCount - 1] = function constructor_body() { - if (arguments.length !== argCount - 1) { - throwBindingError(humanName + - " called with " + - arguments.length + - " arguments, expected " + - (argCount - 1)); - } - destructors.length = 0; - args.length = argCount; - for (var i = 1; i < argCount; ++i) { - args[i] = argTypes[i]["toWireType"](destructors, arguments[i - 1]); - } - var ptr = invoker.apply(null, args); - runDestructors(destructors); - return argTypes[0]["fromWireType"](ptr); - }; - return []; - }); - return []; - }); - } - function craftInvokerFunction(humanName, argTypes, classType, cppInvokerFunc, cppTargetFunc) { - var argCount = argTypes.length; - if (argCount < 2) { - throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!"); - } - var isClassMethodFunc = argTypes[1] !== null && classType !== null; - var needsDestructorStack = false; - for (var i = 1; i < argTypes.length; ++i) { - if (argTypes[i] !== null && - argTypes[i].destructorFunction === undefined) { - needsDestructorStack = true; - break; - } - } - var returns = argTypes[0].name !== "void"; - var expectedArgCount = argCount - 2; - var argsWired = new Array(expectedArgCount); - var invokerFuncArgs = []; - var destructors = []; - return function () { - if (arguments.length !== expectedArgCount) { - throwBindingError("function " + - humanName + - " called with " + - arguments.length + - " arguments, expected " + - expectedArgCount + - " args!"); - } - destructors.length = 0; - var thisWired; - invokerFuncArgs.length = isClassMethodFunc ? 2 : 1; - invokerFuncArgs[0] = cppTargetFunc; - if (isClassMethodFunc) { - thisWired = argTypes[1].toWireType(destructors, this); - invokerFuncArgs[1] = thisWired; - } - for (var i = 0; i < expectedArgCount; ++i) { - argsWired[i] = argTypes[i + 2].toWireType(destructors, arguments[i]); - invokerFuncArgs.push(argsWired[i]); - } - var rv = cppInvokerFunc.apply(null, invokerFuncArgs); - if (needsDestructorStack) { - runDestructors(destructors); - } - else { - for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; i++) { - var param = i === 1 ? thisWired : argsWired[i - 2]; - if (argTypes[i].destructorFunction !== null) { - argTypes[i].destructorFunction(param); - } - } - } - if (returns) { - return argTypes[0].fromWireType(rv); - } - }; - } - function __embind_register_class_function(rawClassType, methodName, argCount, rawArgTypesAddr, invokerSignature, rawInvoker, context, isPureVirtual) { - var rawArgTypes = heap32VectorToArray(argCount, rawArgTypesAddr); - methodName = readLatin1String(methodName); - rawInvoker = embind__requireFunction(invokerSignature, rawInvoker); - whenDependentTypesAreResolved([], [rawClassType], function (classType) { - classType = classType[0]; - var humanName = classType.name + "." + methodName; - if (isPureVirtual) { - classType.registeredClass.pureVirtualFunctions.push(methodName); - } - function unboundTypesHandler() { - throwUnboundTypeError("Cannot call " + humanName + " due to unbound types", rawArgTypes); - } - var proto = classType.registeredClass.instancePrototype; - var method = proto[methodName]; - if (undefined === method || - (undefined === method.overloadTable && - method.className !== classType.name && - method.argCount === argCount - 2)) { - unboundTypesHandler.argCount = argCount - 2; - unboundTypesHandler.className = classType.name; - proto[methodName] = unboundTypesHandler; - } - else { - ensureOverloadTable(proto, methodName, humanName); - proto[methodName].overloadTable[argCount - 2] = unboundTypesHandler; - } - whenDependentTypesAreResolved([], rawArgTypes, function (argTypes) { - var memberFunction = craftInvokerFunction(humanName, argTypes, classType, rawInvoker, context); - if (undefined === proto[methodName].overloadTable) { - memberFunction.argCount = argCount - 2; - proto[methodName] = memberFunction; - } - else { - proto[methodName].overloadTable[argCount - 2] = memberFunction; - } - return []; - }); - return []; - }); - } - var emval_free_list = []; - var emval_handle_array = [ - {}, - { - value: undefined, - }, - { - value: null, - }, - { - value: true, - }, - { - value: false, - }, - ]; - function __emval_decref(handle) { - if (handle > 4 && 0 === --emval_handle_array[handle].refcount) { - emval_handle_array[handle] = undefined; - emval_free_list.push(handle); - } - } - function count_emval_handles() { - var count = 0; - for (var i = 5; i < emval_handle_array.length; ++i) { - if (emval_handle_array[i] !== undefined) { - ++count; - } - } - return count; - } - function get_first_emval() { - for (var i = 5; i < emval_handle_array.length; ++i) { - if (emval_handle_array[i] !== undefined) { - return emval_handle_array[i]; - } - } - return null; - } - function init_emval() { - Module["count_emval_handles"] = count_emval_handles; - Module["get_first_emval"] = get_first_emval; - } - function __emval_register(value) { - switch (value) { - case undefined: { - return 1; - } - case null: { - return 2; - } - case true: { - return 3; - } - case false: { - return 4; - } - default: { - var handle = emval_free_list.length - ? emval_free_list.pop() - : emval_handle_array.length; - emval_handle_array[handle] = { - refcount: 1, - value: value, - }; - return handle; - } - } - } - function __embind_register_emval(rawType, name) { - name = readLatin1String(name); - registerType(rawType, { - name: name, - fromWireType: function (handle) { - var rv = emval_handle_array[handle].value; - __emval_decref(handle); - return rv; - }, - toWireType: function (destructors, value) { - return __emval_register(value); - }, - argPackAdvance: 8, - readValueFromPointer: simpleReadValueFromPointer, - destructorFunction: null, - }); - } - function _embind_repr(v) { - if (v === null) { - return "null"; - } - var t = typeof v; - if (t === "object" || t === "array" || t === "function") { - return v.toString(); - } - else { - return "" + v; - } - } - function floatReadValueFromPointer(name, shift) { - switch (shift) { - case 2: - return function (pointer) { - return this["fromWireType"](GROWABLE_HEAP_F32()[pointer >> 2]); - }; - case 3: - return function (pointer) { - return this["fromWireType"](GROWABLE_HEAP_F64()[pointer >> 3]); - }; - default: - throw new TypeError("Unknown float type: " + name); - } - } - function __embind_register_float(rawType, name, size) { - var shift = getShiftFromSize(size); - name = readLatin1String(name); - registerType(rawType, { - name: name, - fromWireType: function (value) { - return value; - }, - toWireType: function (destructors, value) { - if (typeof value !== "number" && typeof value !== "boolean") { - throw new TypeError('Cannot convert "' + _embind_repr(value) + '" to ' + this.name); - } - return value; - }, - argPackAdvance: 8, - readValueFromPointer: floatReadValueFromPointer(name, shift), - destructorFunction: null, - }); - } - function integerReadValueFromPointer(name, shift, signed) { - switch (shift) { - case 0: - return signed - ? function readS8FromPointer(pointer) { - return GROWABLE_HEAP_I8()[pointer]; - } - : function readU8FromPointer(pointer) { - return GROWABLE_HEAP_U8()[pointer]; - }; - case 1: - return signed - ? function readS16FromPointer(pointer) { - return GROWABLE_HEAP_I16()[pointer >> 1]; - } - : function readU16FromPointer(pointer) { - return GROWABLE_HEAP_U16()[pointer >> 1]; - }; - case 2: - return signed - ? function readS32FromPointer(pointer) { - return GROWABLE_HEAP_I32()[pointer >> 2]; - } - : function readU32FromPointer(pointer) { - return GROWABLE_HEAP_U32()[pointer >> 2]; - }; - default: - throw new TypeError("Unknown integer type: " + name); - } - } - function __embind_register_integer(primitiveType, name, size, minRange, maxRange) { - name = readLatin1String(name); - if (maxRange === -1) { - maxRange = 4294967295; - } - var shift = getShiftFromSize(size); - var fromWireType = function (value) { - return value; - }; - if (minRange === 0) { - var bitshift = 32 - 8 * size; - fromWireType = function (value) { - return (value << bitshift) >>> bitshift; - }; - } - var isUnsignedType = name.indexOf("unsigned") != -1; - registerType(primitiveType, { - name: name, - fromWireType: fromWireType, - toWireType: function (destructors, value) { - if (typeof value !== "number" && typeof value !== "boolean") { - throw new TypeError('Cannot convert "' + _embind_repr(value) + '" to ' + this.name); - } - if (value < minRange || value > maxRange) { - throw new TypeError('Passing a number "' + - _embind_repr(value) + - '" from JS side to C/C++ side to an argument of type "' + - name + - '", which is outside the valid range [' + - minRange + - ", " + - maxRange + - "]!"); - } - return isUnsignedType ? value >>> 0 : value | 0; - }, - argPackAdvance: 8, - readValueFromPointer: integerReadValueFromPointer(name, shift, minRange !== 0), - destructorFunction: null, - }); - } - function __embind_register_memory_view(rawType, dataTypeIndex, name) { - var typeMapping = [ - Int8Array, - Uint8Array, - Int16Array, - Uint16Array, - Int32Array, - Uint32Array, - Float32Array, - Float64Array, - ]; - var TA = typeMapping[dataTypeIndex]; - function decodeMemoryView(handle) { - handle = handle >> 2; - var heap = GROWABLE_HEAP_U32(); - var size = heap[handle]; - var data = heap[handle + 1]; - return new TA(buffer, data, size); - } - name = readLatin1String(name); - registerType(rawType, { - name: name, - fromWireType: decodeMemoryView, - argPackAdvance: 8, - readValueFromPointer: decodeMemoryView, - }, { - ignoreDuplicateRegistrations: true, - }); - } - function __embind_register_std_string(rawType, name) { - name = readLatin1String(name); - var stdStringIsUTF8 = name === "std::string"; - registerType(rawType, { - name: name, - fromWireType: function (value) { - var length = GROWABLE_HEAP_U32()[value >> 2]; - var str; - if (stdStringIsUTF8) { - var decodeStartPtr = value + 4; - for (var i = 0; i <= length; ++i) { - var currentBytePtr = value + 4 + i; - if (i == length || GROWABLE_HEAP_U8()[currentBytePtr] == 0) { - var maxRead = currentBytePtr - decodeStartPtr; - var stringSegment = UTF8ToString(decodeStartPtr, maxRead); - if (str === undefined) { - str = stringSegment; - } - else { - str += String.fromCharCode(0); - str += stringSegment; - } - decodeStartPtr = currentBytePtr + 1; - } - } - } - else { - var a = new Array(length); - for (var i = 0; i < length; ++i) { - a[i] = String.fromCharCode(GROWABLE_HEAP_U8()[value + 4 + i]); - } - str = a.join(""); - } - _free(value); - return str; - }, - toWireType: function (destructors, value) { - if (value instanceof ArrayBuffer) { - value = new Uint8Array(value); - } - var getLength; - var valueIsOfTypeString = typeof value === "string"; - if (!(valueIsOfTypeString || - value instanceof Uint8Array || - value instanceof Uint8ClampedArray || - value instanceof Int8Array)) { - throwBindingError("Cannot pass non-string to std::string"); - } - if (stdStringIsUTF8 && valueIsOfTypeString) { - getLength = function () { - return lengthBytesUTF8(value); - }; - } - else { - getLength = function () { - return value.length; - }; - } - var length = getLength(); - var ptr = _malloc(4 + length + 1); - GROWABLE_HEAP_U32()[ptr >> 2] = length; - if (stdStringIsUTF8 && valueIsOfTypeString) { - stringToUTF8(value, ptr + 4, length + 1); - } - else { - if (valueIsOfTypeString) { - for (var i = 0; i < length; ++i) { - var charCode = value.charCodeAt(i); - if (charCode > 255) { - _free(ptr); - throwBindingError("String has UTF-16 code units that do not fit in 8 bits"); - } - GROWABLE_HEAP_U8()[ptr + 4 + i] = charCode; - } - } - else { - for (var i = 0; i < length; ++i) { - GROWABLE_HEAP_U8()[ptr + 4 + i] = value[i]; - } - } - } - if (destructors !== null) { - destructors.push(_free, ptr); - } - return ptr; - }, - argPackAdvance: 8, - readValueFromPointer: simpleReadValueFromPointer, - destructorFunction: function (ptr) { - _free(ptr); - }, - }); - } - function __embind_register_std_wstring(rawType, charSize, name) { - name = readLatin1String(name); - var decodeString, encodeString, getHeap, lengthBytesUTF, shift; - if (charSize === 2) { - decodeString = UTF16ToString; - encodeString = stringToUTF16; - lengthBytesUTF = lengthBytesUTF16; - getHeap = function () { - return GROWABLE_HEAP_U16(); - }; - shift = 1; - } - else if (charSize === 4) { - decodeString = UTF32ToString; - encodeString = stringToUTF32; - lengthBytesUTF = lengthBytesUTF32; - getHeap = function () { - return GROWABLE_HEAP_U32(); - }; - shift = 2; - } - registerType(rawType, { - name: name, - fromWireType: function (value) { - var length = GROWABLE_HEAP_U32()[value >> 2]; - var HEAP = getHeap(); - var str; - var decodeStartPtr = value + 4; - for (var i = 0; i <= length; ++i) { - var currentBytePtr = value + 4 + i * charSize; - if (i == length || HEAP[currentBytePtr >> shift] == 0) { - var maxReadBytes = currentBytePtr - decodeStartPtr; - var stringSegment = decodeString(decodeStartPtr, maxReadBytes); - if (str === undefined) { - str = stringSegment; - } - else { - str += String.fromCharCode(0); - str += stringSegment; - } - decodeStartPtr = currentBytePtr + charSize; - } - } - _free(value); - return str; - }, - toWireType: function (destructors, value) { - if (!(typeof value === "string")) { - throwBindingError("Cannot pass non-string to C++ string type " + name); - } - var length = lengthBytesUTF(value); - var ptr = _malloc(4 + length + charSize); - GROWABLE_HEAP_U32()[ptr >> 2] = length >> shift; - encodeString(value, ptr + 4, length + charSize); - if (destructors !== null) { - destructors.push(_free, ptr); - } - return ptr; - }, - argPackAdvance: 8, - readValueFromPointer: simpleReadValueFromPointer, - destructorFunction: function (ptr) { - _free(ptr); - }, - }); - } - function __embind_register_void(rawType, name) { - name = readLatin1String(name); - registerType(rawType, { - isVoid: true, - name: name, - argPackAdvance: 0, - fromWireType: function () { - return undefined; - }, - toWireType: function (destructors, o) { - return undefined; - }, - }); - } - function __emscripten_notify_thread_queue(targetThreadId, mainThreadId) { - if (targetThreadId == mainThreadId) { - postMessage({ - cmd: "processQueuedMainThreadWork", - }); - } - else if (ENVIRONMENT_IS_PTHREAD) { - postMessage({ - targetThread: targetThreadId, - cmd: "processThreadQueue", - }); - } - else { - var pthread = PThread.pthreads[targetThreadId]; - var worker = pthread && pthread.worker; - if (!worker) { - return; - } - worker.postMessage({ - cmd: "processThreadQueue", - }); - } - return 1; - } - function __emval_incref(handle) { - if (handle > 4) { - emval_handle_array[handle].refcount += 1; - } - } - function requireRegisteredType(rawType, humanName) { - var impl = registeredTypes[rawType]; - if (undefined === impl) { - throwBindingError(humanName + " has unknown type " + getTypeName(rawType)); - } - return impl; - } - function __emval_take_value(type, argv) { - type = requireRegisteredType(type, "_emval_take_value"); - var v = type["readValueFromPointer"](argv); - return __emval_register(v); - } - function _abort() { - abort(); - } - function _emscripten_asm_const_int(code, sigPtr, argbuf) { - var args = readAsmConstArgs(sigPtr, argbuf); - return ASM_CONSTS[code].apply(null, args); - } - function _emscripten_check_blocking_allowed() { - if (ENVIRONMENT_IS_WORKER) - return; - warnOnce("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread"); - } - function _emscripten_conditional_set_current_thread_status(expectedStatus, newStatus) { - expectedStatus = expectedStatus | 0; - newStatus = newStatus | 0; - } - function _emscripten_futex_wait(addr, val, timeout) { - if (addr <= 0 || addr > GROWABLE_HEAP_I8().length || addr & (3 != 0)) - return -28; - if (!ENVIRONMENT_IS_WEB) { - var ret = Atomics.wait(GROWABLE_HEAP_I32(), addr >> 2, val, timeout); - if (ret === "timed-out") - return -73; - if (ret === "not-equal") - return -6; - if (ret === "ok") - return 0; - throw "Atomics.wait returned an unexpected value " + ret; - } - else { - if (Atomics.load(GROWABLE_HEAP_I32(), addr >> 2) != val) { - return -6; - } - var tNow = performance.now(); - var tEnd = tNow + timeout; - var lastAddr = Atomics.exchange(GROWABLE_HEAP_I32(), PThread.mainThreadFutex >> 2, addr); - while (1) { - tNow = performance.now(); - if (tNow > tEnd) { - lastAddr = Atomics.exchange(GROWABLE_HEAP_I32(), PThread.mainThreadFutex >> 2, 0); - return -73; - } - lastAddr = Atomics.exchange(GROWABLE_HEAP_I32(), PThread.mainThreadFutex >> 2, 0); - if (lastAddr == 0) { - break; - } - _emscripten_main_thread_process_queued_calls(); - if (Atomics.load(GROWABLE_HEAP_I32(), addr >> 2) != val) { - return -6; - } - lastAddr = Atomics.exchange(GROWABLE_HEAP_I32(), PThread.mainThreadFutex >> 2, addr); - } - return 0; - } - } - function _emscripten_is_main_browser_thread() { - return __pthread_is_main_browser_thread | 0; - } - function _emscripten_is_main_runtime_thread() { - return __pthread_is_main_runtime_thread | 0; - } - function _emscripten_memcpy_big(dest, src, num) { - GROWABLE_HEAP_U8().copyWithin(dest, src, src + num); - } - function _emscripten_proxy_to_main_thread_js(index, sync) { - var numCallArgs = arguments.length - 2; - var stack = stackSave(); - var args = stackAlloc(numCallArgs * 8); - var b = args >> 3; - for (var i = 0; i < numCallArgs; i++) { - GROWABLE_HEAP_F64()[b + i] = arguments[2 + i]; - } - var ret = _emscripten_run_in_main_runtime_thread_js(index, numCallArgs, args, sync); - stackRestore(stack); - return ret; - } - var _emscripten_receive_on_main_thread_js_callArgs = []; - var readAsmConstArgsArray = []; - function readAsmConstArgs(sigPtr, buf) { - readAsmConstArgsArray.length = 0; - var ch; - buf >>= 2; - while ((ch = GROWABLE_HEAP_U8()[sigPtr++])) { - var double = ch < 105; - if (double && buf & 1) - buf++; - readAsmConstArgsArray.push(double ? GROWABLE_HEAP_F64()[buf++ >> 1] : GROWABLE_HEAP_I32()[buf]); - ++buf; - } - return readAsmConstArgsArray; - } - function _emscripten_receive_on_main_thread_js(index, numCallArgs, args) { - _emscripten_receive_on_main_thread_js_callArgs.length = numCallArgs; - var b = args >> 3; - for (var i = 0; i < numCallArgs; i++) { - _emscripten_receive_on_main_thread_js_callArgs[i] = GROWABLE_HEAP_F64()[b + i]; - } - var isEmAsmConst = index < 0; - var func = !isEmAsmConst - ? proxiedFunctionTable[index] - : ASM_CONSTS[-index - 1]; - return func.apply(null, _emscripten_receive_on_main_thread_js_callArgs); - } - function _emscripten_get_heap_size() { - return GROWABLE_HEAP_U8().length; - } - function emscripten_realloc_buffer(size) { - try { - wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16); - updateGlobalBufferAndViews(wasmMemory.buffer); - return 1; - } - catch (e) { } - } - function _emscripten_resize_heap(requestedSize) { - requestedSize = requestedSize >>> 0; - var oldSize = _emscripten_get_heap_size(); - if (requestedSize <= oldSize) { - return false; - } - var maxHeapSize = 2147483648; - if (requestedSize > maxHeapSize) { - return false; - } - var minHeapSize = 16777216; - for (var cutDown = 1; cutDown <= 4; cutDown *= 2) { - var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); - overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296); - var newSize = Math.min(maxHeapSize, alignUp(Math.max(minHeapSize, requestedSize, overGrownHeapSize), 65536)); - var replacement = emscripten_realloc_buffer(newSize); - if (replacement) { - return true; - } - } - return false; - } - var JSEvents = { - inEventHandler: 0, - removeAllEventListeners: function () { - for (var i = JSEvents.eventHandlers.length - 1; i >= 0; --i) { - JSEvents._removeHandler(i); - } - JSEvents.eventHandlers = []; - JSEvents.deferredCalls = []; - }, - registerRemoveEventListeners: function () { - if (!JSEvents.removeEventListenersRegistered) { - __ATEXIT__.push(JSEvents.removeAllEventListeners); - JSEvents.removeEventListenersRegistered = true; - } - }, - deferredCalls: [], - deferCall: function (targetFunction, precedence, argsList) { - function arraysHaveEqualContent(arrA, arrB) { - if (arrA.length != arrB.length) - return false; - for (var i in arrA) { - if (arrA[i] != arrB[i]) - return false; - } - return true; - } - for (var i in JSEvents.deferredCalls) { - var call = JSEvents.deferredCalls[i]; - if (call.targetFunction == targetFunction && - arraysHaveEqualContent(call.argsList, argsList)) { - return; - } - } - JSEvents.deferredCalls.push({ - targetFunction: targetFunction, - precedence: precedence, - argsList: argsList, - }); - JSEvents.deferredCalls.sort(function (x, y) { - return x.precedence < y.precedence; - }); - }, - removeDeferredCalls: function (targetFunction) { - for (var i = 0; i < JSEvents.deferredCalls.length; ++i) { - if (JSEvents.deferredCalls[i].targetFunction == targetFunction) { - JSEvents.deferredCalls.splice(i, 1); - --i; - } - } - }, - canPerformEventHandlerRequests: function () { - return (JSEvents.inEventHandler && - JSEvents.currentEventHandler.allowsDeferredCalls); - }, - runDeferredCalls: function () { - if (!JSEvents.canPerformEventHandlerRequests()) { - return; - } - for (var i = 0; i < JSEvents.deferredCalls.length; ++i) { - var call = JSEvents.deferredCalls[i]; - JSEvents.deferredCalls.splice(i, 1); - --i; - call.targetFunction.apply(null, call.argsList); - } - }, - eventHandlers: [], - removeAllHandlersOnTarget: function (target, eventTypeString) { - for (var i = 0; i < JSEvents.eventHandlers.length; ++i) { - if (JSEvents.eventHandlers[i].target == target && - (!eventTypeString || - eventTypeString == JSEvents.eventHandlers[i].eventTypeString)) { - JSEvents._removeHandler(i--); - } - } - }, - _removeHandler: function (i) { - var h = JSEvents.eventHandlers[i]; - h.target.removeEventListener(h.eventTypeString, h.eventListenerFunc, h.useCapture); - JSEvents.eventHandlers.splice(i, 1); - }, - registerOrRemoveHandler: function (eventHandler) { - var jsEventHandler = function jsEventHandler(event) { - ++JSEvents.inEventHandler; - JSEvents.currentEventHandler = eventHandler; - JSEvents.runDeferredCalls(); - eventHandler.handlerFunc(event); - JSEvents.runDeferredCalls(); - --JSEvents.inEventHandler; - }; - if (eventHandler.callbackfunc) { - eventHandler.eventListenerFunc = jsEventHandler; - eventHandler.target.addEventListener(eventHandler.eventTypeString, jsEventHandler, eventHandler.useCapture); - JSEvents.eventHandlers.push(eventHandler); - JSEvents.registerRemoveEventListeners(); - } - else { - for (var i = 0; i < JSEvents.eventHandlers.length; ++i) { - if (JSEvents.eventHandlers[i].target == eventHandler.target && - JSEvents.eventHandlers[i].eventTypeString == - eventHandler.eventTypeString) { - JSEvents._removeHandler(i--); - } - } - } - }, - queueEventHandlerOnThread_iiii: function (targetThread, eventHandlerFunc, eventTypeId, eventData, userData) { - var stackTop = stackSave(); - var varargs = stackAlloc(12); - GROWABLE_HEAP_I32()[varargs >> 2] = eventTypeId; - GROWABLE_HEAP_I32()[(varargs + 4) >> 2] = eventData; - GROWABLE_HEAP_I32()[(varargs + 8) >> 2] = userData; - __emscripten_call_on_thread(0, targetThread, 637534208, eventHandlerFunc, eventData, varargs); - stackRestore(stackTop); - }, - getTargetThreadForEventCallback: function (targetThread) { - switch (targetThread) { - case 1: - return 0; - case 2: - return PThread.currentProxiedOperationCallerThread; - default: - return targetThread; - } - }, - getNodeNameForTarget: function (target) { - if (!target) - return ""; - if (target == window) - return "#window"; - if (target == screen) - return "#screen"; - return target && target.nodeName ? target.nodeName : ""; - }, - fullscreenEnabled: function () { - return document.fullscreenEnabled || document.webkitFullscreenEnabled; - }, - }; - function stringToNewUTF8(jsString) { - var length = lengthBytesUTF8(jsString) + 1; - var cString = _malloc(length); - stringToUTF8(jsString, cString, length); - return cString; - } - function _emscripten_set_offscreencanvas_size_on_target_thread_js(targetThread, targetCanvas, width, height) { - var stackTop = stackSave(); - var varargs = stackAlloc(12); - var targetCanvasPtr = 0; - if (targetCanvas) { - targetCanvasPtr = stringToNewUTF8(targetCanvas); - } - GROWABLE_HEAP_I32()[varargs >> 2] = targetCanvasPtr; - GROWABLE_HEAP_I32()[(varargs + 4) >> 2] = width; - GROWABLE_HEAP_I32()[(varargs + 8) >> 2] = height; - __emscripten_call_on_thread(0, targetThread, 657457152, 0, targetCanvasPtr, varargs); - stackRestore(stackTop); - } - function _emscripten_set_offscreencanvas_size_on_target_thread(targetThread, targetCanvas, width, height) { - targetCanvas = targetCanvas ? UTF8ToString(targetCanvas) : ""; - _emscripten_set_offscreencanvas_size_on_target_thread_js(targetThread, targetCanvas, width, height); - } - function maybeCStringToJsString(cString) { - return cString > 2 ? UTF8ToString(cString) : cString; - } - var specialHTMLTargets = [ - 0, - typeof document !== "undefined" ? document : 0, - typeof window !== "undefined" ? window : 0, - ]; - function findEventTarget(target) { - target = maybeCStringToJsString(target); - var domElement = specialHTMLTargets[target] || - (typeof document !== "undefined" - ? document.querySelector(target) - : undefined); - return domElement; - } - function findCanvasEventTarget(target) { - return findEventTarget(target); - } - function _emscripten_set_canvas_element_size_calling_thread(target, width, height) { - var canvas = findCanvasEventTarget(target); - if (!canvas) - return -4; - if (canvas.canvasSharedPtr) { - GROWABLE_HEAP_I32()[canvas.canvasSharedPtr >> 2] = width; - GROWABLE_HEAP_I32()[(canvas.canvasSharedPtr + 4) >> 2] = height; - } - if (canvas.offscreenCanvas || !canvas.controlTransferredOffscreen) { - if (canvas.offscreenCanvas) - canvas = canvas.offscreenCanvas; - var autoResizeViewport = false; - if (canvas.GLctxObject && canvas.GLctxObject.GLctx) { - var prevViewport = canvas.GLctxObject.GLctx.getParameter(2978); - autoResizeViewport = - prevViewport[0] === 0 && - prevViewport[1] === 0 && - prevViewport[2] === canvas.width && - prevViewport[3] === canvas.height; - } - canvas.width = width; - canvas.height = height; - if (autoResizeViewport) { - canvas.GLctxObject.GLctx.viewport(0, 0, width, height); - } - } - else if (canvas.canvasSharedPtr) { - var targetThread = GROWABLE_HEAP_I32()[(canvas.canvasSharedPtr + 8) >> 2]; - _emscripten_set_offscreencanvas_size_on_target_thread(targetThread, target, width, height); - return 1; - } - else { - return -4; - } - return 0; - } - function _emscripten_set_canvas_element_size_main_thread(target, width, height) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(14, 1, target, width, height); - return _emscripten_set_canvas_element_size_calling_thread(target, width, height); - } - function _emscripten_set_canvas_element_size(target, width, height) { - var canvas = findCanvasEventTarget(target); - if (canvas) { - return _emscripten_set_canvas_element_size_calling_thread(target, width, height); - } - else { - return _emscripten_set_canvas_element_size_main_thread(target, width, height); - } - } - function _emscripten_set_current_thread_status(newStatus) { - newStatus = newStatus | 0; - } - function __webgl_enable_ANGLE_instanced_arrays(ctx) { - var ext = ctx.getExtension("ANGLE_instanced_arrays"); - if (ext) { - ctx["vertexAttribDivisor"] = function (index, divisor) { - ext["vertexAttribDivisorANGLE"](index, divisor); - }; - ctx["drawArraysInstanced"] = function (mode, first, count, primcount) { - ext["drawArraysInstancedANGLE"](mode, first, count, primcount); - }; - ctx["drawElementsInstanced"] = function (mode, count, type, indices, primcount) { - ext["drawElementsInstancedANGLE"](mode, count, type, indices, primcount); - }; - return 1; - } - } - function __webgl_enable_OES_vertex_array_object(ctx) { - var ext = ctx.getExtension("OES_vertex_array_object"); - if (ext) { - ctx["createVertexArray"] = function () { - return ext["createVertexArrayOES"](); - }; - ctx["deleteVertexArray"] = function (vao) { - ext["deleteVertexArrayOES"](vao); - }; - ctx["bindVertexArray"] = function (vao) { - ext["bindVertexArrayOES"](vao); - }; - ctx["isVertexArray"] = function (vao) { - return ext["isVertexArrayOES"](vao); - }; - return 1; - } - } - function __webgl_enable_WEBGL_draw_buffers(ctx) { - var ext = ctx.getExtension("WEBGL_draw_buffers"); - if (ext) { - ctx["drawBuffers"] = function (n, bufs) { - ext["drawBuffersWEBGL"](n, bufs); - }; - return 1; - } - } - function __webgl_enable_WEBGL_multi_draw(ctx) { - return !!(ctx.multiDrawWebgl = ctx.getExtension("WEBGL_multi_draw")); - } - var GL = { - counter: 1, - buffers: [], - programs: [], - framebuffers: [], - renderbuffers: [], - textures: [], - uniforms: [], - shaders: [], - vaos: [], - contexts: {}, - offscreenCanvases: {}, - timerQueriesEXT: [], - programInfos: {}, - stringCache: {}, - unpackAlignment: 4, - recordError: function recordError(errorCode) { - if (!GL.lastError) { - GL.lastError = errorCode; - } - }, - getNewId: function (table) { - var ret = GL.counter++; - for (var i = table.length; i < ret; i++) { - table[i] = null; - } - return ret; - }, - getSource: function (shader, count, string, length) { - var source = ""; - for (var i = 0; i < count; ++i) { - var len = length ? GROWABLE_HEAP_I32()[(length + i * 4) >> 2] : -1; - source += UTF8ToString(GROWABLE_HEAP_I32()[(string + i * 4) >> 2], len < 0 ? undefined : len); - } - return source; - }, - createContext: function (canvas, webGLContextAttributes) { - var ctx = canvas.getContext("webgl", webGLContextAttributes); - if (!ctx) - return 0; - var handle = GL.registerContext(ctx, webGLContextAttributes); - return handle; - }, - registerContext: function (ctx, webGLContextAttributes) { - var handle = _malloc(8); - GROWABLE_HEAP_I32()[(handle + 4) >> 2] = _pthread_self(); - var context = { - handle: handle, - attributes: webGLContextAttributes, - version: webGLContextAttributes.majorVersion, - GLctx: ctx, - }; - if (ctx.canvas) - ctx.canvas.GLctxObject = context; - GL.contexts[handle] = context; - if (typeof webGLContextAttributes.enableExtensionsByDefault === - "undefined" || - webGLContextAttributes.enableExtensionsByDefault) { - GL.initExtensions(context); - } - return handle; - }, - makeContextCurrent: function (contextHandle) { - GL.currentContext = GL.contexts[contextHandle]; - Module.ctx = GLctx = GL.currentContext && GL.currentContext.GLctx; - return !(contextHandle && !GLctx); - }, - getContext: function (contextHandle) { - return GL.contexts[contextHandle]; - }, - deleteContext: function (contextHandle) { - if (GL.currentContext === GL.contexts[contextHandle]) - GL.currentContext = null; - if (typeof JSEvents === "object") - JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas); - if (GL.contexts[contextHandle] && GL.contexts[contextHandle].GLctx.canvas) - GL.contexts[contextHandle].GLctx.canvas.GLctxObject = undefined; - _free(GL.contexts[contextHandle].handle); - GL.contexts[contextHandle] = null; - }, - initExtensions: function (context) { - if (!context) - context = GL.currentContext; - if (context.initExtensionsDone) - return; - context.initExtensionsDone = true; - var GLctx = context.GLctx; - __webgl_enable_ANGLE_instanced_arrays(GLctx); - __webgl_enable_OES_vertex_array_object(GLctx); - __webgl_enable_WEBGL_draw_buffers(GLctx); - GLctx.disjointTimerQueryExt = GLctx.getExtension("EXT_disjoint_timer_query"); - __webgl_enable_WEBGL_multi_draw(GLctx); - var automaticallyEnabledExtensions = [ - "OES_texture_float", - "OES_texture_half_float", - "OES_standard_derivatives", - "OES_vertex_array_object", - "WEBGL_compressed_texture_s3tc", - "WEBGL_depth_texture", - "OES_element_index_uint", - "EXT_texture_filter_anisotropic", - "EXT_frag_depth", - "WEBGL_draw_buffers", - "ANGLE_instanced_arrays", - "OES_texture_float_linear", - "OES_texture_half_float_linear", - "EXT_blend_minmax", - "EXT_shader_texture_lod", - "EXT_texture_norm16", - "WEBGL_compressed_texture_pvrtc", - "EXT_color_buffer_half_float", - "WEBGL_color_buffer_float", - "EXT_sRGB", - "WEBGL_compressed_texture_etc1", - "EXT_disjoint_timer_query", - "WEBGL_compressed_texture_etc", - "WEBGL_compressed_texture_astc", - "EXT_color_buffer_float", - "WEBGL_compressed_texture_s3tc_srgb", - "EXT_disjoint_timer_query_webgl2", - "WEBKIT_WEBGL_compressed_texture_pvrtc", - ]; - var exts = GLctx.getSupportedExtensions() || []; - exts.forEach(function (ext) { - if (automaticallyEnabledExtensions.indexOf(ext) != -1) { - GLctx.getExtension(ext); - } - }); - }, - populateUniformTable: function (program) { - var p = GL.programs[program]; - var ptable = (GL.programInfos[program] = { - uniforms: {}, - maxUniformLength: 0, - maxAttributeLength: -1, - maxUniformBlockNameLength: -1, - }); - var utable = ptable.uniforms; - var numUniforms = GLctx.getProgramParameter(p, 35718); - for (var i = 0; i < numUniforms; ++i) { - var u = GLctx.getActiveUniform(p, i); - var name = u.name; - ptable.maxUniformLength = Math.max(ptable.maxUniformLength, name.length + 1); - if (name.slice(-1) == "]") { - name = name.slice(0, name.lastIndexOf("[")); - } - var loc = GLctx.getUniformLocation(p, name); - if (loc) { - var id = GL.getNewId(GL.uniforms); - utable[name] = [u.size, id]; - GL.uniforms[id] = loc; - for (var j = 1; j < u.size; ++j) { - var n = name + "[" + j + "]"; - loc = GLctx.getUniformLocation(p, n); - id = GL.getNewId(GL.uniforms); - GL.uniforms[id] = loc; - } - } - } - }, - }; - var __emscripten_webgl_power_preferences = [ - "default", - "low-power", - "high-performance", - ]; - function _emscripten_webgl_do_create_context(target, attributes) { - var a = attributes >> 2; - var powerPreference = GROWABLE_HEAP_I32()[a + (24 >> 2)]; - var contextAttributes = { - alpha: !!GROWABLE_HEAP_I32()[a + (0 >> 2)], - depth: !!GROWABLE_HEAP_I32()[a + (4 >> 2)], - stencil: !!GROWABLE_HEAP_I32()[a + (8 >> 2)], - antialias: !!GROWABLE_HEAP_I32()[a + (12 >> 2)], - premultipliedAlpha: !!GROWABLE_HEAP_I32()[a + (16 >> 2)], - preserveDrawingBuffer: !!GROWABLE_HEAP_I32()[a + (20 >> 2)], - powerPreference: __emscripten_webgl_power_preferences[powerPreference], - failIfMajorPerformanceCaveat: !!GROWABLE_HEAP_I32()[a + (28 >> 2)], - majorVersion: GROWABLE_HEAP_I32()[a + (32 >> 2)], - minorVersion: GROWABLE_HEAP_I32()[a + (36 >> 2)], - enableExtensionsByDefault: GROWABLE_HEAP_I32()[a + (40 >> 2)], - explicitSwapControl: GROWABLE_HEAP_I32()[a + (44 >> 2)], - proxyContextToMainThread: GROWABLE_HEAP_I32()[a + (48 >> 2)], - renderViaOffscreenBackBuffer: GROWABLE_HEAP_I32()[a + (52 >> 2)], - }; - var canvas = findCanvasEventTarget(target); - if (!canvas) { - return 0; - } - if (contextAttributes.explicitSwapControl) { - return 0; - } - var contextHandle = GL.createContext(canvas, contextAttributes); - return contextHandle; - } - function _emscripten_webgl_create_context(a0, a1) { - return _emscripten_webgl_do_create_context(a0, a1); - } - var ENV = {}; - function getExecutableName() { - return thisProgram || "./this.program"; - } - function getEnvStrings() { - if (!getEnvStrings.strings) { - var lang = ((typeof navigator === "object" && - navigator.languages && - navigator.languages[0]) || - "C").replace("-", "_") + ".UTF-8"; - var env = { - USER: "web_user", - LOGNAME: "web_user", - PATH: "/", - PWD: "/", - HOME: "/home/web_user", - LANG: lang, - _: getExecutableName(), - }; - for (var x in ENV) { - env[x] = ENV[x]; - } - var strings = []; - for (var x in env) { - strings.push(x + "=" + env[x]); - } - getEnvStrings.strings = strings; - } - return getEnvStrings.strings; - } - function _environ_get(__environ, environ_buf) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(15, 1, __environ, environ_buf); - try { - var bufSize = 0; - getEnvStrings().forEach(function (string, i) { - var ptr = environ_buf + bufSize; - GROWABLE_HEAP_I32()[(__environ + i * 4) >> 2] = ptr; - writeAsciiToMemory(string, ptr); - bufSize += string.length + 1; - }); - return 0; - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return e.errno; - } - } - function _environ_sizes_get(penviron_count, penviron_buf_size) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(16, 1, penviron_count, penviron_buf_size); - try { - var strings = getEnvStrings(); - GROWABLE_HEAP_I32()[penviron_count >> 2] = strings.length; - var bufSize = 0; - strings.forEach(function (string) { - bufSize += string.length + 1; - }); - GROWABLE_HEAP_I32()[penviron_buf_size >> 2] = bufSize; - return 0; - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return e.errno; - } - } - function _exit(status) { - exit(status); - } - function _fd_close(fd) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(17, 1, fd); - try { - var stream = SYSCALLS.getStreamFromFD(fd); - FS.close(stream); - return 0; - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return e.errno; - } - } - function _fd_fdstat_get(fd, pbuf) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(18, 1, fd, pbuf); - try { - var stream = SYSCALLS.getStreamFromFD(fd); - var type = stream.tty - ? 2 - : FS.isDir(stream.mode) - ? 3 - : FS.isLink(stream.mode) - ? 7 - : 4; - GROWABLE_HEAP_I8()[pbuf >> 0] = type; - return 0; - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return e.errno; - } - } - function _fd_read(fd, iov, iovcnt, pnum) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(19, 1, fd, iov, iovcnt, pnum); - try { - var stream = SYSCALLS.getStreamFromFD(fd); - var num = SYSCALLS.doReadv(stream, iov, iovcnt); - GROWABLE_HEAP_I32()[pnum >> 2] = num; - return 0; - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return e.errno; - } - } - function _fd_seek(fd, offset_low, offset_high, whence, newOffset) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(20, 1, fd, offset_low, offset_high, whence, newOffset); - try { - var stream = SYSCALLS.getStreamFromFD(fd); - var HIGH_OFFSET = 4294967296; - var offset = offset_high * HIGH_OFFSET + (offset_low >>> 0); - var DOUBLE_LIMIT = 9007199254740992; - if (offset <= -DOUBLE_LIMIT || offset >= DOUBLE_LIMIT) { - return -61; - } - FS.llseek(stream, offset, whence); - (tempI64 = [ - stream.position >>> 0, - ((tempDouble = stream.position), - +Math.abs(tempDouble) >= 1 - ? tempDouble > 0 - ? (Math.min(+Math.floor(tempDouble / 4294967296), 4294967295) | - 0) >>> - 0 - : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 - : 0), - ]), - (GROWABLE_HEAP_I32()[newOffset >> 2] = tempI64[0]), - (GROWABLE_HEAP_I32()[(newOffset + 4) >> 2] = tempI64[1]); - if (stream.getdents && offset === 0 && whence === 0) - stream.getdents = null; - return 0; - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return e.errno; - } - } - function _fd_write(fd, iov, iovcnt, pnum) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(21, 1, fd, iov, iovcnt, pnum); - try { - var stream = SYSCALLS.getStreamFromFD(fd); - var num = SYSCALLS.doWritev(stream, iov, iovcnt); - GROWABLE_HEAP_I32()[pnum >> 2] = num; - return 0; - } - catch (e) { - if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError)) - abort(e); - return e.errno; - } - } - function _getentropy(buffer, size) { - if (!_getentropy.randomDevice) { - _getentropy.randomDevice = getRandomDevice(); - } - for (var i = 0; i < size; i++) { - GROWABLE_HEAP_I8()[(buffer + i) >> 0] = _getentropy.randomDevice(); - } - return 0; - } - function _tzset() { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(22, 1); - if (_tzset.called) - return; - _tzset.called = true; - var currentYear = new Date().getFullYear(); - var winter = new Date(currentYear, 0, 1); - var summer = new Date(currentYear, 6, 1); - var winterOffset = winter.getTimezoneOffset(); - var summerOffset = summer.getTimezoneOffset(); - var stdTimezoneOffset = Math.max(winterOffset, summerOffset); - GROWABLE_HEAP_I32()[__get_timezone() >> 2] = stdTimezoneOffset * 60; - GROWABLE_HEAP_I32()[__get_daylight() >> 2] = Number(winterOffset != summerOffset); - function extractZone(date) { - var match = date.toTimeString().match(/\(([A-Za-z ]+)\)$/); - return match ? match[1] : "GMT"; - } - var winterName = extractZone(winter); - var summerName = extractZone(summer); - var winterNamePtr = allocateUTF8(winterName); - var summerNamePtr = allocateUTF8(summerName); - if (summerOffset < winterOffset) { - GROWABLE_HEAP_I32()[__get_tzname() >> 2] = winterNamePtr; - GROWABLE_HEAP_I32()[(__get_tzname() + 4) >> 2] = summerNamePtr; - } - else { - GROWABLE_HEAP_I32()[__get_tzname() >> 2] = summerNamePtr; - GROWABLE_HEAP_I32()[(__get_tzname() + 4) >> 2] = winterNamePtr; - } - } - function _localtime_r(time, tmPtr) { - _tzset(); - var date = new Date(GROWABLE_HEAP_I32()[time >> 2] * 1e3); - GROWABLE_HEAP_I32()[tmPtr >> 2] = date.getSeconds(); - GROWABLE_HEAP_I32()[(tmPtr + 4) >> 2] = date.getMinutes(); - GROWABLE_HEAP_I32()[(tmPtr + 8) >> 2] = date.getHours(); - GROWABLE_HEAP_I32()[(tmPtr + 12) >> 2] = date.getDate(); - GROWABLE_HEAP_I32()[(tmPtr + 16) >> 2] = date.getMonth(); - GROWABLE_HEAP_I32()[(tmPtr + 20) >> 2] = date.getFullYear() - 1900; - GROWABLE_HEAP_I32()[(tmPtr + 24) >> 2] = date.getDay(); - var start = new Date(date.getFullYear(), 0, 1); - var yday = ((date.getTime() - start.getTime()) / (1e3 * 60 * 60 * 24)) | 0; - GROWABLE_HEAP_I32()[(tmPtr + 28) >> 2] = yday; - GROWABLE_HEAP_I32()[(tmPtr + 36) >> 2] = -(date.getTimezoneOffset() * 60); - var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset(); - var winterOffset = start.getTimezoneOffset(); - var dst = (summerOffset != winterOffset && - date.getTimezoneOffset() == Math.min(winterOffset, summerOffset)) | 0; - GROWABLE_HEAP_I32()[(tmPtr + 32) >> 2] = dst; - var zonePtr = GROWABLE_HEAP_I32()[(__get_tzname() + (dst ? 4 : 0)) >> 2]; - GROWABLE_HEAP_I32()[(tmPtr + 40) >> 2] = zonePtr; - return tmPtr; - } - function spawnThread(threadParams) { - if (ENVIRONMENT_IS_PTHREAD) - throw "Internal Error! spawnThread() can only ever be called from main application thread!"; - var worker = PThread.getNewWorker(); - if (worker.pthread !== undefined) - throw "Internal error!"; - if (!threadParams.pthread_ptr) - throw "Internal error, no pthread ptr!"; - PThread.runningWorkers.push(worker); - var tlsMemory = _malloc(128 * 4); - for (var i = 0; i < 128; ++i) { - GROWABLE_HEAP_I32()[(tlsMemory + i * 4) >> 2] = 0; - } - var stackHigh = threadParams.stackBase + threadParams.stackSize; - var pthread = (PThread.pthreads[threadParams.pthread_ptr] = { - worker: worker, - stackBase: threadParams.stackBase, - stackSize: threadParams.stackSize, - allocatedOwnStack: threadParams.allocatedOwnStack, - thread: threadParams.pthread_ptr, - threadInfoStruct: threadParams.pthread_ptr, - }); - var tis = pthread.threadInfoStruct >> 2; - Atomics.store(GROWABLE_HEAP_U32(), tis + (0 >> 2), 0); - Atomics.store(GROWABLE_HEAP_U32(), tis + (4 >> 2), 0); - Atomics.store(GROWABLE_HEAP_U32(), tis + (8 >> 2), 0); - Atomics.store(GROWABLE_HEAP_U32(), tis + (68 >> 2), threadParams.detached); - Atomics.store(GROWABLE_HEAP_U32(), tis + (104 >> 2), tlsMemory); - Atomics.store(GROWABLE_HEAP_U32(), tis + (48 >> 2), 0); - Atomics.store(GROWABLE_HEAP_U32(), tis + (40 >> 2), pthread.threadInfoStruct); - Atomics.store(GROWABLE_HEAP_U32(), tis + (44 >> 2), 42); - Atomics.store(GROWABLE_HEAP_U32(), tis + (108 >> 2), threadParams.stackSize); - Atomics.store(GROWABLE_HEAP_U32(), tis + (84 >> 2), threadParams.stackSize); - Atomics.store(GROWABLE_HEAP_U32(), tis + (80 >> 2), stackHigh); - Atomics.store(GROWABLE_HEAP_U32(), tis + ((108 + 8) >> 2), stackHigh); - Atomics.store(GROWABLE_HEAP_U32(), tis + ((108 + 12) >> 2), threadParams.detached); - Atomics.store(GROWABLE_HEAP_U32(), tis + ((108 + 20) >> 2), threadParams.schedPolicy); - Atomics.store(GROWABLE_HEAP_U32(), tis + ((108 + 24) >> 2), threadParams.schedPrio); - var global_libc = _emscripten_get_global_libc(); - var global_locale = global_libc + 40; - Atomics.store(GROWABLE_HEAP_U32(), tis + (176 >> 2), global_locale); - worker.pthread = pthread; - var msg = { - cmd: "run", - start_routine: threadParams.startRoutine, - arg: threadParams.arg, - threadInfoStruct: threadParams.pthread_ptr, - selfThreadId: threadParams.pthread_ptr, - parentThreadId: threadParams.parent_pthread_ptr, - stackBase: threadParams.stackBase, - stackSize: threadParams.stackSize, - }; - worker.runPthread = function () { - msg.time = performance.now(); - worker.postMessage(msg, threadParams.transferList); - }; - if (worker.loaded) { - worker.runPthread(); - delete worker.runPthread; - } - } - function _pthread_getschedparam(thread, policy, schedparam) { - if (!policy && !schedparam) - return ERRNO_CODES.EINVAL; - if (!thread) { - err("pthread_getschedparam called with a null thread pointer!"); - return ERRNO_CODES.ESRCH; - } - var self = GROWABLE_HEAP_I32()[(thread + 12) >> 2]; - if (self !== thread) { - err("pthread_getschedparam attempted on thread " + - thread + - ", which does not point to a valid thread, or does not exist anymore!"); - return ERRNO_CODES.ESRCH; - } - var schedPolicy = Atomics.load(GROWABLE_HEAP_U32(), (thread + 108 + 20) >> 2); - var schedPrio = Atomics.load(GROWABLE_HEAP_U32(), (thread + 108 + 24) >> 2); - if (policy) - GROWABLE_HEAP_I32()[policy >> 2] = schedPolicy; - if (schedparam) - GROWABLE_HEAP_I32()[schedparam >> 2] = schedPrio; - return 0; - } - function _pthread_self() { - return __pthread_ptr | 0; - } - Module["_pthread_self"] = _pthread_self; - function _pthread_create(pthread_ptr, attr, start_routine, arg) { - if (typeof SharedArrayBuffer === "undefined") { - err("Current environment does not support SharedArrayBuffer, pthreads are not available!"); - return 6; - } - if (!pthread_ptr) { - err("pthread_create called with a null thread pointer!"); - return 28; - } - var transferList = []; - var error = 0; - if (ENVIRONMENT_IS_PTHREAD && (transferList.length === 0 || error)) { - return _emscripten_sync_run_in_main_thread_4(687865856, pthread_ptr, attr, start_routine, arg); - } - if (error) - return error; - var stackSize = 0; - var stackBase = 0; - var detached = 0; - var schedPolicy = 0; - var schedPrio = 0; - if (attr) { - stackSize = GROWABLE_HEAP_I32()[attr >> 2]; - stackSize += 81920; - stackBase = GROWABLE_HEAP_I32()[(attr + 8) >> 2]; - detached = GROWABLE_HEAP_I32()[(attr + 12) >> 2] !== 0; - var inheritSched = GROWABLE_HEAP_I32()[(attr + 16) >> 2] === 0; - if (inheritSched) { - var prevSchedPolicy = GROWABLE_HEAP_I32()[(attr + 20) >> 2]; - var prevSchedPrio = GROWABLE_HEAP_I32()[(attr + 24) >> 2]; - var parentThreadPtr = PThread.currentProxiedOperationCallerThread - ? PThread.currentProxiedOperationCallerThread - : _pthread_self(); - _pthread_getschedparam(parentThreadPtr, attr + 20, attr + 24); - schedPolicy = GROWABLE_HEAP_I32()[(attr + 20) >> 2]; - schedPrio = GROWABLE_HEAP_I32()[(attr + 24) >> 2]; - GROWABLE_HEAP_I32()[(attr + 20) >> 2] = prevSchedPolicy; - GROWABLE_HEAP_I32()[(attr + 24) >> 2] = prevSchedPrio; - } - else { - schedPolicy = GROWABLE_HEAP_I32()[(attr + 20) >> 2]; - schedPrio = GROWABLE_HEAP_I32()[(attr + 24) >> 2]; - } - } - else { - stackSize = 2097152; - } - var allocatedOwnStack = stackBase == 0; - if (allocatedOwnStack) { - stackBase = _memalign(16, stackSize); - } - else { - stackBase -= stackSize; - assert(stackBase > 0); - } - var threadInfoStruct = _malloc(232); - for (var i = 0; i < 232 >> 2; ++i) - GROWABLE_HEAP_U32()[(threadInfoStruct >> 2) + i] = 0; - GROWABLE_HEAP_I32()[pthread_ptr >> 2] = threadInfoStruct; - GROWABLE_HEAP_I32()[(threadInfoStruct + 12) >> 2] = threadInfoStruct; - var headPtr = threadInfoStruct + 156; - GROWABLE_HEAP_I32()[headPtr >> 2] = headPtr; - var threadParams = { - stackBase: stackBase, - stackSize: stackSize, - allocatedOwnStack: allocatedOwnStack, - schedPolicy: schedPolicy, - schedPrio: schedPrio, - detached: detached, - startRoutine: start_routine, - pthread_ptr: threadInfoStruct, - parent_pthread_ptr: _pthread_self(), - arg: arg, - transferList: transferList, - }; - if (ENVIRONMENT_IS_PTHREAD) { - threadParams.cmd = "spawnThread"; - postMessage(threadParams, transferList); - } - else { - spawnThread(threadParams); - } - return 0; - } - function __pthread_testcancel_js() { - if (!ENVIRONMENT_IS_PTHREAD) - return; - if (!threadInfoStruct) - return; - var cancelDisabled = Atomics.load(GROWABLE_HEAP_U32(), (threadInfoStruct + 60) >> 2); - if (cancelDisabled) - return; - var canceled = Atomics.load(GROWABLE_HEAP_U32(), (threadInfoStruct + 0) >> 2); - if (canceled == 2) - throw "Canceled!"; - } - function __emscripten_do_pthread_join(thread, status, block) { - if (!thread) { - err("pthread_join attempted on a null thread pointer!"); - return ERRNO_CODES.ESRCH; - } - if (ENVIRONMENT_IS_PTHREAD && selfThreadId == thread) { - err("PThread " + thread + " is attempting to join to itself!"); - return ERRNO_CODES.EDEADLK; - } - else if (!ENVIRONMENT_IS_PTHREAD && PThread.mainThreadBlock == thread) { - err("Main thread " + thread + " is attempting to join to itself!"); - return ERRNO_CODES.EDEADLK; - } - var self = GROWABLE_HEAP_I32()[(thread + 12) >> 2]; - if (self !== thread) { - err("pthread_join attempted on thread " + - thread + - ", which does not point to a valid thread, or does not exist anymore!"); - return ERRNO_CODES.ESRCH; - } - var detached = Atomics.load(GROWABLE_HEAP_U32(), (thread + 68) >> 2); - if (detached) { - err("Attempted to join thread " + thread + ", which was already detached!"); - return ERRNO_CODES.EINVAL; - } - if (block) { - _emscripten_check_blocking_allowed(); - } - for (;;) { - var threadStatus = Atomics.load(GROWABLE_HEAP_U32(), (thread + 0) >> 2); - if (threadStatus == 1) { - var threadExitCode = Atomics.load(GROWABLE_HEAP_U32(), (thread + 4) >> 2); - if (status) - GROWABLE_HEAP_I32()[status >> 2] = threadExitCode; - Atomics.store(GROWABLE_HEAP_U32(), (thread + 68) >> 2, 1); - if (!ENVIRONMENT_IS_PTHREAD) - cleanupThread(thread); - else - postMessage({ - cmd: "cleanupThread", - thread: thread, - }); - return 0; - } - if (!block) { - return ERRNO_CODES.EBUSY; - } - __pthread_testcancel_js(); - if (!ENVIRONMENT_IS_PTHREAD) - _emscripten_main_thread_process_queued_calls(); - _emscripten_futex_wait(thread + 0, threadStatus, ENVIRONMENT_IS_PTHREAD ? 100 : 1); - } - } - function _pthread_join(thread, status) { - return __emscripten_do_pthread_join(thread, status, true); - } - function _setTempRet0($i) { - setTempRet0($i | 0); - } - function __isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); - } - function __arraySum(array, index) { - var sum = 0; - for (var i = 0; i <= index; sum += array[i++]) { } - return sum; - } - var __MONTH_DAYS_LEAP = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - var __MONTH_DAYS_REGULAR = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - function __addDays(date, days) { - var newDate = new Date(date.getTime()); - while (days > 0) { - var leap = __isLeapYear(newDate.getFullYear()); - var currentMonth = newDate.getMonth(); - var daysInCurrentMonth = (leap - ? __MONTH_DAYS_LEAP - : __MONTH_DAYS_REGULAR)[currentMonth]; - if (days > daysInCurrentMonth - newDate.getDate()) { - days -= daysInCurrentMonth - newDate.getDate() + 1; - newDate.setDate(1); - if (currentMonth < 11) { - newDate.setMonth(currentMonth + 1); - } - else { - newDate.setMonth(0); - newDate.setFullYear(newDate.getFullYear() + 1); - } - } - else { - newDate.setDate(newDate.getDate() + days); - return newDate; - } - } - return newDate; - } - function _strftime(s, maxsize, format, tm) { - var tm_zone = GROWABLE_HEAP_I32()[(tm + 40) >> 2]; - var date = { - tm_sec: GROWABLE_HEAP_I32()[tm >> 2], - tm_min: GROWABLE_HEAP_I32()[(tm + 4) >> 2], - tm_hour: GROWABLE_HEAP_I32()[(tm + 8) >> 2], - tm_mday: GROWABLE_HEAP_I32()[(tm + 12) >> 2], - tm_mon: GROWABLE_HEAP_I32()[(tm + 16) >> 2], - tm_year: GROWABLE_HEAP_I32()[(tm + 20) >> 2], - tm_wday: GROWABLE_HEAP_I32()[(tm + 24) >> 2], - tm_yday: GROWABLE_HEAP_I32()[(tm + 28) >> 2], - tm_isdst: GROWABLE_HEAP_I32()[(tm + 32) >> 2], - tm_gmtoff: GROWABLE_HEAP_I32()[(tm + 36) >> 2], - tm_zone: tm_zone ? UTF8ToString(tm_zone) : "", - }; - var pattern = UTF8ToString(format); - var EXPANSION_RULES_1 = { - "%c": "%a %b %d %H:%M:%S %Y", - "%D": "%m/%d/%y", - "%F": "%Y-%m-%d", - "%h": "%b", - "%r": "%I:%M:%S %p", - "%R": "%H:%M", - "%T": "%H:%M:%S", - "%x": "%m/%d/%y", - "%X": "%H:%M:%S", - "%Ec": "%c", - "%EC": "%C", - "%Ex": "%m/%d/%y", - "%EX": "%H:%M:%S", - "%Ey": "%y", - "%EY": "%Y", - "%Od": "%d", - "%Oe": "%e", - "%OH": "%H", - "%OI": "%I", - "%Om": "%m", - "%OM": "%M", - "%OS": "%S", - "%Ou": "%u", - "%OU": "%U", - "%OV": "%V", - "%Ow": "%w", - "%OW": "%W", - "%Oy": "%y", - }; - for (var rule in EXPANSION_RULES_1) { - pattern = pattern.replace(new RegExp(rule, "g"), EXPANSION_RULES_1[rule]); - } - var WEEKDAYS = [ - "Sunday", - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday", - ]; - var MONTHS = [ - "January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December", - ]; - function leadingSomething(value, digits, character) { - var str = typeof value === "number" ? value.toString() : value || ""; - while (str.length < digits) { - str = character[0] + str; - } - return str; - } - function leadingNulls(value, digits) { - return leadingSomething(value, digits, "0"); - } - function compareByDay(date1, date2) { - function sgn(value) { - return value < 0 ? -1 : value > 0 ? 1 : 0; - } - var compare; - if ((compare = sgn(date1.getFullYear() - date2.getFullYear())) === 0) { - if ((compare = sgn(date1.getMonth() - date2.getMonth())) === 0) { - compare = sgn(date1.getDate() - date2.getDate()); - } - } - return compare; - } - function getFirstWeekStartDate(janFourth) { - switch (janFourth.getDay()) { - case 0: - return new Date(janFourth.getFullYear() - 1, 11, 29); - case 1: - return janFourth; - case 2: - return new Date(janFourth.getFullYear(), 0, 3); - case 3: - return new Date(janFourth.getFullYear(), 0, 2); - case 4: - return new Date(janFourth.getFullYear(), 0, 1); - case 5: - return new Date(janFourth.getFullYear() - 1, 11, 31); - case 6: - return new Date(janFourth.getFullYear() - 1, 11, 30); - } - } - function getWeekBasedYear(date) { - var thisDate = __addDays(new Date(date.tm_year + 1900, 0, 1), date.tm_yday); - var janFourthThisYear = new Date(thisDate.getFullYear(), 0, 4); - var janFourthNextYear = new Date(thisDate.getFullYear() + 1, 0, 4); - var firstWeekStartThisYear = getFirstWeekStartDate(janFourthThisYear); - var firstWeekStartNextYear = getFirstWeekStartDate(janFourthNextYear); - if (compareByDay(firstWeekStartThisYear, thisDate) <= 0) { - if (compareByDay(firstWeekStartNextYear, thisDate) <= 0) { - return thisDate.getFullYear() + 1; - } - else { - return thisDate.getFullYear(); - } - } - else { - return thisDate.getFullYear() - 1; - } - } - var EXPANSION_RULES_2 = { - "%a": function (date) { - return WEEKDAYS[date.tm_wday].substring(0, 3); - }, - "%A": function (date) { - return WEEKDAYS[date.tm_wday]; - }, - "%b": function (date) { - return MONTHS[date.tm_mon].substring(0, 3); - }, - "%B": function (date) { - return MONTHS[date.tm_mon]; - }, - "%C": function (date) { - var year = date.tm_year + 1900; - return leadingNulls((year / 100) | 0, 2); - }, - "%d": function (date) { - return leadingNulls(date.tm_mday, 2); - }, - "%e": function (date) { - return leadingSomething(date.tm_mday, 2, " "); - }, - "%g": function (date) { - return getWeekBasedYear(date) - .toString() - .substring(2); - }, - "%G": function (date) { - return getWeekBasedYear(date); - }, - "%H": function (date) { - return leadingNulls(date.tm_hour, 2); - }, - "%I": function (date) { - var twelveHour = date.tm_hour; - if (twelveHour == 0) - twelveHour = 12; - else if (twelveHour > 12) - twelveHour -= 12; - return leadingNulls(twelveHour, 2); - }, - "%j": function (date) { - return leadingNulls(date.tm_mday + - __arraySum(__isLeapYear(date.tm_year + 1900) - ? __MONTH_DAYS_LEAP - : __MONTH_DAYS_REGULAR, date.tm_mon - 1), 3); - }, - "%m": function (date) { - return leadingNulls(date.tm_mon + 1, 2); - }, - "%M": function (date) { - return leadingNulls(date.tm_min, 2); - }, - "%n": function () { - return "\n"; - }, - "%p": function (date) { - if (date.tm_hour >= 0 && date.tm_hour < 12) { - return "AM"; - } - else { - return "PM"; - } - }, - "%S": function (date) { - return leadingNulls(date.tm_sec, 2); - }, - "%t": function () { - return "\t"; - }, - "%u": function (date) { - return date.tm_wday || 7; - }, - "%U": function (date) { - var janFirst = new Date(date.tm_year + 1900, 0, 1); - var firstSunday = janFirst.getDay() === 0 - ? janFirst - : __addDays(janFirst, 7 - janFirst.getDay()); - var endDate = new Date(date.tm_year + 1900, date.tm_mon, date.tm_mday); - if (compareByDay(firstSunday, endDate) < 0) { - var februaryFirstUntilEndMonth = __arraySum(__isLeapYear(endDate.getFullYear()) - ? __MONTH_DAYS_LEAP - : __MONTH_DAYS_REGULAR, endDate.getMonth() - 1) - 31; - var firstSundayUntilEndJanuary = 31 - firstSunday.getDate(); - var days = firstSundayUntilEndJanuary + - februaryFirstUntilEndMonth + - endDate.getDate(); - return leadingNulls(Math.ceil(days / 7), 2); - } - return compareByDay(firstSunday, janFirst) === 0 ? "01" : "00"; - }, - "%V": function (date) { - var janFourthThisYear = new Date(date.tm_year + 1900, 0, 4); - var janFourthNextYear = new Date(date.tm_year + 1901, 0, 4); - var firstWeekStartThisYear = getFirstWeekStartDate(janFourthThisYear); - var firstWeekStartNextYear = getFirstWeekStartDate(janFourthNextYear); - var endDate = __addDays(new Date(date.tm_year + 1900, 0, 1), date.tm_yday); - if (compareByDay(endDate, firstWeekStartThisYear) < 0) { - return "53"; - } - if (compareByDay(firstWeekStartNextYear, endDate) <= 0) { - return "01"; - } - var daysDifference; - if (firstWeekStartThisYear.getFullYear() < date.tm_year + 1900) { - daysDifference = date.tm_yday + 32 - firstWeekStartThisYear.getDate(); - } - else { - daysDifference = date.tm_yday + 1 - firstWeekStartThisYear.getDate(); - } - return leadingNulls(Math.ceil(daysDifference / 7), 2); - }, - "%w": function (date) { - return date.tm_wday; - }, - "%W": function (date) { - var janFirst = new Date(date.tm_year, 0, 1); - var firstMonday = janFirst.getDay() === 1 - ? janFirst - : __addDays(janFirst, janFirst.getDay() === 0 ? 1 : 7 - janFirst.getDay() + 1); - var endDate = new Date(date.tm_year + 1900, date.tm_mon, date.tm_mday); - if (compareByDay(firstMonday, endDate) < 0) { - var februaryFirstUntilEndMonth = __arraySum(__isLeapYear(endDate.getFullYear()) - ? __MONTH_DAYS_LEAP - : __MONTH_DAYS_REGULAR, endDate.getMonth() - 1) - 31; - var firstMondayUntilEndJanuary = 31 - firstMonday.getDate(); - var days = firstMondayUntilEndJanuary + - februaryFirstUntilEndMonth + - endDate.getDate(); - return leadingNulls(Math.ceil(days / 7), 2); - } - return compareByDay(firstMonday, janFirst) === 0 ? "01" : "00"; - }, - "%y": function (date) { - return (date.tm_year + 1900).toString().substring(2); - }, - "%Y": function (date) { - return date.tm_year + 1900; - }, - "%z": function (date) { - var off = date.tm_gmtoff; - var ahead = off >= 0; - off = Math.abs(off) / 60; - off = (off / 60) * 100 + (off % 60); - return (ahead ? "+" : "-") + String("0000" + off).slice(-4); - }, - "%Z": function (date) { - return date.tm_zone; - }, - "%%": function () { - return "%"; - }, - }; - for (var rule in EXPANSION_RULES_2) { - if (pattern.indexOf(rule) >= 0) { - pattern = pattern.replace(new RegExp(rule, "g"), EXPANSION_RULES_2[rule](date)); - } - } - var bytes = intArrayFromString(pattern, false); - if (bytes.length > maxsize) { - return 0; - } - writeArrayToMemory(bytes, s); - return bytes.length - 1; - } - function _strftime_l(s, maxsize, format, tm) { - return _strftime(s, maxsize, format, tm); - } - function _sysconf(name) { - if (ENVIRONMENT_IS_PTHREAD) - return _emscripten_proxy_to_main_thread_js(23, 1, name); - switch (name) { - case 30: - return 16384; - case 85: - var maxHeapSize = 2147483648; - return maxHeapSize / 16384; - case 132: - case 133: - case 12: - case 137: - case 138: - case 15: - case 235: - case 16: - case 17: - case 18: - case 19: - case 20: - case 149: - case 13: - case 10: - case 236: - case 153: - case 9: - case 21: - case 22: - case 159: - case 154: - case 14: - case 77: - case 78: - case 139: - case 80: - case 81: - case 82: - case 68: - case 67: - case 164: - case 11: - case 29: - case 47: - case 48: - case 95: - case 52: - case 51: - case 46: - case 79: - return 200809; - case 27: - case 246: - case 127: - case 128: - case 23: - case 24: - case 160: - case 161: - case 181: - case 182: - case 242: - case 183: - case 184: - case 243: - case 244: - case 245: - case 165: - case 178: - case 179: - case 49: - case 50: - case 168: - case 169: - case 175: - case 170: - case 171: - case 172: - case 97: - case 76: - case 32: - case 173: - case 35: - return -1; - case 176: - case 177: - case 7: - case 155: - case 8: - case 157: - case 125: - case 126: - case 92: - case 93: - case 129: - case 130: - case 131: - case 94: - case 91: - return 1; - case 74: - case 60: - case 69: - case 70: - case 4: - return 1024; - case 31: - case 42: - case 72: - return 32; - case 87: - case 26: - case 33: - return 2147483647; - case 34: - case 1: - return 47839; - case 38: - case 36: - return 99; - case 43: - case 37: - return 2048; - case 0: - return 2097152; - case 3: - return 65536; - case 28: - return 32768; - case 44: - return 32767; - case 75: - return 16384; - case 39: - return 1e3; - case 89: - return 700; - case 71: - return 256; - case 40: - return 255; - case 2: - return 100; - case 180: - return 64; - case 25: - return 20; - case 5: - return 16; - case 6: - return 6; - case 73: - return 4; - case 84: { - if (typeof navigator === "object") - return navigator["hardwareConcurrency"] || 1; - return 1; - } - } - setErrNo(28); - return -1; - } - function _time(ptr) { - var ret = (Date.now() / 1e3) | 0; - if (ptr) { - GROWABLE_HEAP_I32()[ptr >> 2] = ret; - } - return ret; - } - if (!ENVIRONMENT_IS_PTHREAD) - PThread.initMainThreadBlock(); - var FSNode = function (parent, name, mode, rdev) { - if (!parent) { - parent = this; - } - this.parent = parent; - this.mount = parent.mount; - this.mounted = null; - this.id = FS.nextInode++; - this.name = name; - this.mode = mode; - this.node_ops = {}; - this.stream_ops = {}; - this.rdev = rdev; - }; - var readMode = 292 | 73; - var writeMode = 146; - Object.defineProperties(FSNode.prototype, { - read: { - get: function () { - return (this.mode & readMode) === readMode; - }, - set: function (val) { - val ? (this.mode |= readMode) : (this.mode &= ~readMode); - }, - }, - write: { - get: function () { - return (this.mode & writeMode) === writeMode; - }, - set: function (val) { - val ? (this.mode |= writeMode) : (this.mode &= ~writeMode); - }, - }, - isFolder: { - get: function () { - return FS.isDir(this.mode); - }, - }, - isDevice: { - get: function () { - return FS.isChrdev(this.mode); - }, - }, - }); - FS.FSNode = FSNode; - FS.staticInit(); - embind_init_charCodes(); - BindingError = Module["BindingError"] = extendError(Error, "BindingError"); - InternalError = Module["InternalError"] = extendError(Error, "InternalError"); - init_ClassHandle(); - init_RegisteredPointer(); - init_embind(); - UnboundTypeError = Module["UnboundTypeError"] = extendError(Error, "UnboundTypeError"); - init_emval(); - var GLctx; - var proxiedFunctionTable = [ - null, - _atexit, - ___sys_access, - ___sys_fcntl64, - ___sys_fstat64, - ___sys_getcwd, - ___sys_ioctl, - ___sys_mmap2, - ___sys_munmap, - ___sys_open, - ___sys_rename, - ___sys_rmdir, - ___sys_stat64, - ___sys_unlink, - _emscripten_set_canvas_element_size_main_thread, - _environ_get, - _environ_sizes_get, - _fd_close, - _fd_fdstat_get, - _fd_read, - _fd_seek, - _fd_write, - _tzset, - _sysconf, - ]; - var ASSERTIONS = false; - function intArrayFromString(stringy, dontAddNull, length) { - var len = length > 0 ? length : lengthBytesUTF8(stringy) + 1; - var u8array = new Array(len); - var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length); - if (dontAddNull) - u8array.length = numBytesWritten; - return u8array; - } - if (!ENVIRONMENT_IS_PTHREAD) - __ATINIT__.push({ - func: function () { - ___wasm_call_ctors(); - }, - }); - var asmLibraryArg = { - __assert_fail: ___assert_fail, - __clock_gettime: ___clock_gettime, - __cxa_allocate_exception: ___cxa_allocate_exception, - __cxa_atexit: ___cxa_atexit, - __cxa_thread_atexit: ___cxa_thread_atexit, - __cxa_throw: ___cxa_throw, - __sys_access: ___sys_access, - __sys_fcntl64: ___sys_fcntl64, - __sys_fstat64: ___sys_fstat64, - __sys_getcwd: ___sys_getcwd, - __sys_ioctl: ___sys_ioctl, - __sys_mmap2: ___sys_mmap2, - __sys_munmap: ___sys_munmap, - __sys_open: ___sys_open, - __sys_rename: ___sys_rename, - __sys_rmdir: ___sys_rmdir, - __sys_stat64: ___sys_stat64, - __sys_unlink: ___sys_unlink, - __sys_wait4: ___sys_wait4, - _embind_register_bool: __embind_register_bool, - _embind_register_class: __embind_register_class, - _embind_register_class_constructor: __embind_register_class_constructor, - _embind_register_class_function: __embind_register_class_function, - _embind_register_emval: __embind_register_emval, - _embind_register_float: __embind_register_float, - _embind_register_integer: __embind_register_integer, - _embind_register_memory_view: __embind_register_memory_view, - _embind_register_std_string: __embind_register_std_string, - _embind_register_std_wstring: __embind_register_std_wstring, - _embind_register_void: __embind_register_void, - _emscripten_notify_thread_queue: __emscripten_notify_thread_queue, - _emval_decref: __emval_decref, - _emval_incref: __emval_incref, - _emval_take_value: __emval_take_value, - abort: _abort, - clock_gettime: _clock_gettime, - emscripten_asm_const_int: _emscripten_asm_const_int, - emscripten_check_blocking_allowed: _emscripten_check_blocking_allowed, - emscripten_conditional_set_current_thread_status: _emscripten_conditional_set_current_thread_status, - emscripten_futex_wait: _emscripten_futex_wait, - emscripten_futex_wake: _emscripten_futex_wake, - emscripten_get_now: _emscripten_get_now, - emscripten_is_main_browser_thread: _emscripten_is_main_browser_thread, - emscripten_is_main_runtime_thread: _emscripten_is_main_runtime_thread, - emscripten_memcpy_big: _emscripten_memcpy_big, - emscripten_receive_on_main_thread_js: _emscripten_receive_on_main_thread_js, - emscripten_resize_heap: _emscripten_resize_heap, - emscripten_set_canvas_element_size: _emscripten_set_canvas_element_size, - emscripten_set_current_thread_status: _emscripten_set_current_thread_status, - emscripten_webgl_create_context: _emscripten_webgl_create_context, - environ_get: _environ_get, - environ_sizes_get: _environ_sizes_get, - exit: _exit, - fd_close: _fd_close, - fd_fdstat_get: _fd_fdstat_get, - fd_read: _fd_read, - fd_seek: _fd_seek, - fd_write: _fd_write, - getentropy: _getentropy, - initPthreadsJS: initPthreadsJS, - localtime_r: _localtime_r, - memory: wasmMemory, - pthread_cleanup_push: _pthread_cleanup_push, - pthread_create: _pthread_create, - pthread_join: _pthread_join, - pthread_self: _pthread_self, - setTempRet0: _setTempRet0, - strftime_l: _strftime_l, - sysconf: _sysconf, - time: _time, - }; - var asm = createWasm(); - var ___wasm_call_ctors = (Module["___wasm_call_ctors"] = function () { - return (___wasm_call_ctors = Module["___wasm_call_ctors"] = - Module["asm"]["__wasm_call_ctors"]).apply(null, arguments); - }); - var _free = (Module["_free"] = function () { - return (_free = Module["_free"] = Module["asm"]["free"]).apply(null, arguments); - }); - var _malloc = (Module["_malloc"] = function () { - return (_malloc = Module["_malloc"] = Module["asm"]["malloc"]).apply(null, arguments); - }); - var ___errno_location = (Module["___errno_location"] = function () { - return (___errno_location = Module["___errno_location"] = - Module["asm"]["__errno_location"]).apply(null, arguments); - }); - var _memset = (Module["_memset"] = function () { - return (_memset = Module["_memset"] = Module["asm"]["memset"]).apply(null, arguments); - }); - var ___getTypeName = (Module["___getTypeName"] = function () { - return (___getTypeName = Module["___getTypeName"] = - Module["asm"]["__getTypeName"]).apply(null, arguments); - }); - var ___embind_register_native_and_builtin_types = (Module["___embind_register_native_and_builtin_types"] = function () { - return (___embind_register_native_and_builtin_types = Module["___embind_register_native_and_builtin_types"] = Module["asm"]["__embind_register_native_and_builtin_types"]).apply(null, arguments); - }); - var ___emscripten_pthread_data_constructor = (Module["___emscripten_pthread_data_constructor"] = function () { - return (___emscripten_pthread_data_constructor = Module["___emscripten_pthread_data_constructor"] = Module["asm"]["__emscripten_pthread_data_constructor"]).apply(null, arguments); - }); - var _emscripten_get_global_libc = (Module["_emscripten_get_global_libc"] = function () { - return (_emscripten_get_global_libc = Module["_emscripten_get_global_libc"] = Module["asm"]["emscripten_get_global_libc"]).apply(null, arguments); - }); - var __get_tzname = (Module["__get_tzname"] = function () { - return (__get_tzname = Module["__get_tzname"] = - Module["asm"]["_get_tzname"]).apply(null, arguments); - }); - var __get_daylight = (Module["__get_daylight"] = function () { - return (__get_daylight = Module["__get_daylight"] = - Module["asm"]["_get_daylight"]).apply(null, arguments); - }); - var __get_timezone = (Module["__get_timezone"] = function () { - return (__get_timezone = Module["__get_timezone"] = - Module["asm"]["_get_timezone"]).apply(null, arguments); - }); - var stackSave = (Module["stackSave"] = function () { - return (stackSave = Module["stackSave"] = Module["asm"]["stackSave"]).apply(null, arguments); - }); - var stackRestore = (Module["stackRestore"] = function () { - return (stackRestore = Module["stackRestore"] = - Module["asm"]["stackRestore"]).apply(null, arguments); - }); - var stackAlloc = (Module["stackAlloc"] = function () { - return (stackAlloc = Module["stackAlloc"] = - Module["asm"]["stackAlloc"]).apply(null, arguments); - }); - var _emscripten_stack_set_limits = (Module["_emscripten_stack_set_limits"] = function () { - return (_emscripten_stack_set_limits = Module["_emscripten_stack_set_limits"] = Module["asm"]["emscripten_stack_set_limits"]).apply(null, arguments); - }); - var _setThrew = (Module["_setThrew"] = function () { - return (_setThrew = Module["_setThrew"] = Module["asm"]["setThrew"]).apply(null, arguments); - }); - var _memalign = (Module["_memalign"] = function () { - return (_memalign = Module["_memalign"] = Module["asm"]["memalign"]).apply(null, arguments); - }); - var _emscripten_main_browser_thread_id = (Module["_emscripten_main_browser_thread_id"] = function () { - return (_emscripten_main_browser_thread_id = Module["_emscripten_main_browser_thread_id"] = Module["asm"]["emscripten_main_browser_thread_id"]).apply(null, arguments); - }); - var ___pthread_tsd_run_dtors = (Module["___pthread_tsd_run_dtors"] = function () { - return (___pthread_tsd_run_dtors = Module["___pthread_tsd_run_dtors"] = - Module["asm"]["__pthread_tsd_run_dtors"]).apply(null, arguments); - }); - var _emscripten_main_thread_process_queued_calls = (Module["_emscripten_main_thread_process_queued_calls"] = function () { - return (_emscripten_main_thread_process_queued_calls = Module["_emscripten_main_thread_process_queued_calls"] = Module["asm"]["emscripten_main_thread_process_queued_calls"]).apply(null, arguments); - }); - var _emscripten_current_thread_process_queued_calls = (Module["_emscripten_current_thread_process_queued_calls"] = function () { - return (_emscripten_current_thread_process_queued_calls = Module["_emscripten_current_thread_process_queued_calls"] = Module["asm"]["emscripten_current_thread_process_queued_calls"]).apply(null, arguments); - }); - var _emscripten_register_main_browser_thread_id = (Module["_emscripten_register_main_browser_thread_id"] = function () { - return (_emscripten_register_main_browser_thread_id = Module["_emscripten_register_main_browser_thread_id"] = Module["asm"]["emscripten_register_main_browser_thread_id"]).apply(null, arguments); - }); - var _do_emscripten_dispatch_to_thread = (Module["_do_emscripten_dispatch_to_thread"] = function () { - return (_do_emscripten_dispatch_to_thread = Module["_do_emscripten_dispatch_to_thread"] = Module["asm"]["do_emscripten_dispatch_to_thread"]).apply(null, arguments); - }); - var _emscripten_async_run_in_main_thread = (Module["_emscripten_async_run_in_main_thread"] = function () { - return (_emscripten_async_run_in_main_thread = Module["_emscripten_async_run_in_main_thread"] = Module["asm"]["emscripten_async_run_in_main_thread"]).apply(null, arguments); - }); - var _emscripten_sync_run_in_main_thread = (Module["_emscripten_sync_run_in_main_thread"] = function () { - return (_emscripten_sync_run_in_main_thread = Module["_emscripten_sync_run_in_main_thread"] = Module["asm"]["emscripten_sync_run_in_main_thread"]).apply(null, arguments); - }); - var _emscripten_sync_run_in_main_thread_0 = (Module["_emscripten_sync_run_in_main_thread_0"] = function () { - return (_emscripten_sync_run_in_main_thread_0 = Module["_emscripten_sync_run_in_main_thread_0"] = Module["asm"]["emscripten_sync_run_in_main_thread_0"]).apply(null, arguments); - }); - var _emscripten_sync_run_in_main_thread_1 = (Module["_emscripten_sync_run_in_main_thread_1"] = function () { - return (_emscripten_sync_run_in_main_thread_1 = Module["_emscripten_sync_run_in_main_thread_1"] = Module["asm"]["emscripten_sync_run_in_main_thread_1"]).apply(null, arguments); - }); - var _emscripten_sync_run_in_main_thread_2 = (Module["_emscripten_sync_run_in_main_thread_2"] = function () { - return (_emscripten_sync_run_in_main_thread_2 = Module["_emscripten_sync_run_in_main_thread_2"] = Module["asm"]["emscripten_sync_run_in_main_thread_2"]).apply(null, arguments); - }); - var _emscripten_sync_run_in_main_thread_xprintf_varargs = (Module["_emscripten_sync_run_in_main_thread_xprintf_varargs"] = function () { - return (_emscripten_sync_run_in_main_thread_xprintf_varargs = Module["_emscripten_sync_run_in_main_thread_xprintf_varargs"] = - Module["asm"]["emscripten_sync_run_in_main_thread_xprintf_varargs"]).apply(null, arguments); - }); - var _emscripten_sync_run_in_main_thread_3 = (Module["_emscripten_sync_run_in_main_thread_3"] = function () { - return (_emscripten_sync_run_in_main_thread_3 = Module["_emscripten_sync_run_in_main_thread_3"] = Module["asm"]["emscripten_sync_run_in_main_thread_3"]).apply(null, arguments); - }); - var _emscripten_sync_run_in_main_thread_4 = (Module["_emscripten_sync_run_in_main_thread_4"] = function () { - return (_emscripten_sync_run_in_main_thread_4 = Module["_emscripten_sync_run_in_main_thread_4"] = Module["asm"]["emscripten_sync_run_in_main_thread_4"]).apply(null, arguments); - }); - var _emscripten_sync_run_in_main_thread_5 = (Module["_emscripten_sync_run_in_main_thread_5"] = function () { - return (_emscripten_sync_run_in_main_thread_5 = Module["_emscripten_sync_run_in_main_thread_5"] = Module["asm"]["emscripten_sync_run_in_main_thread_5"]).apply(null, arguments); - }); - var _emscripten_sync_run_in_main_thread_6 = (Module["_emscripten_sync_run_in_main_thread_6"] = function () { - return (_emscripten_sync_run_in_main_thread_6 = Module["_emscripten_sync_run_in_main_thread_6"] = Module["asm"]["emscripten_sync_run_in_main_thread_6"]).apply(null, arguments); - }); - var _emscripten_sync_run_in_main_thread_7 = (Module["_emscripten_sync_run_in_main_thread_7"] = function () { - return (_emscripten_sync_run_in_main_thread_7 = Module["_emscripten_sync_run_in_main_thread_7"] = Module["asm"]["emscripten_sync_run_in_main_thread_7"]).apply(null, arguments); - }); - var _emscripten_run_in_main_runtime_thread_js = (Module["_emscripten_run_in_main_runtime_thread_js"] = function () { - return (_emscripten_run_in_main_runtime_thread_js = Module["_emscripten_run_in_main_runtime_thread_js"] = Module["asm"]["emscripten_run_in_main_runtime_thread_js"]).apply(null, arguments); - }); - var __emscripten_call_on_thread = (Module["__emscripten_call_on_thread"] = function () { - return (__emscripten_call_on_thread = Module["__emscripten_call_on_thread"] = Module["asm"]["_emscripten_call_on_thread"]).apply(null, arguments); - }); - var _emscripten_tls_init = (Module["_emscripten_tls_init"] = function () { - return (_emscripten_tls_init = Module["_emscripten_tls_init"] = - Module["asm"]["emscripten_tls_init"]).apply(null, arguments); - }); - var dynCall_viijii = (Module["dynCall_viijii"] = function () { - return (dynCall_viijii = Module["dynCall_viijii"] = - Module["asm"]["dynCall_viijii"]).apply(null, arguments); - }); - var dynCall_ji = (Module["dynCall_ji"] = function () { - return (dynCall_ji = Module["dynCall_ji"] = - Module["asm"]["dynCall_ji"]).apply(null, arguments); - }); - var dynCall_jiji = (Module["dynCall_jiji"] = function () { - return (dynCall_jiji = Module["dynCall_jiji"] = - Module["asm"]["dynCall_jiji"]).apply(null, arguments); - }); - var dynCall_iiiiij = (Module["dynCall_iiiiij"] = function () { - return (dynCall_iiiiij = Module["dynCall_iiiiij"] = - Module["asm"]["dynCall_iiiiij"]).apply(null, arguments); - }); - var dynCall_iiiiijj = (Module["dynCall_iiiiijj"] = function () { - return (dynCall_iiiiijj = Module["dynCall_iiiiijj"] = - Module["asm"]["dynCall_iiiiijj"]).apply(null, arguments); - }); - var dynCall_iiiiiijj = (Module["dynCall_iiiiiijj"] = function () { - return (dynCall_iiiiiijj = Module["dynCall_iiiiiijj"] = - Module["asm"]["dynCall_iiiiiijj"]).apply(null, arguments); - }); - var _main_thread_futex = (Module["_main_thread_futex"] = 1563104); - Module["addOnPreMain"] = addOnPreMain; - Module["PThread"] = PThread; - Module["PThread"] = PThread; - Module["_pthread_self"] = _pthread_self; - Module["wasmMemory"] = wasmMemory; - Module["ExitStatus"] = ExitStatus; - var calledRun; - function ExitStatus(status) { - this.name = "ExitStatus"; - this.message = "Program terminated with exit(" + status + ")"; - this.status = status; - } - dependenciesFulfilled = function runCaller() { - if (!calledRun) - run(); - if (!calledRun) - dependenciesFulfilled = runCaller; - }; - function run(args) { - args = args || arguments_; - if (runDependencies > 0) { - return; - } - preRun(); - if (runDependencies > 0) - return; - function doRun() { - if (calledRun) - return; - calledRun = true; - Module["calledRun"] = true; - if (ABORT) - return; - initRuntime(); - preMain(); - if (Module["onRuntimeInitialized"]) - Module["onRuntimeInitialized"](); - postRun(); - } - if (Module["setStatus"]) { - Module["setStatus"]("Running..."); - setTimeout(function () { - setTimeout(function () { - Module["setStatus"](""); - }, 1); - doRun(); - }, 1); - } - else { - doRun(); - } - } - Module["run"] = run; - function exit(status, implicit) { - if (implicit && noExitRuntime && status === 0) { - return; - } - if (noExitRuntime) { - } - else { - PThread.terminateAllThreads(); - EXITSTATUS = status; - exitRuntime(); - if (Module["onExit"]) - Module["onExit"](status); - ABORT = true; - } - quit_(status, new ExitStatus(status)); - } - if (Module["preInit"]) { - if (typeof Module["preInit"] == "function") - Module["preInit"] = [Module["preInit"]]; - while (Module["preInit"].length > 0) { - Module["preInit"].pop()(); - } - } - if (!ENVIRONMENT_IS_PTHREAD) - noExitRuntime = true; - if (!ENVIRONMENT_IS_PTHREAD) { - run(); - } - else { - PThread.initWorker(); - } - return { addOnPreMain, Module }; -} -exports.loadEmscriptenGlueCode = loadEmscriptenGlueCode; - - -/***/ }), - -/***/ 9493: -/*!***************************************************************************!*\ - !*** ../core/ts/web-worker-scripts/translation-worker.js/digestSha256.ts ***! - \***************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.digestSha256 = void 0; -/** - * Derived from https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest - */ -const digestSha256 = (buffer) => __awaiter(void 0, void 0, void 0, function* () { - // hash the message - const hashBuffer = yield crypto.subtle.digest("SHA-256", buffer); - // convert buffer to byte array - const hashArray = Array.from(new Uint8Array(hashBuffer)); - // convert bytes to hex string - return hashArray.map(b => b.toString(16).padStart(2, "0")).join(""); -}); -exports.digestSha256 = digestSha256; - - -/***/ }), - -/***/ 3519: -/*!***********************************************************************************************!*\ - !*** ../core/ts/web-worker-scripts/translation-worker.js/getBergamotModelsForLanguagePair.ts ***! - \***********************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getBergamotModelsForLanguagePair = exports.LanguagePairUnsupportedError = void 0; -const setupPersistRemoteFileWithProgressDuringDownload_1 = __webpack_require__(/*! ./setupPersistRemoteFileWithProgressDuringDownload */ 5333); -const mb = bytes => Math.round((bytes / 1024 / 1024) * 10) / 10; -class LanguagePairUnsupportedError extends Error { - constructor() { - super(...arguments); - this.name = "LanguagePairUnsupportedError"; - } -} -exports.LanguagePairUnsupportedError = LanguagePairUnsupportedError; -const getBergamotModelsForLanguagePair = (languagePair, bergamotModelsBaseUrl, modelRegistry, cache, log, onModelDownloadProgress) => __awaiter(void 0, void 0, void 0, function* () { - if (!modelRegistry[languagePair]) { - throw new LanguagePairUnsupportedError(`Language pair '${languagePair}' not supported`); - } - const downloadStart = Date.now(); - const modelRegistryEntry = modelRegistry[languagePair]; - const modelFiles = Object.keys(modelRegistryEntry).map((type) => { - const { name, size, estimatedCompressedSize, expectedSha256Hash, } = modelRegistryEntry[type]; - const url = `${bergamotModelsBaseUrl}/${languagePair}/${name}`; - return { - type, - url, - name, - size, - estimatedCompressedSize, - expectedSha256Hash, - }; - }); - // Check remaining storage quota - const quota = yield navigator.storage.estimate(); - const percentageUsed = (quota.usage / quota.quota) * 100; - console.info(`${Math.round(percentageUsed * 100) / - 100}% used of the available storage (${mb(quota.quota)} mb).`); - const approximateRemainingQuota = quota.quota - quota.usage; - console.info(`Remaining storage quota: ${mb(approximateRemainingQuota)} mb.`); - // Don't attempt to persist model files if remaining quota suggest that it won't work - let persistFiles = true; - const modelFilesSize = modelFiles - .map(({ size }) => size) - .reduce((a, b) => a + b, 0); - if (modelFilesSize > approximateRemainingQuota) { - persistFiles = false; - log(`${languagePair}: Will not attempt to persist the model files (${mb(modelFilesSize)} mb) since approximate remaining quota (${mb(approximateRemainingQuota)} mb) is too small`); - } - // Summarize periodical updates on total language pair download progress - const bytesTransferredByType = { - lex: 0, - model: 0, - vocab: 0, - }; - const filesToTransferByType = { - lex: false, - model: false, - vocab: false, - }; - const sumLanguagePairFileToTransferSize = attribute => { - return ["lex", "model", "vocab"] - .map(type => filesToTransferByType[type] ? modelRegistryEntry[type][attribute] : 0) - .reduce((a, b) => a + b, 0); - }; - const broadcastDownloadProgressUpdate = () => { - const languagePairBytesTransferred = bytesTransferredByType.lex + - bytesTransferredByType.model + - bytesTransferredByType.vocab; - const languagePairBytesToTransfer = sumLanguagePairFileToTransferSize("size"); - const languagePairEstimatedCompressedBytesToTransfer = sumLanguagePairFileToTransferSize("estimatedCompressedSize"); - const percentTransferred = languagePairBytesToTransfer > 0 - ? languagePairBytesTransferred / languagePairBytesToTransfer - : 1.0; - const downloadDurationMs = Date.now() - downloadStart; - const modelDownloadProgress = { - bytesDownloaded: Math.round(percentTransferred * languagePairEstimatedCompressedBytesToTransfer), - bytesToDownload: languagePairEstimatedCompressedBytesToTransfer, - startTs: downloadStart, - durationMs: downloadDurationMs, - endTs: undefined, - }; - onModelDownloadProgress(modelDownloadProgress); - /* - console.debug( - `${languagePair}: onDownloadProgressUpdate - ${Math.round( - percentTransferred * 100, - )}% out of ${mb(languagePairEstimatedCompressedBytesToTransfer)} mb (${mb( - languagePairBytesToTransfer, - )} mb uncompressed) transferred`, - ); - */ - }; - // Download or restore model files from persistent cache - const persistRemoteFileWithProgressDuringDownload = setupPersistRemoteFileWithProgressDuringDownload_1.setupPersistRemoteFileWithProgressDuringDownload(languagePair, persistFiles, cache, log, filesToTransferByType, bytesTransferredByType, broadcastDownloadProgressUpdate); - const downloadedFiles = yield Promise.all(modelFiles.map(persistRemoteFileWithProgressDuringDownload)); - // Measure the time it took to acquire model files - const downloadEnd = Date.now(); - const downloadDurationMs = downloadEnd - downloadStart; - const totalBytes = downloadedFiles - .map(({ arrayBuffer }) => arrayBuffer.byteLength) - .reduce((a, b) => a + b, 0); - const totalBytesDownloaded = downloadedFiles - .filter(({ downloaded }) => downloaded) - .map(({ arrayBuffer }) => arrayBuffer.byteLength) - .reduce((a, b) => a + b, 0); - // Either report the total time for downloading or the time it has taken to load cached model files - if (totalBytesDownloaded > 0) { - const languagePairEstimatedCompressedBytesToTransfer = sumLanguagePairFileToTransferSize("estimatedCompressedSize"); - const finalModelDownloadProgress = { - bytesDownloaded: languagePairEstimatedCompressedBytesToTransfer, - bytesToDownload: languagePairEstimatedCompressedBytesToTransfer, - startTs: downloadStart, - durationMs: downloadDurationMs, - endTs: downloadEnd, - }; - onModelDownloadProgress(finalModelDownloadProgress); - } - else { - const finalModelDownloadProgress = { - bytesDownloaded: 0, - bytesToDownload: 0, - startTs: downloadStart, - durationMs: downloadDurationMs, - endTs: downloadEnd, - }; - onModelDownloadProgress(finalModelDownloadProgress); - } - log(`All model files for ${languagePair} downloaded / restored from persistent cache in ${downloadDurationMs / - 1000} seconds (total uncompressed size of model files: ${mb(totalBytes)} mb, of which ${Math.round((totalBytesDownloaded / totalBytes) * 100)}% was downloaded)`); - return downloadedFiles; -}); -exports.getBergamotModelsForLanguagePair = getBergamotModelsForLanguagePair; - - -/***/ }), - -/***/ 5716: -/*!********************************************************************!*\ - !*** ../core/ts/web-worker-scripts/translation-worker.js/index.ts ***! - \********************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const bergamot_translator_worker_1 = __webpack_require__(/*! ./bergamot-translator-worker */ 31); -const getBergamotModelsForLanguagePair_1 = __webpack_require__(/*! ./getBergamotModelsForLanguagePair */ 3519); -const config_1 = __webpack_require__(/*! ../../config */ 7843); -const modelRegistry_1 = __webpack_require__(/*! ../../modelRegistry */ 2050); -const setupPersistRemoteFileWithProgressDuringDownload_1 = __webpack_require__(/*! ./setupPersistRemoteFileWithProgressDuringDownload */ 5333); -// https://stackoverflow.com/a/54382037 -const ctx = self; -const init = () => __awaiter(void 0, void 0, void 0, function* () { - const log = message => { - ctx.postMessage({ - type: "log", - message, - }); - }; - const name = "bergamot-translator-worker.wasm"; - const remoteWasmBinary = { - type: "wasm-binary", - url: `${config_1.config.wasmBinariesBaseUrl}/${name}`, - name, - size: 6732404, - estimatedCompressedSize: 1827872, - expectedSha256Hash: "396d5e4df660f6746af00de961bfe257f7163e0f3aff413146072f93126e1c77", - }; - const persistFiles = true; - const wasmBinaryCache = yield caches.open("bergamot-wasm-binaries"); - const filesToTransferByType = { "wasm-binary": undefined }; - const bytesTransferredByType = { "wasm-binary": 0 }; - const persistRemoteFileWithProgressDuringDownload = setupPersistRemoteFileWithProgressDuringDownload_1.setupPersistRemoteFileWithProgressDuringDownload("bergamot-translator", persistFiles, wasmBinaryCache, log, filesToTransferByType, bytesTransferredByType, () => { - console.log("WASM binary download progress update", { - filesToTransferByType, - bytesTransferredByType, - }); - }); - const downloadedWasmBinary = yield persistRemoteFileWithProgressDuringDownload(remoteWasmBinary); - const initialModule = { - wasmBinary: downloadedWasmBinary.arrayBuffer, - }; - const { addOnPreMain, Module } = bergamot_translator_worker_1.loadEmscriptenGlueCode(initialModule); - addOnPreMain(function () { - let model; - /** - * If we end up in a situation where we want to make sure that an instance is deleted - * and the instance was in fact already deleted, then let that happen without throwing - * a fatal error. - * - * @param instance - */ - const safelyDeleteInstance = instance => { - try { - instance.delete(); - } - catch (err) { - if (err.name === "BindingError" && - err.message.includes("instance already deleted")) { - // ignore - return; - } - throw err; - } - }; - /** - * Automatically download the appropriate translation models, vocabularies and lexical shortlists if not already locally present - */ - const downloadModel = (from, to, bergamotModelsBaseUrl, onModelDownloadProgress) => __awaiter(this, void 0, void 0, function* () { - log(`downloadModel(${from}, ${to}, ${bergamotModelsBaseUrl})`); - const languagePair = `${from}${to}`; - const cache = yield caches.open("bergamot-models"); - const downloadedFiles = yield getBergamotModelsForLanguagePair_1.getBergamotModelsForLanguagePair(languagePair, bergamotModelsBaseUrl, modelRegistry_1.modelRegistry, cache, log, onModelDownloadProgress); - const downloadedFilesByType = { - lex: undefined, - model: undefined, - vocab: undefined, - }; - downloadedFiles.forEach(downloadedFile => { - downloadedFilesByType[downloadedFile.type] = downloadedFile; - }); - return downloadedFilesByType; - }); - const loadModel = (from, to, bergamotModelsBaseUrl, onModelDownloadProgress) => __awaiter(this, void 0, void 0, function* () { - log(`loadModel(${from}, ${to})`); - // Delete previous instance if a model is already loaded - if (model) { - safelyDeleteInstance(model); - } - // Download or hydrate model files to/from persistent storage - const downloadedFilesByType = yield downloadModel(from, to, bergamotModelsBaseUrl, onModelDownloadProgress); - const loadModelStart = performance.now(); - // This function constructs the AlignedMemory from the array buffer and the alignment size - const constructAlignedMemoryFromBuffer = (buffer, alignmentSize) => { - const byteArray = new Int8Array(buffer); - // console.debug("byteArray size: ", byteArray.byteLength); - const alignedMemory = new Module.AlignedMemory(byteArray.byteLength, alignmentSize); - const alignedByteArrayView = alignedMemory.getByteArrayView(); - alignedByteArrayView.set(byteArray); - return alignedMemory; - }; - // Set the Model Configuration as YAML formatted string. - // For available configuration options, please check: https://marian-nmt.github.io/docs/cmd/marian-decoder/ - // This example captures the most relevant options: model file, vocabulary files and shortlist file - const modelConfig = `beam-size: 1 -normalize: 1.0 -word-penalty: 0 -max-length-break: 128 -mini-batch-words: 1024 -workspace: 128 -max-length-factor: 2.0 -skip-cost: true -cpu-threads: 0 -quiet: true -quiet-translation: true -gemm-precision: int8shift -`; - console.log("modelConfig: ", modelConfig); - // Instantiate the TranslationModel - const modelBuffer = downloadedFilesByType.model.arrayBuffer; - const shortListBuffer = downloadedFilesByType.lex.arrayBuffer; - const vocabBuffers = [downloadedFilesByType.vocab.arrayBuffer]; - // Construct AlignedMemory objects with downloaded buffers - const alignedModelMemory = constructAlignedMemoryFromBuffer(modelBuffer, 256); - const alignedShortlistMemory = constructAlignedMemoryFromBuffer(shortListBuffer, 64); - const alignedVocabsMemoryList = new Module.AlignedMemoryList(); - vocabBuffers.forEach(item => alignedVocabsMemoryList.push_back(constructAlignedMemoryFromBuffer(item, 64))); - model = new Module.TranslationModel(modelConfig, alignedModelMemory, alignedShortlistMemory, alignedVocabsMemoryList); - const loadModelEnd = performance.now(); - const modelLoadWallTimeMs = loadModelEnd - loadModelStart; - const alignmentIsSupported = model.isAlignmentSupported(); - console.debug("Alignment:", alignmentIsSupported); - return { alignmentIsSupported, modelLoadWallTimeMs }; - }); - const translate = (texts) => { - log(`translate()`); - if (!model) { - throw new Error("Translate attempted before model was loaded"); - } - // TODO: Check that the loaded model supports the translation direction - // Prepare results object - const translationResults = { - originalTexts: [], - translatedTexts: [], - }; - // Instantiate the arguments of translate() API i.e. TranslationRequest and input (vector) - const request = new Module.TranslationRequest(); - const input = new Module.VectorString(); - // Add texts to translate - texts.forEach(text => { - input.push_back(text); - }); - // Access input (just for debugging) - console.debug("Input size=", input.size()); - /* - for (let i = 0; i < input.size(); i++) { - console.debug(" val:" + input.get(i)); - } - */ - // Translate the input; the result is a vector - const result = model.translate(input, request); - // Access input after translation (just for debugging) - console.debug("Input size after translate API call =", input.size()); - // Access original and translated text from each entry of vector - console.debug("Result size=", result.size()); - for (let i = 0; i < result.size(); i++) { - const originalText = result.get(i).getOriginalText(); - const translatedText = result.get(i).getTranslatedText(); - translationResults.originalTexts.push(originalText); - translationResults.translatedTexts.push(translatedText); - } - // Clean up the instances - safelyDeleteInstance(request); - safelyDeleteInstance(input); - return translationResults; - }; - const handleError = (error, requestId, errorSource) => { - console.info(`Error/exception caught in worker during ${errorSource}:`, error); - log(`Error/exception caught in worker during ${errorSource}: ${error} ${error.stack}`); - const message = { - type: `error`, - message: `Error/exception caught in worker during ${errorSource}: ${error.toString()}`, - requestId, - errorSource, - }; - ctx.postMessage(message); - }; - onmessage = function (msg) { - const { data } = msg; - if (!data.type || !data.requestId) { - return; - } - const requestId = data.requestId; - if (data.type === "loadModel") { - try { - loadModel(data.loadModelParams.from, data.loadModelParams.to, data.loadModelParams.bergamotModelsBaseUrl, (modelDownloadProgress) => { - const message = { - type: "modelDownloadProgress", - requestId, - modelDownloadProgress, - }; - ctx.postMessage(message); - }) - .then(loadModelResults => { - const message = { - type: "loadModelResults", - requestId, - loadModelResults, - }; - ctx.postMessage(message); - }) - .catch(error => { - if (error.name === "FileDownloadError") { - handleError(error, requestId, "downloadModel"); - } - else if (error.name === "LanguagePairUnsupportedError") { - handleError(error, requestId, "downloadModel"); - } - else { - handleError(error, requestId, "loadModel"); - } - }); - } - catch (error) { - handleError(error, requestId, "loadModel"); - } - } - else if (data.type === "translate") { - try { - console.log("Messages to translate: ", data.translateParams.texts); - const translationResults = translate(data.translateParams.texts); - const message = { - type: "translationResults", - requestId, - translationResults, - }; - ctx.postMessage(message); - } - catch (error) { - handleError(error, requestId, "translate"); - } - } - else { - throw new Error(`Unexpected message data payload sent to translation worker: "${JSON.stringify(data)}"`); - } - }; - // Send a message indicating that the worker is ready to receive WASM-related messages - ctx.postMessage("ready"); - log("The worker is ready to receive translation-related messages"); - }); -}); -init(); - - -/***/ }), - -/***/ 1136: -/*!*****************************************************************************************************!*\ - !*** ../core/ts/web-worker-scripts/translation-worker.js/instrumentResponseWithProgressCallback.ts ***! - \*****************************************************************************************************/ -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.instrumentResponseWithProgressCallback = void 0; -const instrumentResponseWithProgressCallback = (response, onProgress) => { - const { body, headers, status } = response; - // Only attempt to track download progress on valid responses - if (status >= 400) { - return response; - } - const reader = body.getReader(); - let bytesTransferred = 0; - const stream = new ReadableStream({ - start(controller) { - function push() { - reader.read().then(({ done, value }) => { - if (done) { - controller.close(); - return; - } - if (value) { - onProgress(bytesTransferred); - bytesTransferred += value.length; - } - controller.enqueue(value); - push(); - }); - } - push(); - }, - }); - return new Response(stream, { headers, status }); -}; -exports.instrumentResponseWithProgressCallback = instrumentResponseWithProgressCallback; - - -/***/ }), - -/***/ 1836: -/*!******************************************************************************!*\ - !*** ../core/ts/web-worker-scripts/translation-worker.js/persistResponse.ts ***! - \******************************************************************************/ -/***/ (function(__unused_webpack_module, exports) { - - -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.persistResponse = void 0; -const persistResponse = (cache, url, response, log) => __awaiter(void 0, void 0, void 0, function* () { - // Both fetch() and cache.put() "consume" the request, so we need to make a copy. - // (see https://developer.mozilla.org/en-US/docs/Web/API/Request/clone) - try { - // Store fetched contents in cache - yield cache.put(url, response.clone()); - } - catch (err) { - console.warn("Error occurred during cache.put()", { err }); - // Note that this error is currently not thrown at all due to https://github.com/jimmywarting/cache-polyfill/issues/4 - if (err && err.name === "QuotaExceededError") { - // Don't bail just because we can't persist the model file across browser restarts - console.warn(err); - log(`${name}: Ran into and ignored a QuotaExceededError`); - } - else { - throw err; - } - } -}); -exports.persistResponse = persistResponse; - - -/***/ }), - -/***/ 5333: -/*!***************************************************************************************************************!*\ - !*** ../core/ts/web-worker-scripts/translation-worker.js/setupPersistRemoteFileWithProgressDuringDownload.ts ***! - \***************************************************************************************************************/ -/***/ (function(__unused_webpack_module, exports, __webpack_require__) { - - -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()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.setupPersistRemoteFileWithProgressDuringDownload = exports.FileDownloadError = void 0; -const instrumentResponseWithProgressCallback_1 = __webpack_require__(/*! ./instrumentResponseWithProgressCallback */ 1136); -const persistResponse_1 = __webpack_require__(/*! ./persistResponse */ 1836); -const digestSha256_1 = __webpack_require__(/*! ./digestSha256 */ 9493); -const throttle_1 = __webpack_require__(/*! ./throttle */ 2297); -class FileDownloadError extends Error { - constructor() { - super(...arguments); - this.name = "FileDownloadError"; - } -} -exports.FileDownloadError = FileDownloadError; -const setupPersistRemoteFileWithProgressDuringDownload = (contextName, persistFiles, cache, log, filesToTransferByType, bytesTransferredByType, broadcastDownloadProgressUpdate) => { - const throttledBroadcastDownloadProgressUpdate = throttle_1.throttle(broadcastDownloadProgressUpdate, 100); - return ({ type, url, name, expectedSha256Hash }) => __awaiter(void 0, void 0, void 0, function* () { - let response = yield cache.match(url); - let downloaded = false; - if (!response || response.status >= 400) { - log(`Downloading file ${name} from ${url}`); - downloaded = true; - filesToTransferByType[type] = true; - try { - const downloadResponsePromise = fetch(url); - // Await initial response headers before continuing - const downloadResponseRaw = yield downloadResponsePromise; - // Hook up progress callbacks to track actual download of the files - const onProgress = (bytesTransferred) => { - // console.debug(`${name}: onProgress - ${mb(bytesTransferred)} mb out of ${mb(size)} mb transferred`); - bytesTransferredByType[type] = bytesTransferred; - throttledBroadcastDownloadProgressUpdate(); - }; - response = instrumentResponseWithProgressCallback_1.instrumentResponseWithProgressCallback(downloadResponseRaw, onProgress); - log(`Response for ${url} from network is: ${response.status}`); - if (persistFiles) { - // This avoids caching responses that we know are errors (i.e. HTTP status code of 4xx or 5xx). - if (response.status < 400) { - yield persistResponse_1.persistResponse(cache, url, response, log); - } - else { - log(`${name}: Not caching the response to ${url} since the status was >= 400`); - } - } - } - catch ($$err) { - console.warn(`${name}: An error occurred while downloading/persisting the file`, { $$err }); - const errorToThrow = new FileDownloadError($$err.message); - errorToThrow.stack = $$err.stack; - throw errorToThrow; - } - } - else { - log(`${name}: File from ${url} previously downloaded already`); - } - if (response.status >= 400) { - throw new FileDownloadError("File download failed"); - } - const arrayBuffer = yield response.arrayBuffer(); - // Verify the hash of downloaded files - const sha256Hash = yield digestSha256_1.digestSha256(arrayBuffer); - if (sha256Hash !== expectedSha256Hash) { - console.warn(`File download integrity check failed for ${contextName}'s ${type} file`, { - sha256Hash, - expectedSha256Hash, - }); - throw new FileDownloadError(`File download integrity check failed for ${contextName}'s ${type} file`); - } - return { type, name, arrayBuffer, downloaded, sha256Hash }; - }); -}; -exports.setupPersistRemoteFileWithProgressDuringDownload = setupPersistRemoteFileWithProgressDuringDownload; - - -/***/ }), - -/***/ 2297: -/*!***********************************************************************!*\ - !*** ../core/ts/web-worker-scripts/translation-worker.js/throttle.ts ***! - \***********************************************************************/ -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.throttle = void 0; -/** - * Execute a callback immediately and then at most once each {ms} ms - * Derived from https://stackoverflow.com/a/27078401/682317 - */ -const throttle = (callback, ms) => { - let waiting = false; - return function () { - if (!waiting) { - callback.apply(this, arguments); - waiting = true; - setTimeout(function () { - waiting = false; - }, ms); - } - }; -}; -exports.throttle = throttle; - - -/***/ }) - -/******/ }); -/************************************************************************/ -/******/ // The module cache -/******/ var __webpack_module_cache__ = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ // Check if module is in cache -/******/ if(__webpack_module_cache__[moduleId]) { -/******/ return __webpack_module_cache__[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = __webpack_module_cache__[moduleId] = { -/******/ // no module.id needed -/******/ // no module.loaded needed -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/************************************************************************/ -/******/ -/******/ // startup -/******/ // Load entry module and return exports -/******/ // This entry module is referenced by other modules so it can't be inlined -/******/ var __webpack_exports__ = __webpack_require__(5716); -/******/ -/******/ })() -; -//# sourceMappingURL=translation-worker.js.map \ No newline at end of file diff --git a/browser/extensions/translations/import_xpi.py b/browser/extensions/translations/import_xpi.py deleted file mode 100644 index 1b553bcc7d6b..000000000000 --- a/browser/extensions/translations/import_xpi.py +++ /dev/null @@ -1,127 +0,0 @@ -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at http://mozilla.org/MPL/2.0/. - -# script to pull and import Firefox Translations's extension source code - -import os.path -from zipfile import ZipFile -import subprocess -import shutil -import sys - -# the version number is the only part of this script that needs to be updated -# in order to update the in-tree version with the latest xpi version -extension_version = input( - "Type the extension's version (tag) on Github you want to import: " -) -print("Importing version:", extension_version) -if not extension_version: - sys.exit("Value can't be empty.") - -extension_folder = "firefox-translations-src" - -if not os.path.exists("import_xpi.py"): - sys.exit("This script is intended to be executed from its local folder") - -have_xpi = "N" -local_xpi_file = ( - "firefox-translations-src/dist/production/firefox/" - "firefox-infobar-ui/firefox-translations-" + extension_version + ".xpi" -) -if os.path.isfile(local_xpi_file): - have_xpi = input( - "Extension xpi exists. Press Y to use it or any other key to rebuild it." - ) - -if have_xpi.lower() != "y": - # deleting old files if any - shutil.rmtree(extension_folder, ignore_errors=True) - # cloning the extension - subprocess.call( - ( - "git clone -b v" + extension_version + " " - "https://github.com/mozilla-extensions/firefox-translations/ " - + extension_folder - + " " - ).split() - ) - # setting up the repo - subprocess.call("yarn install".split(), cwd=extension_folder) - # pulling bergamot-translator submodule, the repo containing the port of the - # neural machine translation engine to wasm - subprocess.call( - "git submodule update --init --recursive".split(), - cwd=extension_folder, - ) - # build the wasm nmt module - subprocess.call( - "./bergamot-translator/build-wasm.sh".split(), - cwd=extension_folder, - ) - # import the generated wasm module to the extension - subprocess.call( - "./import-bergamot-translator.sh ./bergamot-translator/build-wasm/".split(), - cwd=extension_folder, - ) - # build the final xpi - env = { - **os.environ, - "MC": str(1), - } - subprocess.call( - "yarn build:firefox-infobar-ui".split(), cwd=extension_folder, env=env - ) - -shutil.rmtree("extension", ignore_errors=True) -os.mkdir("extension") -file_exceptions = [ - "META-INF", - ".md", - "BRANCH", - "COMMITHASH", - "LASTCOMMITDATETIME", - "VERSION", - ".map", - ".yaml", -] - - -def isValidFile(filename): - for exception in file_exceptions: - if exception in filename: - return False - return True - - -file_set = set() -# read xpi files -with ZipFile(local_xpi_file, "r") as zip: - namelist = zip.namelist() - cleared_namelist = [] - for filename in namelist: - if isValidFile(filename): - full_file_path = zip.extract(filename, "extension") - if filename.endswith(".js"): - filename = "browser/extensions/translations/{}".format(full_file_path) - subprocess.call( - str( - "./mach lint --linter license {} --fix".format(filename) - ).split(), - cwd="../../../", - ) - -# patching BrowserGlue.jsm -with open("../../components/BrowserGlue.jsm") as fp: - count = 0 - Lines = fp.readlines() - for line in Lines: - if "resource://builtin-addons/translations/" in line: - Lines[count - 1] = ' "{}",\n'.format(extension_version) - with open("../../components/BrowserGlue.jsm", "w") as outfile: - outfile.write("".join(Lines)) - break - count += 1 - - -print("Import finalized successfully") diff --git a/browser/extensions/translations/jar.mn b/browser/extensions/translations/jar.mn deleted file mode 100644 index 60b54dc8de2c..000000000000 --- a/browser/extensions/translations/jar.mn +++ /dev/null @@ -1,8 +0,0 @@ -##### This file was automatically generated by the import_xpi.py script #### -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at http://mozilla.org/MPL/2.0/. - -browser.jar: -% resource builtin-addons %builtin-addons/ contentaccessible=yes - builtin-addons/translations/ (extension/**) diff --git a/browser/extensions/translations/moz.build b/browser/extensions/translations/moz.build deleted file mode 100644 index cf94675fc45a..000000000000 --- a/browser/extensions/translations/moz.build +++ /dev/null @@ -1,4 +0,0 @@ -with Files("**"): - BUG_COMPONENT = ("Firefox", "Translations") - -JAR_MANIFESTS += ["jar.mn"]