/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./app/assets/javascripts/index.js");
/******/ })
/************************************************************************/
/******/ ({
/***/ "../snjs/dist/snjs.js":
/*!****************************!*\
!*** ../snjs/dist/snjs.js ***!
\****************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
(function webpackUniversalModuleDefinition(root,factory){if(true)module.exports=factory();else {}})(window,function(){return(/******/function(modules){// webpackBootstrap
/******/ // The module cache
/******/var installedModules={};/******/ /******/ // The require function
/******/function __webpack_require__(moduleId){/******/ /******/ // Check if module is in cache
/******/if(installedModules[moduleId]){/******/return installedModules[moduleId].exports;/******/}/******/ // Create a new module (and put it into the cache)
/******/var module=installedModules[moduleId]={/******/i:moduleId,/******/l:false,/******/exports:{}/******/};/******/ /******/ // Execute the module function
/******/modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);/******/ /******/ // Flag the module as loaded
/******/module.l=true;/******/ /******/ // Return the exports of the module
/******/return module.exports;/******/}/******/ /******/ /******/ // expose the modules object (__webpack_modules__)
/******/__webpack_require__.m=modules;/******/ /******/ // expose the module cache
/******/__webpack_require__.c=installedModules;/******/ /******/ // define getter function for harmony exports
/******/__webpack_require__.d=function(exports,name,getter){/******/if(!__webpack_require__.o(exports,name)){/******/Object.defineProperty(exports,name,{enumerable:true,get:getter});/******/}/******/};/******/ /******/ // define __esModule on exports
/******/__webpack_require__.r=function(exports){/******/if(typeof Symbol!=='undefined'&&Symbol.toStringTag){/******/Object.defineProperty(exports,Symbol.toStringTag,{value:'Module'});/******/}/******/Object.defineProperty(exports,'__esModule',{value:true});/******/};/******/ /******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/__webpack_require__.t=function(value,mode){/******/if(mode&1)value=__webpack_require__(value);/******/if(mode&8)return value;/******/if(mode&4&&typeof value==='object'&&value&&value.__esModule)return value;/******/var ns=Object.create(null);/******/__webpack_require__.r(ns);/******/Object.defineProperty(ns,'default',{enumerable:true,value:value});/******/if(mode&2&&typeof value!='string')for(var key in value)__webpack_require__.d(ns,key,function(key){return value[key];}.bind(null,key));/******/return ns;/******/};/******/ /******/ // getDefaultExport function for compatibility with non-harmony modules
/******/__webpack_require__.n=function(module){/******/var getter=module&&module.__esModule?/******/function getDefault(){return module['default'];}:/******/function getModuleExports(){return module;};/******/__webpack_require__.d(getter,'a',getter);/******/return getter;/******/};/******/ /******/ // Object.prototype.hasOwnProperty.call
/******/__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property);};/******/ /******/ // __webpack_public_path__
/******/__webpack_require__.p="";/******/ /******/ /******/ // Load entry module and return exports
/******/return __webpack_require__(__webpack_require__.s="./lib/main.js");/******/}(/************************************************************************/ /******/{/***/"../sncrypto/dist/sncrypto.js":/*!************************************!*\
!*** ../sncrypto/dist/sncrypto.js ***!
\************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){/* WEBPACK VAR INJECTION */(function(module){var __WEBPACK_AMD_DEFINE_FACTORY__,__WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__;function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}!function(e,r){"object"==(false?undefined:_typeof(exports))&&"object"==(false?undefined:_typeof(module))?module.exports=r():true?!(__WEBPACK_AMD_DEFINE_ARRAY__=[],__WEBPACK_AMD_DEFINE_FACTORY__=r,__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__)):undefined;}(window,function(){return function(e){var r={};function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports;}return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:n});},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0});},t.t=function(e,r){if(1&r&&(e=t(e)),8&r)return e;if(4&r&&"object"==_typeof(e)&&e&&e.__esModule)return e;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var o in e){t.d(n,o,function(r){return e[r];}.bind(null,o));}return n;},t.n=function(e){var r=e&&e.__esModule?function(){return e.default;}:function(){return e;};return t.d(r,"a",r),r;},t.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r);},t.p="",t(t.s="./lib/main.js");}({"./lib/crypto/pure_crypto.js":/*!***********************************!*\
!*** ./lib/crypto/pure_crypto.js ***!
\***********************************/ /*! exports provided: SNPureCrypto */function libCryptoPure_cryptoJs(e,r,t){"use strict";t.r(r),t.d(r,"SNPureCrypto",function(){return u;});var n=t(/*! @Lib/utils */"./lib/utils.js");function o(e,r){for(var t=0;t>3]>>o%8*4&15;return("x"==e?r:3&r|8).toString(16);});}var u=new Date().getTime();return e.performance&&"function"==typeof e.performance.now&&(u+=performance.now()),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var r=(u+16*Math.random())%16|0;return u=Math.floor(u/16),("x"==e?r:3&r|8).toString(16);});}t.d(r,"getGlobalScope",function(){return n;}),t.d(r,"ieOrEdge",function(){return o;}),t.d(r,"isWebCryptoAvailable",function(){return u;}),t.d(r,"getSubtleCrypto",function(){return a;}),t.d(r,"generateUUIDSync",function(){return c;});}.call(this,t(/*! ./../node_modules/webpack/buildin/global.js */"./node_modules/webpack/buildin/global.js"));},"./node_modules/webpack/buildin/global.js":/*!***********************************!*\
!*** (webpack)/buildin/global.js ***!
\***********************************/ /*! no static exports found */function node_modulesWebpackBuildinGlobalJs(e,r){function t(e){return(t="function"==typeof Symbol&&"symbol"==_typeof(Symbol.iterator)?function(e){return _typeof(e);}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":_typeof(e);})(e);}var n;n=function(){return this;}();try{n=n||new Function("return this")();}catch(e){"object"===("undefined"==typeof window?"undefined":t(window))&&(n=window);}e.exports=n;}});});/* WEBPACK VAR INJECTION */}).call(this,__webpack_require__(/*! ./../../snjs/node_modules/webpack/buildin/module.js */"./node_modules/webpack/buildin/module.js")(module));/***/},/***/"./lib/application.js":/*!****************************!*\
!*** ./lib/application.js ***!
\****************************/ /*! exports provided: SNApplication */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"SNApplication",function(){return SNApplication;});/* harmony import */var _Lib_utils__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Lib/utils */"./lib/utils.js");/* harmony import */var _Models_content_types__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Models/content_types */"./lib/models/content_types.js");/* harmony import */var _Payloads_generator__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! @Payloads/generator */"./lib/protocol/payloads/generator.js");/* harmony import */var _Lib__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! @Lib */"./lib/index.js");/* harmony import */var _Services__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(/*! @Services */"./lib/services/index.js");function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0&&arguments[0]!==undefined?arguments[0]:{},environment=_ref.environment,platform=_ref.platform,namespace=_ref.namespace,host=_ref.host,deviceInterface=_ref.deviceInterface,swapClasses=_ref.swapClasses,skipClasses=_ref.skipClasses,crypto=_ref.crypto;_classCallCheck(this,SNApplication);if(!deviceInterface){throw'Device Interface must be supplied.';}if(!environment){throw'Environment must be supplied when creating an application.';}if(!platform){throw'Platform must be supplied when creating an application.';}this.environment=environment;this.platform=platform;this.namespace=namespace||'';this.host=host;this.deviceInterface=deviceInterface;this.crypto=crypto;this.swapClasses=swapClasses;this.skipClasses=skipClasses;this.eventHandlers=[];this.services=[];this.streamObservers=[];this.serviceObservers=[];this.managedSubscribers=[];this.constructServices();}/**
* @publilc
* The first thing consumers should call when starting their app.
* This function will load all services in their correct order.
* @param callbacks
* async .requiresChallengeResponses(challenges)
* @param challenges
* .handleChallengeFailures
*
An array of DeviceAuthentication Challenges that require responses.
*/_createClass(SNApplication,[{key:"prepareForLaunch",value:function prepareForLaunch(_ref2){var callbacks;return regeneratorRuntime.async(function prepareForLaunch$(_context){while(1){switch(_context.prev=_context.next){case 0:callbacks=_ref2.callbacks;if(callbacks.requiresChallengeResponses){_context.next=3;break;}throw'Application.launch callbacks are not properly configured.';case 3:this.launchCallbacks=callbacks;_context.next=6;return regeneratorRuntime.awrap(this.deviceInterface.openDatabase());case 6:_context.next=8;return regeneratorRuntime.awrap(this.migrationService.initialize());case 8:_context.next=10;return regeneratorRuntime.awrap(this.handleStage(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationStages"].PreparingForLaunch_0));case 10:_context.next=12;return regeneratorRuntime.awrap(this.storageManager.initializeFromDisk());case 12:_context.next=14;return regeneratorRuntime.awrap(this.keyManager.initialize());case 14:_context.next=16;return regeneratorRuntime.awrap(this.handleStage(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationStages"].ReadyForLaunch_05));case 16:this.started=true;this.notifyEvent(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationEvents"].ApplicationStarted);case 18:case"end":return _context.stop();}}},null,this);}/**
* @publilc
* Runs migrations, handles device authentication, unlocks application, and
* issues a callback if a device activation requires user input
* (i.e local passcode or fingerprint).
* @param awaitDatabaseLoad Option to await database load before marking the app
* as ready. Used as far as we know only for unit tests.
*/},{key:"launch",value:function launch(){var _this=this;var _ref3,awaitDatabaseLoad,databasePayloads,loadPromise,_args3=arguments;return regeneratorRuntime.async(function launch$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:_ref3=_args3.length>0&&_args3[0]!==undefined?_args3[0]:{},awaitDatabaseLoad=_ref3.awaitDatabaseLoad;_context3.next=3;return regeneratorRuntime.awrap(this.handleLaunchAuthentication());case 3:_context3.next=5;return regeneratorRuntime.awrap(this.storageManager.isStorageWrapped());case 5:if(!_context3.sent){_context3.next=8;break;}_context3.next=8;return regeneratorRuntime.awrap(this.storageManager.decryptStorage());case 8:_context3.next=10;return regeneratorRuntime.awrap(this.sessionManager.initializeFromDisk());case 10:this.historyManager.initializeFromDisk();this.unlocked=true;this.notifyEvent(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationEvents"].ApplicationUnlocked);_context3.next=15;return regeneratorRuntime.awrap(this.handleStage(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationStages"].StorageDecrypted_09));case 15:_context3.next=17;return regeneratorRuntime.awrap(this.handleStage(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationStages"].Launched_10));case 17:_context3.next=19;return regeneratorRuntime.awrap(this.syncManager.getDatabasePayloads());case 19:databasePayloads=_context3.sent;_context3.next=22;return regeneratorRuntime.awrap(this.handleStage(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationStages"].LoadingDatabase_11));case 22:/**
* We don't want to await this, as we want to begin allowing the app to function
* before local data has been loaded fully. We await only initial
* `getDatabasePayloads` to lock in on database state.
*/loadPromise=this.syncManager.loadDatabasePayloads(databasePayloads).then(function _callee(){return regeneratorRuntime.async(function _callee$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:if(!_this.dealloced){_context2.next=2;break;}throw'Application has been destroyed.';case 2:_context2.next=4;return regeneratorRuntime.awrap(_this.handleStage(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationStages"].LoadedDatabase_12));case 4:_this.beginAutoSyncTimer();return _context2.abrupt("return",_this.syncManager.sync({mode:_Services__WEBPACK_IMPORTED_MODULE_4__["SYNC_MODE_DOWNLOAD_FIRST"]}));case 6:case"end":return _context2.stop();}}});});if(!awaitDatabaseLoad){_context3.next=26;break;}_context3.next=26;return regeneratorRuntime.awrap(loadPromise);case 26:case"end":return _context3.stop();}}},null,this);}},{key:"beginAutoSyncTimer",value:function beginAutoSyncTimer(){var _this2=this;this.autoSyncInterval=this.deviceInterface.interval(function(){_this2.syncManager.log('Syncing from autosync');_this2.sync();},DEFAULT_AUTO_SYNC_INTERVAL);}/**
* @private
* @param previousResponses Applications may require authetnication earlier than launch
* in the case of migrations. We can reuse their valid responses.
*/},{key:"handleLaunchAuthentication",value:function handleLaunchAuthentication(){var pendingChallenges;return regeneratorRuntime.async(function handleLaunchAuthentication$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:_context4.next=2;return regeneratorRuntime.awrap(this.deviceAuthService.getLaunchChallenges());case 2:pendingChallenges=_context4.sent;_context4.next=5;return regeneratorRuntime.awrap(this.handleLaunchChallenge(pendingChallenges));case 5:case"end":return _context4.stop();}}},null,this);}/** @private */},{key:"handleLaunchChallenge",value:function handleLaunchChallenge(challenges){var pendingChallenges,response,responses,_iteratorNormalCompletion,_didIteratorError,_iteratorError,_iterator,_step,_response,valid;return regeneratorRuntime.async(function handleLaunchChallenge$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:pendingChallenges=challenges.slice();case 1:if(!(pendingChallenges.length>0)){_context5.next=43;break;}_context5.next=4;return regeneratorRuntime.awrap(this.launchCallbacks.requiresChallengeResponses(pendingChallenges));case 4:response=_context5.sent;responses=Array.isArray(response)?response:[response];_iteratorNormalCompletion=true;_didIteratorError=false;_iteratorError=undefined;_context5.prev=9;_iterator=responses[Symbol.iterator]();case 11:if(_iteratorNormalCompletion=(_step=_iterator.next()).done){_context5.next=27;break;}_response=_step.value;_context5.next=15;return regeneratorRuntime.awrap(this.deviceAuthService.validateChallengeResponse(_response));case 15:valid=_context5.sent;if(!valid){_context5.next=22;break;}_context5.next=19;return regeneratorRuntime.awrap(this.deviceAuthService.handleChallengeResponse(_response));case 19:Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["removeFromArray"])(pendingChallenges,_response.challenge);_context5.next=24;break;case 22:_context5.next=24;return regeneratorRuntime.awrap(this.launchCallbacks.handleChallengeFailures([_response]));case 24:_iteratorNormalCompletion=true;_context5.next=11;break;case 27:_context5.next=33;break;case 29:_context5.prev=29;_context5.t0=_context5["catch"](9);_didIteratorError=true;_iteratorError=_context5.t0;case 33:_context5.prev=33;_context5.prev=34;if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return();}case 36:_context5.prev=36;if(!_didIteratorError){_context5.next=39;break;}throw _iteratorError;case 39:return _context5.finish(36);case 40:return _context5.finish(33);case 41:_context5.next=1;break;case 43:case"end":return _context5.stop();}}},null,this,[[9,29,33,41],[34,,36,40]]);}/** @private */},{key:"getMigrationChallengeResponder",value:function getMigrationChallengeResponder(){var _this3=this;return function _callee2(challenge){var responses;return regeneratorRuntime.async(function _callee2$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:_context6.next=2;return regeneratorRuntime.awrap(_this3.launchCallbacks.requiresChallengeResponses([challenge]));case 2:responses=_context6.sent;return _context6.abrupt("return",responses[0]);case 4:case"end":return _context6.stop();}}});};}/** @private */},{key:"handleStage",value:function handleStage(stage){var _iteratorNormalCompletion2,_didIteratorError2,_iteratorError2,_iterator2,_step2,service;return regeneratorRuntime.async(function handleStage$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:_iteratorNormalCompletion2=true;_didIteratorError2=false;_iteratorError2=undefined;_context7.prev=3;_iterator2=this.services[Symbol.iterator]();case 5:if(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done){_context7.next=12;break;}service=_step2.value;_context7.next=9;return regeneratorRuntime.awrap(service.handleApplicationStage(stage));case 9:_iteratorNormalCompletion2=true;_context7.next=5;break;case 12:_context7.next=18;break;case 14:_context7.prev=14;_context7.t0=_context7["catch"](3);_didIteratorError2=true;_iteratorError2=_context7.t0;case 18:_context7.prev=18;_context7.prev=19;if(!_iteratorNormalCompletion2&&_iterator2.return!=null){_iterator2.return();}case 21:_context7.prev=21;if(!_didIteratorError2){_context7.next=24;break;}throw _iteratorError2;case 24:return _context7.finish(21);case 25:return _context7.finish(18);case 26:case"end":return _context7.stop();}}},null,this,[[3,14,18,26],[19,,21,25]]);}/**
* @public
* @param singleEvent A private param used to destroy observer after it is called once
* for this event.
*/},{key:"addEventObserver",value:function addEventObserver(callback,singleEvent,singleUse,autoUnsubscribe){var _this4=this;var observer={callback:callback,singleEvent:singleEvent,singleUse:singleUse,autoUnsubscribe:autoUnsubscribe};this.eventHandlers.push(observer);return function(){Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["removeFromArray"])(_this4.eventHandlers,observer);};}/** @public */},{key:"onSync",value:function onSync(callback){var event=_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationEvents"].CompletedSync;var singleUse=false;var autoUnsubscribe=true;return this.addEventObserver(function(firedEvent){if(firedEvent===event){callback();}},event,singleUse,autoUnsubscribe);}/**
* @public
* When the root key or root key wrapper changes. Includes events like account state
* changes (registering, signing in, changing pw, logging out) and passcode state
* changes (adding, removing, changing).
*/},{key:"onCredentialChange",value:function onCredentialChange(callback){var uninstall=this.keyManager.onStatusChange(callback);this.managedSubscribers.push(uninstall);}/**
* @public
* Called when the application has initialized and is ready for launch, but before
* the application has been unlocked, if applicable. Use this to do pre-launch
* configuration, but do not attempt to access user data like notes or tags.
*/},{key:"onStart",value:function onStart(callback){if(this.started){callback();}else{this.addSingleUseObserver(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationEvents"].ApplicationStarted,callback);}}/**
* @public
* Called when the application has been fully decrypted and unlocked. Use this to
* to begin streaming data like notes and tags.
*/},{key:"onUnlock",value:function onUnlock(callback){if(this.unlocked){callback();}else{this.addSingleUseObserver(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationEvents"].ApplicationUnlocked,callback);}}},{key:"addSingleUseObserver",value:function addSingleUseObserver(eventName,callback){var singleUse=true;this.addEventObserver(function(firedEvent){if(firedEvent===eventName){callback();}},eventName,singleUse);}/** @private */},{key:"notifyEvent",value:function notifyEvent(event,data){var _iteratorNormalCompletion3,_didIteratorError3,_iteratorError3,_iterator3,_step3,observer;return regeneratorRuntime.async(function notifyEvent$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:_iteratorNormalCompletion3=true;_didIteratorError3=false;_iteratorError3=undefined;_context8.prev=3;_iterator3=this.eventHandlers.slice()[Symbol.iterator]();case 5:if(_iteratorNormalCompletion3=(_step3=_iterator3.next()).done){_context8.next=19;break;}observer=_step3.value;if(!(observer.singleEvent&&observer.singleEvent===event)){_context8.next=13;break;}_context8.next=10;return regeneratorRuntime.awrap(observer.callback(event,data||{}));case 10:if(observer.singleUse){Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["removeFromArray"])(this.eventHandlers,observer);}_context8.next=16;break;case 13:if(observer.singleEvent){_context8.next=16;break;}_context8.next=16;return regeneratorRuntime.awrap(observer.callback(event,data||{}));case 16:_iteratorNormalCompletion3=true;_context8.next=5;break;case 19:_context8.next=25;break;case 21:_context8.prev=21;_context8.t0=_context8["catch"](3);_didIteratorError3=true;_iteratorError3=_context8.t0;case 25:_context8.prev=25;_context8.prev=26;if(!_iteratorNormalCompletion3&&_iterator3.return!=null){_iterator3.return();}case 28:_context8.prev=28;if(!_didIteratorError3){_context8.next=31;break;}throw _iteratorError3;case 31:return _context8.finish(28);case 32:return _context8.finish(25);case 33:case"end":return _context8.stop();}}},null,this,[[3,21,25,33],[26,,28,32]]);}/** @public */},{key:"isDatabaseLoaded",value:function isDatabaseLoaded(){return this.syncManager.isDatabaseLoaded();}/** @public */},{key:"savePayload",value:function savePayload(_ref4){var payload,dirtied;return regeneratorRuntime.async(function savePayload$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:payload=_ref4.payload;dirtied=Object(_Payloads_generator__WEBPACK_IMPORTED_MODULE_2__["CopyPayload"])({payload:payload,override:{dirty:true}});_context9.next=4;return regeneratorRuntime.awrap(this.modelManager.mapPayloadToLocalItem({payload:dirtied}));case 4:_context9.next=6;return regeneratorRuntime.awrap(this.syncManager.sync());case 6:case"end":return _context9.stop();}}},null,this);}/**
* @public
* Finds an item by UUID.
*/},{key:"findItem",value:function findItem(_ref5){var uuid;return regeneratorRuntime.async(function findItem$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:uuid=_ref5.uuid;return _context10.abrupt("return",this.modelManager.findItem(uuid));case 2:case"end":return _context10.stop();}}},null,this);}/** @public */},{key:"mergeItem",value:function mergeItem(_ref6){var item,source;return regeneratorRuntime.async(function mergeItem$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:item=_ref6.item,source=_ref6.source;return _context11.abrupt("return",this.modelManager.mapItem({item:item,source:source}));case 2:case"end":return _context11.stop();}}},null,this);}/**
* @public
* @param add Whether to add the item to application state.
* @param needsSync Whether to mark the item as needing sync. `add` must also be true.
*/},{key:"createItem",value:function createItem(_ref7){var contentType,content,add,needsSync,item;return regeneratorRuntime.async(function createItem$(_context12){while(1){switch(_context12.prev=_context12.next){case 0:contentType=_ref7.contentType,content=_ref7.content,add=_ref7.add,needsSync=_ref7.needsSync;_context12.next=3;return regeneratorRuntime.awrap(this.modelManager.createItem({contentType:contentType,content:content,add:add,needsSync:needsSync}));case 3:item=_context12.sent;return _context12.abrupt("return",item);case 5:case"end":return _context12.stop();}}},null,this);}/** @public */},{key:"saveItem",value:function saveItem(_ref8){var item;return regeneratorRuntime.async(function saveItem$(_context13){while(1){switch(_context13.prev=_context13.next){case 0:item=_ref8.item;_context13.next=3;return regeneratorRuntime.awrap(this.modelManager.setItemDirty(item,true));case 3:_context13.next=5;return regeneratorRuntime.awrap(this.syncManager.sync());case 5:if(item.content_type===_Models_content_types__WEBPACK_IMPORTED_MODULE_1__["ContentTypes"].Tag){this.modelManager.reorderTagLocation(item);}case 6:case"end":return _context13.stop();}}},null,this);}/** @public */},{key:"saveItems",value:function saveItems(_ref9){var items;return regeneratorRuntime.async(function saveItems$(_context14){while(1){switch(_context14.prev=_context14.next){case 0:items=_ref9.items;_context14.next=3;return regeneratorRuntime.awrap(this.modelManager.setItemsDirty(items));case 3:_context14.next=5;return regeneratorRuntime.awrap(this.syncManager.sync());case 5:case"end":return _context14.stop();}}},null,this);}/**
* @public
* @param updateUserModifiedDate
* Whether to change the modified date the user sees of the item.
*/},{key:"setItemNeedsSync",value:function setItemNeedsSync(_ref10){var item,updateUserModifiedDate;return regeneratorRuntime.async(function setItemNeedsSync$(_context15){while(1){switch(_context15.prev=_context15.next){case 0:item=_ref10.item,updateUserModifiedDate=_ref10.updateUserModifiedDate;return _context15.abrupt("return",this.modelManager.setItemDirty(item,true,updateUserModifiedDate));case 2:case"end":return _context15.stop();}}},null,this);}/**
* @public
* @param updateUserModifiedDate
* Whether to change the modified date the user sees of the item.
*/},{key:"setItemsNeedsSync",value:function setItemsNeedsSync(_ref11){var items;return regeneratorRuntime.async(function setItemsNeedsSync$(_context16){while(1){switch(_context16.prev=_context16.next){case 0:items=_ref11.items;return _context16.abrupt("return",this.modelManager.setItemsDirty(items));case 2:case"end":return _context16.stop();}}},null,this);}/** @public */},{key:"deleteItem",value:function deleteItem(_ref12){var item;return regeneratorRuntime.async(function deleteItem$(_context17){while(1){switch(_context17.prev=_context17.next){case 0:item=_ref12.item;this.modelManager.setItemToBeDeleted(item);this.sync();case 3:case"end":return _context17.stop();}}},null,this);}/** @public */},{key:"deleteItemLocally",value:function deleteItemLocally(_ref13){var item;return regeneratorRuntime.async(function deleteItemLocally$(_context18){while(1){switch(_context18.prev=_context18.next){case 0:item=_ref13.item;this.modelManager.removeItemLocally(item);case 2:case"end":return _context18.stop();}}},null,this);}/** @public */},{key:"emptyTrash",value:function emptyTrash(){return regeneratorRuntime.async(function emptyTrash$(_context19){while(1){switch(_context19.prev=_context19.next){case 0:return _context19.abrupt("return",this.modelManager.emptyTrash());case 1:case"end":return _context19.stop();}}},null,this);}/** @public */},{key:"getTrashedItems",value:function getTrashedItems(){return this.modelManager.trashedItems();}/**
* @public
* @param contentType A string, array of strings, or '*'
*/},{key:"getItems",value:function getItems(_ref14){var contentType=_ref14.contentType;return this.modelManager.getItems(contentType);}/** @public */},{key:"getDisplayableItems",value:function getDisplayableItems(_ref15){var contentType=_ref15.contentType;return this.modelManager.validItemsForContentType(contentType);}/** @public */},{key:"getNotesMatchingSmartTag",value:function getNotesMatchingSmartTag(_ref16){var smartTag=_ref16.smartTag;return this.modelManager.notesMatchingSmartTag(smartTag);}/** @public */},{key:"findTag",value:function findTag(_ref17){var title=_ref17.title;return this.modelManager.findTag({title:title});}/** @public */},{key:"findOrCreateTag",value:function findOrCreateTag(_ref18){var title;return regeneratorRuntime.async(function findOrCreateTag$(_context20){while(1){switch(_context20.prev=_context20.next){case 0:title=_ref18.title;return _context20.abrupt("return",this.modelManager.findOrCreateTag({title:title}));case 2:case"end":return _context20.stop();}}},null,this);}/** @public */},{key:"getSmartTags",value:function getSmartTags(){return this.modelManager.getSmartTags();}/** @public */},{key:"getNoteCount",value:function getNoteCount(){return this.modelManager.noteCount();}/**
* @public
* Begin streaming items to display in the UI.
* @param contentType Can be string, '*', or array of types.
*/},{key:"streamItems",value:function streamItems(_ref19){var contentType=_ref19.contentType,stream=_ref19.stream;var observer=this.modelManager.addMappingObserver(contentType,function(allItems,validItems,deletedItems,source,sourceKey){var includedContentTypes=allItems.map(function(item){return item.content_type;});stream({items:allItems,contentTypes:includedContentTypes,source:source,sourceKey:sourceKey});});this.streamObservers.push(observer);}/** @public */},{key:"setHost",value:function setHost(host){return regeneratorRuntime.async(function setHost$(_context21){while(1){switch(_context21.prev=_context21.next){case 0:return _context21.abrupt("return",this.apiService.setHost(host));case 1:case"end":return _context21.stop();}}},null,this);}/** @public */},{key:"getHost",value:function getHost(){return regeneratorRuntime.async(function getHost$(_context22){while(1){switch(_context22.prev=_context22.next){case 0:return _context22.abrupt("return",this.apiService.getHost());case 1:case"end":return _context22.stop();}}},null,this);}/** @public */},{key:"getUser",value:function getUser(){if(!this.unlocked){throw'Attempting to access user before application unlocked';}return this.sessionManager.getUser();}/** @public */},{key:"getUserVersion",value:function getUserVersion(){return regeneratorRuntime.async(function getUserVersion$(_context23){while(1){switch(_context23.prev=_context23.next){case 0:return _context23.abrupt("return",this.protocolService.getUserVersion());case 1:case"end":return _context23.stop();}}},null,this);}/** @public */},{key:"noAccount",value:function noAccount(){var user=this.getUser();return Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["isNullOrUndefined"])(user);}/**
* @public
* @return A dictionary with `affectedItems` as the items that were either created
* or dirtied by this import and `errorCount`, which is the number of items
* that were not imported due to failure to decrypt.
*/},{key:"importData",value:function importData(_ref20){var data,password,decryptedPayloads,validPayloads,affectedItems;return regeneratorRuntime.async(function importData$(_context24){while(1){switch(_context24.prev=_context24.next){case 0:data=_ref20.data,password=_ref20.password;_context24.next=3;return regeneratorRuntime.awrap(this.protocolService.payloadsByDecryptingBackupFile({data:data,password:password}));case 3:decryptedPayloads=_context24.sent;validPayloads=decryptedPayloads.filter(function(payload){return!payload.errorDecrypting;});_context24.next=7;return regeneratorRuntime.awrap(this.modelManager.importPayloads(validPayloads));case 7:affectedItems=_context24.sent;this.sync();return _context24.abrupt("return",{affectedItems:affectedItems,errorCount:decryptedPayloads.length-validPayloads.length});case 10:case"end":return _context24.stop();}}},null,this);}/** @public */},{key:"isEphemeralSession",value:function isEphemeralSession(){return this.storageManager.isEphemeralSession();}/** @private */},{key:"lockSyncing",value:function lockSyncing(){this.syncManager.lockSyncing();}/** @private */},{key:"unlockSyncing",value:function unlockSyncing(){this.syncManager.unlockSyncing();}/** @public */},{key:"getSyncStatus",value:function getSyncStatus(){return regeneratorRuntime.async(function getSyncStatus$(_context25){while(1){switch(_context25.prev=_context25.next){case 0:return _context25.abrupt("return",this.syncManager.status);case 1:case"end":return _context25.stop();}}},null,this);}/** @public */},{key:"markAllItemsAsNeedingSync",value:function markAllItemsAsNeedingSync(){var _ref21,alternateUuids,_args26=arguments;return regeneratorRuntime.async(function markAllItemsAsNeedingSync$(_context26){while(1){switch(_context26.prev=_context26.next){case 0:_ref21=_args26.length>0&&_args26[0]!==undefined?_args26[0]:{},alternateUuids=_ref21.alternateUuids;return _context26.abrupt("return",this.syncManager.markAllItemsAsNeedingSync({alternateUuids:alternateUuids}));case 2:case"end":return _context26.stop();}}},null,this);}/** @public */},{key:"sync",value:function sync(options){return regeneratorRuntime.async(function sync$(_context27){while(1){switch(_context27.prev=_context27.next){case 0:return _context27.abrupt("return",this.syncManager.sync(options));case 1:case"end":return _context27.stop();}}},null,this);}/** @public */},{key:"resolveOutOfSync",value:function resolveOutOfSync(){return regeneratorRuntime.async(function resolveOutOfSync$(_context28){while(1){switch(_context28.prev=_context28.next){case 0:return _context28.abrupt("return",this.syncManager.resolveOutOfSync());case 1:case"end":return _context28.stop();}}},null,this);}/** @public */},{key:"setValue",value:function setValue(key,value,mode){return regeneratorRuntime.async(function setValue$(_context29){while(1){switch(_context29.prev=_context29.next){case 0:return _context29.abrupt("return",this.storageManager.setValue(key,value,mode));case 1:case"end":return _context29.stop();}}},null,this);}/** @public */},{key:"getValue",value:function getValue(key,mode){return regeneratorRuntime.async(function getValue$(_context30){while(1){switch(_context30.prev=_context30.next){case 0:return _context30.abrupt("return",this.storageManager.getValue(key,mode));case 1:case"end":return _context30.stop();}}},null,this);}/** @public */},{key:"removeValue",value:function removeValue(key,mode){return regeneratorRuntime.async(function removeValue$(_context31){while(1){switch(_context31.prev=_context31.next){case 0:return _context31.abrupt("return",this.storageManager.removeValue(key,mode));case 1:case"end":return _context31.stop();}}},null,this);}/**
* @public
* Deletes all payloads from storage.
*/},{key:"destroyDatabase",value:function destroyDatabase(){return regeneratorRuntime.async(function destroyDatabase$(_context32){while(1){switch(_context32.prev=_context32.next){case 0:return _context32.abrupt("return",this.application.storageManager.clearAllPayloads());case 1:case"end":return _context32.stop();}}},null,this);}/** @public */},{key:"restart",value:function restart(){return regeneratorRuntime.async(function restart$(_context33){while(1){switch(_context33.prev=_context33.next){case 0:_context33.next=2;return regeneratorRuntime.awrap(this.deinit());case 2:this.dealloced=false;this.constructServices();_context33.next=6;return regeneratorRuntime.awrap(this.prepareForLaunch({callbacks:this.launchCallbacks}));case 6:_context33.next=8;return regeneratorRuntime.awrap(this.launch());case 8:case"end":return _context33.stop();}}},null,this);}/**
* @public
* Destroys the application instance.
*/},{key:"deinit",value:function deinit(){var _iteratorNormalCompletion4,_didIteratorError4,_iteratorError4,_iterator4,_step4,uninstallObserver,_iteratorNormalCompletion5,_didIteratorError5,_iteratorError5,_iterator5,_step5,observer,_iteratorNormalCompletion6,_didIteratorError6,_iteratorError6,_iterator6,_step6,uninstallSubscriber,_iteratorNormalCompletion7,_didIteratorError7,_iteratorError7,_iterator7,_step7,service;return regeneratorRuntime.async(function deinit$(_context34){while(1){switch(_context34.prev=_context34.next){case 0:clearInterval(this.autoSyncInterval);_iteratorNormalCompletion4=true;_didIteratorError4=false;_iteratorError4=undefined;_context34.prev=4;for(_iterator4=this.serviceObservers[Symbol.iterator]();!(_iteratorNormalCompletion4=(_step4=_iterator4.next()).done);_iteratorNormalCompletion4=true){uninstallObserver=_step4.value;uninstallObserver();}_context34.next=12;break;case 8:_context34.prev=8;_context34.t0=_context34["catch"](4);_didIteratorError4=true;_iteratorError4=_context34.t0;case 12:_context34.prev=12;_context34.prev=13;if(!_iteratorNormalCompletion4&&_iterator4.return!=null){_iterator4.return();}case 15:_context34.prev=15;if(!_didIteratorError4){_context34.next=18;break;}throw _iteratorError4;case 18:return _context34.finish(15);case 19:return _context34.finish(12);case 20:_iteratorNormalCompletion5=true;_didIteratorError5=false;_iteratorError5=undefined;_context34.prev=23;for(_iterator5=this.eventHandlers.slice()[Symbol.iterator]();!(_iteratorNormalCompletion5=(_step5=_iterator5.next()).done);_iteratorNormalCompletion5=true){observer=_step5.value;if(observer.autoUnsubscribe){Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["removeFromArray"])(this.eventHandlers,observer);}}_context34.next=31;break;case 27:_context34.prev=27;_context34.t1=_context34["catch"](23);_didIteratorError5=true;_iteratorError5=_context34.t1;case 31:_context34.prev=31;_context34.prev=32;if(!_iteratorNormalCompletion5&&_iterator5.return!=null){_iterator5.return();}case 34:_context34.prev=34;if(!_didIteratorError5){_context34.next=37;break;}throw _iteratorError5;case 37:return _context34.finish(34);case 38:return _context34.finish(31);case 39:_iteratorNormalCompletion6=true;_didIteratorError6=false;_iteratorError6=undefined;_context34.prev=42;for(_iterator6=this.managedSubscribers[Symbol.iterator]();!(_iteratorNormalCompletion6=(_step6=_iterator6.next()).done);_iteratorNormalCompletion6=true){uninstallSubscriber=_step6.value;uninstallSubscriber();}_context34.next=50;break;case 46:_context34.prev=46;_context34.t2=_context34["catch"](42);_didIteratorError6=true;_iteratorError6=_context34.t2;case 50:_context34.prev=50;_context34.prev=51;if(!_iteratorNormalCompletion6&&_iterator6.return!=null){_iterator6.return();}case 53:_context34.prev=53;if(!_didIteratorError6){_context34.next=56;break;}throw _iteratorError6;case 56:return _context34.finish(53);case 57:return _context34.finish(50);case 58:_iteratorNormalCompletion7=true;_didIteratorError7=false;_iteratorError7=undefined;_context34.prev=61;_iterator7=this.services[Symbol.iterator]();case 63:if(_iteratorNormalCompletion7=(_step7=_iterator7.next()).done){_context34.next=71;break;}service=_step7.value;if(!service.deinit){_context34.next=68;break;}_context34.next=68;return regeneratorRuntime.awrap(service.deinit());case 68:_iteratorNormalCompletion7=true;_context34.next=63;break;case 71:_context34.next=77;break;case 73:_context34.prev=73;_context34.t3=_context34["catch"](61);_didIteratorError7=true;_iteratorError7=_context34.t3;case 77:_context34.prev=77;_context34.prev=78;if(!_iteratorNormalCompletion7&&_iterator7.return!=null){_iterator7.return();}case 80:_context34.prev=80;if(!_didIteratorError7){_context34.next=83;break;}throw _iteratorError7;case 83:return _context34.finish(80);case 84:return _context34.finish(77);case 85:this.clearServices();this.dealloced=true;case 87:case"end":return _context34.stop();}}},null,this,[[4,8,12,20],[13,,15,19],[23,27,31,39],[32,,34,38],[42,46,50,58],[51,,53,57],[61,73,77,85],[78,,80,84]]);}/**
* @public
* Allows your PureService subclass to receive `deinit` event to unload observers.
*/},{key:"registerService",value:function registerService(service){this.services.push(service);}/**
* @public
* @param mergeLocal Whether to merge existing offline data into account. If false,
* any pre-existing data will be fully deleted upon success.
*/},{key:"register",value:function register(_ref22){var email,password,ephemeral,mergeLocal,result;return regeneratorRuntime.async(function register$(_context35){while(1){switch(_context35.prev=_context35.next){case 0:email=_ref22.email,password=_ref22.password,ephemeral=_ref22.ephemeral,mergeLocal=_ref22.mergeLocal;this.lockSyncing();_context35.next=4;return regeneratorRuntime.awrap(this.sessionManager.register({email:email,password:password}));case 4:result=_context35.sent;this.unlockSyncing();if(result.response.error){_context35.next=19;break;}_context35.next=9;return regeneratorRuntime.awrap(this.keyManager.setNewRootKey({key:result.rootKey,keyParams:result.keyParams}));case 9:_context35.next=11;return regeneratorRuntime.awrap(this.storageManager.setPersistencePolicy(ephemeral?_Services__WEBPACK_IMPORTED_MODULE_4__["StoragePersistencePolicies"].Ephemeral:_Services__WEBPACK_IMPORTED_MODULE_4__["StoragePersistencePolicies"].Default));case 11:if(mergeLocal){_context35.next=15;break;}this.modelManager.removeAllItemsFromMemory();_context35.next=15;return regeneratorRuntime.awrap(this.storageManager.clearAllPayloads());case 15:this.notifyEvent(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationEvents"].SignedIn);_context35.next=18;return regeneratorRuntime.awrap(this.syncManager.sync({mode:_Services__WEBPACK_IMPORTED_MODULE_4__["SYNC_MODE_DOWNLOAD_FIRST"]}));case 18:this.protocolService.decryptErroredItems();case 19:return _context35.abrupt("return",result.response);case 20:case"end":return _context35.stop();}}},null,this);}/**
* @public
* @param mergeLocal Whether to merge existing offline data into account. If false,
* any pre-existing data will be fully deleted upon success.
*/},{key:"signIn",value:function signIn(_ref23){var email,password,strict,ephemeral,mfaKeyPath,mfaCode,_ref23$mergeLocal,mergeLocal,result;return regeneratorRuntime.async(function signIn$(_context36){while(1){switch(_context36.prev=_context36.next){case 0:email=_ref23.email,password=_ref23.password,strict=_ref23.strict,ephemeral=_ref23.ephemeral,mfaKeyPath=_ref23.mfaKeyPath,mfaCode=_ref23.mfaCode,_ref23$mergeLocal=_ref23.mergeLocal,mergeLocal=_ref23$mergeLocal===void 0?true:_ref23$mergeLocal;/** Prevent a timed sync from occuring while signing in. */this.notifyEvent(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationEvents"].WillSignIn);this.lockSyncing();_context36.next=5;return regeneratorRuntime.awrap(this.sessionManager.signIn({email:email,password:password,strict:strict,mfaKeyPath:mfaKeyPath,mfaCode:mfaCode}));case 5:result=_context36.sent;this.unlockSyncing();if(result.response.error){_context36.next=20;break;}_context36.next=10;return regeneratorRuntime.awrap(this.keyManager.setNewRootKey({key:result.rootKey,keyParams:result.keyParams}));case 10:_context36.next=12;return regeneratorRuntime.awrap(this.storageManager.setPersistencePolicy(ephemeral?_Services__WEBPACK_IMPORTED_MODULE_4__["StoragePersistencePolicies"].Ephemeral:_Services__WEBPACK_IMPORTED_MODULE_4__["StoragePersistencePolicies"].Default));case 12:if(mergeLocal){_context36.next=16;break;}this.modelManager.removeAllItemsFromMemory();_context36.next=16;return regeneratorRuntime.awrap(this.storageManager.clearAllPayloads());case 16:this.notifyEvent(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationEvents"].SignedIn);_context36.next=19;return regeneratorRuntime.awrap(this.syncManager.sync({mode:_Services__WEBPACK_IMPORTED_MODULE_4__["SYNC_MODE_DOWNLOAD_FIRST"]}));case 19:this.protocolService.decryptErroredItems();case 20:return _context36.abrupt("return",result.response);case 21:case"end":return _context36.stop();}}},null,this);}/** @public */},{key:"changePassword",value:function changePassword(_ref24){var email,currentPassword,newPassword,rotateItemsKey,currentKeyParams,result,newKeyParams,versionUpgraded;return regeneratorRuntime.async(function changePassword$(_context37){while(1){switch(_context37.prev=_context37.next){case 0:email=_ref24.email,currentPassword=_ref24.currentPassword,newPassword=_ref24.newPassword,rotateItemsKey=_ref24.rotateItemsKey;_context37.next=3;return regeneratorRuntime.awrap(this.keyManager.getRootKeyParams());case 3:currentKeyParams=_context37.sent;this.lockSyncing();_context37.next=7;return regeneratorRuntime.awrap(this.sessionManager.changePassword({email:email,currentPassword:currentPassword,currentKeyParams:currentKeyParams,newPassword:newPassword}));case 7:result=_context37.sent;this.unlockSyncing();if(result.response.error){_context37.next=19;break;}_context37.next=12;return regeneratorRuntime.awrap(this.keyManager.setNewRootKey({key:result.rootKey,keyParams:result.keyParams}));case 12:newKeyParams=result.keyParams;versionUpgraded=newKeyParams.version!==currentKeyParams.version;if(!(rotateItemsKey||versionUpgraded)){_context37.next=17;break;}_context37.next=17;return regeneratorRuntime.awrap(this.itemsKeyManager.createNewDefaultItemsKey());case 17:_context37.next=19;return regeneratorRuntime.awrap(this.syncManager.sync());case 19:return _context37.abrupt("return",result.response);case 20:case"end":return _context37.stop();}}},null,this);}/** @public */},{key:"signOut",value:function signOut(){var _ref25,dontClearData,_args38=arguments;return regeneratorRuntime.async(function signOut$(_context38){while(1){switch(_context38.prev=_context38.next){case 0:_ref25=_args38.length>0&&_args38[0]!==undefined?_args38[0]:{},dontClearData=_ref25.dontClearData;_context38.next=3;return regeneratorRuntime.awrap(this.sessionManager.signOut());case 3:_context38.next=5;return regeneratorRuntime.awrap(this.syncManager.handleSignOut());case 5:_context38.next=7;return regeneratorRuntime.awrap(this.modelManager.handleSignOut());case 7:_context38.next=9;return regeneratorRuntime.awrap(this.keyManager.clearLocalKeyState());case 9:if(dontClearData){_context38.next=12;break;}_context38.next=12;return regeneratorRuntime.awrap(this.storageManager.clearAllData());case 12:_context38.next=14;return regeneratorRuntime.awrap(this.syncManager.sync());case 14:this.notifyEvent(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationEvents"].SignedOut);case 15:case"end":return _context38.stop();}}},null,this);}/** @public */},{key:"validateAccountPassword",value:function validateAccountPassword(_ref26){var password;return regeneratorRuntime.async(function validateAccountPassword$(_context39){while(1){switch(_context39.prev=_context39.next){case 0:password=_ref26.password;return _context39.abrupt("return",this.keyManager.validateAccountPassword(password));case 2:case"end":return _context39.stop();}}},null,this);}/** @public */},{key:"hasPasscode",value:function hasPasscode(){return regeneratorRuntime.async(function hasPasscode$(_context40){while(1){switch(_context40.prev=_context40.next){case 0:return _context40.abrupt("return",this.keyManager.hasRootKeyWrapper());case 1:case"end":return _context40.stop();}}},null,this);}/** @public */},{key:"isPasscodeLocked",value:function isPasscodeLocked(){return regeneratorRuntime.async(function isPasscodeLocked$(_context41){while(1){switch(_context41.prev=_context41.next){case 0:return _context41.abrupt("return",this.keyManager.rootKeyNeedsUnwrapping());case 1:case"end":return _context41.stop();}}},null,this);}/** @public */},{key:"passcodeLock",value:function passcodeLock(){return regeneratorRuntime.async(function passcodeLock$(_context42){while(1){switch(_context42.prev=_context42.next){case 0:return _context42.abrupt("return",this.restart());case 1:case"end":return _context42.stop();}}},null,this);}/** @public */},{key:"setPasscode",value:function setPasscode(passcode){var identifier,_ref27,key,keyParams;return regeneratorRuntime.async(function setPasscode$(_context43){while(1){switch(_context43.prev=_context43.next){case 0:_context43.next=2;return regeneratorRuntime.awrap(this.protocolService.crypto.generateUUID());case 2:identifier=_context43.sent;_context43.next=5;return regeneratorRuntime.awrap(this.protocolService.createRootKey({identifier:identifier,password:passcode}));case 5:_ref27=_context43.sent;key=_ref27.key;keyParams=_ref27.keyParams;_context43.next=10;return regeneratorRuntime.awrap(this.keyManager.setNewRootKeyWrapper({wrappingKey:key,keyParams:keyParams}));case 10:_context43.next=12;return regeneratorRuntime.awrap(this.syncManager.sync());case 12:case"end":return _context43.stop();}}},null,this);}/** @public */},{key:"removePasscode",value:function removePasscode(){return regeneratorRuntime.async(function removePasscode$(_context44){while(1){switch(_context44.prev=_context44.next){case 0:_context44.next=2;return regeneratorRuntime.awrap(this.keyManager.removeRootKeyWrapper());case 2:case"end":return _context44.stop();}}},null,this);}/** @public */},{key:"changePasscode",value:function changePasscode(passcode){return regeneratorRuntime.async(function changePasscode$(_context45){while(1){switch(_context45.prev=_context45.next){case 0:_context45.next=2;return regeneratorRuntime.awrap(this.removePasscode());case 2:return _context45.abrupt("return",this.setPasscode(passcode));case 3:case"end":return _context45.stop();}}},null,this);}/** @public */},{key:"setStorageEncryptionPolicy",value:function setStorageEncryptionPolicy(encryptionPolicy){return regeneratorRuntime.async(function setStorageEncryptionPolicy$(_context46){while(1){switch(_context46.prev=_context46.next){case 0:_context46.next=2;return regeneratorRuntime.awrap(this.storageManager.setEncryptionPolicy(encryptionPolicy));case 2:return _context46.abrupt("return",this.syncManager.repersistAllItems());case 3:case"end":return _context46.stop();}}},null,this);}/** @public */},{key:"generateUuid",value:function generateUuid(){return regeneratorRuntime.async(function generateUuid$(_context47){while(1){switch(_context47.prev=_context47.next){case 0:return _context47.abrupt("return",this.protocolService.crypto.generateUUID());case 1:case"end":return _context47.stop();}}},null,this);}/**
* @public
* Dynamically change the device interface, i.e when Desktop wants to override
* default web interface.
*/},{key:"changeDeviceInterface",value:function changeDeviceInterface(deviceInterface){return regeneratorRuntime.async(function changeDeviceInterface$(_context48){while(1){switch(_context48.prev=_context48.next){case 0:this.deviceInterface=deviceInterface;this.keyManager.setDeviceInterface(this.deviceInterface);case 2:case"end":return _context48.stop();}}},null,this);}/**
* @private
*/ /** @private */},{key:"constructServices",value:function constructServices(){this.createModelManager();this.createProtocolService(this.modelManager);this.createMigrationService();this.createAlertManager();this.createHttpManager();this.createStorageManager();this.createApiService();this.createSessionManager();this.createSyncManager();this.createItemsKeyManager();this.createKeyManager();this.protocolService.setKeyManager(this.keyManager);this.protocolService.setItemsKeyManager(this.itemsKeyManager);this.itemsKeyManager.setKeyManager(this.keyManager);this.keyManager.setDeviceInterface(this.deviceInterface);this.createDeviceAuthService();this.createSingletonManager();this.createComponentManager();this.createPrivilegesManager();this.createHistoryManager();this.createActionsManager();}/** @private */},{key:"clearServices",value:function clearServices(){this.migrationService=null;this.alertManager=null;this.httpManager=null;this.modelManager=null;this.protocolService=null;this.storageManager=null;this.apiService=null;this.sessionManager=null;this.syncManager=null;this.keyManager=null;this.itemsKeyManager=null;this.deviceAuthService=null;this.singletonManager=null;this.componentManager=null;this.privilegesManager=null;this.actionsManager=null;}},{key:"createMigrationService",value:function createMigrationService(){this.migrationService=new(this.getClass(_Services__WEBPACK_IMPORTED_MODULE_4__["SNMigrationService"]))({application:this,challengeResponder:this.getMigrationChallengeResponder()});this.services.push(this.migrationService);}},{key:"createAlertManager",value:function createAlertManager(){if(this.shouldSkipClass(_Services__WEBPACK_IMPORTED_MODULE_4__["SNAlertManager"])){return;}this.alertManager=new(this.getClass(_Services__WEBPACK_IMPORTED_MODULE_4__["SNAlertManager"]))({deviceInterface:this.deviceInterface});this.services.push(this.alertManager);}},{key:"createApiService",value:function createApiService(){this.apiService=new(this.getClass(_Services__WEBPACK_IMPORTED_MODULE_4__["SNApiService"]))({storageManager:this.storageManager,httpManager:this.httpManager,host:this.host});this.services.push(this.apiService);}},{key:"createComponentManager",value:function createComponentManager(){if(this.shouldSkipClass(_Services__WEBPACK_IMPORTED_MODULE_4__["SNComponentManager"])){return;}this.componentManager=new(this.getClass(_Services__WEBPACK_IMPORTED_MODULE_4__["SNComponentManager"]))({modelManager:this.modelManager,syncManager:this.syncManager,alertManager:this.alertManager,timeout:this.deviceInterface.timeout,environment:this.environment,platform:this.platform});this.services.push(this.componentManager);}},{key:"createHttpManager",value:function createHttpManager(){this.httpManager=new(this.getClass(_Services__WEBPACK_IMPORTED_MODULE_4__["SNHttpManager"]))();this.services.push(this.httpManager);}},{key:"createKeyManager",value:function createKeyManager(){this.keyManager=new(this.getClass(_Services__WEBPACK_IMPORTED_MODULE_4__["SNKeyManager"]))({modelManager:this.modelManager,storageManager:this.storageManager,protocolService:this.protocolService,itemsKeyManager:this.itemsKeyManager});this.services.push(this.keyManager);}},{key:"createItemsKeyManager",value:function createItemsKeyManager(){this.itemsKeyManager=new(this.getClass(_Services__WEBPACK_IMPORTED_MODULE_4__["ItemsKeyManager"]))({modelManager:this.modelManager,syncManager:this.syncManager,protocolService:this.protocolService});this.services.push(this.itemsKeyManager);}},{key:"createModelManager",value:function createModelManager(){this.modelManager=new(this.getClass(_Services__WEBPACK_IMPORTED_MODULE_4__["SNModelManager"]))({timeout:this.deviceInterface.timeout});this.services.push(this.modelManager);}},{key:"createSingletonManager",value:function createSingletonManager(){this.singletonManager=new(this.getClass(_Services__WEBPACK_IMPORTED_MODULE_4__["SNSingletonManager"]))({modelManager:this.modelManager,syncManager:this.syncManager});this.services.push(this.singletonManager);}},{key:"createStorageManager",value:function createStorageManager(){this.storageManager=new(this.getClass(_Services__WEBPACK_IMPORTED_MODULE_4__["SNStorageManager"]))({protocolService:this.protocolService,namespace:this.namespace,deviceInterface:this.deviceInterface});this.services.push(this.storageManager);}},{key:"createProtocolService",value:function createProtocolService(modelManager){this.protocolService=new(this.getClass(_Services__WEBPACK_IMPORTED_MODULE_4__["SNProtocolService"]))({modelManager:modelManager,crypto:this.crypto});this.services.push(this.protocolService);}},{key:"createSessionManager",value:function createSessionManager(){this.sessionManager=new(this.getClass(_Services__WEBPACK_IMPORTED_MODULE_4__["SNSessionManager"]))({storageManager:this.storageManager,alertManager:this.alertManager,protocolService:this.protocolService,apiService:this.apiService,timeout:this.deviceInterface.timeout});this.services.push(this.sessionManager);}},{key:"createSyncManager",value:function createSyncManager(){var _this5=this;this.syncManager=new(this.getClass(_Services__WEBPACK_IMPORTED_MODULE_4__["SNSyncManager"]))({modelManager:this.modelManager,storageManager:this.storageManager,sessionManager:this.sessionManager,protocolService:this.protocolService,apiService:this.apiService,interval:this.deviceInterface.interval});var uninstall=this.syncManager.addEventObserver(function _callee3(eventName){return regeneratorRuntime.async(function _callee3$(_context49){while(1){switch(_context49.prev=_context49.next){case 0:if(!(eventName===_Lib__WEBPACK_IMPORTED_MODULE_3__["SyncEvents"].FullSyncCompleted)){_context49.next=5;break;}_context49.next=3;return regeneratorRuntime.awrap(_this5.notifyEvent(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationEvents"].CompletedSync));case 3:_context49.next=18;break;case 5:if(!(eventName===_Lib__WEBPACK_IMPORTED_MODULE_3__["SyncEvents"].LocalDataLoaded)){_context49.next=10;break;}_context49.next=8;return regeneratorRuntime.awrap(_this5.notifyEvent(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationEvents"].LoadedLocalData));case 8:_context49.next=18;break;case 10:if(!(eventName===_Lib__WEBPACK_IMPORTED_MODULE_3__["SyncEvents"].SyncTakingTooLong)){_context49.next=15;break;}_context49.next=13;return regeneratorRuntime.awrap(_this5.notifyEvent(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationEvents"].HighLatencySync));case 13:_context49.next=18;break;case 15:if(!(eventName===_Lib__WEBPACK_IMPORTED_MODULE_3__["SyncEvents"].SyncError)){_context49.next=18;break;}_context49.next=18;return regeneratorRuntime.awrap(_this5.notifyEvent(_Lib__WEBPACK_IMPORTED_MODULE_3__["ApplicationEvents"].FailedSync));case 18:case"end":return _context49.stop();}}});});this.serviceObservers.push(uninstall);this.services.push(this.syncManager);}},{key:"createDeviceAuthService",value:function createDeviceAuthService(){this.deviceAuthService=new(this.getClass(_Services__WEBPACK_IMPORTED_MODULE_4__["DeviceAuthService"]))({storageManager:this.storageManager,protocolService:this.protocolService,keyManager:this.keyManager});this.services.push(this.deviceAuthService);}},{key:"createPrivilegesManager",value:function createPrivilegesManager(){this.privilegesManager=new(this.getClass(_Services__WEBPACK_IMPORTED_MODULE_4__["SNPrivilegesManager"]))({storageManager:this.storageManager,keyManager:this.keyManager,modelManager:this.modelManager,syncManager:this.syncManager,sessionManager:this.sessionManager,singletonManager:this.singletonManager});this.services.push(this.privilegesManager);}},{key:"createHistoryManager",value:function createHistoryManager(){this.historyManager=new(this.getClass(_Services__WEBPACK_IMPORTED_MODULE_4__["SNHistoryManager"]))({storageManager:this.storageManager,modelManager:this.modelManager,contentTypes:[_Models_content_types__WEBPACK_IMPORTED_MODULE_1__["ContentTypes"].Note],timeout:this.deviceInterface.timeout});this.services.push(this.historyManager);}},{key:"createActionsManager",value:function createActionsManager(){this.actionsManager=new(this.getClass(_Services__WEBPACK_IMPORTED_MODULE_4__["SNActionsManager"]))({httpManager:this.httpManager,modelManager:this.modelManager,syncManager:this.syncManager,deviceInterface:this.deviceInterface});this.services.push(this.actionsManager);}},{key:"shouldSkipClass",value:function shouldSkipClass(classCandidate){return this.skipClasses&&this.skipClasses.includes(classCandidate);}},{key:"getClass",value:function getClass(base){var swapClass=this.swapClasses&&this.swapClasses.find(function(candidate){return candidate.swap===base;});if(swapClass){return swapClass.with;}else{return base;}}}]);return SNApplication;}();/***/},/***/"./lib/challenges.js":/*!***************************!*\
!*** ./lib/challenges.js ***!
\***************************/ /*! exports provided: Challenges */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"Challenges",function(){return Challenges;});var Challenges={LocalPasscode:1,AccountPassword:2,Biometric:3};/***/},/***/"./lib/device_interface.js":/*!*********************************!*\
!*** ./lib/device_interface.js ***!
\*********************************/ /*! exports provided: DeviceInterface */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"DeviceInterface",function(){return DeviceInterface;});/* harmony import */var _Lib_utils__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Lib/utils */"./lib/utils.js");function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0&&arguments[0]!==undefined?arguments[0]:{},namespace=_ref.namespace,timeout=_ref.timeout,interval=_ref.interval;_classCallCheck(this,DeviceInterface);if(!timeout||!interval){throw"'timeout' and 'interval' are required to initialize device interface.";}this.namespace=namespace;this.timeout=timeout||setTimeout.bind(Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["getGlobalScope"])());this.interval=interval||setInterval.bind(Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["getGlobalScope"])());}_createClass(DeviceInterface,[{key:"getRawStorageValue",value:function getRawStorageValue(key){return regeneratorRuntime.async(function getRawStorageValue$(_context){while(1){switch(_context.prev=_context.next){case 0:throw'Must override DeviceInterface.getRawStorageValue';case 1:case"end":return _context.stop();}}});}},{key:"getJsonParsedStorageValue",value:function getJsonParsedStorageValue(key){var value;return regeneratorRuntime.async(function getJsonParsedStorageValue$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:_context2.next=2;return regeneratorRuntime.awrap(this.getRawStorageValue(key));case 2:value=_context2.sent;return _context2.abrupt("return",value?JSON.parse(value):value);case 4:case"end":return _context2.stop();}}},null,this);}},{key:"getAllRawStorageKeyValues",value:function getAllRawStorageKeyValues(){return regeneratorRuntime.async(function getAllRawStorageKeyValues$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:throw'Must override DeviceInterface.getAllRawStorageKeyValues';case 1:case"end":return _context3.stop();}}});}},{key:"setRawStorageValue",value:function setRawStorageValue(key,value){return regeneratorRuntime.async(function setRawStorageValue$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:throw'Must override DeviceInterface.setRawStorageValue';case 1:case"end":return _context4.stop();}}});}},{key:"removeRawStorageValue",value:function removeRawStorageValue(key){return regeneratorRuntime.async(function removeRawStorageValue$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:throw'Must override DeviceInterface.removeRawStorageValue';case 1:case"end":return _context5.stop();}}});}},{key:"removeAllRawStorageValues",value:function removeAllRawStorageValues(){return regeneratorRuntime.async(function removeAllRawStorageValues$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:throw'Must override DeviceInterface.removeAllRawStorageValues';case 1:case"end":return _context6.stop();}}});}},{key:"openDatabase",value:function openDatabase(){return regeneratorRuntime.async(function openDatabase$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:throw'Must override DeviceInterface.openDatabase';case 1:case"end":return _context7.stop();}}});}},{key:"getAllRawDatabasePayloads",value:function getAllRawDatabasePayloads(){return regeneratorRuntime.async(function getAllRawDatabasePayloads$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:throw'Must override DeviceInterface.getAllRawDatabasePayloads';case 1:case"end":return _context8.stop();}}});}},{key:"saveRawDatabasePayload",value:function saveRawDatabasePayload(payload){return regeneratorRuntime.async(function saveRawDatabasePayload$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:throw'Must override DeviceInterface.saveRawDatabasePayload';case 1:case"end":return _context9.stop();}}});}},{key:"saveRawDatabasePayloads",value:function saveRawDatabasePayloads(payloads){return regeneratorRuntime.async(function saveRawDatabasePayloads$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:throw'Must override DeviceInterface.saveRawDatabasePayloads';case 1:case"end":return _context10.stop();}}});}},{key:"removeRawDatabasePayloadWithId",value:function removeRawDatabasePayloadWithId(id){return regeneratorRuntime.async(function removeRawDatabasePayloadWithId$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:throw'Must override DeviceInterface.removeRawDatabasePayloadWithId';case 1:case"end":return _context11.stop();}}});}},{key:"removeAllRawDatabasePayloads",value:function removeAllRawDatabasePayloads(){return regeneratorRuntime.async(function removeAllRawDatabasePayloads$(_context12){while(1){switch(_context12.prev=_context12.next){case 0:throw'Must override DeviceInterface.removeAllRawDatabasePayloads';case 1:case"end":return _context12.stop();}}});}},{key:"getRawKeychainValue",value:function getRawKeychainValue(){return regeneratorRuntime.async(function getRawKeychainValue$(_context13){while(1){switch(_context13.prev=_context13.next){case 0:throw'Must override DeviceInterface.getRawKeychainValue';case 1:case"end":return _context13.stop();}}});}},{key:"setKeychainValue",value:function setKeychainValue(value){return regeneratorRuntime.async(function setKeychainValue$(_context14){while(1){switch(_context14.prev=_context14.next){case 0:throw'Must override DeviceInterface.setKeychainValue';case 1:case"end":return _context14.stop();}}});}},{key:"clearKeychainValue",value:function clearKeychainValue(){return regeneratorRuntime.async(function clearKeychainValue$(_context15){while(1){switch(_context15.prev=_context15.next){case 0:throw'Must override DeviceInterface.clearKeychainValue';case 1:case"end":return _context15.stop();}}});}}]);return DeviceInterface;}();/***/},/***/"./lib/events.js":/*!***********************!*\
!*** ./lib/events.js ***!
\***********************/ /*! exports provided: ApplicationEvents, SyncEvents */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"ApplicationEvents",function(){return ApplicationEvents;});/* harmony import */var _Services_sync_events__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Services/sync/events */"./lib/services/sync/events.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SyncEvents",function(){return _Services_sync_events__WEBPACK_IMPORTED_MODULE_0__["SyncEvents"];});var ApplicationEvents={WillSignIn:1,SignedIn:2,SignedOut:3,LoadedLocalData:4,CompletedSync:5,FailedSync:6,HighLatencySync:7,EnteredOutOfSync:8,ExitedOutOfSync:9,/** The application has finished it `prepareForLaunch` state and is now ready for unlock */ApplicationStarted:10,/** The applicaiton is fully unlocked and ready for i/o */ApplicationUnlocked:11,PasscodeStatusChanged:12};/***/},/***/"./lib/index.js":/*!**********************!*\
!*** ./lib/index.js ***!
\**********************/ /*! exports provided: DEFAULT_APP_DOMAIN, ApplicationEvents, SyncEvents, ApplicationStages, Environments, Platforms, isEnvironmentWebOrDesktop, isEnvironmentMobile, Challenges, StorageKeys, namespacedKey, RAW_STORAGE_KEY_LAST_MIGRATION_TIMESTAMP */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"DEFAULT_APP_DOMAIN",function(){return DEFAULT_APP_DOMAIN;});/* harmony import */var _Lib_events__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Lib/events */"./lib/events.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"ApplicationEvents",function(){return _Lib_events__WEBPACK_IMPORTED_MODULE_0__["ApplicationEvents"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SyncEvents",function(){return _Lib_events__WEBPACK_IMPORTED_MODULE_0__["SyncEvents"];});/* harmony import */var _Lib_stages__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Lib/stages */"./lib/stages.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"ApplicationStages",function(){return _Lib_stages__WEBPACK_IMPORTED_MODULE_1__["ApplicationStages"];});/* harmony import */var _Lib_platforms__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! @Lib/platforms */"./lib/platforms.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"Environments",function(){return _Lib_platforms__WEBPACK_IMPORTED_MODULE_2__["Environments"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"Platforms",function(){return _Lib_platforms__WEBPACK_IMPORTED_MODULE_2__["Platforms"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"isEnvironmentWebOrDesktop",function(){return _Lib_platforms__WEBPACK_IMPORTED_MODULE_2__["isEnvironmentWebOrDesktop"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"isEnvironmentMobile",function(){return _Lib_platforms__WEBPACK_IMPORTED_MODULE_2__["isEnvironmentMobile"];});/* harmony import */var _Lib_challenges__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! @Lib/challenges */"./lib/challenges.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"Challenges",function(){return _Lib_challenges__WEBPACK_IMPORTED_MODULE_3__["Challenges"];});/* harmony import */var _Lib_storage_keys__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(/*! @Lib/storage_keys */"./lib/storage_keys.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"StorageKeys",function(){return _Lib_storage_keys__WEBPACK_IMPORTED_MODULE_4__["StorageKeys"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"namespacedKey",function(){return _Lib_storage_keys__WEBPACK_IMPORTED_MODULE_4__["namespacedKey"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"RAW_STORAGE_KEY_LAST_MIGRATION_TIMESTAMP",function(){return _Lib_storage_keys__WEBPACK_IMPORTED_MODULE_4__["RAW_STORAGE_KEY_LAST_MIGRATION_TIMESTAMP"];});var DEFAULT_APP_DOMAIN='org.standardnotes.sn';/***/},/***/"./lib/main.js":/*!*********************!*\
!*** ./lib/main.js ***!
\*********************/ /*! exports provided: SNApplication, SNProtocolService, SNProtocolOperator001, SNProtocolOperator002, SNProtocolOperator003, SNProtocolOperator004, DeviceInterface, SFItem, SNItemsKey, SFPredicate, SNNote, SNTag, SNSmartTag, SNActionsExtension, Action, SNTheme, SNEncryptedStorage, SNMfa, SNServerExtension, SNComponent, SNEditor, SNComponentManager, HistorySession, ItemHistory, ItemHistoryEntry, SFPrivileges, SNWebCrypto, SNReactNativeCrypto, SNModelManager, SNHttpManager, DeviceAuthService, ChallengeResponse, PureService, SNStorageManager, StoragePersistencePolicies, StorageEncryptionPolicies, StorageValueModes, Challenges, SNSyncManager, TIMING_STRATEGY_RESOLVE_ON_NEXT, TIMING_STRATEGY_FORCE_SPAWN_NEW, SNSessionManager, SNMigrationService, SNAlertManager, SNHistoryManager, SNPrivilegesManager, SNSingletonManager, SNKeyManager, KEY_MODE_ROOT_KEY_NONE, KEY_MODE_ROOT_KEY_ONLY, KEY_MODE_ROOT_KEY_PLUS_WRAPPER, KEY_MODE_WRAPPER_ONLY, SNApiService, findInArray, isNullOrUndefined, deepMerge, extendArray, removeFromIndex, subtractFromArray, arrayByDifference, uniqCombineObjArrays, greaterOfTwoDates, getGlobalScope, Uuid, EncryptionIntents, isLocalStorageIntent, isFileIntent, isDecryptedIntent, intentRequiresEncryption, ContentTypes, ApplicationEvents, Environments, Platforms, isEnvironmentWebOrDesktop, isEnvironmentMobile, platformFromString, SyncEvents, SNPureItemPayload, SNStorageItemPayload, PayloadCollection, CreateMaxPayloadFromAnyObject, CreateSourcedPayloadFromObject, PayloadSources, isPayloadSourceRetrieved, PayloadFormats, StorageKeys, BaseMigration, ProtectedActions, PrivilegeCredentials, PRIVILEGE_SESSION_LENGTH_NONE, PRIVILEGE_SESSION_LENGTH_FIVE_MINUTES, PRIVILEGE_SESSION_LENGTH_ONE_HOUR, PRIVILEGE_SESSION_LENGTH_ONE_WEEK */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony import */var _Lib_application__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Lib/application */"./lib/application.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNApplication",function(){return _Lib_application__WEBPACK_IMPORTED_MODULE_0__["SNApplication"];});/* harmony import */var _Services_protocol_service__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Services/protocol_service */"./lib/services/protocol_service.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNProtocolService",function(){return _Services_protocol_service__WEBPACK_IMPORTED_MODULE_1__["SNProtocolService"];});/* harmony import */var _Protocol_versions_001_operator_001__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! @Protocol/versions/001/operator_001 */"./lib/protocol/versions/001/operator_001.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNProtocolOperator001",function(){return _Protocol_versions_001_operator_001__WEBPACK_IMPORTED_MODULE_2__["SNProtocolOperator001"];});/* harmony import */var _Protocol_versions_002_operator_002__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! @Protocol/versions/002/operator_002 */"./lib/protocol/versions/002/operator_002.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNProtocolOperator002",function(){return _Protocol_versions_002_operator_002__WEBPACK_IMPORTED_MODULE_3__["SNProtocolOperator002"];});/* harmony import */var _Protocol_versions_003_operator_003__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(/*! @Protocol/versions/003/operator_003 */"./lib/protocol/versions/003/operator_003.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNProtocolOperator003",function(){return _Protocol_versions_003_operator_003__WEBPACK_IMPORTED_MODULE_4__["SNProtocolOperator003"];});/* harmony import */var _Protocol_versions_004_operator_004__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__(/*! @Protocol/versions/004/operator_004 */"./lib/protocol/versions/004/operator_004.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNProtocolOperator004",function(){return _Protocol_versions_004_operator_004__WEBPACK_IMPORTED_MODULE_5__["SNProtocolOperator004"];});/* harmony import */var _Lib_device_interface__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__(/*! @Lib/device_interface */"./lib/device_interface.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"DeviceInterface",function(){return _Lib_device_interface__WEBPACK_IMPORTED_MODULE_6__["DeviceInterface"];});/* harmony import */var _models__WEBPACK_IMPORTED_MODULE_7__=__webpack_require__(/*! ./models */"./lib/models/index.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SFItem",function(){return _models__WEBPACK_IMPORTED_MODULE_7__["SFItem"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNItemsKey",function(){return _models__WEBPACK_IMPORTED_MODULE_7__["SNItemsKey"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SFPredicate",function(){return _models__WEBPACK_IMPORTED_MODULE_7__["SFPredicate"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNNote",function(){return _models__WEBPACK_IMPORTED_MODULE_7__["SNNote"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNTag",function(){return _models__WEBPACK_IMPORTED_MODULE_7__["SNTag"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNSmartTag",function(){return _models__WEBPACK_IMPORTED_MODULE_7__["SNSmartTag"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNActionsExtension",function(){return _models__WEBPACK_IMPORTED_MODULE_7__["SNActionsExtension"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"Action",function(){return _models__WEBPACK_IMPORTED_MODULE_7__["Action"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNTheme",function(){return _models__WEBPACK_IMPORTED_MODULE_7__["SNTheme"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNEncryptedStorage",function(){return _models__WEBPACK_IMPORTED_MODULE_7__["SNEncryptedStorage"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNMfa",function(){return _models__WEBPACK_IMPORTED_MODULE_7__["SNMfa"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNServerExtension",function(){return _models__WEBPACK_IMPORTED_MODULE_7__["SNServerExtension"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNComponent",function(){return _models__WEBPACK_IMPORTED_MODULE_7__["SNComponent"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNEditor",function(){return _models__WEBPACK_IMPORTED_MODULE_7__["SNEditor"];});/* harmony import */var _services_component_manager__WEBPACK_IMPORTED_MODULE_8__=__webpack_require__(/*! ./services/component_manager */"./lib/services/component_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNComponentManager",function(){return _services_component_manager__WEBPACK_IMPORTED_MODULE_8__["SNComponentManager"];});/* harmony import */var _Services_history_history_session__WEBPACK_IMPORTED_MODULE_9__=__webpack_require__(/*! @Services/history/history_session */"./lib/services/history/history_session.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"HistorySession",function(){return _Services_history_history_session__WEBPACK_IMPORTED_MODULE_9__["HistorySession"];});/* harmony import */var _Services_history_item_history__WEBPACK_IMPORTED_MODULE_10__=__webpack_require__(/*! @Services/history/item_history */"./lib/services/history/item_history.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"ItemHistory",function(){return _Services_history_item_history__WEBPACK_IMPORTED_MODULE_10__["ItemHistory"];});/* harmony import */var _Services_history_item_history_entry__WEBPACK_IMPORTED_MODULE_11__=__webpack_require__(/*! @Services/history/item_history_entry */"./lib/services/history/item_history_entry.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"ItemHistoryEntry",function(){return _Services_history_item_history_entry__WEBPACK_IMPORTED_MODULE_11__["ItemHistoryEntry"];});/* harmony import */var _models_privileges_privileges__WEBPACK_IMPORTED_MODULE_12__=__webpack_require__(/*! ./models/privileges/privileges */"./lib/models/privileges/privileges.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SFPrivileges",function(){return _models_privileges_privileges__WEBPACK_IMPORTED_MODULE_12__["SFPrivileges"];});/* harmony import */var sncrypto__WEBPACK_IMPORTED_MODULE_13__=__webpack_require__(/*! sncrypto */"../sncrypto/dist/sncrypto.js");/* harmony import */var sncrypto__WEBPACK_IMPORTED_MODULE_13___default=/*#__PURE__*/__webpack_require__.n(sncrypto__WEBPACK_IMPORTED_MODULE_13__);/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNWebCrypto",function(){return sncrypto__WEBPACK_IMPORTED_MODULE_13__["SNWebCrypto"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNReactNativeCrypto",function(){return sncrypto__WEBPACK_IMPORTED_MODULE_13__["SNReactNativeCrypto"];});/* harmony import */var _services_model_manager__WEBPACK_IMPORTED_MODULE_14__=__webpack_require__(/*! ./services/model_manager */"./lib/services/model_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNModelManager",function(){return _services_model_manager__WEBPACK_IMPORTED_MODULE_14__["SNModelManager"];});/* harmony import */var _services_http_manager__WEBPACK_IMPORTED_MODULE_15__=__webpack_require__(/*! ./services/http_manager */"./lib/services/http_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNHttpManager",function(){return _services_http_manager__WEBPACK_IMPORTED_MODULE_15__["SNHttpManager"];});/* harmony import */var _services_device_auth_service__WEBPACK_IMPORTED_MODULE_16__=__webpack_require__(/*! ./services/device_auth/service */"./lib/services/device_auth/service.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"DeviceAuthService",function(){return _services_device_auth_service__WEBPACK_IMPORTED_MODULE_16__["DeviceAuthService"];});/* harmony import */var _Services_device_auth_response__WEBPACK_IMPORTED_MODULE_17__=__webpack_require__(/*! @Services/device_auth/response */"./lib/services/device_auth/response.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"ChallengeResponse",function(){return _Services_device_auth_response__WEBPACK_IMPORTED_MODULE_17__["ChallengeResponse"];});/* harmony import */var _Services_pure_service__WEBPACK_IMPORTED_MODULE_18__=__webpack_require__(/*! @Services/pure_service */"./lib/services/pure_service.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"PureService",function(){return _Services_pure_service__WEBPACK_IMPORTED_MODULE_18__["PureService"];});/* harmony import */var _services_storage_manager__WEBPACK_IMPORTED_MODULE_19__=__webpack_require__(/*! ./services/storage_manager */"./lib/services/storage_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNStorageManager",function(){return _services_storage_manager__WEBPACK_IMPORTED_MODULE_19__["SNStorageManager"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"StoragePersistencePolicies",function(){return _services_storage_manager__WEBPACK_IMPORTED_MODULE_19__["StoragePersistencePolicies"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"StorageEncryptionPolicies",function(){return _services_storage_manager__WEBPACK_IMPORTED_MODULE_19__["StorageEncryptionPolicies"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"StorageValueModes",function(){return _services_storage_manager__WEBPACK_IMPORTED_MODULE_19__["StorageValueModes"];});/* harmony import */var _Lib_challenges__WEBPACK_IMPORTED_MODULE_20__=__webpack_require__(/*! @Lib/challenges */"./lib/challenges.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"Challenges",function(){return _Lib_challenges__WEBPACK_IMPORTED_MODULE_20__["Challenges"];});/* harmony import */var _services_sync_sync_manager__WEBPACK_IMPORTED_MODULE_21__=__webpack_require__(/*! ./services/sync/sync_manager */"./lib/services/sync/sync_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNSyncManager",function(){return _services_sync_sync_manager__WEBPACK_IMPORTED_MODULE_21__["SNSyncManager"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"TIMING_STRATEGY_RESOLVE_ON_NEXT",function(){return _services_sync_sync_manager__WEBPACK_IMPORTED_MODULE_21__["TIMING_STRATEGY_RESOLVE_ON_NEXT"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"TIMING_STRATEGY_FORCE_SPAWN_NEW",function(){return _services_sync_sync_manager__WEBPACK_IMPORTED_MODULE_21__["TIMING_STRATEGY_FORCE_SPAWN_NEW"];});/* harmony import */var _services_api_session_manager__WEBPACK_IMPORTED_MODULE_22__=__webpack_require__(/*! ./services/api/session_manager */"./lib/services/api/session_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNSessionManager",function(){return _services_api_session_manager__WEBPACK_IMPORTED_MODULE_22__["SNSessionManager"];});/* harmony import */var _migration_service__WEBPACK_IMPORTED_MODULE_23__=__webpack_require__(/*! ./migration/service */"./lib/migration/service.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNMigrationService",function(){return _migration_service__WEBPACK_IMPORTED_MODULE_23__["SNMigrationService"];});/* harmony import */var _services_alert_manager__WEBPACK_IMPORTED_MODULE_24__=__webpack_require__(/*! ./services/alert_manager */"./lib/services/alert_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNAlertManager",function(){return _services_alert_manager__WEBPACK_IMPORTED_MODULE_24__["SNAlertManager"];});/* harmony import */var _services_history_history_manager__WEBPACK_IMPORTED_MODULE_25__=__webpack_require__(/*! ./services/history/history_manager */"./lib/services/history/history_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNHistoryManager",function(){return _services_history_history_manager__WEBPACK_IMPORTED_MODULE_25__["SNHistoryManager"];});/* harmony import */var _services_privileges_privileges_manager__WEBPACK_IMPORTED_MODULE_26__=__webpack_require__(/*! ./services/privileges/privileges_manager */"./lib/services/privileges/privileges_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNPrivilegesManager",function(){return _services_privileges_privileges_manager__WEBPACK_IMPORTED_MODULE_26__["SNPrivilegesManager"];});/* harmony import */var _services_singleton_manager__WEBPACK_IMPORTED_MODULE_27__=__webpack_require__(/*! ./services/singleton_manager */"./lib/services/singleton_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNSingletonManager",function(){return _services_singleton_manager__WEBPACK_IMPORTED_MODULE_27__["SNSingletonManager"];});/* harmony import */var _services_key_manager__WEBPACK_IMPORTED_MODULE_28__=__webpack_require__(/*! ./services/key_manager */"./lib/services/key_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNKeyManager",function(){return _services_key_manager__WEBPACK_IMPORTED_MODULE_28__["SNKeyManager"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"KEY_MODE_ROOT_KEY_NONE",function(){return _services_key_manager__WEBPACK_IMPORTED_MODULE_28__["KEY_MODE_ROOT_KEY_NONE"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"KEY_MODE_ROOT_KEY_ONLY",function(){return _services_key_manager__WEBPACK_IMPORTED_MODULE_28__["KEY_MODE_ROOT_KEY_ONLY"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"KEY_MODE_ROOT_KEY_PLUS_WRAPPER",function(){return _services_key_manager__WEBPACK_IMPORTED_MODULE_28__["KEY_MODE_ROOT_KEY_PLUS_WRAPPER"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"KEY_MODE_WRAPPER_ONLY",function(){return _services_key_manager__WEBPACK_IMPORTED_MODULE_28__["KEY_MODE_WRAPPER_ONLY"];});/* harmony import */var _services_api_api_service__WEBPACK_IMPORTED_MODULE_29__=__webpack_require__(/*! ./services/api/api_service */"./lib/services/api/api_service.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNApiService",function(){return _services_api_api_service__WEBPACK_IMPORTED_MODULE_29__["SNApiService"];});/* harmony import */var _utils__WEBPACK_IMPORTED_MODULE_30__=__webpack_require__(/*! ./utils */"./lib/utils.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"findInArray",function(){return _utils__WEBPACK_IMPORTED_MODULE_30__["findInArray"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"isNullOrUndefined",function(){return _utils__WEBPACK_IMPORTED_MODULE_30__["isNullOrUndefined"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"deepMerge",function(){return _utils__WEBPACK_IMPORTED_MODULE_30__["deepMerge"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"extendArray",function(){return _utils__WEBPACK_IMPORTED_MODULE_30__["extendArray"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"removeFromIndex",function(){return _utils__WEBPACK_IMPORTED_MODULE_30__["removeFromIndex"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"subtractFromArray",function(){return _utils__WEBPACK_IMPORTED_MODULE_30__["subtractFromArray"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"arrayByDifference",function(){return _utils__WEBPACK_IMPORTED_MODULE_30__["arrayByDifference"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"uniqCombineObjArrays",function(){return _utils__WEBPACK_IMPORTED_MODULE_30__["uniqCombineObjArrays"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"greaterOfTwoDates",function(){return _utils__WEBPACK_IMPORTED_MODULE_30__["greaterOfTwoDates"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"getGlobalScope",function(){return _utils__WEBPACK_IMPORTED_MODULE_30__["getGlobalScope"];});/* harmony import */var _Lib_uuid__WEBPACK_IMPORTED_MODULE_31__=__webpack_require__(/*! @Lib/uuid */"./lib/uuid.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"Uuid",function(){return _Lib_uuid__WEBPACK_IMPORTED_MODULE_31__["Uuid"];});/* harmony import */var _Protocol_intents__WEBPACK_IMPORTED_MODULE_32__=__webpack_require__(/*! @Protocol/intents */"./lib/protocol/intents.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"EncryptionIntents",function(){return _Protocol_intents__WEBPACK_IMPORTED_MODULE_32__["EncryptionIntents"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"isLocalStorageIntent",function(){return _Protocol_intents__WEBPACK_IMPORTED_MODULE_32__["isLocalStorageIntent"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"isFileIntent",function(){return _Protocol_intents__WEBPACK_IMPORTED_MODULE_32__["isFileIntent"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"isDecryptedIntent",function(){return _Protocol_intents__WEBPACK_IMPORTED_MODULE_32__["isDecryptedIntent"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"intentRequiresEncryption",function(){return _Protocol_intents__WEBPACK_IMPORTED_MODULE_32__["intentRequiresEncryption"];});/* harmony import */var _Models_content_types__WEBPACK_IMPORTED_MODULE_33__=__webpack_require__(/*! @Models/content_types */"./lib/models/content_types.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"ContentTypes",function(){return _Models_content_types__WEBPACK_IMPORTED_MODULE_33__["ContentTypes"];});/* harmony import */var _Lib_events__WEBPACK_IMPORTED_MODULE_34__=__webpack_require__(/*! @Lib/events */"./lib/events.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"ApplicationEvents",function(){return _Lib_events__WEBPACK_IMPORTED_MODULE_34__["ApplicationEvents"];});/* harmony import */var _Lib_platforms__WEBPACK_IMPORTED_MODULE_35__=__webpack_require__(/*! @Lib/platforms */"./lib/platforms.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"Environments",function(){return _Lib_platforms__WEBPACK_IMPORTED_MODULE_35__["Environments"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"Platforms",function(){return _Lib_platforms__WEBPACK_IMPORTED_MODULE_35__["Platforms"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"isEnvironmentWebOrDesktop",function(){return _Lib_platforms__WEBPACK_IMPORTED_MODULE_35__["isEnvironmentWebOrDesktop"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"isEnvironmentMobile",function(){return _Lib_platforms__WEBPACK_IMPORTED_MODULE_35__["isEnvironmentMobile"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"platformFromString",function(){return _Lib_platforms__WEBPACK_IMPORTED_MODULE_35__["platformFromString"];});/* harmony import */var _Lib_services__WEBPACK_IMPORTED_MODULE_36__=__webpack_require__(/*! @Lib/services */"./lib/services/index.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SyncEvents",function(){return _Lib_services__WEBPACK_IMPORTED_MODULE_36__["SyncEvents"];});/* harmony import */var _Payloads_pure_item_payload__WEBPACK_IMPORTED_MODULE_37__=__webpack_require__(/*! @Payloads/pure_item_payload */"./lib/protocol/payloads/pure_item_payload.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNPureItemPayload",function(){return _Payloads_pure_item_payload__WEBPACK_IMPORTED_MODULE_37__["SNPureItemPayload"];});/* harmony import */var _Payloads_storage_item_payload__WEBPACK_IMPORTED_MODULE_38__=__webpack_require__(/*! @Payloads/storage_item_payload */"./lib/protocol/payloads/storage_item_payload.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNStorageItemPayload",function(){return _Payloads_storage_item_payload__WEBPACK_IMPORTED_MODULE_38__["SNStorageItemPayload"];});/* harmony import */var _Payloads_collection__WEBPACK_IMPORTED_MODULE_39__=__webpack_require__(/*! @Payloads/collection */"./lib/protocol/payloads/collection.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"PayloadCollection",function(){return _Payloads_collection__WEBPACK_IMPORTED_MODULE_39__["PayloadCollection"];});/* harmony import */var _Payloads_generator__WEBPACK_IMPORTED_MODULE_40__=__webpack_require__(/*! @Payloads/generator */"./lib/protocol/payloads/generator.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"CreateMaxPayloadFromAnyObject",function(){return _Payloads_generator__WEBPACK_IMPORTED_MODULE_40__["CreateMaxPayloadFromAnyObject"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"CreateSourcedPayloadFromObject",function(){return _Payloads_generator__WEBPACK_IMPORTED_MODULE_40__["CreateSourcedPayloadFromObject"];});/* harmony import */var _Lib_protocol_payloads_sources__WEBPACK_IMPORTED_MODULE_41__=__webpack_require__(/*! @Lib/protocol/payloads/sources */"./lib/protocol/payloads/sources.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"PayloadSources",function(){return _Lib_protocol_payloads_sources__WEBPACK_IMPORTED_MODULE_41__["PayloadSources"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"isPayloadSourceRetrieved",function(){return _Lib_protocol_payloads_sources__WEBPACK_IMPORTED_MODULE_41__["isPayloadSourceRetrieved"];});/* harmony import */var _Payloads_formats__WEBPACK_IMPORTED_MODULE_42__=__webpack_require__(/*! @Payloads/formats */"./lib/protocol/payloads/formats.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"PayloadFormats",function(){return _Payloads_formats__WEBPACK_IMPORTED_MODULE_42__["PayloadFormats"];});/* harmony import */var _Lib_storage_keys__WEBPACK_IMPORTED_MODULE_43__=__webpack_require__(/*! @Lib/storage_keys */"./lib/storage_keys.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"StorageKeys",function(){return _Lib_storage_keys__WEBPACK_IMPORTED_MODULE_43__["StorageKeys"];});/* harmony import */var _Lib_migration_migrations_2020_01_01_base__WEBPACK_IMPORTED_MODULE_44__=__webpack_require__(/*! @Lib/migration/migrations/2020-01-01-base */"./lib/migration/migrations/2020-01-01-base.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"BaseMigration",function(){return _Lib_migration_migrations_2020_01_01_base__WEBPACK_IMPORTED_MODULE_44__["BaseMigration"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"ProtectedActions",function(){return _services_privileges_privileges_manager__WEBPACK_IMPORTED_MODULE_26__["ProtectedActions"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"PrivilegeCredentials",function(){return _services_privileges_privileges_manager__WEBPACK_IMPORTED_MODULE_26__["PrivilegeCredentials"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"PRIVILEGE_SESSION_LENGTH_NONE",function(){return _services_privileges_privileges_manager__WEBPACK_IMPORTED_MODULE_26__["PRIVILEGE_SESSION_LENGTH_NONE"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"PRIVILEGE_SESSION_LENGTH_FIVE_MINUTES",function(){return _services_privileges_privileges_manager__WEBPACK_IMPORTED_MODULE_26__["PRIVILEGE_SESSION_LENGTH_FIVE_MINUTES"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"PRIVILEGE_SESSION_LENGTH_ONE_HOUR",function(){return _services_privileges_privileges_manager__WEBPACK_IMPORTED_MODULE_26__["PRIVILEGE_SESSION_LENGTH_ONE_HOUR"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"PRIVILEGE_SESSION_LENGTH_ONE_WEEK",function(){return _services_privileges_privileges_manager__WEBPACK_IMPORTED_MODULE_26__["PRIVILEGE_SESSION_LENGTH_ONE_WEEK"];});/** Payloads */ /** Migrations */ /** Privileges */ /***/},/***/"./lib/migration/migrations/2020-01-01-base.js":/*!*****************************************************!*\
!*** ./lib/migration/migrations/2020-01-01-base.js ***!
\*****************************************************/ /*! exports provided: BaseMigration */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"BaseMigration",function(){return BaseMigration;});/* harmony import */var _Lib_migration_migrations_migration__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Lib/migration/migrations/migration */"./lib/migration/migrations/migration.js");/* harmony import */var _Lib_storage_keys__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Lib/storage_keys */"./lib/storage_keys.js");/* harmony import */var _Lib_stages__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! @Lib/stages */"./lib/stages.js");/* harmony import */var _Lib_utils__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! @Lib/utils */"./lib/utils.js");function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i masterKey).
*/},{key:"migrateStorageStructureForMobile",value:function migrateStorageStructureForMobile(){var _nonwrapped,_this2=this;var wrappedAccountKey,rawAccountKeyParams,rawPasscodeParams,rawStructure,keychainValue,passcodeParams,getPasscodeKey,timing,passcodeKey,unwrappedAccountKey,accountKeyContent,defaultVersion,newAccountKey,newWrappedAccountKey,_passcodeKey,payload,wrapped,hasAccount,_defaultVersion,accountKey;return regeneratorRuntime.async(function migrateStorageStructureForMobile$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:_context10.next=2;return regeneratorRuntime.awrap(this.application.deviceInterface.getJsonParsedStorageValue(LEGACY_MOBILE_WRAPPED_ROOT_KEY_KEY));case 2:wrappedAccountKey=_context10.sent;_context10.next=5;return regeneratorRuntime.awrap(this.application.deviceInterface.getJsonParsedStorageValue(LEGACY_ALL_ACCOUNT_KEY_PARAMS_KEY));case 5:rawAccountKeyParams=_context10.sent;_context10.next=8;return regeneratorRuntime.awrap(this.application.deviceInterface.getJsonParsedStorageValue(LEGACY_MOBILE_PASSCODE_PARAMS_KEY));case 8:rawPasscodeParams=_context10.sent;rawStructure={nonwrapped:(_nonwrapped={},_defineProperty(_nonwrapped,_Lib__WEBPACK_IMPORTED_MODULE_1__["StorageKeys"].WrappedRootKey,wrappedAccountKey),_defineProperty(_nonwrapped,_Lib__WEBPACK_IMPORTED_MODULE_1__["StorageKeys"].RootKeyWrapperKeyParams,rawPasscodeParams),_defineProperty(_nonwrapped,_Lib__WEBPACK_IMPORTED_MODULE_1__["StorageKeys"].RootKeyParams,rawAccountKeyParams),_nonwrapped),unwrapped:{}};_context10.next=12;return regeneratorRuntime.awrap(this.application.deviceInterface.getRawKeychainValue());case 12:keychainValue=_context10.sent;if(!rawPasscodeParams){_context10.next=53;break;}passcodeParams=this.application.protocolService.createKeyParams(rawPasscodeParams);getPasscodeKey=function getPasscodeKey(){var keychainValue,pwHash,passcodeKey,response,passcode;return regeneratorRuntime.async(function getPasscodeKey$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:_context9.next=2;return regeneratorRuntime.awrap(_this2.application.deviceInterface.getRawKeychainValue());case 2:keychainValue=_context9.sent;/** Validate current passcode by comparing against keychain offline.pw value */pwHash=keychainValue.offline.pw;passcodeKey={serverPassword:null};case 5:if(!(passcodeKey.serverPassword!==pwHash)){_context9.next=15;break;}_context9.next=8;return regeneratorRuntime.awrap(_this2.requestChallengeResponse(_Lib__WEBPACK_IMPORTED_MODULE_1__["Challenges"].LocalPasscode));case 8:response=_context9.sent;passcode=response.value;_context9.next=12;return regeneratorRuntime.awrap(_this2.application.protocolService.computeRootKey({password:passcode,keyParams:passcodeParams}));case 12:passcodeKey=_context9.sent;_context9.next=5;break;case 15:return _context9.abrupt("return",passcodeKey);case 16:case"end":return _context9.stop();}}});};timing=keychainValue.offline.timing;rawStructure.unwrapped[_Lib__WEBPACK_IMPORTED_MODULE_1__["StorageKeys"].MobilePasscodeTiming]=timing;if(!wrappedAccountKey){_context10.next=34;break;}_context10.next=21;return regeneratorRuntime.awrap(getPasscodeKey());case 21:passcodeKey=_context10.sent;_context10.next=24;return regeneratorRuntime.awrap(this.application.protocolService.payloadByDecryptingPayload({payload:Object(_Payloads__WEBPACK_IMPORTED_MODULE_2__["CreateMaxPayloadFromAnyObject"])({object:wrappedAccountKey}),key:passcodeKey}));case 24:unwrappedAccountKey=_context10.sent;accountKeyContent=unwrappedAccountKey.content.accountKeys;defaultVersion=!Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_3__["isNullOrUndefined"])(accountKeyContent.ak)?_Protocol__WEBPACK_IMPORTED_MODULE_4__["ProtocolVersions"].V003:_Protocol__WEBPACK_IMPORTED_MODULE_4__["ProtocolVersions"].V002;newAccountKey=Object(_Payloads__WEBPACK_IMPORTED_MODULE_2__["CopyPayload"])({payload:unwrappedAccountKey,override:{content:{masterKey:accountKeyContent.mk,serverPassword:accountKeyContent.pw,dataAuthenticationKey:accountKeyContent.ak,version:accountKeyContent.version||defaultVersion,accountKeys:null}}});_context10.next=30;return regeneratorRuntime.awrap(this.application.protocolService.payloadByEncryptingPayload({payload:newAccountKey,key:passcodeKey,intent:_Protocol__WEBPACK_IMPORTED_MODULE_4__["EncryptionIntents"].LocalStoragePreferEncrypted}));case 30:newWrappedAccountKey=_context10.sent;rawStructure.nonwrapped[_Lib__WEBPACK_IMPORTED_MODULE_1__["StorageKeys"].WrappedRootKey]=newWrappedAccountKey;_context10.next=51;break;case 34:if(wrappedAccountKey){_context10.next=51;break;}_context10.next=37;return regeneratorRuntime.awrap(getPasscodeKey());case 37:_passcodeKey=_context10.sent;_context10.t0=_Payloads__WEBPACK_IMPORTED_MODULE_2__["CreateMaxPayloadFromAnyObject"];_context10.next=41;return regeneratorRuntime.awrap(_Lib_uuid__WEBPACK_IMPORTED_MODULE_7__["Uuid"].GenerateUuid());case 41:_context10.t1=_context10.sent;_context10.t2=rawStructure.unwrapped;_context10.t3=_Models__WEBPACK_IMPORTED_MODULE_5__["ContentTypes"].EncryptedStorage;_context10.t4={uuid:_context10.t1,content:_context10.t2,content_type:_context10.t3};_context10.t5={object:_context10.t4};payload=(0,_context10.t0)(_context10.t5);_context10.next=49;return regeneratorRuntime.awrap(this.application.protocolService.payloadByEncryptingPayload({payload:payload,key:_passcodeKey,intent:_Protocol__WEBPACK_IMPORTED_MODULE_4__["EncryptionIntents"].LocalStoragePreferEncrypted}));case 49:wrapped=_context10.sent;rawStructure.wrapped=wrapped;case 51:_context10.next=61;break;case 53:/** No passcode, potentially account. Migrate keychain property keys. */hasAccount=keychainValue&&keychainValue.mk;if(!hasAccount){_context10.next=61;break;}_defaultVersion=!Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_3__["isNullOrUndefined"])(keychainValue.ak)?_Protocol__WEBPACK_IMPORTED_MODULE_4__["ProtocolVersions"].V003:_Protocol__WEBPACK_IMPORTED_MODULE_4__["ProtocolVersions"].V002;_context10.next=58;return regeneratorRuntime.awrap(_Protocol__WEBPACK_IMPORTED_MODULE_4__["SNRootKey"].Create({content:{masterKey:keychainValue.mk,serverPassword:keychainValue.pw,dataAuthenticationKey:keychainValue.ak,version:keychainValue.version||_defaultVersion}}));case 58:accountKey=_context10.sent;_context10.next=61;return regeneratorRuntime.awrap(this.application.deviceInterface.setKeychainValue(accountKey.getRootValues()));case 61:_context10.next=63;return regeneratorRuntime.awrap(this.allPlatformHelperSetStorageStructure(rawStructure));case 63:case"end":return _context10.stop();}}},null,this);}/**
* @private
* @allplatform
* Migrate all previously independently stored storage keys into new
* managed approach. These keys are ones that do not need to be renamed.
*/},{key:"migrateArbitraryRawStorageToManagedStorageAllPlatforms",value:function migrateArbitraryRawStorageToManagedStorageAllPlatforms(){var allKeyValues,keysToExclude,tryJsonParse,_iteratorNormalCompletion,_didIteratorError,_iteratorError,_iterator,_step,keyValuePair,key,value,newValue;return regeneratorRuntime.async(function migrateArbitraryRawStorageToManagedStorageAllPlatforms$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:_context11.next=2;return regeneratorRuntime.awrap(this.application.deviceInterface.getAllRawStorageKeyValues());case 2:allKeyValues=_context11.sent;keysToExclude=[Object(_Lib__WEBPACK_IMPORTED_MODULE_1__["namespacedKey"])(this.application.namespace,_Lib__WEBPACK_IMPORTED_MODULE_1__["StorageKeys"].StorageObject),LEGACY_WEB_ENCRYPTED_STORAGE_KEY,LEGACY_WEB_PASSCODE_PARAMS_KEY,LEGACY_MOBILE_PASSCODE_PARAMS_KEY];tryJsonParse=function tryJsonParse(value){try{return JSON.parse(value);}catch(e){return value;}};_iteratorNormalCompletion=true;_didIteratorError=false;_iteratorError=undefined;_context11.prev=8;_iterator=allKeyValues[Symbol.iterator]();case 10:if(_iteratorNormalCompletion=(_step=_iterator.next()).done){_context11.next=23;break;}keyValuePair=_step.value;key=keyValuePair.key;value=keyValuePair.value;if(!keysToExclude.includes(key)){_context11.next=16;break;}return _context11.abrupt("continue",20);case 16:if(Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_3__["isNullOrUndefined"])(value)){_context11.next=20;break;}/**
* Raw values should always have been json stringified.
* New values should always be objects/parsed.
*/newValue=tryJsonParse(value);_context11.next=20;return regeneratorRuntime.awrap(this.application.storageManager.setValue(key,newValue));case 20:_iteratorNormalCompletion=true;_context11.next=10;break;case 23:_context11.next=29;break;case 25:_context11.prev=25;_context11.t0=_context11["catch"](8);_didIteratorError=true;_iteratorError=_context11.t0;case 29:_context11.prev=29;_context11.prev=30;if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return();}case 32:_context11.prev=32;if(!_didIteratorError){_context11.next=35;break;}throw _iteratorError;case 35:return _context11.finish(32);case 36:return _context11.finish(29);case 37:case"end":return _context11.stop();}}},null,this,[[8,25,29,37],[30,,32,36]]);}/**
* @private
* @allplatform
* Create new default SNItemsKey from root key.
* Otherwise, when data is loaded, we won't be able to decrypt it
* without existence of an item key. This will mean that if this migration
* is run on two different platforms for the same user, they will create
* two new items keys. Which one they use to decrypt past items and encrypt
* future items doesn't really matter.
*/},{key:"createDefaultItemsKeyForAllPlatforms",value:function createDefaultItemsKeyForAllPlatforms(){var rootKey,rootKeyParams,itemsKey;return regeneratorRuntime.async(function createDefaultItemsKeyForAllPlatforms$(_context12){while(1){switch(_context12.prev=_context12.next){case 0:_context12.next=2;return regeneratorRuntime.awrap(this.application.keyManager.getRootKey());case 2:rootKey=_context12.sent;if(!rootKey){_context12.next=14;break;}_context12.next=6;return regeneratorRuntime.awrap(this.application.keyManager.getRootKeyParams());case 6:rootKeyParams=_context12.sent;itemsKey=_Models__WEBPACK_IMPORTED_MODULE_5__["SNItemsKey"].FromRaw({itemsKey:rootKey.masterKey,dataAuthenticationKey:rootKey.dataAuthenticationKey,version:rootKeyParams.version});_context12.next=10;return regeneratorRuntime.awrap(itemsKey.initUUID());case 10:_context12.next=12;return regeneratorRuntime.awrap(this.application.modelManager.mapItem({item:itemsKey}));case 12:_context12.next=14;return regeneratorRuntime.awrap(this.application.modelManager.setItemDirty(itemsKey));case 14:case"end":return _context12.stop();}}},null,this);}}],[{key:"timestamp",value:function timestamp(){return new Date('2020-01-15').getTime();}}]);return Migration20200115;}(_Lib_migration_migrations_migration__WEBPACK_IMPORTED_MODULE_0__["Migration"]);/***/},/***/"./lib/migration/migrations/index.js":/*!*******************************************!*\
!*** ./lib/migration/migrations/index.js ***!
\*******************************************/ /*! exports provided: Migration20200115 */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony import */var _2020_01_15__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! ./2020-01-15 */"./lib/migration/migrations/2020-01-15.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"Migration20200115",function(){return _2020_01_15__WEBPACK_IMPORTED_MODULE_0__["Migration20200115"];});/***/},/***/"./lib/migration/migrations/migration.js":/*!***********************************************!*\
!*** ./lib/migration/migrations/migration.js ***!
\***********************************************/ /*! exports provided: Migration */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"Migration",function(){return Migration;});function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0){lastMigration=Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_5__["lastElement"])(this.activeMigrations);lastMigration.onDone(function _callee(){return regeneratorRuntime.async(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return regeneratorRuntime.awrap(_this2.saveLastMigrationTimestamp(lastMigration.constructor.timestamp()));case 2:case"end":return _context.stop();}}});});}case 6:case"end":return _context2.stop();}}},null,this);}/**
* @public
* Application instances will call this function directly when they arrive
* at a certain migratory state.
*/},{key:"handleApplicationStage",value:function handleApplicationStage(stage){return regeneratorRuntime.async(function handleApplicationStage$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:_context3.next=2;return regeneratorRuntime.awrap(_get(_getPrototypeOf(SNMigrationService.prototype),"handleApplicationStage",this).call(this,stage));case 2:if(stage===_Lib__WEBPACK_IMPORTED_MODULE_1__["ApplicationStages"].ReadyForLaunch_05){this.addLoginObserver();this.addSyncObserver();}_context3.next=5;return regeneratorRuntime.awrap(this.handleStage(stage));case 5:case"end":return _context3.stop();}}},null,this);}},{key:"runBaseMigration",value:function runBaseMigration(){var baseMigration;return regeneratorRuntime.async(function runBaseMigration$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:baseMigration=new _Lib_migration_migrations_2020_01_01_base__WEBPACK_IMPORTED_MODULE_2__["BaseMigration"]({application:this.application});_context4.next=3;return regeneratorRuntime.awrap(baseMigration.handleStage(_Lib__WEBPACK_IMPORTED_MODULE_1__["ApplicationStages"].PreparingForLaunch_0));case 3:case"end":return _context4.stop();}}},null,this);}},{key:"getRequiredMigrations",value:function getRequiredMigrations(){var lastMigrationTimestamp,activeMigrations,migrationClasses,_iteratorNormalCompletion,_didIteratorError,_iteratorError,_iterator,_step,migrationClass,migrationTimestamp;return regeneratorRuntime.async(function getRequiredMigrations$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:_context5.next=2;return regeneratorRuntime.awrap(this.getLastMigrationTimestamp());case 2:lastMigrationTimestamp=_context5.sent;activeMigrations=[];migrationClasses=Object.keys(_Lib_migration_migrations__WEBPACK_IMPORTED_MODULE_0__).map(function(key){return _Lib_migration_migrations__WEBPACK_IMPORTED_MODULE_0__[key];}).sort(function(a,b){var aTimestamp=a.timestamp();var bTimestamp=b.timestamp();if(aTimestampbTimestamp){return 1;}else{return 0;}});_iteratorNormalCompletion=true;_didIteratorError=false;_iteratorError=undefined;_context5.prev=8;for(_iterator=migrationClasses[Symbol.iterator]();!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){migrationClass=_step.value;migrationTimestamp=migrationClass.timestamp();if(migrationTimestamp>lastMigrationTimestamp){// eslint-disable-next-line new-cap
activeMigrations.push(new migrationClass({application:this.application,challengeResponder:this.challengeResponder}));}}_context5.next=16;break;case 12:_context5.prev=12;_context5.t0=_context5["catch"](8);_didIteratorError=true;_iteratorError=_context5.t0;case 16:_context5.prev=16;_context5.prev=17;if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return();}case 19:_context5.prev=19;if(!_didIteratorError){_context5.next=22;break;}throw _iteratorError;case 22:return _context5.finish(19);case 23:return _context5.finish(16);case 24:return _context5.abrupt("return",activeMigrations);case 25:case"end":return _context5.stop();}}},null,this,[[8,12,16,24],[17,,19,23]]);}},{key:"getTimeStampKey",value:function getTimeStampKey(){return Object(_Lib_storage_keys__WEBPACK_IMPORTED_MODULE_4__["namespacedKey"])(this.application.namespace,_Lib_storage_keys__WEBPACK_IMPORTED_MODULE_4__["RAW_STORAGE_KEY_LAST_MIGRATION_TIMESTAMP"]);}},{key:"getLastMigrationTimestamp",value:function getLastMigrationTimestamp(){var timestamp;return regeneratorRuntime.async(function getLastMigrationTimestamp$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:_context6.next=2;return regeneratorRuntime.awrap(this.application.deviceInterface.getRawStorageValue(this.getTimeStampKey()));case 2:timestamp=_context6.sent;if(!Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_5__["isNullOrUndefined"])(timestamp)){_context6.next=5;break;}throw'Timestamp should not be null. Be sure to run base migration first.';case 5:return _context6.abrupt("return",JSON.parse(timestamp));case 6:case"end":return _context6.stop();}}},null,this);}},{key:"saveLastMigrationTimestamp",value:function saveLastMigrationTimestamp(timestamp){return regeneratorRuntime.async(function saveLastMigrationTimestamp$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:_context7.next=2;return regeneratorRuntime.awrap(this.application.deviceInterface.setRawStorageValue(this.getTimeStampKey(),JSON.stringify(timestamp)));case 2:case"end":return _context7.stop();}}},null,this);}/**
* @private
*/},{key:"addLoginObserver",value:function addLoginObserver(){var _this3=this;this.application.addEventObserver(function _callee2(event,data){return regeneratorRuntime.async(function _callee2$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:if(!(event===_Lib__WEBPACK_IMPORTED_MODULE_1__["ApplicationEvents"].SignedIn)){_context8.next=3;break;}_context8.next=3;return regeneratorRuntime.awrap(_this3.handleStage(_Lib__WEBPACK_IMPORTED_MODULE_1__["ApplicationStages"].SignedIn_30));case 3:case"end":return _context8.stop();}}});});}},{key:"addSyncObserver",value:function addSyncObserver(){var _this4=this;this.application.syncManager.addEventObserver(function _callee3(event,data){return regeneratorRuntime.async(function _callee3$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:if(!(event===_Lib__WEBPACK_IMPORTED_MODULE_1__["SyncEvents"].FullSyncCompleted)){_context9.next=3;break;}_context9.next=3;return regeneratorRuntime.awrap(_this4.handleStage(_Lib__WEBPACK_IMPORTED_MODULE_1__["ApplicationStages"].FullSyncCompleted_13));case 3:case"end":return _context9.stop();}}});});}},{key:"handleStage",value:function handleStage(stage){var _iteratorNormalCompletion2,_didIteratorError2,_iteratorError2,_iterator2,_step2,migration;return regeneratorRuntime.async(function handleStage$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:_iteratorNormalCompletion2=true;_didIteratorError2=false;_iteratorError2=undefined;_context10.prev=3;_iterator2=this.activeMigrations[Symbol.iterator]();case 5:if(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done){_context10.next=12;break;}migration=_step2.value;_context10.next=9;return regeneratorRuntime.awrap(migration.handleStage(stage));case 9:_iteratorNormalCompletion2=true;_context10.next=5;break;case 12:_context10.next=18;break;case 14:_context10.prev=14;_context10.t0=_context10["catch"](3);_didIteratorError2=true;_iteratorError2=_context10.t0;case 18:_context10.prev=18;_context10.prev=19;if(!_iteratorNormalCompletion2&&_iterator2.return!=null){_iterator2.return();}case 21:_context10.prev=21;if(!_didIteratorError2){_context10.next=24;break;}throw _iteratorError2;case 24:return _context10.finish(21);case 25:return _context10.finish(18);case 26:case"end":return _context10.stop();}}},null,this,[[3,14,18,26],[19,,21,25]]);}}]);return SNMigrationService;}(_Services_pure_service__WEBPACK_IMPORTED_MODULE_3__["PureService"]);/***/},/***/"./lib/models/app/action.js":/*!**********************************!*\
!*** ./lib/models/app/action.js ***!
\**********************************/ /*! exports provided: Action */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"Action",function(){return Action;});/* harmony import */var lodash_merge__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! lodash/merge */"./node_modules/lodash/merge.js");/* harmony import */var lodash_merge__WEBPACK_IMPORTED_MODULE_0___default=/*#__PURE__*/__webpack_require__.n(lodash_merge__WEBPACK_IMPORTED_MODULE_0__);function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var Action=function Action(json){_classCallCheck(this,Action);lodash_merge__WEBPACK_IMPORTED_MODULE_0___default()(this,json);this.running=false;this.error=false;if(this.lastExecuted){this.lastExecuted=new Date(this.lastExecuted);}};/***/},/***/"./lib/models/app/component.js":/*!*************************************!*\
!*** ./lib/models/app/component.js ***!
\*************************************/ /*! exports provided: SNComponent */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"SNComponent",function(){return SNComponent;});/* harmony import */var _Models_core_item__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Models/core/item */"./lib/models/core/item.js");/* harmony import */var _Models_content_types__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Models/content_types */"./lib/models/content_types.js");/* harmony import */var _Models_core_predicate__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! @Models/core/predicate */"./lib/models/core/predicate.js");/* harmony import */var _Payloads__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! @Payloads */"./lib/protocol/payloads/index.js");function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;ib.title;}).map(function(tag,i){return'#'+tag.title;}).join(' ');}}]);return SNTag;}(_Models_core_item__WEBPACK_IMPORTED_MODULE_2__["SFItem"]);/***/},/***/"./lib/models/app/theme.js":/*!*********************************!*\
!*** ./lib/models/app/theme.js ***!
\*********************************/ /*! exports provided: SNTheme */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"SNTheme",function(){return SNTheme;});/* harmony import */var _Payloads__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Payloads */"./lib/protocol/payloads/index.js");/* harmony import */var _Models_content_types__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Models/content_types */"./lib/models/content_types.js");/* harmony import */var _Models_app_component__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! @Models/app/component */"./lib/models/app/component.js");function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0&&arguments[0]!==undefined?arguments[0]:{},override=_ref.override;return Object(_Payloads__WEBPACK_IMPORTED_MODULE_3__["CreateMaxPayloadFromAnyObject"])({object:this,override:override});}/**
* If creating from external payload, it may not include values for .references and .appData
* Here we want to initialize these values with default values.
*/},{key:"populateDefaultContentValues",value:function populateDefaultContentValues(){if(this.errorDecrypting||this.deleted){return;}if(!this.content.references){this.content.references=[];}if(!this.content.appData){this.content.appData=_defineProperty({},_Lib__WEBPACK_IMPORTED_MODULE_4__["DEFAULT_APP_DOMAIN"],{});}}/**
* Consumers who create items without a syncronous UUID generation function
* must manually call this function when creating an item. The consumer must
* have previously called Uuid.SetGenerators.
*/},{key:"initUUID",value:function initUUID(){return regeneratorRuntime.async(function initUUID$(_context){while(1){switch(_context.prev=_context.next){case 0:if(this.uuid){_context.next=4;break;}_context.next=3;return regeneratorRuntime.awrap(SFItem.GenerateUuid());case 3:this.uuid=_context.sent;case 4:case"end":return _context.stop();}}},null,this);}},{key:"updateFromPayload",value:function updateFromPayload(payload){if(!payload){return;}var fieldsToCopy=[_Payloads__WEBPACK_IMPORTED_MODULE_3__["PayloadFields"].Content];var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=payload.fields()[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var field=_step.value;if(Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["hasGetter"])(this,field)){continue;}var value=payload[field];if(fieldsToCopy.includes(field)){var copy=Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["Copy"])(value||null);this[field]=copy;}else{this[field]=value;}}}catch(err){_didIteratorError=true;_iteratorError=err;}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return();}}finally{if(_didIteratorError){throw _iteratorError;}}}if(this.content){this.mapContentToLocalProperties(this.content);}else if(payload.deleted===true){this.handleDeletedContent();}if(this.dirtiedDate&&typeof this.dirtiedDate==='string'){this.dirtiedDate=new Date(this.dirtiedDate);}if(this.lastSyncBegan&&typeof this.lastSyncBegan==='string'){this.lastSyncBegan=new Date(this.lastSyncBegan);}if(this.created_at){this.created_at=new Date(this.created_at);}else{this.created_at=new Date();}if(this.updated_at){this.updated_at=new Date(this.updated_at);}else{this.updated_at=new Date(0);}// Epoch
/** Allows the getter to be re-invoked */this._client_updated_at=null;this.populateDefaultContentValues();}},{key:"mapContentToLocalProperties",value:function mapContentToLocalProperties(content){}/** Optional override */ /**
* Merges any fields we get from `this.structureParams` into our .content object.
* Subclasses can override `structureParams`, and add their own custom content
* and properties to the object returned from `structureParams`.
* These are properties that this superclass will not be aware of,
* like `title` or `text`. When we call `collapseContent`, we want to update
* our own inherit 'content' field with the values returned from structureParams,
* so that our content field is up to date. Each subclass will call
* `super.structureParams` and merge it with its own custom result object.
* Since our own `structureParams` gets a real-time copy of our content,
* it should be safe to merge the aggregate value back into our own content field.
*/},{key:"collapseContent",value:function collapseContent(){var contentCopy=this.structureParams();Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["deepMerge"])(this.content,contentCopy);return contentCopy;}},{key:"structureParams",value:function structureParams(){return this.getContentCopy();}/** Allows consumers to check if object is an SFItem subclass and not a generic JS object */},{key:"handleDeletedContent",/* Allows the item to handle the case where the item is deleted and the content is null */value:function handleDeletedContent(){/** Subclasses can override */}},{key:"setDirty",value:function setDirty(_ref2){var dirty=_ref2.dirty,updateClientDate=_ref2.updateClientDate,authorized=_ref2.authorized;if(!authorized){throw'Do not call setDirty directly. Use modelManager.setItemDirty';}this.dirty=dirty;this.dirtiedDate=new Date();if(dirty&&updateClientDate){// Set the client modified date to now if marking the item as dirty
this.client_updated_at=new Date();}else if(!this.hasRawClientUpdatedAtValue()){// if we don't have an explcit raw value, we initialize client_updated_at.
this.client_updated_at=new Date(this.updated_at);}this.collapseContent();}/**
* Loops through all memory-based referenced items and checks to see
* if they're in our content.references. If not, we remove them from
* our memory state.
*/},{key:"updateLocalRelationships",value:function updateLocalRelationships(){var references=this.content.references;var uuids=references.map(function(ref){return ref.uuid;});var existingUuids=Object.keys(this._referencedItems);for(var _i=0,_existingUuids=existingUuids;_i<_existingUuids.length;_i++){var uuid=_existingUuids[_i];var ref=this._referencedItems[uuid];if(!uuids.includes(ref.uuid)){delete this._referencedItems[uuid];ref.setIsNoLongerReferencedBy(this);}}}},{key:"addItemAsRelationship",value:function addItemAsRelationship(item){item.setIsBeingReferencedBy(this);if(!this._referencedItems[item.uuid]){this._referencedItems[item.uuid]=item;}if(this.hasRelationshipWithItem(item)){return;}var references=this.content.references||[];references.push({uuid:item.uuid,content_type:item.content_type});this.content.references=references;}},{key:"removeItemAsRelationship",value:function removeItemAsRelationship(item){item.setIsNoLongerReferencedBy(this);this.removeReferenceWithUuid(item.uuid);delete this._referencedItems[item.uuid];}/**
* When another object has a relationship with us, we push that object
* into memory here. We use this so that when `this` is deleted, we're able
* to update the references of those other objects.
*/},{key:"setIsBeingReferencedBy",value:function setIsBeingReferencedBy(item){if(!this._referencingItems[item.uuid]){this._referencingItems[item.uuid]=item;}}},{key:"setIsNoLongerReferencedBy",value:function setIsNoLongerReferencedBy(item){delete this._referencingItems[item.uuid];}},{key:"removeReferenceWithUuid",value:function removeReferenceWithUuid(uuid){var references=this.content.references||[];references=references.filter(function(r){return r.uuid!==uuid;});this.content.references=references;delete this._referencedItems[uuid];}},{key:"hasRelationshipWithItem",value:function hasRelationshipWithItem(item){var target=this.content.references.find(function(r){return r.uuid===item.uuid;});return!Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["isNullOrUndefined"])(target);}},{key:"isBeingRemovedLocally",value:function isBeingRemovedLocally(){for(var _i2=0,_Object$keys=Object.keys(this._referencedItems);_i2<_Object$keys.length;_i2++){var uuid=_Object$keys[_i2];var item=this._referencedItems[uuid];item.setIsNoLongerReferencedBy(this);}}/** The number of items this item currently references */},{key:"resetLocalReferencePointers",value:function resetLocalReferencePointers(){this._referencingItems={};this._referencedItems={};}},{key:"didCompleteMapping",value:function didCompleteMapping(source){/** Optional override */}},{key:"doNotEncrypt",value:function doNotEncrypt(){return false;}/*
App Data
*/},{key:"setDomainDataItem",value:function setDomainDataItem(key,value,domain){if(!domain){console.error('DEFAULT_APP_DOMAIN needs to be set.');return;}if(this.errorDecrypting){return;}if(!this.content.appData){this.content.appData={};}var data=this.content.appData[domain];if(!data){data={};}data[key]=value;this.content.appData[domain]=data;}},{key:"getDomainDataItem",value:function getDomainDataItem(key,domain){if(!domain){console.error('DEFAULT_APP_DOMAIN needs to be set.');return;}if(this.errorDecrypting){return;}if(!this.content.appData){this.content.appData={};}var data=this.content.appData[domain];if(data){return data[key];}else{return null;}}},{key:"setAppDataItem",value:function setAppDataItem(key,value){this.setDomainDataItem(key,value,_Lib__WEBPACK_IMPORTED_MODULE_4__["DEFAULT_APP_DOMAIN"]);}},{key:"getAppDataItem",value:function getAppDataItem(key){return this.getDomainDataItem(key,_Lib__WEBPACK_IMPORTED_MODULE_4__["DEFAULT_APP_DOMAIN"]);}},{key:"hasRawClientUpdatedAtValue",value:function hasRawClientUpdatedAtValue(){return this.getAppDataItem('client_updated_at')!=null;}// eslint-disable-next-line camelcase
},{key:"contentKeysToIgnoreWhenCheckingEquality",/*
During sync conflicts, when determing whether to create a duplicate for an item, we can omit keys that have no
meaningful weight and can be ignored. For example, if one component has active = true and another component has active = false,
it would be silly to duplicate them, so instead we ignore this.
*/value:function contentKeysToIgnoreWhenCheckingEquality(){return['conflict_of'];}// Same as above, but keys inside appData[Item.AppDomain]
},{key:"appDatacontentKeysToIgnoreWhenCheckingEquality",value:function appDatacontentKeysToIgnoreWhenCheckingEquality(){return['client_updated_at'];}},{key:"getContentCopy",value:function getContentCopy(){var contentCopy=JSON.parse(JSON.stringify(this.content));return contentCopy;}/** Whether the item has never been synced to a server */},{key:"strategyWhenConflictingWithItem",/**
* Subclasses can override this method and provide their own opinion on whether
* they want to be duplicated. For example, if this.content.x = 12 and
* item.content.x = 13, this function can be overriden to always return
* ConflictStrategies.KeepLeft to say 'don't create a duplicate at all, the
* change is not important.'
*
* In the default implementation, we create a duplicate if content differs.
* However, if they only differ by references, we KEEP_LEFT_MERGE_REFS.
*/value:function strategyWhenConflictingWithItem(_ref3){var item=_ref3.item;if(this.errorDecrypting){return _Payloads__WEBPACK_IMPORTED_MODULE_3__["ConflictStrategies"].KeepLeftDuplicateRight;}if(this.isSingleton){return _Payloads__WEBPACK_IMPORTED_MODULE_3__["ConflictStrategies"].KeepLeft;}/**
* The number of seconds in between changes to constitue a
* subjective measure of what we think is active editing of an item
*/ // const IS_ACTIVELY_EDITING_THRESHOLD = 10;
// function ItemIsBeingActivelyEdited(item) {
// const isEpoch = item.client_updated_at.getTime() === 0;
// if (!item.client_updated_at) {
// return false;
// }
// return (new Date() - item.client_updated_at) / 1000 < IS_ACTIVELY_EDITING_THRESHOLD;
// }
if(this.deleted||item.deleted){return _Payloads__WEBPACK_IMPORTED_MODULE_3__["ConflictStrategies"].KeepRight;}var contentDiffers=Object(_Models_core_functions__WEBPACK_IMPORTED_MODULE_2__["ItemContentsDiffer"])(this,item);if(!contentDiffers){return _Payloads__WEBPACK_IMPORTED_MODULE_3__["ConflictStrategies"].KeepRight;}var differsExclRefs=Object(_Models_core_functions__WEBPACK_IMPORTED_MODULE_2__["ItemContentsDiffer"])(this,item,['references']);if(differsExclRefs){return _Payloads__WEBPACK_IMPORTED_MODULE_3__["ConflictStrategies"].KeepLeftDuplicateRight;}else{/** Is only references change */return _Payloads__WEBPACK_IMPORTED_MODULE_3__["ConflictStrategies"].KeepLeftMergeRefs;}}},{key:"isItemContentEqualWith",value:function isItemContentEqualWith(otherItem){return Object(_Models_core_functions__WEBPACK_IMPORTED_MODULE_2__["ItemContentsEqual"])({leftContent:this.content,rightContent:otherItem.content,keysToIgnore:this.contentKeysToIgnoreWhenCheckingEquality(),appDataKeysToIgnore:this.appDatacontentKeysToIgnoreWhenCheckingEquality()});}},{key:"satisfiesPredicate",value:function satisfiesPredicate(predicate){return _Models_core_predicate__WEBPACK_IMPORTED_MODULE_1__["SFPredicate"].ItemSatisfiesPredicate(this,predicate);}/*
Dates
*/},{key:"createdAtString",value:function createdAtString(){return this.dateToLocalizedString(this.created_at);}},{key:"updatedAtString",value:function updatedAtString(){return this.dateToLocalizedString(this.client_updated_at);}},{key:"updatedAtTimestamp",value:function updatedAtTimestamp(){return this.updated_at.getTime();}},{key:"dateToLocalizedString",value:function dateToLocalizedString(date){if(typeof Intl!=='undefined'&&Intl.DateTimeFormat){if(!SFItem.sharedDateFormatter){var locale=navigator.languages&&navigator.languages.length?navigator.languages[0]:navigator.language;SFItem.sharedDateFormatter=new Intl.DateTimeFormat(locale,{year:'numeric',month:'short',day:'2-digit',weekday:'long',hour:'2-digit',minute:'2-digit'});}return SFItem.sharedDateFormatter.format(date);}else{// IE < 11, Safari <= 9.0.
// In English, this generates the string most similar to
// the toLocaleDateString() result above.
return date.toDateString()+' '+date.toLocaleTimeString();}}},{key:"isItem",get:function get(){return true;}},{key:"referencedItemsCount",get:function get(){return Object.keys(this._referencedItems).length;}/** The number of items that currently reference this item */},{key:"referencingItemsCount",get:function get(){return Object.keys(this._referencingItems).length;}},{key:"allReferencingItems",get:function get(){var _this=this;return Object.keys(this._referencingItems).map(function(uuid){return _this._referencingItems[uuid];});}},{key:"pinned",get:function get(){return this.getAppDataItem('pinned');}},{key:"archived",get:function get(){return this.getAppDataItem('archived');}},{key:"locked",get:function get(){return this.getAppDataItem('locked');}},{key:"client_updated_at",get:function get(){if(!this._client_updated_at){var saved=this.getAppDataItem('client_updated_at');if(saved){this._client_updated_at=new Date(saved);}else{this._client_updated_at=new Date(this.updated_at);}}return this._client_updated_at;}// eslint-disable-next-line camelcase
,set:function set(date){this._client_updated_at=date;this.setAppDataItem('client_updated_at',date);}},{key:"neverSynced",get:function get(){return!this.updated_at||this.updated_at.getTime()===0;}/**
* Subclasses can override this getter to return true if they want only
* one of this item to exist, depending on custom criteria.
*/},{key:"isSingleton",get:function get(){return false;}/** The predicate by which singleton items should be unique */},{key:"singletonPredicate",get:function get(){throw'Must override SFItem.singletonPredicate';}},{key:"singletonStrategy",get:function get(){return SingletonStrategies.KeepEarliest;}}]);return SFItem;}();/***/},/***/"./lib/models/core/predicate.js":/*!**************************************!*\
!*** ./lib/models/core/predicate.js ***!
\**************************************/ /*! exports provided: SFPredicate */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"SFPredicate",function(){return SFPredicate;});function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i'){return valueAtKeyPath>predicateValue;}else if(predicate.operator==='<='){return valueAtKeyPath<=predicateValue;}else if(predicate.operator==='>='){return valueAtKeyPath>=predicateValue;}else if(predicate.operator==='startsWith'){return valueAtKeyPath.startsWith(predicateValue);}else if(predicate.operator==='in'){return predicateValue.indexOf(valueAtKeyPath)!==-1;}else if(predicate.operator==='includes'){return this.resolveIncludesPredicate(valueAtKeyPath,predicateValue);}else if(predicate.operator==='matches'){var regex=new RegExp(predicateValue);return regex.test(valueAtKeyPath);}return false;}},{key:"resolveIncludesPredicate",value:function resolveIncludesPredicate(valueAtKeyPath,predicateValue){// includes can be a string or a predicate (in array form)
if(typeof predicateValue==='string'){// if string, simply check if the valueAtKeyPath includes the predicate value
return valueAtKeyPath.includes(predicateValue);}else{// is a predicate array or predicate object
var innerPredicate;if(Array.isArray(predicateValue)){innerPredicate=SFPredicate.FromArray(predicateValue);}else{innerPredicate=predicateValue;}var _iteratorNormalCompletion3=true;var _didIteratorError3=false;var _iteratorError3=undefined;try{for(var _iterator3=valueAtKeyPath[Symbol.iterator](),_step3;!(_iteratorNormalCompletion3=(_step3=_iterator3.next()).done);_iteratorNormalCompletion3=true){var obj=_step3.value;if(this.ObjectSatisfiesPredicate(obj,innerPredicate)){return true;}}}catch(err){_didIteratorError3=true;_iteratorError3=err;}finally{try{if(!_iteratorNormalCompletion3&&_iterator3.return!=null){_iterator3.return();}}finally{if(_didIteratorError3){throw _iteratorError3;}}}return false;}}},{key:"ItemSatisfiesPredicate",value:function ItemSatisfiesPredicate(item,predicate){if(Array.isArray(predicate)){predicate=SFPredicate.FromArray(predicate);}return this.ObjectSatisfiesPredicate(item,predicate);}},{key:"ItemSatisfiesPredicates",value:function ItemSatisfiesPredicates(item,predicates){var _iteratorNormalCompletion4=true;var _didIteratorError4=false;var _iteratorError4=undefined;try{for(var _iterator4=predicates[Symbol.iterator](),_step4;!(_iteratorNormalCompletion4=(_step4=_iterator4.next()).done);_iteratorNormalCompletion4=true){var predicate=_step4.value;if(!this.ItemSatisfiesPredicate(item,predicate)){return false;}}}catch(err){_didIteratorError4=true;_iteratorError4=err;}finally{try{if(!_iteratorNormalCompletion4&&_iterator4.return!=null){_iterator4.return();}}finally{if(_didIteratorError4){throw _iteratorError4;}}}return true;}},{key:"DateFromString",value:function DateFromString(string){// x.days.ago, x.hours.ago
var comps=string.split('.');var unit=comps[1];var date=new Date();var offset=parseInt(comps[0]);if(unit==='days'){date.setDate(date.getDate()-offset);}else if(unit==='hours'){date.setHours(date.getHours()-offset);}return date;}},{key:"IsRecursiveOperator",value:function IsRecursiveOperator(operator){return['and','or'].includes(operator);}}]);return SFPredicate;}();/***/},/***/"./lib/models/generator.js":/*!*********************************!*\
!*** ./lib/models/generator.js ***!
\*********************************/ /*! exports provided: CreateItemFromPayload */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"CreateItemFromPayload",function(){return CreateItemFromPayload;});/* harmony import */var _Models__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Models */"./lib/models/index.js");/* harmony import */var _Models_content_types__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Models/content_types */"./lib/models/content_types.js");var _ContentTypeClassMapp;function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}var ContentTypeClassMapping=(_ContentTypeClassMapp={},_defineProperty(_ContentTypeClassMapp,_Models_content_types__WEBPACK_IMPORTED_MODULE_1__["ContentTypes"].Note,_Models__WEBPACK_IMPORTED_MODULE_0__["SNNote"]),_defineProperty(_ContentTypeClassMapp,_Models_content_types__WEBPACK_IMPORTED_MODULE_1__["ContentTypes"].Tag,_Models__WEBPACK_IMPORTED_MODULE_0__["SNTag"]),_defineProperty(_ContentTypeClassMapp,_Models_content_types__WEBPACK_IMPORTED_MODULE_1__["ContentTypes"].ItemsKey,_Models__WEBPACK_IMPORTED_MODULE_0__["SNItemsKey"]),_defineProperty(_ContentTypeClassMapp,_Models_content_types__WEBPACK_IMPORTED_MODULE_1__["ContentTypes"].SmartTag,_Models__WEBPACK_IMPORTED_MODULE_0__["SNSmartTag"]),_defineProperty(_ContentTypeClassMapp,_Models_content_types__WEBPACK_IMPORTED_MODULE_1__["ContentTypes"].ActionsExtension,_Models__WEBPACK_IMPORTED_MODULE_0__["SNActionsExtension"]),_defineProperty(_ContentTypeClassMapp,_Models_content_types__WEBPACK_IMPORTED_MODULE_1__["ContentTypes"].Editor,_Models__WEBPACK_IMPORTED_MODULE_0__["SNEditor"]),_defineProperty(_ContentTypeClassMapp,_Models_content_types__WEBPACK_IMPORTED_MODULE_1__["ContentTypes"].Theme,_Models__WEBPACK_IMPORTED_MODULE_0__["SNTheme"]),_defineProperty(_ContentTypeClassMapp,_Models_content_types__WEBPACK_IMPORTED_MODULE_1__["ContentTypes"].Component,_Models__WEBPACK_IMPORTED_MODULE_0__["SNComponent"]),_defineProperty(_ContentTypeClassMapp,_Models_content_types__WEBPACK_IMPORTED_MODULE_1__["ContentTypes"].ServerExtension,_Models__WEBPACK_IMPORTED_MODULE_0__["SNServerExtension"]),_defineProperty(_ContentTypeClassMapp,_Models_content_types__WEBPACK_IMPORTED_MODULE_1__["ContentTypes"].Mfa,_Models__WEBPACK_IMPORTED_MODULE_0__["SNMfa"]),_defineProperty(_ContentTypeClassMapp,_Models_content_types__WEBPACK_IMPORTED_MODULE_1__["ContentTypes"].Privileges,_Models__WEBPACK_IMPORTED_MODULE_0__["SFPrivileges"]),_defineProperty(_ContentTypeClassMapp,_Models_content_types__WEBPACK_IMPORTED_MODULE_1__["ContentTypes"].UserPrefs,_Models__WEBPACK_IMPORTED_MODULE_0__["SNUserPrefs"]),_ContentTypeClassMapp);function CreateItemFromPayload(payload){if(!payload.isPayload){throw'Attempting to create item from non-payload object.';}var itemClass=ContentTypeClassMapping[payload.content_type]||_Models__WEBPACK_IMPORTED_MODULE_0__["SFItem"];// eslint-disable-next-line new-cap
return new itemClass(payload);}/***/},/***/"./lib/models/index.js":/*!*****************************!*\
!*** ./lib/models/index.js ***!
\*****************************/ /*! exports provided: SFItem, SingletonStrategies, SNItemsKey, SFPredicate, SNComponent, SNEditor, SNActionsExtension, Action, SNNote, SNTag, SNUserPrefs, SFPrivileges, SNMfa, SNServerExtension, SNSmartTag, SNTheme, SNEncryptedStorage, ContentTypes, displayStringForContentType, CreateItemFromPayload */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony import */var _Models_core_item__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Models/core/item */"./lib/models/core/item.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SFItem",function(){return _Models_core_item__WEBPACK_IMPORTED_MODULE_0__["SFItem"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SingletonStrategies",function(){return _Models_core_item__WEBPACK_IMPORTED_MODULE_0__["SingletonStrategies"];});/* harmony import */var _Models_app_items_key__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Models/app/items_key */"./lib/models/app/items_key.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNItemsKey",function(){return _Models_app_items_key__WEBPACK_IMPORTED_MODULE_1__["SNItemsKey"];});/* harmony import */var _Models_core_predicate__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! @Models/core/predicate */"./lib/models/core/predicate.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SFPredicate",function(){return _Models_core_predicate__WEBPACK_IMPORTED_MODULE_2__["SFPredicate"];});/* harmony import */var _Models_app_component__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! @Models/app/component */"./lib/models/app/component.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNComponent",function(){return _Models_app_component__WEBPACK_IMPORTED_MODULE_3__["SNComponent"];});/* harmony import */var _Models_app_editor__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(/*! @Models/app/editor */"./lib/models/app/editor.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNEditor",function(){return _Models_app_editor__WEBPACK_IMPORTED_MODULE_4__["SNEditor"];});/* harmony import */var _Models_app_extension__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__(/*! @Models/app/extension */"./lib/models/app/extension.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNActionsExtension",function(){return _Models_app_extension__WEBPACK_IMPORTED_MODULE_5__["SNActionsExtension"];});/* harmony import */var _Models_app_action__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__(/*! @Models/app/action */"./lib/models/app/action.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"Action",function(){return _Models_app_action__WEBPACK_IMPORTED_MODULE_6__["Action"];});/* harmony import */var _Models_app_note__WEBPACK_IMPORTED_MODULE_7__=__webpack_require__(/*! @Models/app/note */"./lib/models/app/note.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNNote",function(){return _Models_app_note__WEBPACK_IMPORTED_MODULE_7__["SNNote"];});/* harmony import */var _Models_app_tag__WEBPACK_IMPORTED_MODULE_8__=__webpack_require__(/*! @Models/app/tag */"./lib/models/app/tag.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNTag",function(){return _Models_app_tag__WEBPACK_IMPORTED_MODULE_8__["SNTag"];});/* harmony import */var _Models_app_userPrefs__WEBPACK_IMPORTED_MODULE_9__=__webpack_require__(/*! @Models/app/userPrefs */"./lib/models/app/userPrefs.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNUserPrefs",function(){return _Models_app_userPrefs__WEBPACK_IMPORTED_MODULE_9__["SNUserPrefs"];});/* harmony import */var _Models_privileges_privileges__WEBPACK_IMPORTED_MODULE_10__=__webpack_require__(/*! @Models/privileges/privileges */"./lib/models/privileges/privileges.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SFPrivileges",function(){return _Models_privileges_privileges__WEBPACK_IMPORTED_MODULE_10__["SFPrivileges"];});/* harmony import */var _Models_server_mfa__WEBPACK_IMPORTED_MODULE_11__=__webpack_require__(/*! @Models/server/mfa */"./lib/models/server/mfa.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNMfa",function(){return _Models_server_mfa__WEBPACK_IMPORTED_MODULE_11__["SNMfa"];});/* harmony import */var _Models_server_serverExtension__WEBPACK_IMPORTED_MODULE_12__=__webpack_require__(/*! @Models/server/serverExtension */"./lib/models/server/serverExtension.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNServerExtension",function(){return _Models_server_serverExtension__WEBPACK_IMPORTED_MODULE_12__["SNServerExtension"];});/* harmony import */var _Models_app_smartTag__WEBPACK_IMPORTED_MODULE_13__=__webpack_require__(/*! @Models/app/smartTag */"./lib/models/app/smartTag.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNSmartTag",function(){return _Models_app_smartTag__WEBPACK_IMPORTED_MODULE_13__["SNSmartTag"];});/* harmony import */var _Models_app_theme__WEBPACK_IMPORTED_MODULE_14__=__webpack_require__(/*! @Models/app/theme */"./lib/models/app/theme.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNTheme",function(){return _Models_app_theme__WEBPACK_IMPORTED_MODULE_14__["SNTheme"];});/* harmony import */var _Models_local_encryptedStorage__WEBPACK_IMPORTED_MODULE_15__=__webpack_require__(/*! @Models/local/encryptedStorage */"./lib/models/local/encryptedStorage.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNEncryptedStorage",function(){return _Models_local_encryptedStorage__WEBPACK_IMPORTED_MODULE_15__["SNEncryptedStorage"];});/* harmony import */var _Models_content_types__WEBPACK_IMPORTED_MODULE_16__=__webpack_require__(/*! @Models/content_types */"./lib/models/content_types.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"ContentTypes",function(){return _Models_content_types__WEBPACK_IMPORTED_MODULE_16__["ContentTypes"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"displayStringForContentType",function(){return _Models_content_types__WEBPACK_IMPORTED_MODULE_16__["displayStringForContentType"];});/* harmony import */var _Models_generator__WEBPACK_IMPORTED_MODULE_17__=__webpack_require__(/*! @Models/generator */"./lib/models/generator.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"CreateItemFromPayload",function(){return _Models_generator__WEBPACK_IMPORTED_MODULE_17__["CreateItemFromPayload"];});/***/},/***/"./lib/models/local/encryptedStorage.js":/*!**********************************************!*\
!*** ./lib/models/local/encryptedStorage.js ***!
\**********************************************/ /*! exports provided: SNEncryptedStorage */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"SNEncryptedStorage",function(){return SNEncryptedStorage;});/* harmony import */var _Models_core_item__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Models/core/item */"./lib/models/core/item.js");/* harmony import */var _Models_content_types__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Models/content_types */"./lib/models/content_types.js");function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0&&arguments[0]!==undefined?arguments[0]:{},_ref$payloads=_ref.payloads,payloads=_ref$payloads===void 0?[]:_ref$payloads,source=_ref.source;_classCallCheck(this,PayloadCollection);this.source=source;this.payloadMap={};this.allPayloads=payloads;var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=payloads[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var payload=_step.value;this.payloadMap[payload.uuid]=payload;}}catch(err){_didIteratorError=true;_iteratorError=err;}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return();}}finally{if(_didIteratorError){throw _iteratorError;}}}Object.freeze(this);}_createClass(PayloadCollection,[{key:"findPayload",value:function findPayload(id){return this.payloadMap[id];}},{key:"concat",value:function concat(collection){return new PayloadCollection({payloads:this.allPayloads.concat(collection.allPayloads),source:this.source});}},{key:"payloadsThatReferencePayload",value:function payloadsThatReferencePayload(inPayload){var results=[];for(var _i=0,_Object$keys=Object.keys(this.payloadMap);_i<_Object$keys.length;_i++){var uuid=_Object$keys[_i];var payload=this.payloadMap[uuid];var references=Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["findInArray"])(payload.content.references,'uuid',inPayload.uuid);if(references){results.push(payload);}}return results;}}]);return PayloadCollection;}();/***/},/***/"./lib/protocol/payloads/collection_set.js":/*!*************************************************!*\
!*** ./lib/protocol/payloads/collection_set.js ***!
\*************************************************/ /*! exports provided: PayloadCollectionSet */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"PayloadCollectionSet",function(){return PayloadCollectionSet;});function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0&&_args4[0]!==undefined?_args4[0]:{},ciphertextToAuth=_ref3.ciphertextToAuth,contentCiphertext=_ref3.contentCiphertext,encryptionKey=_ref3.encryptionKey,iv=_ref3.iv;_context4.next=3;return regeneratorRuntime.awrap(this.crypto.hexStringToArrayBuffer(encryptionKey));case 3:keyData=_context4.sent;_context4.next=6;return regeneratorRuntime.awrap(this.crypto.hexStringToArrayBuffer(iv||''));case 6:ivData=_context4.sent;if(!ivData){// in 001, iv can be null, so we'll initialize to an empty array buffer instead
ivData=new ArrayBuffer(16);}return _context4.abrupt("return",this.crypto.aes256CbcDecrypt(contentCiphertext,keyData,ivData));case 9:case"end":return _context4.stop();}}},null,this);}},{key:"encryptText",value:function encryptText(text,rawKey,iv){var keyData,ivData;return regeneratorRuntime.async(function encryptText$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:_context5.next=2;return regeneratorRuntime.awrap(this.crypto.hexStringToArrayBuffer(rawKey));case 2:keyData=_context5.sent;_context5.next=5;return regeneratorRuntime.awrap(this.crypto.hexStringToArrayBuffer(iv||''));case 5:ivData=_context5.sent;if(!ivData){// in 001, iv can be null, so we'll initialize to an empty array buffer instead
ivData=new ArrayBuffer(16);}return _context5.abrupt("return",this.crypto.aes256CbcEncrypt(text,keyData,ivData));case 8:case"end":return _context5.stop();}}},null,this);}},{key:"generateEncryptionParameters",value:function generateEncryptionParameters(_ref4){var payload,key,format,itemKey,encItemKey,ek,ak,ciphertext,authHash;return regeneratorRuntime.async(function generateEncryptionParameters$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:payload=_ref4.payload,key=_ref4.key,format=_ref4.format;if(!(format===_Payloads_formats__WEBPACK_IMPORTED_MODULE_3__["PayloadFormats"].DecryptedBareObject||format===_Payloads_formats__WEBPACK_IMPORTED_MODULE_3__["PayloadFormats"].DecryptedBase64String)){_context6.next=3;break;}return _context6.abrupt("return",_get(_getPrototypeOf(SNProtocolOperator001.prototype),"generateEncryptionParameters",this).call(this,{payload:payload,key:key,format:format}));case 3:if(!(format!==_Payloads_formats__WEBPACK_IMPORTED_MODULE_3__["PayloadFormats"].EncryptedString)){_context6.next=5;break;}throw"Unsupport format for generateEncryptionParameters ".concat(format);case 5:if(!(!key||!key.itemsKey)){_context6.next=7;break;}throw'Attempting to generateEncryptionParameters with no itemsKey.';case 7:_context6.next=9;return regeneratorRuntime.awrap(this.crypto.generateRandomKey(ENCRYPTION_KEY_LENGTH*2));case 9:itemKey=_context6.sent;_context6.next=12;return regeneratorRuntime.awrap(this.encryptText(itemKey,key.itemsKey,null));case 12:encItemKey=_context6.sent;_context6.next=15;return regeneratorRuntime.awrap(this.firstHalfOfKey(itemKey));case 15:ek=_context6.sent;_context6.next=18;return regeneratorRuntime.awrap(this.secondHalfOfKey(itemKey));case 18:ak=_context6.sent;_context6.next=21;return regeneratorRuntime.awrap(this.privateEncryptString(JSON.stringify(payload.content),ek,ak,payload.uuid,key.version));case 21:ciphertext=_context6.sent;_context6.next=24;return regeneratorRuntime.awrap(this.crypto.hmac256(ciphertext,ak));case 24:authHash=_context6.sent;return _context6.abrupt("return",Object(_Payloads_generator__WEBPACK_IMPORTED_MODULE_4__["CreateEncryptionParameters"])({enc_item_key:encItemKey,content:ciphertext,auth_hash:authHash}));case 26:case"end":return _context6.stop();}}},null,this);}},{key:"generateDecryptedParameters",value:function generateDecryptedParameters(_ref5){var encryptedParameters,key,format,encryptedItemKey,itemKeyComponents,_override,itemKey,_override2,itemParams,_override3,content,_override4,_override5;return regeneratorRuntime.async(function generateDecryptedParameters$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:encryptedParameters=_ref5.encryptedParameters,key=_ref5.key;format=encryptedParameters.getContentFormat();if(!(format===_Payloads_formats__WEBPACK_IMPORTED_MODULE_3__["PayloadFormats"].DecryptedBareObject||format===_Payloads_formats__WEBPACK_IMPORTED_MODULE_3__["PayloadFormats"].DecryptedBase64String)){_context7.next=4;break;}return _context7.abrupt("return",_get(_getPrototypeOf(SNProtocolOperator001.prototype),"generateDecryptedParameters",this).call(this,{encryptedParameters:encryptedParameters,key:key}));case 4:if(encryptedParameters.enc_item_key){_context7.next=7;break;}console.error("Missing item encryption key, skipping decryption.");return _context7.abrupt("return",encryptedParameters);case 7:/** Decrypt encrypted key */encryptedItemKey=encryptedParameters.enc_item_key;encryptedItemKey=_Protocol_versions__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V001+encryptedItemKey;itemKeyComponents=this.encryptionComponentsFromString(encryptedItemKey,key.itemsKey);// return if uuid in auth hash does not match item uuid. Signs of tampering.
if(!(itemKeyComponents.uuid&&itemKeyComponents.uuid!==encryptedParameters.uuid)){_context7.next=13;break;}console.error("Item key params UUID does not match item UUID");return _context7.abrupt("return",Object(_Payloads_generator__WEBPACK_IMPORTED_MODULE_4__["CopyEncryptionParameters"])({encryptionParameters:encryptedParameters,override:(_override={},_defineProperty(_override,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecrypting,true),_defineProperty(_override,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecryptingChanged,!encryptedParameters.errorDecrypting),_override)}));case 13:_context7.next=15;return regeneratorRuntime.awrap(this.decryptText(itemKeyComponents));case 15:itemKey=_context7.sent;if(itemKey){_context7.next=19;break;}console.error("Error decrypting parameters",encryptedParameters);return _context7.abrupt("return",Object(_Payloads_generator__WEBPACK_IMPORTED_MODULE_4__["CopyEncryptionParameters"])({encryptionParameters:encryptedParameters,override:(_override2={},_defineProperty(_override2,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecrypting,true),_defineProperty(_override2,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecryptingChanged,!encryptedParameters.errorDecrypting),_override2)}));case 19:itemParams=this.encryptionComponentsFromString(encryptedParameters.content,itemKey);// return if uuid in auth hash does not match item uuid. Signs of tampering.
if(!(itemParams.uuid&&itemParams.uuid!==encryptedParameters.uuid)){_context7.next=22;break;}return _context7.abrupt("return",Object(_Payloads_generator__WEBPACK_IMPORTED_MODULE_4__["CopyEncryptionParameters"])({encryptionParameters:encryptedParameters,override:(_override3={},_defineProperty(_override3,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecrypting,true),_defineProperty(_override3,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecryptingChanged,!encryptedParameters.errorDecrypting),_override3)}));case 22:_context7.next=24;return regeneratorRuntime.awrap(this.decryptText(itemParams,true));case 24:content=_context7.sent;if(content){_context7.next=29;break;}return _context7.abrupt("return",Object(_Payloads_generator__WEBPACK_IMPORTED_MODULE_4__["CopyEncryptionParameters"])({encryptionParameters:encryptedParameters,override:(_override4={},_defineProperty(_override4,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecrypting,true),_defineProperty(_override4,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecryptingChanged,!encryptedParameters.errorDecrypting),_override4)}));case 29:return _context7.abrupt("return",Object(_Payloads_generator__WEBPACK_IMPORTED_MODULE_4__["CopyEncryptionParameters"])({encryptionParameters:encryptedParameters,override:(_override5={},_defineProperty(_override5,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].Content,JSON.parse(content)),_defineProperty(_override5,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecrypting,false),_defineProperty(_override5,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecryptingChanged,encryptedParameters.errorDecrypting===true),_defineProperty(_override5,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].WaitingForKey,false),_override5)}));case 30:case"end":return _context7.stop();}}},null,this);}/**
* @private
*/},{key:"encryptionComponentsFromString",value:function encryptionComponentsFromString(string,encryptionKey){var encryptionVersion=string.substring(0,_Protocol_versions__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].VersionLength);return{contentCiphertext:string.substring(_Protocol_versions__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].VersionLength,string.length),encryptionVersion:encryptionVersion,encryptionKey:encryptionKey,iv:null};}},{key:"deriveKey",value:function deriveKey(){var _ref6,password,pwSalt,pwCost,derivedKey,partitions,key,_args8=arguments;return regeneratorRuntime.async(function deriveKey$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:_ref6=_args8.length>0&&_args8[0]!==undefined?_args8[0]:{},password=_ref6.password,pwSalt=_ref6.pwSalt,pwCost=_ref6.pwCost;_context8.next=3;return regeneratorRuntime.awrap(this.crypto.pbkdf2({password:password,salt:pwSalt,iterations:pwCost,length:PBKDF2_OUTPUT_KEY_LENGTH}));case 3:derivedKey=_context8.sent;_context8.next=6;return regeneratorRuntime.awrap(this.splitKey({key:derivedKey,numParts:2}));case 6:partitions=_context8.sent;_context8.next=9;return regeneratorRuntime.awrap(_Protocol_versions_root_key__WEBPACK_IMPORTED_MODULE_6__["SNRootKey"].Create({content:{serverPassword:partitions[0],masterKey:partitions[1],version:this.constructor.versionString()}}));case 9:key=_context8.sent;return _context8.abrupt("return",key);case 11:case"end":return _context8.stop();}}},null,this);}/** @private */},{key:"privateEncryptString",value:function privateEncryptString(string,encryptionKey,authKey,uuid,version){var contentCiphertext,fullCiphertext;return regeneratorRuntime.async(function privateEncryptString$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:_context9.next=2;return regeneratorRuntime.awrap(this.encryptText(string,encryptionKey,null));case 2:contentCiphertext=_context9.sent;fullCiphertext=version+contentCiphertext;return _context9.abrupt("return",fullCiphertext);case 5:case"end":return _context9.stop();}}},null,this);}}],[{key:"pwCost",value:function pwCost(){return PBKDF2_ITERATIONS;}},{key:"versionString",value:function versionString(){return _Protocol_versions__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V001;}},{key:"encryptionKeyLength",value:function encryptionKeyLength(){return ENCRYPTION_KEY_LENGTH;}}]);return SNProtocolOperator001;}(_Protocol_versions_operator__WEBPACK_IMPORTED_MODULE_0__["SNProtocolOperator"]);/***/},/***/"./lib/protocol/versions/002/operator_002.js":/*!***************************************************!*\
!*** ./lib/protocol/versions/002/operator_002.js ***!
\***************************************************/ /*! exports provided: SNProtocolOperator002 */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"SNProtocolOperator002",function(){return SNProtocolOperator002;});/* harmony import */var _Protocol_versions_key_params__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Protocol/versions/key_params */"./lib/protocol/versions/key_params.js");/* harmony import */var _Protocol_versions_001_operator_001__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Protocol/versions/001/operator_001 */"./lib/protocol/versions/001/operator_001.js");/* harmony import */var _Payloads_fields__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! @Payloads/fields */"./lib/protocol/payloads/fields.js");/* harmony import */var _Payloads_formats__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! @Payloads/formats */"./lib/protocol/payloads/formats.js");/* harmony import */var _Payloads_generator__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(/*! @Payloads/generator */"./lib/protocol/payloads/generator.js");/* harmony import */var _Protocol_versions__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__(/*! @Protocol/versions */"./lib/protocol/versions.js");/* harmony import */var _Protocol_versions_root_key__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__(/*! @Protocol/versions/root_key */"./lib/protocol/versions/root_key.js");function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0&&_args4[0]!==undefined?_args4[0]:{},ciphertextToAuth=_ref3.ciphertextToAuth,contentCiphertext=_ref3.contentCiphertext,encryptionKey=_ref3.encryptionKey,iv=_ref3.iv,authHash=_ref3.authHash,authKey=_ref3.authKey;requiresAuth=_args4.length>1?_args4[1]:undefined;if(encryptionKey){_context4.next=4;break;}throw'Attempting to decryptText with null encryptionKey';case 4:if(!(requiresAuth&&!authHash)){_context4.next=7;break;}console.error("Auth hash is required.");return _context4.abrupt("return");case 7:if(!authHash){_context4.next=14;break;}_context4.next=10;return regeneratorRuntime.awrap(this.crypto.hmac256(ciphertextToAuth,authKey));case 10:localAuthHash=_context4.sent;if(!(this.crypto.timingSafeEqual(authHash,localAuthHash)===false)){_context4.next=14;break;}console.error("Auth hash does not match, returning null.");return _context4.abrupt("return",null);case 14:_context4.next=16;return regeneratorRuntime.awrap(this.crypto.hexStringToArrayBuffer(encryptionKey));case 16:keyData=_context4.sent;_context4.next=19;return regeneratorRuntime.awrap(this.crypto.hexStringToArrayBuffer(iv||""));case 19:ivData=_context4.sent;return _context4.abrupt("return",this.crypto.aes256CbcDecrypt(contentCiphertext,keyData,ivData));case 21:case"end":return _context4.stop();}}},null,this);}},{key:"encryptText",value:function encryptText(text,rawKey,iv){var keyData,ivData;return regeneratorRuntime.async(function encryptText$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:_context5.next=2;return regeneratorRuntime.awrap(this.crypto.hexStringToArrayBuffer(rawKey));case 2:keyData=_context5.sent;_context5.next=5;return regeneratorRuntime.awrap(this.crypto.hexStringToArrayBuffer(iv||""));case 5:ivData=_context5.sent;return _context5.abrupt("return",this.crypto.aes256CbcEncrypt(text,keyData,ivData));case 7:case"end":return _context5.stop();}}},null,this);}},{key:"generateEncryptionParameters",value:function generateEncryptionParameters(_ref4){var payload,key,format,itemKey,encItemKey,ek,ak,ciphertext;return regeneratorRuntime.async(function generateEncryptionParameters$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:payload=_ref4.payload,key=_ref4.key,format=_ref4.format;if(!(format===_Payloads_formats__WEBPACK_IMPORTED_MODULE_3__["PayloadFormats"].DecryptedBareObject||format===_Payloads_formats__WEBPACK_IMPORTED_MODULE_3__["PayloadFormats"].DecryptedBase64String)){_context6.next=3;break;}return _context6.abrupt("return",_get(_getPrototypeOf(SNProtocolOperator002.prototype),"generateEncryptionParameters",this).call(this,{payload:payload,key:key,format:format}));case 3:if(!(format!==_Payloads_formats__WEBPACK_IMPORTED_MODULE_3__["PayloadFormats"].EncryptedString)){_context6.next=5;break;}throw"Unsupport format for generateEncryptionParameters ".concat(format);case 5:if(!(!key||!key.itemsKey)){_context6.next=7;break;}throw'Attempting to generateEncryptionParameters with no itemsKey.';case 7:_context6.next=9;return regeneratorRuntime.awrap(this.crypto.generateRandomKey(ENCRYPTION_KEY_LENGTH*2));case 9:itemKey=_context6.sent;_context6.next=12;return regeneratorRuntime.awrap(this.privateEncryptString(itemKey,key.itemsKey,key.dataAuthenticationKey,payload.uuid,key.version));case 12:encItemKey=_context6.sent;_context6.next=15;return regeneratorRuntime.awrap(this.firstHalfOfKey(itemKey));case 15:ek=_context6.sent;_context6.next=18;return regeneratorRuntime.awrap(this.secondHalfOfKey(itemKey));case 18:ak=_context6.sent;_context6.next=21;return regeneratorRuntime.awrap(this.privateEncryptString(JSON.stringify(payload.content),ek,ak,payload.uuid,key.version));case 21:ciphertext=_context6.sent;return _context6.abrupt("return",Object(_Payloads_generator__WEBPACK_IMPORTED_MODULE_4__["CreateEncryptionParameters"])({content:ciphertext,enc_item_key:encItemKey}));case 23:case"end":return _context6.stop();}}},null,this);}},{key:"generateDecryptedParameters",value:function generateDecryptedParameters(_ref5){var encryptedParameters,key,format,encryptedItemKey,requiresAuth,itemKeyComponents,_override,itemKey,_override2,ek,ak,itemParams,_override3,content,_override4,_override5,authParams;return regeneratorRuntime.async(function generateDecryptedParameters$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:encryptedParameters=_ref5.encryptedParameters,key=_ref5.key;format=encryptedParameters.getContentFormat();if(!(format===_Payloads_formats__WEBPACK_IMPORTED_MODULE_3__["PayloadFormats"].DecryptedBareObject||format===_Payloads_formats__WEBPACK_IMPORTED_MODULE_3__["PayloadFormats"].DecryptedBase64String)){_context7.next=4;break;}return _context7.abrupt("return",_get(_getPrototypeOf(SNProtocolOperator002.prototype),"generateDecryptedParameters",this).call(this,{encryptedParameters:encryptedParameters,key:key}));case 4:if(encryptedParameters.enc_item_key){_context7.next=7;break;}console.error("Missing item encryption key, skipping decryption.");return _context7.abrupt("return",encryptedParameters);case 7:if(!(!key||!key.itemsKey)){_context7.next=9;break;}throw'Attempting to generateDecryptedParameters with no itemsKey.';case 9:// decrypt encrypted key
encryptedItemKey=encryptedParameters.enc_item_key;requiresAuth=true;itemKeyComponents=this.encryptionComponentsFromString(encryptedItemKey,key.itemsKey,key.dataAuthenticationKey);// return if uuid in auth hash does not match item uuid. Signs of tampering.
if(!(itemKeyComponents.uuid&&itemKeyComponents.uuid!==encryptedParameters.uuid)){_context7.next=15;break;}console.error("Item key params UUID does not match item UUID");return _context7.abrupt("return",Object(_Payloads_generator__WEBPACK_IMPORTED_MODULE_4__["CopyEncryptionParameters"])({encryptionParameters:encryptedParameters,override:(_override={},_defineProperty(_override,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecrypting,true),_defineProperty(_override,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecryptingChanged,!encryptedParameters.errorDecrypting),_override)}));case 15:_context7.next=17;return regeneratorRuntime.awrap(this.decryptText(itemKeyComponents,requiresAuth));case 17:itemKey=_context7.sent;if(itemKey){_context7.next=21;break;}itemKey.error("Error decrypting item_key parameters",encryptedParameters);return _context7.abrupt("return",Object(_Payloads_generator__WEBPACK_IMPORTED_MODULE_4__["CopyEncryptionParameters"])({encryptionParameters:encryptedParameters,override:(_override2={},_defineProperty(_override2,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecrypting,true),_defineProperty(_override2,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecryptingChanged,!encryptedParameters.errorDecrypting),_override2)}));case 21:_context7.next=23;return regeneratorRuntime.awrap(this.firstHalfOfKey(itemKey));case 23:ek=_context7.sent;_context7.next=26;return regeneratorRuntime.awrap(this.secondHalfOfKey(itemKey));case 26:ak=_context7.sent;itemParams=this.encryptionComponentsFromString(encryptedParameters.content,ek,ak);// return if uuid in auth hash does not match item uuid. Signs of tampering.
if(!(itemParams.uuid&&itemParams.uuid!==encryptedParameters.uuid)){_context7.next=30;break;}return _context7.abrupt("return",Object(_Payloads_generator__WEBPACK_IMPORTED_MODULE_4__["CopyEncryptionParameters"])({encryptionParameters:encryptedParameters,override:(_override3={},_defineProperty(_override3,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecrypting,true),_defineProperty(_override3,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecryptingChanged,!encryptedParameters.errorDecrypting),_override3)}));case 30:_context7.next=32;return regeneratorRuntime.awrap(this.decryptText(itemParams,true));case 32:content=_context7.sent;if(content){_context7.next=37;break;}return _context7.abrupt("return",Object(_Payloads_generator__WEBPACK_IMPORTED_MODULE_4__["CopyEncryptionParameters"])({encryptionParameters:encryptedParameters,override:(_override4={},_defineProperty(_override4,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecrypting,true),_defineProperty(_override4,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecryptingChanged,!encryptedParameters.errorDecrypting),_override4)}));case 37:_context7.prev=37;_context7.t0=JSON;_context7.next=41;return regeneratorRuntime.awrap(this.crypto.base64Decode(itemParams.authParams));case 41:_context7.t1=_context7.sent;authParams=_context7.t0.parse.call(_context7.t0,_context7.t1);_context7.next=47;break;case 45:_context7.prev=45;_context7.t2=_context7["catch"](37);case 47:return _context7.abrupt("return",Object(_Payloads_generator__WEBPACK_IMPORTED_MODULE_4__["CopyEncryptionParameters"])({encryptionParameters:encryptedParameters,override:(_override5={},_defineProperty(_override5,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].Content,JSON.parse(content)),_defineProperty(_override5,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].Legacy003AuthParams,authParams),_defineProperty(_override5,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecrypting,false),_defineProperty(_override5,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].ErrorDecryptingChanged,encryptedParameters.errorDecrypting===true),_defineProperty(_override5,_Payloads_fields__WEBPACK_IMPORTED_MODULE_2__["PayloadFields"].WaitingForKey,false),_override5)}));case 48:case"end":return _context7.stop();}}},null,this,[[37,45]]);}/** @protected */},{key:"deriveKey",value:function deriveKey(){var _ref6,password,pwSalt,pwCost,derivedKey,partitions,key,_args8=arguments;return regeneratorRuntime.async(function deriveKey$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:_ref6=_args8.length>0&&_args8[0]!==undefined?_args8[0]:{},password=_ref6.password,pwSalt=_ref6.pwSalt,pwCost=_ref6.pwCost;if(!(!pwCost||!pwSalt||!password)){_context8.next=3;break;}throw'Attempting to 003.deriveKey with invalid parameters';case 3:_context8.next=5;return regeneratorRuntime.awrap(this.crypto.pbkdf2({password:password,salt:pwSalt,iterations:pwCost,length:PBKDF2_OUTPUT_KEY_LENGTH}));case 5:derivedKey=_context8.sent;_context8.next=8;return regeneratorRuntime.awrap(this.splitKey({key:derivedKey,numParts:3}));case 8:partitions=_context8.sent;_context8.next=11;return regeneratorRuntime.awrap(_Protocol_versions_root_key__WEBPACK_IMPORTED_MODULE_6__["SNRootKey"].Create({content:{serverPassword:partitions[0],masterKey:partitions[1],dataAuthenticationKey:partitions[2],version:this.constructor.versionString()}}));case 11:key=_context8.sent;return _context8.abrupt("return",key);case 13:case"end":return _context8.stop();}}},null,this);}/** @private */},{key:"privateEncryptString",value:function privateEncryptString(string,encryptionKey,authKey,uuid,version){var iv,contentCiphertext,ciphertextToAuth,authHash,fullCiphertext;return regeneratorRuntime.async(function privateEncryptString$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:_context9.next=2;return regeneratorRuntime.awrap(this.crypto.generateRandomKey(ENCRYPTION_IV_LENGTH));case 2:iv=_context9.sent;_context9.next=5;return regeneratorRuntime.awrap(this.encryptText(string,encryptionKey,iv));case 5:contentCiphertext=_context9.sent;ciphertextToAuth=[version,uuid,iv,contentCiphertext].join(':');_context9.next=9;return regeneratorRuntime.awrap(this.crypto.hmac256(ciphertextToAuth,authKey));case 9:authHash=_context9.sent;fullCiphertext=[version,authHash,uuid,iv,contentCiphertext].join(':');return _context9.abrupt("return",fullCiphertext);case 12:case"end":return _context9.stop();}}},null,this);}},{key:"encryptionComponentsFromString",value:function encryptionComponentsFromString(string,encryptionKey,authKey){var components=string.split(':');return{encryptionVersion:components[0],authHash:components[1],uuid:components[2],iv:components[3],contentCiphertext:components[4],ciphertextToAuth:[components[0],components[2],components[3],components[4]].join(':'),encryptionKey:encryptionKey,authKey:authKey};}}],[{key:"pwCost",value:function pwCost(){return PBKDF2_ITERATIONS;}},{key:"versionString",value:function versionString(){return _Protocol_versions__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V002;}},{key:"encryptionKeyLength",value:function encryptionKeyLength(){return ENCRYPTION_KEY_LENGTH;}}]);return SNProtocolOperator002;}(_Protocol_versions_001_operator_001__WEBPACK_IMPORTED_MODULE_1__["SNProtocolOperator001"]);/***/},/***/"./lib/protocol/versions/003/operator_003.js":/*!***************************************************!*\
!*** ./lib/protocol/versions/003/operator_003.js ***!
\***************************************************/ /*! exports provided: SNProtocolOperator003 */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"SNProtocolOperator003",function(){return SNProtocolOperator003;});/* harmony import */var _Protocol_versions_key_params__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Protocol/versions/key_params */"./lib/protocol/versions/key_params.js");/* harmony import */var _Protocol_versions_002_operator_002__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Protocol/versions/002/operator_002 */"./lib/protocol/versions/002/operator_002.js");/* harmony import */var _Protocol_versions__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! @Protocol/versions */"./lib/protocol/versions.js");function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0&&_args10[0]!==undefined?_args10[0]:{},password=_ref9.password,salt=_ref9.salt,iterations=_ref9.iterations;if(!(!iterations||!salt||!password)){_context10.next=3;break;}throw'Attempting to 004.deriveKey with invalid parameters';case 3:_context10.next=5;return regeneratorRuntime.awrap(this.crypto.pbkdf2({password:password,salt:salt,iterations:iterations,length:PBKDF2_OUTPUT_KEY_LENGTH}));case 5:derivedKey=_context10.sent;_context10.next=8;return regeneratorRuntime.awrap(this.splitKey({key:derivedKey,numParts:2}));case 8:partitions=_context10.sent;masterKey=partitions[0];serverPassword=partitions[1];/** @todo: HKDF each key to domain-seperate. */_context10.next=13;return regeneratorRuntime.awrap(_Protocol_versions_root_key__WEBPACK_IMPORTED_MODULE_6__["SNRootKey"].Create({content:{masterKey:masterKey,serverPassword:serverPassword,version:this.constructor.versionString()}}));case 13:key=_context10.sent;return _context10.abrupt("return",key);case 15:case"end":return _context10.stop();}}},null,this);}}],[{key:"versionString",/**
* The protocol version. Will be prefixed to encrypted payloads.
*/value:function versionString(){return _Protocol_versions__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V004;}/**
* The number of PBKDF2 iterations.
*/},{key:"kdfIterations",value:function kdfIterations(){return PBKDF2_ITERATIONS;}},{key:"encryptionAlgorithm",value:function encryptionAlgorithm(){return ENCRYPTION_ALGORITHM;}},{key:"encryptionKeyLength",value:function encryptionKeyLength(){return ENCRYPTION_KEY_LENGTH;}}]);return SNProtocolOperator004;}(_Protocol_versions_003_operator_003__WEBPACK_IMPORTED_MODULE_1__["SNProtocolOperator003"]);/***/},/***/"./lib/protocol/versions/key_params.js":/*!*********************************************!*\
!*** ./lib/protocol/versions/key_params.js ***!
\*********************************************/ /*! exports provided: CreateKeyParams, SNRootKeyParams */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"CreateKeyParams",function(){return CreateKeyParams;});/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"SNRootKeyParams",function(){return SNRootKeyParams;});/* harmony import */var _Lib_utils__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Lib/utils */"./lib/utils.js");function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0;});}/**
* Loads an extension in the context of a certain item.
* The server then has the chance to respond with actions that are
* relevant just to this item. The response extension is not saved,
* just displayed as a one-time thing.
*/},{key:"loadExtensionInContextOfItem",value:function loadExtensionInContextOfItem(extension,item){var params;return regeneratorRuntime.async(function loadExtensionInContextOfItem$(_context){while(1){switch(_context.prev=_context.next){case 0:params={content_type:item.content_type,item_uuid:item.uuid};return _context.abrupt("return",this.httpManager.getAbsolute({url:extension.url,params:params}).then(function(response){if(response.description){extension.description=response.description;}if(response.supported_types){extension.supported_types=response.supported_types;}if(response.actions){extension.actions=response.actions.map(function(action){return new _Models__WEBPACK_IMPORTED_MODULE_3__["Action"](action);});}else{extension.actions=[];}return extension;}).catch(function(response){console.error("Error loading extension",response);return null;}));case 2:case"end":return _context.stop();}}},null,this);}},{key:"runAction",value:function runAction(_ref2){var action,item,passwordRequestHandler,result;return regeneratorRuntime.async(function runAction$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:action=_ref2.action,item=_ref2.item,passwordRequestHandler=_ref2.passwordRequestHandler;action.running=true;_context2.t0=action.verb;_context2.next=_context2.t0==='get'?5:_context2.t0==='render'?9:_context2.t0==='show'?13:_context2.t0==='post'?17:21;break;case 5:_context2.next=7;return regeneratorRuntime.awrap(this.handleGetAction({action:action,passwordRequestHandler:passwordRequestHandler}));case 7:result=_context2.sent;return _context2.abrupt("break",22);case 9:_context2.next=11;return regeneratorRuntime.awrap(this.handleRenderAction({action:action,passwordRequestHandler:passwordRequestHandler}));case 11:result=_context2.sent;return _context2.abrupt("break",22);case 13:_context2.next=15;return regeneratorRuntime.awrap(this.handleShowAction(action));case 15:result=_context2.sent;return _context2.abrupt("break",22);case 17:_context2.next=19;return regeneratorRuntime.awrap(this.handlePostAction(action,item));case 19:result=_context2.sent;return _context2.abrupt("break",22);case 21:return _context2.abrupt("break",22);case 22:action.lastExecuted=new Date();action.running=false;return _context2.abrupt("return",result);case 25:case"end":return _context2.stop();}}},null,this);}},{key:"handleGetAction",value:function handleGetAction(_ref3){var _this2=this;var action,passwordRequestHandler;return regeneratorRuntime.async(function handleGetAction$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:action=_ref3.action,passwordRequestHandler=_ref3.passwordRequestHandler;return _context3.abrupt("return",new Promise(function(resolve,reject){_this2.application.alertManager.confirm({text:"Are you sure you want to replace the current note contents with this action's results?",onConfirm:function onConfirm(){_this2.runConfirmedGetAction({action:action,passwordRequestHandler:passwordRequestHandler}).then(resolve);}});}));case 2:case"end":return _context3.stop();}}});}},{key:"runConfirmedGetAction",value:function runConfirmedGetAction(_ref4){var _this3=this;var action,passwordRequestHandler,response,payload,items,_iteratorNormalCompletion,_didIteratorError,_iteratorError,_iterator,_step,mappedItem;return regeneratorRuntime.async(function runConfirmedGetAction$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:action=_ref4.action,passwordRequestHandler=_ref4.passwordRequestHandler;_context4.next=3;return regeneratorRuntime.awrap(this.httpManager.getAbsolute(action.url,{}).catch(function(response){var error=response&&response.error||{message:"An issue occurred while processing this action. Please try again."};_this3.application.alertManager.alert({text:error.message});action.error=true;return{error:error};}));case 3:response=_context4.sent;if(!response.error){_context4.next=6;break;}return _context4.abrupt("return",response);case 6:action.error=false;_context4.next=9;return regeneratorRuntime.awrap(this.payloadByDecryptingResponse({response:response,passwordRequestHandler:passwordRequestHandler}));case 9:payload=_context4.sent;_context4.next=12;return regeneratorRuntime.awrap(this.modelManager.mapPayload({payload:payload,source:_Payloads__WEBPACK_IMPORTED_MODULE_0__["PayloadSources"].RemoteActionRetrieved}));case 12:items=_context4.sent;_iteratorNormalCompletion=true;_didIteratorError=false;_iteratorError=undefined;_context4.prev=16;for(_iterator=items[Symbol.iterator]();!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){mappedItem=_step.value;this.modelManager.setItemDirty(mappedItem,true);}_context4.next=24;break;case 20:_context4.prev=20;_context4.t0=_context4["catch"](16);_didIteratorError=true;_iteratorError=_context4.t0;case 24:_context4.prev=24;_context4.prev=25;if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return();}case 27:_context4.prev=27;if(!_didIteratorError){_context4.next=30;break;}throw _iteratorError;case 30:return _context4.finish(27);case 31:return _context4.finish(24);case 32:this.syncManager.sync();return _context4.abrupt("return",{response:response,item:response.item});case 34:case"end":return _context4.stop();}}},null,this,[[16,20,24,32],[25,,27,31]]);}},{key:"handleRenderAction",value:function handleRenderAction(_ref5){var _this4=this;var action,passwordRequestHandler;return regeneratorRuntime.async(function handleRenderAction$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:action=_ref5.action,passwordRequestHandler=_ref5.passwordRequestHandler;return _context6.abrupt("return",this.httpManager.getAbsolute(action.url,{}).then(function _callee(response){var payload,item;return regeneratorRuntime.async(function _callee$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:action.error=false;_context5.next=3;return regeneratorRuntime.awrap(_this4.payloadByDecryptingResponse({response:response,passwordRequestHandler:passwordRequestHandler}));case 3:payload=_context5.sent;if(!payload){_context5.next=7;break;}item=_this4.modelManager.mapPayload({payload:payload});return _context5.abrupt("return",{response:response,item:item});case 7:case"end":return _context5.stop();}}});}).catch(function(response){var error=response&&response.error||{message:"An issue occurred while processing this action. Please try again."};_this4.application.alertManager.alert({text:error.message});action.error=true;return{error:error};}));case 2:case"end":return _context6.stop();}}},null,this);}},{key:"payloadByDecryptingResponse",value:function payloadByDecryptingResponse(_ref6){var response,key,passwordRequestHandler,decryptedPayload,triedPasswords,_iteratorNormalCompletion2,_didIteratorError2,_iteratorError2,_iterator2,_step2,passwordCandidate,_key,nestedResponse,password;return regeneratorRuntime.async(function payloadByDecryptingResponse$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:response=_ref6.response,key=_ref6.key,passwordRequestHandler=_ref6.passwordRequestHandler;_context7.next=3;return regeneratorRuntime.awrap(this.protocolService.payloadsByDecryptingRawPayload({rawPayload:response.item,key:key}));case 3:decryptedPayload=_context7.sent;if(decryptedPayload.errorDecrypting){_context7.next=6;break;}return _context7.abrupt("return",decryptedPayload);case 6:if(response.auth_params){_context7.next=9;break;}/**
* In some cases revisions were missing auth params.
* Instruct the user to email us to get this remedied.
*/this.application.alertManager.alert({text:"We were unable to decrypt this revision using your current keys, \n and this revision is missing metadata that would allow us to try different \n keys to decrypt it. This can likely be fixed with some manual intervention. \n Please email hello@standardnotes.org for assistance."});return _context7.abrupt("return",null);case 9:/* Try previous passwords */triedPasswords=[];_iteratorNormalCompletion2=true;_didIteratorError2=false;_iteratorError2=undefined;_context7.prev=13;_iterator2=this.previousPasswords[Symbol.iterator]();case 15:if(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done){_context7.next=33;break;}passwordCandidate=_step2.value;if(!triedPasswords.includes(passwordCandidate)){_context7.next=19;break;}return _context7.abrupt("continue",30);case 19:triedPasswords.push(passwordCandidate);_context7.next=22;return regeneratorRuntime.awrap(this.protocolService.computeRootKey({password:passwordCandidate,keyParams:response.auth_params}));case 22:_key=_context7.sent;if(_key){_context7.next=25;break;}return _context7.abrupt("continue",30);case 25:_context7.next=27;return regeneratorRuntime.awrap(this.payloadByDecryptingResponse({response:response,key:_key,passwordRequestHandler:passwordRequestHandler}));case 27:nestedResponse=_context7.sent;if(!nestedResponse){_context7.next=30;break;}return _context7.abrupt("return",nestedResponse);case 30:_iteratorNormalCompletion2=true;_context7.next=15;break;case 33:_context7.next=39;break;case 35:_context7.prev=35;_context7.t0=_context7["catch"](13);_didIteratorError2=true;_iteratorError2=_context7.t0;case 39:_context7.prev=39;_context7.prev=40;if(!_iteratorNormalCompletion2&&_iterator2.return!=null){_iterator2.return();}case 42:_context7.prev=42;if(!_didIteratorError2){_context7.next=45;break;}throw _iteratorError2;case 45:return _context7.finish(42);case 46:return _context7.finish(39);case 47:_context7.next=49;return regeneratorRuntime.awrap(passwordRequestHandler());case 49:password=_context7.sent;this.previousPasswords.push(password);return _context7.abrupt("return",this.payloadByDecryptingResponse({response:response,key:key,passwordRequestHandler:passwordRequestHandler}));case 52:case"end":return _context7.stop();}}},null,this,[[13,35,39,47],[40,,42,46]]);}},{key:"handlePostAction",value:function handlePostAction(action,item){var _this5=this;var decrypted,itemParams,params;return regeneratorRuntime.async(function handlePostAction$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:decrypted=action.access_type==='decrypted';_context8.next=3;return regeneratorRuntime.awrap(this.outgoingPayloadForItem({item:item,decrypted:decrypted}));case 3:itemParams=_context8.sent;params={items:[itemParams]};return _context8.abrupt("return",this.httpManager.postAbsolute(action.url,params).then(function(response){action.error=false;return{response:response};}).catch(function(response){action.error=true;console.error("Action error response:",response);_this5.application.alertManager.alert({text:"An issue occurred while processing this action. Please try again."});return{response:response};}));case 6:case"end":return _context8.stop();}}},null,this);}},{key:"handleShowAction",value:function handleShowAction(action){return regeneratorRuntime.async(function handleShowAction$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:this.deviceInterface.openUrl(action.url);return _context9.abrupt("return",{response:null});case 2:case"end":return _context9.stop();}}},null,this);}},{key:"outgoingPayloadForItem",value:function outgoingPayloadForItem(_ref7){var item,_ref7$decrypted,decrypted,intent;return regeneratorRuntime.async(function outgoingPayloadForItem$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:item=_ref7.item,_ref7$decrypted=_ref7.decrypted,decrypted=_ref7$decrypted===void 0?false:_ref7$decrypted;intent=decrypted?_Protocol__WEBPACK_IMPORTED_MODULE_1__["EncryptionIntents"].FileDecrypted:_Protocol__WEBPACK_IMPORTED_MODULE_1__["EncryptionIntents"].FileEncrypted;return _context10.abrupt("return",this.protocolService.payloadByEncryptingPayload({payload:item.payloadRepresentation(),intent:intent}));case 3:case"end":return _context10.stop();}}},null,this);}}]);return SNActionsManager;}(_Lib_services_pure_service__WEBPACK_IMPORTED_MODULE_2__["PureService"]);/***/},/***/"./lib/services/alert_manager.js":/*!***************************************!*\
!*** ./lib/services/alert_manager.js ***!
\***************************************/ /*! exports provided: SNAlertManager */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"SNAlertManager",function(){return SNAlertManager;});/* harmony import */var _Lib_services_pure_service__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Lib/services/pure_service */"./lib/services/pure_service.js");function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0&&source!==_Payloads__WEBPACK_IMPORTED_MODULE_5__["PayloadSources"].RemoteSaved){// Ensure any component in our data is installed by the system
if(_this2.isDesktop){_this2.desktopManager.syncComponentsInstallation(syncedComponents);}}_iteratorNormalCompletion=true;_didIteratorError=false;_iteratorError=undefined;_context.prev=5;_iterator=syncedComponents[Symbol.iterator]();case 7:if(_iteratorNormalCompletion=(_step=_iterator.next()).done){_context.next=21;break;}component=_step.value;activeComponent=lodash_find__WEBPACK_IMPORTED_MODULE_0___default()(_this2.activeComponents,{uuid:component.uuid});if(!(component.active&&!component.deleted&&!activeComponent)){_context.next=15;break;}_context.next=13;return regeneratorRuntime.awrap(_this2.activateComponent(component));case 13:_context.next=18;break;case 15:if(!(!component.active&&activeComponent)){_context.next=18;break;}_context.next=18;return regeneratorRuntime.awrap(_this2.deactivateComponent(component));case 18:_iteratorNormalCompletion=true;_context.next=7;break;case 21:_context.next=27;break;case 23:_context.prev=23;_context.t0=_context["catch"](5);_didIteratorError=true;_iteratorError=_context.t0;case 27:_context.prev=27;_context.prev=28;if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return();}case 30:_context.prev=30;if(!_didIteratorError){_context.next=33;break;}throw _iteratorError;case 33:return _context.finish(30);case 34:return _context.finish(27);case 35:_iteratorNormalCompletion2=true;_didIteratorError2=false;_iteratorError2=undefined;_context.prev=38;_loop=function _loop(){var observer=_step2.value;if(sourceKey&&sourceKey===observer.component.uuid){// Don't notify source of change, as it is the originator, doesn't need duplicate event.
return"continue";}var relevantItems=allItems.filter(function(item){return observer.contentTypes.indexOf(item.content_type)!==-1;});if(relevantItems.length===0){return"continue";}var requiredPermissions=[{name:"stream-items",content_types:observer.contentTypes.sort()}];_this2.runWithPermissions(observer.component,requiredPermissions,function(){_this2.sendItemsInReply(observer.component,relevantItems,observer.originalMessage);});};_iterator2=_this2.streamObservers[Symbol.iterator]();case 41:if(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done){_context.next=48;break;}_ret=_loop();if(!(_ret==="continue")){_context.next=45;break;}return _context.abrupt("continue",45);case 45:_iteratorNormalCompletion2=true;_context.next=41;break;case 48:_context.next=54;break;case 50:_context.prev=50;_context.t1=_context["catch"](38);_didIteratorError2=true;_iteratorError2=_context.t1;case 54:_context.prev=54;_context.prev=55;if(!_iteratorNormalCompletion2&&_iterator2.return!=null){_iterator2.return();}case 57:_context.prev=57;if(!_didIteratorError2){_context.next=60;break;}throw _iteratorError2;case 60:return _context.finish(57);case 61:return _context.finish(54);case 62:requiredContextPermissions=[{name:"stream-context-item"}];_iteratorNormalCompletion3=true;_didIteratorError3=false;_iteratorError3=undefined;_context.prev=66;_loop2=function _loop2(){var observer=_step3.value;if(sourceKey&&sourceKey===observer.component.uuid){// Don't notify source of change, as it is the originator, doesn't need duplicate event.
return"continue";}var _iteratorNormalCompletion4=true;var _didIteratorError4=false;var _iteratorError4=undefined;try{for(var _iterator4=_this2.handlers[Symbol.iterator](),_step4;!(_iteratorNormalCompletion4=(_step4=_iterator4.next()).done);_iteratorNormalCompletion4=true){var handler=_step4.value;if(!handler.areas.includes(observer.component.area)&&!handler.areas.includes("*")){continue;}if(handler.contextRequestHandler){var itemInContext=handler.contextRequestHandler(observer.component);if(itemInContext){(function(){var matchingItem=lodash_find__WEBPACK_IMPORTED_MODULE_0___default()(allItems,{uuid:itemInContext.uuid});if(matchingItem){_this2.runWithPermissions(observer.component,requiredContextPermissions,function(){_this2.sendContextItemInReply(observer.component,matchingItem,observer.originalMessage,source);});}})();}}}}catch(err){_didIteratorError4=true;_iteratorError4=err;}finally{try{if(!_iteratorNormalCompletion4&&_iterator4.return!=null){_iterator4.return();}}finally{if(_didIteratorError4){throw _iteratorError4;}}}};_iterator3=_this2.contextStreamObservers[Symbol.iterator]();case 69:if(_iteratorNormalCompletion3=(_step3=_iterator3.next()).done){_context.next=76;break;}_ret2=_loop2();if(!(_ret2==="continue")){_context.next=73;break;}return _context.abrupt("continue",73);case 73:_iteratorNormalCompletion3=true;_context.next=69;break;case 76:_context.next=82;break;case 78:_context.prev=78;_context.t2=_context["catch"](66);_didIteratorError3=true;_iteratorError3=_context.t2;case 82:_context.prev=82;_context.prev=83;if(!_iteratorNormalCompletion3&&_iterator3.return!=null){_iterator3.return();}case 85:_context.prev=85;if(!_didIteratorError3){_context.next=88;break;}throw _iteratorError3;case 88:return _context.finish(85);case 89:return _context.finish(82);case 90:case"end":return _context.stop();}}},null,null,[[5,23,27,35],[28,,30,34],[38,50,54,62],[55,,57,61],[66,78,82,90],[83,,85,89]]);});}},{key:"configureForNonMobileUsage",value:function configureForNonMobileUsage(){var _this3=this;var detectFocusChange=function detectFocusChange(event){var _iteratorNormalCompletion5=true;var _didIteratorError5=false;var _iteratorError5=undefined;try{var _loop3=function _loop3(){var component=_step5.value;if(document.activeElement===_this3.iframeForComponent(component)){_this3.timeout(function(){_this3.focusChangedForComponent(component);});return"break";}};for(var _iterator5=_this3.activeComponents[Symbol.iterator](),_step5;!(_iteratorNormalCompletion5=(_step5=_iterator5.next()).done);_iteratorNormalCompletion5=true){var _ret3=_loop3();if(_ret3==="break")break;}}catch(err){_didIteratorError5=true;_iteratorError5=err;}finally{try{if(!_iteratorNormalCompletion5&&_iterator5.return!=null){_iterator5.return();}}finally{if(_didIteratorError5){throw _iteratorError5;}}}};window.addEventListener?window.addEventListener('focus',detectFocusChange,true):window.attachEvent('onfocusout',detectFocusChange);window.addEventListener?window.addEventListener('blur',detectFocusChange,true):window.attachEvent('onblur',detectFocusChange);// On mobile, events listeners are handled by a respective component
window.addEventListener("message",function(event){_this3.log("Web app: received message",event);// Make sure this message is for us
if(event.data.sessionKey){_this3.handleMessage(_this3.componentForSessionKey(event.data.sessionKey),event.data);}},false);}},{key:"configureForDesktop",value:function configureForDesktop(){var _this4=this;this.desktopManager.registerUpdateObserver(function(component){// Reload theme if active
if(component.active&&component.isTheme()){_this4.postActiveThemesToAllComponents();}});}},{key:"postActiveThemesToAllComponents",value:function postActiveThemesToAllComponents(){var _iteratorNormalCompletion6=true;var _didIteratorError6=false;var _iteratorError6=undefined;try{for(var _iterator6=this.components[Symbol.iterator](),_step6;!(_iteratorNormalCompletion6=(_step6=_iterator6.next()).done);_iteratorNormalCompletion6=true){var component=_step6.value;// Skip over components that are themes themselves,
// or components that are not active, or components that don't have a window
if(component.isTheme()||!component.active||!component.window){continue;}this.postActiveThemesToComponent(component);}}catch(err){_didIteratorError6=true;_iteratorError6=err;}finally{try{if(!_iteratorNormalCompletion6&&_iterator6.return!=null){_iterator6.return();}}finally{if(_didIteratorError6){throw _iteratorError6;}}}}},{key:"getActiveThemes",value:function getActiveThemes(){return this.componentsForArea("themes").filter(function(theme){return theme.active;});}},{key:"urlsForActiveThemes",value:function urlsForActiveThemes(){var _this5=this;var themes=this.getActiveThemes();return themes.map(function(theme){return _this5.urlForComponent(theme);});}},{key:"postActiveThemesToComponent",value:function postActiveThemesToComponent(component){var urls=this.urlsForActiveThemes();var data={themes:urls};this.sendMessageToComponent(component,{action:"themes",data:data});}},{key:"contextItemDidChangeInArea",value:function contextItemDidChangeInArea(area){var _iteratorNormalCompletion7=true;var _didIteratorError7=false;var _iteratorError7=undefined;try{for(var _iterator7=this.handlers[Symbol.iterator](),_step7;!(_iteratorNormalCompletion7=(_step7=_iterator7.next()).done);_iteratorNormalCompletion7=true){var handler=_step7.value;if(handler.areas.includes(area)===false&&!handler.areas.includes("*")){continue;}var observers=this.contextStreamObservers.filter(function(observer){return observer.component.area===area;});var _iteratorNormalCompletion8=true;var _didIteratorError8=false;var _iteratorError8=undefined;try{for(var _iterator8=observers[Symbol.iterator](),_step8;!(_iteratorNormalCompletion8=(_step8=_iterator8.next()).done);_iteratorNormalCompletion8=true){var observer=_step8.value;if(handler.contextRequestHandler){var itemInContext=handler.contextRequestHandler(observer.component);if(itemInContext){this.sendContextItemInReply(observer.component,itemInContext,observer.originalMessage);}}}}catch(err){_didIteratorError8=true;_iteratorError8=err;}finally{try{if(!_iteratorNormalCompletion8&&_iterator8.return!=null){_iterator8.return();}}finally{if(_didIteratorError8){throw _iteratorError8;}}}}}catch(err){_didIteratorError7=true;_iteratorError7=err;}finally{try{if(!_iteratorNormalCompletion7&&_iterator7.return!=null){_iterator7.return();}}finally{if(_didIteratorError7){throw _iteratorError7;}}}}},{key:"setComponentHidden",value:function setComponentHidden(component,hidden){/*
A hidden component will not receive messages.
However, when a component is unhidden, we need to send it any items it may have
registered streaming for.
*/if(hidden){component.hidden=true;}else if(component.hidden){// Only enter this condition if component is hidden to make this note have double side effects.
component.hidden=false;// streamContextItem
var contextObserver=lodash_find__WEBPACK_IMPORTED_MODULE_0___default()(this.contextStreamObservers,{identifier:component.uuid});if(contextObserver){this.handleStreamContextItemMessage(component,contextObserver.originalMessage);}// streamItems
var streamObserver=lodash_find__WEBPACK_IMPORTED_MODULE_0___default()(this.streamObservers,{identifier:component.uuid});if(streamObserver){this.handleStreamItemsMessage(component,streamObserver.originalMessage);}}}},{key:"jsonForItem",value:function jsonForItem(item,component,source){var params={uuid:item.uuid,content_type:item.content_type,created_at:item.created_at,updated_at:item.updated_at,deleted:item.deleted};params.content=item.collapseContent();params.clientData=item.getDomainDataItem(component.getClientDataKey(),SNComponentManager.ClientDataDomain)||{};// isMetadataUpdate implies that the extension should make reference of updated metadata,
// but not update content values as they may be stale relative to what the extension currently has
// Changes are always metadata updates if the mapping source is PayloadSources.RemoteSaved || source === PayloadSources.LocalSaved.
//
if(source&&(source===_Payloads__WEBPACK_IMPORTED_MODULE_5__["PayloadSources"].RemoteSaved||source===_Payloads__WEBPACK_IMPORTED_MODULE_5__["PayloadSources"].LocalSaved)){params.isMetadataUpdate=true;}this.removePrivatePropertiesFromResponseItems([params],component,{type:"outgoing"});return params;}},{key:"sendItemsInReply",value:function sendItemsInReply(component,items,message,source){var _this6=this;this.log("Web|componentManager|sendItemsInReply",component,items,message);var response={items:{}};var mapped=items.map(function(item){return _this6.jsonForItem(item,component,source);});response.items=mapped;this.replyToMessage(component,message,response);}},{key:"sendContextItemInReply",value:function sendContextItemInReply(component,item,originalMessage,source){this.log("Web|componentManager|sendContextItemInReply",component,item,originalMessage);var response={item:this.jsonForItem(item,component,source)};this.replyToMessage(component,originalMessage,response);}},{key:"replyToMessage",value:function replyToMessage(component,originalMessage,replyData){var reply={action:"reply",original:originalMessage,data:replyData};this.sendMessageToComponent(component,reply);}},{key:"sendMessageToComponent",value:function sendMessageToComponent(component,message){var permissibleActionsWhileHidden=["component-registered","themes"];if(component.hidden&&!permissibleActionsWhileHidden.includes(message.action)){this.log("Component disabled for current item, not sending any messages.",component.name);return;}this.log("Web|sendMessageToComponent",component,message);var origin=this.urlForComponent(component);if(!origin.startsWith("http")&&!origin.startsWith("file")){// Native extension running in web, prefix current host
origin=window.location.href+origin;}if(!component.window){this.alertManager.alert({text:"Standard Notes is trying to communicate with ".concat(component.name,", but an error is occurring. Please restart this extension and try again.")});}// Mobile messaging requires json
if(this.isMobile){message=JSON.stringify(message);}component.window.postMessage(message,origin);}},{key:"componentsForArea",value:function componentsForArea(area){return this.components.filter(function(component){return component.area===area;});}},{key:"urlForComponent",value:function urlForComponent(component){// offlineOnly is available only on desktop, and not on web or mobile.
if(component.offlineOnly&&!this.isDesktop){return null;}if(component.offlineOnly||this.isDesktop&&component.local_url){return component.local_url&&component.local_url.replace("sn://",this.desktopManager.getExtServerHost());}else{var url=component.hosted_url||component.legacy_url;if(this.isMobile){var localReplacement=this.platform==="ios"?"localhost":"10.0.2.2";url=url.replace("localhost",localReplacement).replace("sn.local",localReplacement);}return url;}}},{key:"componentForUrl",value:function componentForUrl(url){return this.components.filter(function(component){return component.hosted_url===url||component.legacy_url===url;})[0];}},{key:"componentForSessionKey",value:function componentForSessionKey(key){var component=lodash_find__WEBPACK_IMPORTED_MODULE_0___default()(this.components,{sessionKey:key});if(!component){var _iteratorNormalCompletion9=true;var _didIteratorError9=false;var _iteratorError9=undefined;try{for(var _iterator9=this.handlers[Symbol.iterator](),_step9;!(_iteratorNormalCompletion9=(_step9=_iterator9.next()).done);_iteratorNormalCompletion9=true){var handler=_step9.value;if(handler.componentForSessionKeyHandler){component=handler.componentForSessionKeyHandler(key);if(component){break;}}}}catch(err){_didIteratorError9=true;_iteratorError9=err;}finally{try{if(!_iteratorNormalCompletion9&&_iterator9.return!=null){_iterator9.return();}}finally{if(_didIteratorError9){throw _iteratorError9;}}}}return component;}},{key:"handleMessage",value:function handleMessage(component,message){var _this7=this;if(!component){this.log("Component not defined for message, returning",message);this.alertManager.alert({text:"An extension is trying to communicate with Standard Notes, but there is an error establishing a bridge. Please restart the app and try again."});return;}// Actions that won't succeeed with readonly mode
var readwriteActions=["save-items","associate-item","deassociate-item","create-item","create-items","delete-items","set-component-data"];if(component.readonly&&readwriteActions.includes(message.action)){// A component can be marked readonly if changes should not be saved.
// Particullary used for revision preview windows where the notes should not be savable.
this.alertManager.alert({text:"The extension ".concat(component.name," is trying to save, but it is in a locked state and cannot accept changes.")});return;}/**
Possible Messages:
set-size
stream-items
stream-context-item
save-items
select-item
associate-item
deassociate-item
clear-selection
create-item
create-items
delete-items
set-component-data
install-local-component
toggle-activate-component
request-permissions
present-conflict-resolution
*/if(message.action==="stream-items"){this.handleStreamItemsMessage(component,message);}else if(message.action==="stream-context-item"){this.handleStreamContextItemMessage(component,message);}else if(message.action==="set-component-data"){this.handleSetComponentDataMessage(component,message);}else if(message.action==="delete-items"){this.handleDeleteItemsMessage(component,message);}else if(message.action==="create-items"||message.action==="create-item"){this.handleCreateItemsMessage(component,message);}else if(message.action==="save-items"){this.handleSaveItemsMessage(component,message);}else if(message.action==="toggle-activate-component"){var componentToToggle=this.modelManager.findItem(message.data.uuid);this.handleToggleComponentMessage(component,componentToToggle,message);}else if(message.action==="request-permissions"){this.handleRequestPermissionsMessage(component,message);}else if(message.action==="install-local-component"){this.handleInstallLocalComponentMessage(component,message);}else if(message.action==="duplicate-item"){this.handleDuplicateItemMessage(component,message);}// Notify observers
var _iteratorNormalCompletion10=true;var _didIteratorError10=false;var _iteratorError10=undefined;try{var _loop4=function _loop4(){var handler=_step10.value;if(handler.actionHandler&&(handler.areas.includes(component.area)||handler.areas.includes("*"))){_this7.timeout(function(){handler.actionHandler(component,message.action,message.data);});}};for(var _iterator10=this.handlers[Symbol.iterator](),_step10;!(_iteratorNormalCompletion10=(_step10=_iterator10.next()).done);_iteratorNormalCompletion10=true){_loop4();}}catch(err){_didIteratorError10=true;_iteratorError10=err;}finally{try{if(!_iteratorNormalCompletion10&&_iterator10.return!=null){_iterator10.return();}}finally{if(_didIteratorError10){throw _iteratorError10;}}}}},{key:"removePrivatePropertiesFromResponseItems",value:function removePrivatePropertiesFromResponseItems(responseItems,component){var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};// can be 'incoming' or 'outgoing'. We want to remove updated_at if incoming, but keep it if outgoing
if(options.type==="incoming"){var privateTopLevelProperties=["updated_at"];// Maintaining our own updated_at value is imperative for sync to work properly, we ignore any incoming value.
var _iteratorNormalCompletion11=true;var _didIteratorError11=false;var _iteratorError11=undefined;try{for(var _iterator11=responseItems[Symbol.iterator](),_step11;!(_iteratorNormalCompletion11=(_step11=_iterator11.next()).done);_iteratorNormalCompletion11=true){var responseItem=_step11.value;if(responseItem.isItem){console.error("Attempting to pass object. Use JSON.");continue;}var _iteratorNormalCompletion12=true;var _didIteratorError12=false;var _iteratorError12=undefined;try{for(var _iterator12=privateTopLevelProperties[Symbol.iterator](),_step12;!(_iteratorNormalCompletion12=(_step12=_iterator12.next()).done);_iteratorNormalCompletion12=true){var privateProperty=_step12.value;delete responseItem[privateProperty];}}catch(err){_didIteratorError12=true;_iteratorError12=err;}finally{try{if(!_iteratorNormalCompletion12&&_iterator12.return!=null){_iterator12.return();}}finally{if(_didIteratorError12){throw _iteratorError12;}}}}}catch(err){_didIteratorError11=true;_iteratorError11=err;}finally{try{if(!_iteratorNormalCompletion11&&_iterator11.return!=null){_iterator11.return();}}finally{if(_didIteratorError11){throw _iteratorError11;}}}}if(component){// System extensions can bypass this step
if(component.isNativeExtension){return;}}// Don't allow component to overwrite these properties.
var privateContentProperties=["autoupdateDisabled","permissions","active"];if(options){if(options.includeUrls){privateContentProperties=privateContentProperties.concat(["url","hosted_url","local_url"]);}}var _iteratorNormalCompletion13=true;var _didIteratorError13=false;var _iteratorError13=undefined;try{for(var _iterator13=responseItems[Symbol.iterator](),_step13;!(_iteratorNormalCompletion13=(_step13=_iterator13.next()).done);_iteratorNormalCompletion13=true){var _responseItem=_step13.value;// Do not pass in actual items here, otherwise that would be destructive.
// Instead, generic JS/JSON objects should be passed.
if(_responseItem.isItem){console.error("Attempting to pass object. Use JSON.");continue;}var _iteratorNormalCompletion14=true;var _didIteratorError14=false;var _iteratorError14=undefined;try{for(var _iterator14=privateContentProperties[Symbol.iterator](),_step14;!(_iteratorNormalCompletion14=(_step14=_iterator14.next()).done);_iteratorNormalCompletion14=true){var prop=_step14.value;delete _responseItem.content[prop];}}catch(err){_didIteratorError14=true;_iteratorError14=err;}finally{try{if(!_iteratorNormalCompletion14&&_iterator14.return!=null){_iterator14.return();}}finally{if(_didIteratorError14){throw _iteratorError14;}}}}}catch(err){_didIteratorError13=true;_iteratorError13=err;}finally{try{if(!_iteratorNormalCompletion13&&_iterator13.return!=null){_iterator13.return();}}finally{if(_didIteratorError13){throw _iteratorError13;}}}}},{key:"handleStreamItemsMessage",value:function handleStreamItemsMessage(component,message){var _this8=this;var requiredPermissions=[{name:"stream-items",content_types:message.data.content_types.sort()}];this.runWithPermissions(component,requiredPermissions,function(){if(!lodash_find__WEBPACK_IMPORTED_MODULE_0___default()(_this8.streamObservers,{identifier:component.uuid})){// for pushing laster as changes come in
_this8.streamObservers.push({identifier:component.uuid,component:component,originalMessage:message,contentTypes:message.data.content_types});}// push immediately now
var items=[];var _iteratorNormalCompletion15=true;var _didIteratorError15=false;var _iteratorError15=undefined;try{for(var _iterator15=message.data.content_types[Symbol.iterator](),_step15;!(_iteratorNormalCompletion15=(_step15=_iterator15.next()).done);_iteratorNormalCompletion15=true){var contentType=_step15.value;items=items.concat(_this8.modelManager.validItemsForContentType(contentType));}}catch(err){_didIteratorError15=true;_iteratorError15=err;}finally{try{if(!_iteratorNormalCompletion15&&_iterator15.return!=null){_iterator15.return();}}finally{if(_didIteratorError15){throw _iteratorError15;}}}_this8.sendItemsInReply(component,items,message);});}},{key:"handleStreamContextItemMessage",value:function handleStreamContextItemMessage(component,message){var _this9=this;var requiredPermissions=[{name:"stream-context-item"}];this.runWithPermissions(component,requiredPermissions,function(){if(!lodash_find__WEBPACK_IMPORTED_MODULE_0___default()(_this9.contextStreamObservers,{identifier:component.uuid})){// for pushing laster as changes come in
_this9.contextStreamObservers.push({identifier:component.uuid,component:component,originalMessage:message});}// push immediately now
var _iteratorNormalCompletion16=true;var _didIteratorError16=false;var _iteratorError16=undefined;try{for(var _iterator16=_this9.handlersForArea(component.area)[Symbol.iterator](),_step16;!(_iteratorNormalCompletion16=(_step16=_iterator16.next()).done);_iteratorNormalCompletion16=true){var handler=_step16.value;if(handler.contextRequestHandler){var itemInContext=handler.contextRequestHandler(component);if(itemInContext){_this9.sendContextItemInReply(component,itemInContext,message);}}}}catch(err){_didIteratorError16=true;_iteratorError16=err;}finally{try{if(!_iteratorNormalCompletion16&&_iterator16.return!=null){_iterator16.return();}}finally{if(_didIteratorError16){throw _iteratorError16;}}}});}},{key:"isItemIdWithinComponentContextJurisdiction",value:function isItemIdWithinComponentContextJurisdiction(uuid,component){var itemIdsInJurisdiction=this.itemIdsInContextJurisdictionForComponent(component);return itemIdsInJurisdiction.includes(uuid);}/* Returns items that given component has context permissions for */},{key:"itemIdsInContextJurisdictionForComponent",value:function itemIdsInContextJurisdictionForComponent(component){var itemIds=[];var _iteratorNormalCompletion17=true;var _didIteratorError17=false;var _iteratorError17=undefined;try{for(var _iterator17=this.handlersForArea(component.area)[Symbol.iterator](),_step17;!(_iteratorNormalCompletion17=(_step17=_iterator17.next()).done);_iteratorNormalCompletion17=true){var handler=_step17.value;if(handler.contextRequestHandler){var itemInContext=handler.contextRequestHandler(component);if(itemInContext){itemIds.push(itemInContext.uuid);}}}}catch(err){_didIteratorError17=true;_iteratorError17=err;}finally{try{if(!_iteratorNormalCompletion17&&_iterator17.return!=null){_iterator17.return();}}finally{if(_didIteratorError17){throw _iteratorError17;}}}return itemIds;}},{key:"handlersForArea",value:function handlersForArea(area){return this.handlers.filter(function(candidate){return candidate.areas.includes(area);});}},{key:"handleSaveItemsMessage",value:function handleSaveItemsMessage(component,message){var _this10=this;var responseItems,requiredPermissions,itemIdsInContextJurisdiction,pendingResponseItems,_iteratorNormalCompletion18,_didIteratorError18,_iteratorError18,_iterator18,_step18,responseItem,requiredContentTypes;return regeneratorRuntime.async(function handleSaveItemsMessage$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:responseItems=message.data.items;requiredPermissions=[];itemIdsInContextJurisdiction=this.itemIdsInContextJurisdictionForComponent(component);// Pending as in needed to be accounted for in permissions.
pendingResponseItems=responseItems.slice();_iteratorNormalCompletion18=true;_didIteratorError18=false;_iteratorError18=undefined;_context3.prev=7;_iterator18=responseItems.slice()[Symbol.iterator]();case 9:if(_iteratorNormalCompletion18=(_step18=_iterator18.next()).done){_context3.next=18;break;}responseItem=_step18.value;if(!itemIdsInContextJurisdiction.includes(responseItem.uuid)){_context3.next=15;break;}requiredPermissions.push({name:"stream-context-item"});lodash_pull__WEBPACK_IMPORTED_MODULE_1___default()(pendingResponseItems,responseItem);// We break because there can only be one context item
return _context3.abrupt("break",18);case 15:_iteratorNormalCompletion18=true;_context3.next=9;break;case 18:_context3.next=24;break;case 20:_context3.prev=20;_context3.t0=_context3["catch"](7);_didIteratorError18=true;_iteratorError18=_context3.t0;case 24:_context3.prev=24;_context3.prev=25;if(!_iteratorNormalCompletion18&&_iterator18.return!=null){_iterator18.return();}case 27:_context3.prev=27;if(!_didIteratorError18){_context3.next=30;break;}throw _iteratorError18;case 30:return _context3.finish(27);case 31:return _context3.finish(24);case 32:// Check to see if additional privileges are required
if(pendingResponseItems.length>0){requiredContentTypes=lodash_uniq__WEBPACK_IMPORTED_MODULE_2___default()(pendingResponseItems.map(function(i){return i.content_type;})).sort();requiredPermissions.push({name:"stream-items",content_types:requiredContentTypes});}this.runWithPermissions(component,requiredPermissions,function _callee2(){var ids,items,lockedCount,_iteratorNormalCompletion19,_didIteratorError19,_iteratorError19,_iterator19,_step19,item,itemNoun,auxVerb,payloads,localItems,_iteratorNormalCompletion20,_didIteratorError20,_iteratorError20,_iterator20,_step20,responseItem,_item;return regeneratorRuntime.async(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:_this10.removePrivatePropertiesFromResponseItems(responseItems,component,{includeUrls:true,type:"incoming"});/*
We map the items here because modelManager is what updates the UI. If you were to instead get the items directly,
this would update them server side via sync, but would never make its way back to the UI.
*/ // Filter locked items
ids=responseItems.map(function(i){return i.uuid;});items=_this10.modelManager.findItems(ids);lockedCount=0;_iteratorNormalCompletion19=true;_didIteratorError19=false;_iteratorError19=undefined;_context2.prev=7;for(_iterator19=items[Symbol.iterator]();!(_iteratorNormalCompletion19=(_step19=_iterator19.next()).done);_iteratorNormalCompletion19=true){item=_step19.value;if(item.locked){lodash_remove__WEBPACK_IMPORTED_MODULE_3___default()(responseItems,{uuid:item.uuid});lockedCount++;}}_context2.next=15;break;case 11:_context2.prev=11;_context2.t0=_context2["catch"](7);_didIteratorError19=true;_iteratorError19=_context2.t0;case 15:_context2.prev=15;_context2.prev=16;if(!_iteratorNormalCompletion19&&_iterator19.return!=null){_iterator19.return();}case 18:_context2.prev=18;if(!_didIteratorError19){_context2.next=21;break;}throw _iteratorError19;case 21:return _context2.finish(18);case 22:return _context2.finish(15);case 23:if(lockedCount>0){itemNoun=lockedCount===1?"item":"items";auxVerb=lockedCount===1?"is":"are";_this10.alertManager.alert({title:'Items Locked',text:"".concat(lockedCount," ").concat(itemNoun," you are attempting to save ").concat(auxVerb," locked and cannot be edited.")});}payloads=responseItems.map(function(responseItem){return Object(_Payloads__WEBPACK_IMPORTED_MODULE_5__["CreateMaxPayloadFromAnyObject"])({object:responseItem});});_context2.next=27;return regeneratorRuntime.awrap(_this10.modelManager.mapPayloadsToLocalItems({paylods:payloads,source:_Payloads__WEBPACK_IMPORTED_MODULE_5__["PayloadSources"].ComponentRetrieved,sourceKey:component.uuid}));case 27:localItems=_context2.sent;_iteratorNormalCompletion20=true;_didIteratorError20=false;_iteratorError20=undefined;_context2.prev=31;_iterator20=responseItems[Symbol.iterator]();case 33:if(_iteratorNormalCompletion20=(_step20=_iterator20.next()).done){_context2.next=46;break;}responseItem=_step20.value;_item=lodash_find__WEBPACK_IMPORTED_MODULE_0___default()(localItems,{uuid:responseItem.uuid});if(_item){_context2.next=39;break;}// An item this extension is trying to save was possibly removed locally, notify user
_this10.alertManager.alert({text:"The extension ".concat(component.name," is trying to save an item with type ").concat(responseItem.content_type,", but that item does not exist. Please restart this extension and try again.")});return _context2.abrupt("continue",43);case 39:if(_item.locked){_context2.next=43;break;}if(responseItem.clientData){_item.setDomainDataItem(component.getClientDataKey(),responseItem.clientData,SNComponentManager.ClientDataDomain);}_context2.next=43;return regeneratorRuntime.awrap(_this10.modelManager.setItemDirty(_item,true,true,_Payloads__WEBPACK_IMPORTED_MODULE_5__["PayloadSources"].ComponentRetrieved,component.uuid));case 43:_iteratorNormalCompletion20=true;_context2.next=33;break;case 46:_context2.next=52;break;case 48:_context2.prev=48;_context2.t1=_context2["catch"](31);_didIteratorError20=true;_iteratorError20=_context2.t1;case 52:_context2.prev=52;_context2.prev=53;if(!_iteratorNormalCompletion20&&_iterator20.return!=null){_iterator20.return();}case 55:_context2.prev=55;if(!_didIteratorError20){_context2.next=58;break;}throw _iteratorError20;case 58:return _context2.finish(55);case 59:return _context2.finish(52);case 60:_this10.syncManager.sync().then(function(response){// Allow handlers to be notified when a save begins and ends, to update the UI
var saveMessage=Object.assign({},message);saveMessage.action=response&&response.error?"save-error":"save-success";_this10.replyToMessage(component,message,{error:response&&response.error});_this10.handleMessage(component,saveMessage);});case 61:case"end":return _context2.stop();}}},null,null,[[7,11,15,23],[16,,18,22],[31,48,52,60],[53,,55,59]]);});case 34:case"end":return _context3.stop();}}},null,this,[[7,20,24,32],[25,,27,31]]);}},{key:"handleDuplicateItemMessage",value:function handleDuplicateItemMessage(component,message){var _this11=this;var itemParams=message.data.item;var item=this.modelManager.findItem(itemParams.uuid);var requiredPermissions=[{name:"stream-items",content_types:[item.content_type]}];this.runWithPermissions(component,requiredPermissions,function _callee3(){var duplicate;return regeneratorRuntime.async(function _callee3$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:_context4.next=2;return regeneratorRuntime.awrap(_this11.modelManager.duplicateItem({item:item}));case 2:duplicate=_context4.sent;_this11.syncManager.sync();_this11.replyToMessage(component,message,{item:_this11.jsonForItem(duplicate,component)});case 5:case"end":return _context4.stop();}}});});}},{key:"handleCreateItemsMessage",value:function handleCreateItemsMessage(component,message){var _this12=this;var responseItems=message.data.item?[message.data.item]:message.data.items;var uniqueContentTypes=lodash_uniq__WEBPACK_IMPORTED_MODULE_2___default()(responseItems.map(function(item){return item.content_type;}));var requiredPermissions=[{name:"stream-items",content_types:uniqueContentTypes}];this.runWithPermissions(component,requiredPermissions,function _callee4(){var processedItems,_iteratorNormalCompletion21,_didIteratorError21,_iteratorError21,_iterator21,_step21,responseItem,payload,item,reply;return regeneratorRuntime.async(function _callee4$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:_this12.removePrivatePropertiesFromResponseItems(responseItems,component,{type:"incoming"});processedItems=[];_iteratorNormalCompletion21=true;_didIteratorError21=false;_iteratorError21=undefined;_context5.prev=5;_iterator21=responseItems[Symbol.iterator]();case 7:if(_iteratorNormalCompletion21=(_step21=_iterator21.next()).done){_context5.next=21;break;}responseItem=_step21.value;payload=Object(_Payloads__WEBPACK_IMPORTED_MODULE_5__["CreateSourcedPayloadFromObject"])({object:responseItem,source:_Payloads__WEBPACK_IMPORTED_MODULE_5__["PayloadSources"].RemoteRetrieved});item=Object(_Models__WEBPACK_IMPORTED_MODULE_6__["CreateItemFromPayload"])(payload);if(responseItem.clientData){item.setDomainDataItem(component.getClientDataKey(),responseItem.clientData,SNComponentManager.ClientDataDomain);}_this12.modelManager.addItem(item);_context5.next=15;return regeneratorRuntime.awrap(_this12.modelManager.resolveReferencesForItem(item,true));case 15:_context5.next=17;return regeneratorRuntime.awrap(_this12.modelManager.setItemDirty(item,true));case 17:processedItems.push(item);case 18:_iteratorNormalCompletion21=true;_context5.next=7;break;case 21:_context5.next=27;break;case 23:_context5.prev=23;_context5.t0=_context5["catch"](5);_didIteratorError21=true;_iteratorError21=_context5.t0;case 27:_context5.prev=27;_context5.prev=28;if(!_iteratorNormalCompletion21&&_iterator21.return!=null){_iterator21.return();}case 30:_context5.prev=30;if(!_didIteratorError21){_context5.next=33;break;}throw _iteratorError21;case 33:return _context5.finish(30);case 34:return _context5.finish(27);case 35:_this12.syncManager.sync();// "create-item" or "create-items" are possible messages handled here
reply=message.action==="create-item"?{item:_this12.jsonForItem(processedItems[0],component)}:{items:processedItems.map(function(item){return _this12.jsonForItem(item,component);})};_this12.replyToMessage(component,message,reply);case 38:case"end":return _context5.stop();}}},null,null,[[5,23,27,35],[28,,30,34]]);});}},{key:"handleDeleteItemsMessage",value:function handleDeleteItemsMessage(component,message){var _this13=this;var requiredContentTypes=lodash_uniq__WEBPACK_IMPORTED_MODULE_2___default()(message.data.items.map(function(i){return i.content_type;})).sort();var requiredPermissions=[{name:"stream-items",content_types:requiredContentTypes}];this.runWithPermissions(component,requiredPermissions,function _callee5(){var itemsData,noun,reply,didConfirm,_iteratorNormalCompletion22,_didIteratorError22,_iteratorError22,_iterator22,_step22,itemData,model;return regeneratorRuntime.async(function _callee5$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:itemsData=message.data.items;noun=itemsData.length===1?"item":"items";reply=null;didConfirm=true;_context6.next=6;return regeneratorRuntime.awrap(_this13.alertManager.confirm({text:"Are you sure you want to delete ".concat(itemsData.length," ").concat(noun,"?")}).catch(function(){didConfirm=false;}));case 6:if(!didConfirm){_context6.next=45;break;}// Filter for any components and deactivate before deleting
_iteratorNormalCompletion22=true;_didIteratorError22=false;_iteratorError22=undefined;_context6.prev=10;_iterator22=itemsData[Symbol.iterator]();case 12:if(_iteratorNormalCompletion22=(_step22=_iterator22.next()).done){_context6.next=27;break;}itemData=_step22.value;model=_this13.modelManager.findItem(itemData.uuid);if(model){_context6.next=18;break;}_this13.alertManager.alert({text:"The item you are trying to delete cannot be found."});return _context6.abrupt("continue",24);case 18:if(![_Models__WEBPACK_IMPORTED_MODULE_6__["ContentTypes"].Component,_Models__WEBPACK_IMPORTED_MODULE_6__["ContentTypes"].Theme].includes(model.content_type)){_context6.next=21;break;}_context6.next=21;return regeneratorRuntime.awrap(_this13.deactivateComponent(model,true));case 21:_context6.next=23;return regeneratorRuntime.awrap(_this13.modelManager.setItemToBeDeleted(model));case 23:// Currently extensions are not notified of association until a full server sync completes.
// We manually notify observers.
_this13.modelManager.notifyMappingObservers([model],_Payloads__WEBPACK_IMPORTED_MODULE_5__["PayloadSources"].RemoteSaved);case 24:_iteratorNormalCompletion22=true;_context6.next=12;break;case 27:_context6.next=33;break;case 29:_context6.prev=29;_context6.t0=_context6["catch"](10);_didIteratorError22=true;_iteratorError22=_context6.t0;case 33:_context6.prev=33;_context6.prev=34;if(!_iteratorNormalCompletion22&&_iterator22.return!=null){_iterator22.return();}case 36:_context6.prev=36;if(!_didIteratorError22){_context6.next=39;break;}throw _iteratorError22;case 39:return _context6.finish(36);case 40:return _context6.finish(33);case 41:_this13.syncManager.sync();reply={deleted:true};_context6.next=46;break;case 45:// Rejected by user
reply={deleted:false};case 46:_this13.replyToMessage(component,message,reply);case 47:case"end":return _context6.stop();}}},null,null,[[10,29,33,41],[34,,36,40]]);});}},{key:"handleRequestPermissionsMessage",value:function handleRequestPermissionsMessage(component,message){var _this14=this;this.runWithPermissions(component,message.data.permissions,function(){_this14.replyToMessage(component,message,{approved:true});});}},{key:"handleSetComponentDataMessage",value:function handleSetComponentDataMessage(component,message){var _this15=this;// A component setting its own data does not require special permissions
this.runWithPermissions(component,[],function _callee6(){return regeneratorRuntime.async(function _callee6$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:component.componentData=message.data.componentData;_context7.next=3;return regeneratorRuntime.awrap(_this15.modelManager.setItemDirty(component,true));case 3:_this15.syncManager.sync();case 4:case"end":return _context7.stop();}}});});}},{key:"handleToggleComponentMessage",value:function handleToggleComponentMessage(sourceComponent,targetComponent,message){this.toggleComponent(targetComponent);}},{key:"toggleComponent",value:function toggleComponent(component){var _this16=this;var activeThemes;return regeneratorRuntime.async(function toggleComponent$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:if(!(component.area==='modal')){_context9.next=4;break;}this.openModalComponent(component);_context9.next=18;break;case 4:if(!component.active){_context9.next=9;break;}_context9.next=7;return regeneratorRuntime.awrap(this.deactivateComponent(component));case 7:_context9.next=18;break;case 9:if(!(component.content_type===_Models__WEBPACK_IMPORTED_MODULE_6__["ContentTypes"].Theme)){_context9.next=16;break;}// Deactive currently active theme if new theme is not layerable
activeThemes=this.getActiveThemes();// Activate current before deactivating others, so as not to flicker
_context9.next=13;return regeneratorRuntime.awrap(this.activateComponent(component));case 13:if(!component.isLayerable()){setTimeout(function _callee7(){var _iteratorNormalCompletion23,_didIteratorError23,_iteratorError23,_iterator23,_step23,theme;return regeneratorRuntime.async(function _callee7$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:_iteratorNormalCompletion23=true;_didIteratorError23=false;_iteratorError23=undefined;_context8.prev=3;_iterator23=activeThemes[Symbol.iterator]();case 5:if(_iteratorNormalCompletion23=(_step23=_iterator23.next()).done){_context8.next=13;break;}theme=_step23.value;if(!(theme&&!theme.isLayerable())){_context8.next=10;break;}_context8.next=10;return regeneratorRuntime.awrap(_this16.deactivateComponent(theme));case 10:_iteratorNormalCompletion23=true;_context8.next=5;break;case 13:_context8.next=19;break;case 15:_context8.prev=15;_context8.t0=_context8["catch"](3);_didIteratorError23=true;_iteratorError23=_context8.t0;case 19:_context8.prev=19;_context8.prev=20;if(!_iteratorNormalCompletion23&&_iterator23.return!=null){_iterator23.return();}case 22:_context8.prev=22;if(!_didIteratorError23){_context8.next=25;break;}throw _iteratorError23;case 25:return _context8.finish(22);case 26:return _context8.finish(19);case 27:case"end":return _context8.stop();}}},null,null,[[3,15,19,27],[20,,22,26]]);},10);}_context9.next=18;break;case 16:_context9.next=18;return regeneratorRuntime.awrap(this.activateComponent(component));case 18:case"end":return _context9.stop();}}},null,this);}},{key:"handleInstallLocalComponentMessage",value:function handleInstallLocalComponentMessage(sourceComponent,message){// Only extensions manager has this permission
if(!sourceComponent.isNativeExtension){return;}var targetComponent=this.modelManager.findItem(message.data.uuid);this.desktopManager.installComponent(targetComponent);}},{key:"runWithPermissions",value:function runWithPermissions(component,requiredPermissions,runFunction){if(!component.permissions){component.permissions=[];}// Make copy as not to mutate input values
requiredPermissions=JSON.parse(JSON.stringify(requiredPermissions));var acquiredPermissions=component.permissions;var _iteratorNormalCompletion24=true;var _didIteratorError24=false;var _iteratorError24=undefined;try{var _loop5=function _loop5(){var required=_step24.value;// Remove anything we already have
var respectiveAcquired=acquiredPermissions.find(function(candidate){return candidate.name===required.name;});if(!respectiveAcquired){return"continue";}// We now match on name, lets substract from required.content_types anything we have in acquired.
var requiredContentTypes=required.content_types;if(!requiredContentTypes){// If this permission does not require any content types (i.e stream-context-item)
// then we can remove this from required since we match by name (respectiveAcquired.name === required.name)
lodash_pull__WEBPACK_IMPORTED_MODULE_1___default()(requiredPermissions,required);return"continue";}var _iteratorNormalCompletion25=true;var _didIteratorError25=false;var _iteratorError25=undefined;try{for(var _iterator25=respectiveAcquired.content_types[Symbol.iterator](),_step25;!(_iteratorNormalCompletion25=(_step25=_iterator25.next()).done);_iteratorNormalCompletion25=true){var acquiredContentType=_step25.value;lodash_pull__WEBPACK_IMPORTED_MODULE_1___default()(requiredContentTypes,acquiredContentType);}}catch(err){_didIteratorError25=true;_iteratorError25=err;}finally{try{if(!_iteratorNormalCompletion25&&_iterator25.return!=null){_iterator25.return();}}finally{if(_didIteratorError25){throw _iteratorError25;}}}if(requiredContentTypes.length===0){// We've removed all acquired and end up with zero, means we already have all these permissions
lodash_pull__WEBPACK_IMPORTED_MODULE_1___default()(requiredPermissions,required);}};for(var _iterator24=requiredPermissions.slice()[Symbol.iterator](),_step24;!(_iteratorNormalCompletion24=(_step24=_iterator24.next()).done);_iteratorNormalCompletion24=true){var _ret4=_loop5();if(_ret4==="continue")continue;}}catch(err){_didIteratorError24=true;_iteratorError24=err;}finally{try{if(!_iteratorNormalCompletion24&&_iterator24.return!=null){_iterator24.return();}}finally{if(_didIteratorError24){throw _iteratorError24;}}}if(requiredPermissions.length>0){this.promptForPermissions(component,requiredPermissions,function(approved){if(approved){runFunction();}});}else{runFunction();}}},{key:"promptForPermissions",value:function promptForPermissions(component,permissions,callback){var _this17=this;var params={};params.component=component;params.permissions=permissions;params.permissionsString=this.permissionsStringForPermissions(permissions,component);params.actionBlock=callback;params.callback=function _callee8(approved){var _iteratorNormalCompletion26,_didIteratorError26,_iteratorError26,_loop6,_iterator26,_step26;return regeneratorRuntime.async(function _callee8$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:if(!approved){_context10.next=24;break;}_iteratorNormalCompletion26=true;_didIteratorError26=false;_iteratorError26=undefined;_context10.prev=4;_loop6=function _loop6(){var permission=_step26.value;var matchingPermission=component.permissions.find(function(candidate){return candidate.name===permission.name;});if(!matchingPermission){component.permissions.push(permission);}else{// Permission already exists, but content_types may have been expanded
var contentTypes=matchingPermission.content_types||[];matchingPermission.content_types=lodash_uniq__WEBPACK_IMPORTED_MODULE_2___default()(contentTypes.concat(permission.content_types));}};for(_iterator26=permissions[Symbol.iterator]();!(_iteratorNormalCompletion26=(_step26=_iterator26.next()).done);_iteratorNormalCompletion26=true){_loop6();}_context10.next=13;break;case 9:_context10.prev=9;_context10.t0=_context10["catch"](4);_didIteratorError26=true;_iteratorError26=_context10.t0;case 13:_context10.prev=13;_context10.prev=14;if(!_iteratorNormalCompletion26&&_iterator26.return!=null){_iterator26.return();}case 16:_context10.prev=16;if(!_didIteratorError26){_context10.next=19;break;}throw _iteratorError26;case 19:return _context10.finish(16);case 20:return _context10.finish(13);case 21:_context10.next=23;return regeneratorRuntime.awrap(_this17.modelManager.setItemDirty(component,true));case 23:_this17.syncManager.sync();case 24:_this17.permissionDialogs=_this17.permissionDialogs.filter(function(pendingDialog){// Remove self
if(pendingDialog===params){pendingDialog.actionBlock&&pendingDialog.actionBlock(approved);return false;}var containsObjectSubset=function containsObjectSubset(source,target){return!target.some(function(val){return!source.find(function(candidate){return JSON.stringify(candidate)===JSON.stringify(val);});});};if(pendingDialog.component===component){// remove pending dialogs that are encapsulated by already approved permissions, and run its function
if(pendingDialog.permissions===permissions||containsObjectSubset(permissions,pendingDialog.permissions)){// If approved, run the action block. Otherwise, if canceled, cancel any pending ones as well, since the user was
// explicit in their intentions
if(approved){pendingDialog.actionBlock&&pendingDialog.actionBlock(approved);}return false;}}return true;});if(_this17.permissionDialogs.length>0){_this17.presentPermissionsDialog(_this17.permissionDialogs[0]);}case 26:case"end":return _context10.stop();}}},null,null,[[4,9,13,21],[14,,16,20]]);};// since these calls are asyncronous, multiple dialogs may be requested at the same time. We only want to present one and trigger all callbacks based on one modal result
var existingDialog=lodash_find__WEBPACK_IMPORTED_MODULE_0___default()(this.permissionDialogs,{component:component});this.permissionDialogs.push(params);if(!existingDialog){this.presentPermissionsDialog(params);}else{this.log("Existing dialog, not presenting.");}}},{key:"presentPermissionsDialog",value:function presentPermissionsDialog(dialog){console.error("Must override SNComponentManager.presentPermissionsDialog");}},{key:"openModalComponent",value:function openModalComponent(component){console.error("Must override SNComponentManager.presentPermissionsDialog");}},{key:"registerHandler",value:function registerHandler(handler){this.handlers.push(handler);}},{key:"deregisterHandler",value:function deregisterHandler(identifier){var handler=lodash_find__WEBPACK_IMPORTED_MODULE_0___default()(this.handlers,{identifier:identifier});if(!handler){this.log("Attempting to deregister non-existing handler");return;}this.handlers.splice(this.handlers.indexOf(handler),1);}// Called by other views when the iframe is ready
},{key:"registerComponentWindow",value:function registerComponentWindow(component,componentWindow){return regeneratorRuntime.async(function registerComponentWindow$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:if(component.window===componentWindow){this.log("Web|componentManager","attempting to re-register same component window.");}this.log("Web|componentManager|registerComponentWindow",component);component.window=componentWindow;_context11.next=5;return regeneratorRuntime.awrap(_Lib_uuid__WEBPACK_IMPORTED_MODULE_7__["Uuid"].GenerateUuid());case 5:component.sessionKey=_context11.sent;this.sendMessageToComponent(component,{action:"component-registered",sessionKey:component.sessionKey,componentData:component.componentData,data:{uuid:component.uuid,environment:this.environment,platform:this.platform,activeThemeUrls:this.urlsForActiveThemes()}});this.postActiveThemesToComponent(component);if(this.desktopManager){this.desktopManager.notifyComponentActivation(component);}case 9:case"end":return _context11.stop();}}},null,this);}},{key:"activateComponent",value:function activateComponent(component){var dontSync,didChange,_iteratorNormalCompletion27,_didIteratorError27,_iteratorError27,_iterator27,_step27,handler,_args12=arguments;return regeneratorRuntime.async(function activateComponent$(_context12){while(1){switch(_context12.prev=_context12.next){case 0:dontSync=_args12.length>1&&_args12[1]!==undefined?_args12[1]:false;didChange=component.active!==true;component.active=true;_iteratorNormalCompletion27=true;_didIteratorError27=false;_iteratorError27=undefined;_context12.prev=6;for(_iterator27=this.handlers[Symbol.iterator]();!(_iteratorNormalCompletion27=(_step27=_iterator27.next()).done);_iteratorNormalCompletion27=true){handler=_step27.value;if(handler.areas.includes(component.area)||handler.areas.includes("*")){handler.activationHandler&&handler.activationHandler(component);}}_context12.next=14;break;case 10:_context12.prev=10;_context12.t0=_context12["catch"](6);_didIteratorError27=true;_iteratorError27=_context12.t0;case 14:_context12.prev=14;_context12.prev=15;if(!_iteratorNormalCompletion27&&_iterator27.return!=null){_iterator27.return();}case 17:_context12.prev=17;if(!_didIteratorError27){_context12.next=20;break;}throw _iteratorError27;case 20:return _context12.finish(17);case 21:return _context12.finish(14);case 22:if(!(didChange&&!dontSync)){_context12.next=26;break;}_context12.next=25;return regeneratorRuntime.awrap(this.modelManager.setItemDirty(component,true));case 25:this.syncManager.sync();case 26:if(!this.activeComponents.includes(component)){this.activeComponents.push(component);}if(component.area==="themes"){this.postActiveThemesToAllComponents();}case 28:case"end":return _context12.stop();}}},null,this,[[6,10,14,22],[15,,17,21]]);}},{key:"deactivateComponent",value:function deactivateComponent(component){var dontSync,didChange,_iteratorNormalCompletion28,_didIteratorError28,_iteratorError28,_iterator28,_step28,handler,_args13=arguments;return regeneratorRuntime.async(function deactivateComponent$(_context13){while(1){switch(_context13.prev=_context13.next){case 0:dontSync=_args13.length>1&&_args13[1]!==undefined?_args13[1]:false;didChange=component.active!==false;component.active=false;component.sessionKey=null;_iteratorNormalCompletion28=true;_didIteratorError28=false;_iteratorError28=undefined;_context13.prev=7;for(_iterator28=this.handlers[Symbol.iterator]();!(_iteratorNormalCompletion28=(_step28=_iterator28.next()).done);_iteratorNormalCompletion28=true){handler=_step28.value;if(handler.areas.includes(component.area)||handler.areas.includes("*")){handler.activationHandler&&handler.activationHandler(component);}}_context13.next=15;break;case 11:_context13.prev=11;_context13.t0=_context13["catch"](7);_didIteratorError28=true;_iteratorError28=_context13.t0;case 15:_context13.prev=15;_context13.prev=16;if(!_iteratorNormalCompletion28&&_iterator28.return!=null){_iterator28.return();}case 18:_context13.prev=18;if(!_didIteratorError28){_context13.next=21;break;}throw _iteratorError28;case 21:return _context13.finish(18);case 22:return _context13.finish(15);case 23:if(!(didChange&&!dontSync)){_context13.next=27;break;}_context13.next=26;return regeneratorRuntime.awrap(this.modelManager.setItemDirty(component,true));case 26:this.syncManager.sync();case 27:lodash_pull__WEBPACK_IMPORTED_MODULE_1___default()(this.activeComponents,component);this.streamObservers=this.streamObservers.filter(function(o){return o.component!==component;});this.contextStreamObservers=this.contextStreamObservers.filter(function(o){return o.component!==component;});if(component.area==="themes"){this.postActiveThemesToAllComponents();}case 31:case"end":return _context13.stop();}}},null,this,[[7,11,15,23],[16,,18,22]]);}},{key:"reloadComponent",value:function reloadComponent(component){var _this18=this;var _iteratorNormalCompletion29,_didIteratorError29,_iteratorError29,_iterator29,_step29,handler;return regeneratorRuntime.async(function reloadComponent$(_context14){while(1){switch(_context14.prev=_context14.next){case 0://
// Do soft deactivate
//
component.active=false;_iteratorNormalCompletion29=true;_didIteratorError29=false;_iteratorError29=undefined;_context14.prev=4;for(_iterator29=this.handlers[Symbol.iterator]();!(_iteratorNormalCompletion29=(_step29=_iterator29.next()).done);_iteratorNormalCompletion29=true){handler=_step29.value;if(handler.areas.includes(component.area)||handler.areas.includes("*")){handler.activationHandler&&handler.activationHandler(component);}}_context14.next=12;break;case 8:_context14.prev=8;_context14.t0=_context14["catch"](4);_didIteratorError29=true;_iteratorError29=_context14.t0;case 12:_context14.prev=12;_context14.prev=13;if(!_iteratorNormalCompletion29&&_iterator29.return!=null){_iterator29.return();}case 15:_context14.prev=15;if(!_didIteratorError29){_context14.next=18;break;}throw _iteratorError29;case 18:return _context14.finish(15);case 19:return _context14.finish(12);case 20:this.streamObservers=this.streamObservers.filter(function(o){return o.component!==component;});this.contextStreamObservers=this.contextStreamObservers.filter(function(o){return o.component!==component;});if(component.area==="themes"){this.postActiveThemesToAllComponents();}//
// Do soft activate
//
return _context14.abrupt("return",new Promise(function(resolve,reject){_this18.timeout(function(){component.active=true;var _iteratorNormalCompletion30=true;var _didIteratorError30=false;var _iteratorError30=undefined;try{for(var _iterator30=_this18.handlers[Symbol.iterator](),_step30;!(_iteratorNormalCompletion30=(_step30=_iterator30.next()).done);_iteratorNormalCompletion30=true){var handler=_step30.value;if(handler.areas.includes(component.area)||handler.areas.includes("*")){handler.activationHandler&&handler.activationHandler(component);resolve();}}}catch(err){_didIteratorError30=true;_iteratorError30=err;}finally{try{if(!_iteratorNormalCompletion30&&_iterator30.return!=null){_iterator30.return();}}finally{if(_didIteratorError30){throw _iteratorError30;}}}if(!_this18.activeComponents.includes(component)){_this18.activeComponents.push(component);}if(component.area==="themes"){_this18.postActiveThemesToAllComponents();}// Resolve again in case first resolve in for loop isn't reached.
// Should be no effect if resolved twice, only first will be used.
resolve();});}));case 24:case"end":return _context14.stop();}}},null,this,[[4,8,12,20],[13,,15,19]]);}},{key:"deleteComponent",value:function deleteComponent(component){return regeneratorRuntime.async(function deleteComponent$(_context15){while(1){switch(_context15.prev=_context15.next){case 0:_context15.next=2;return regeneratorRuntime.awrap(this.modelManager.setItemToBeDeleted(component));case 2:this.syncManager.sync();case 3:case"end":return _context15.stop();}}},null,this);}},{key:"isComponentActive",value:function isComponentActive(component){return component.active;}},{key:"iframeForComponent",value:function iframeForComponent(component){for(var _i=0,_Array$from=Array.from(document.getElementsByTagName("iframe"));_i<_Array$from.length;_i++){var frame=_Array$from[_i];var componentId=frame.dataset.componentId;if(componentId===component.uuid){return frame;}}}},{key:"focusChangedForComponent",value:function focusChangedForComponent(component){var focused=document.activeElement===this.iframeForComponent(component);var _iteratorNormalCompletion31=true;var _didIteratorError31=false;var _iteratorError31=undefined;try{for(var _iterator31=this.handlers[Symbol.iterator](),_step31;!(_iteratorNormalCompletion31=(_step31=_iterator31.next()).done);_iteratorNormalCompletion31=true){var handler=_step31.value;// Notify all handlers, and not just ones that match this component type
handler.focusHandler&&handler.focusHandler(component,focused);}}catch(err){_didIteratorError31=true;_iteratorError31=err;}finally{try{if(!_iteratorNormalCompletion31&&_iterator31.return!=null){_iterator31.return();}}finally{if(_didIteratorError31){throw _iteratorError31;}}}}},{key:"handleSetSizeEvent",value:function handleSetSizeEvent(component,data){var setSize=function setSize(element,size){var widthString=typeof size.width==='string'?size.width:"".concat(data.width,"px");var heightString=typeof size.height==='string'?size.height:"".concat(data.height,"px");if(element){element.setAttribute("style","width:".concat(widthString,"; height:").concat(heightString,";"));}};if(component.area==="rooms"||component.area==="modal"){var selector=component.area==="rooms"?"inner":"outer";var content=document.getElementById("component-content-".concat(selector,"-").concat(component.uuid));if(content){setSize(content,data);}}else{var iframe=this.iframeForComponent(component);if(!iframe){return;}setSize(iframe,data);// On Firefox, resizing a component iframe does not seem to have an effect with editor-stack extensions.
// Sizing the parent does the trick, however, we can't do this globally, otherwise, areas like the note-tags will
// not be able to expand outside of the bounds (to display autocomplete, for example).
if(component.area==="editor-stack"){var parent=iframe.parentElement;if(parent){setSize(parent,data);}}// content object in this case is === to the iframe object above. This is probably
// legacy code from when we would size content and container individually, which we no longer do.
// const content = document.getElementById(`component-iframe-${component.uuid}`);
// if(content) {
// setSize(content, data);
// }
}}},{key:"editorForNote",value:function editorForNote(note){var editors=this.componentsForArea("editor-editor");var _iteratorNormalCompletion32=true;var _didIteratorError32=false;var _iteratorError32=undefined;try{for(var _iterator32=editors[Symbol.iterator](),_step32;!(_iteratorNormalCompletion32=(_step32=_iterator32.next()).done);_iteratorNormalCompletion32=true){var editor=_step32.value;if(editor.isExplicitlyEnabledForItem(note)){return editor;}}// No editor found for note. Use default editor, if note does not prefer system editor
}catch(err){_didIteratorError32=true;_iteratorError32=err;}finally{try{if(!_iteratorNormalCompletion32&&_iterator32.return!=null){_iterator32.return();}}finally{if(_didIteratorError32){throw _iteratorError32;}}}if(this.isMobile){if(!note.content.mobilePrefersPlainEditor){return this.getDefaultEditor();}}else{if(!note.getAppDataItem("prefersPlainEditor")){return editors.filter(function(e){return e.isDefaultEditor();})[0];}}}},{key:"permissionsStringForPermissions",value:function permissionsStringForPermissions(permissions,component){var finalString="";var permissionsCount=permissions.length;var addSeparator=function addSeparator(index,length){if(index>0){if(index===length-1){if(length===2){return" and ";}else{return", and ";}}else{return", ";}}return"";};permissions.forEach(function(permission,index){if(permission.name==="stream-items"){var types=permission.content_types.map(function(type){var desc=Object(_Models__WEBPACK_IMPORTED_MODULE_6__["displayStringForContentType"])(type);if(desc){return desc+"s";}else{return"items of type "+type;}});var typesString="";for(var i=0;i=2&&indexthis.itemRevisionThreshold){itemHistory.optimize();}}}]);return HistorySession;}();/***/},/***/"./lib/services/history/item_history.js":/*!**********************************************!*\
!*** ./lib/services/history/item_history.js ***!
\**********************************************/ /*! exports provided: ItemHistory */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"ItemHistory",function(){return ItemHistory;});/* harmony import */var _functions__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! ./functions */"./lib/services/history/functions.js");function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0&&arguments[0]!==undefined?arguments[0]:{};_classCallCheck(this,ItemHistory);if(!this.entries){this.entries=[];}/** Deserialize the entries into entry objects. */if(params.entries){var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=params.entries[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var entryParams=_step.value;var entry=this.createEntryForItem(entryParams.item);entry.setPreviousEntry(this.getLastEntry());this.entries.push(entry);}}catch(err){_didIteratorError=true;_iteratorError=err;}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return();}}finally{if(_didIteratorError){throw _iteratorError;}}}}}_createClass(ItemHistory,[{key:"createEntryForItem",value:function createEntryForItem(item){return Object(_functions__WEBPACK_IMPORTED_MODULE_0__["CreateHistoryEntryForItem"])(item);}},{key:"getLastEntry",value:function getLastEntry(){return this.entries[this.entries.length-1];}},{key:"addHistoryEntryForItem",value:function addHistoryEntryForItem(item){var prospectiveEntry=this.createEntryForItem(item);var previousEntry=this.getLastEntry();prospectiveEntry.setPreviousEntry(previousEntry);if(prospectiveEntry.isSameAsEntry(previousEntry)){return;}this.entries.push(prospectiveEntry);return prospectiveEntry;}},{key:"clear",value:function clear(){this.entries.length=0;}},{key:"optimize",value:function optimize(){var _this=this;var keepEntries=[];var isEntrySignificant=function isEntrySignificant(entry){return entry.deltaSize()>LARGE_ENTRY_DELTA_THRESHOLD;};var processEntry=function processEntry(entry,index,keep){/**
* Entries may be processed retrospectively, meaning it can be
* decided to be deleted, then an upcoming processing can change that.
*/if(keep){keepEntries.push(entry);}else{/** Remove if in keep */var _index=keepEntries.indexOf(entry);if(_index!==-1){keepEntries.splice(_index,1);}}if(keep&&isEntrySignificant(entry)&&entry.operationVector()===-1){/** This is a large negative change. Hang on to the previous entry. */var previousEntry=_this.entries[index-1];if(previousEntry){keepEntries.push(previousEntry);}}};this.entries.forEach(function(entry,index){if(index===0||index===_this.entries.length-1){/** Keep the first and last */processEntry(entry,index,true);}else{var significant=isEntrySignificant(entry);processEntry(entry,index,significant);}});this.entries=this.entries.filter(function(entry,index){return keepEntries.indexOf(entry)!==-1;});}}]);return ItemHistory;}();/***/},/***/"./lib/services/history/item_history_entry.js":/*!****************************************************!*\
!*** ./lib/services/history/item_history_entry.js ***!
\****************************************************/ /*! exports provided: ItemHistoryEntry */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"ItemHistoryEntry",function(){return ItemHistoryEntry;});/* harmony import */var _Models_core_item__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Models/core/item */"./lib/models/core/item.js");/* harmony import */var _Lib_utils__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Lib/utils */"./lib/utils.js");/* harmony import */var _Payloads_generator__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! @Payloads/generator */"./lib/protocol/payloads/generator.js");function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0){return"".concat(this.textCharDiffLength," characters added");}else{return"Title or metadata changed";}}}]);return NoteHistoryEntry;}(_Services_history_item_history_entry__WEBPACK_IMPORTED_MODULE_0__["ItemHistoryEntry"]);/***/},/***/"./lib/services/http_manager.js":/*!**************************************!*\
!*** ./lib/services/http_manager.js ***!
\**************************************/ /*! exports provided: SNHttpManager */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"SNHttpManager",function(){return SNHttpManager;});/* harmony import */var _Lib_services_pure_service__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Lib/services/pure_service */"./lib/services/pure_service.js");/* harmony import */var _Lib_utils__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Lib/utils */"./lib/utils.js");function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0){url=this.urlForUrlAndParams(url,params);}request.open(verb,url,true);request.setRequestHeader('Content-type','application/json');if(authentication){request.setRequestHeader('Authorization','Bearer '+authentication);}return request;}},{key:"runRequest",value:function runRequest(_ref6){var _this=this;var request,verb,params;return regeneratorRuntime.async(function runRequest$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:request=_ref6.request,verb=_ref6.verb,params=_ref6.params;return _context5.abrupt("return",new Promise(function(resolve,reject){request.onreadystatechange=function(){_this.stateChangeHandlerForRequest(request,resolve,reject);};if(verb===HTTP_VERB_POST||verb===HTTP_VERB_PATCH){request.send(JSON.stringify(params));}else{request.send();}}));case 2:case"end":return _context5.stop();}}});}},{key:"stateChangeHandlerForRequest",value:function stateChangeHandlerForRequest(request,resolve,reject){if(request.readyState!==REQUEST_READY_STATE_COMPLETED){return;}var response=request.responseText;if(response){try{response=JSON.parse(response);// eslint-disable-next-line no-empty
}catch(e){}}var httpStatus=request.status;if(httpStatus>=HTTP_STATUS_MIN_SUCCESS&&httpStatus<=HTTP_STATUS_MAX_SUCCESS){response.status=httpStatus;resolve(response);}else{console.error('Request error:',response);if(Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_1__["isString"])(response)){response={error:{message:response}};}response.status=httpStatus;reject(response);}}},{key:"urlForUrlAndParams",value:function urlForUrlAndParams(url,params){var keyValueString=Object.keys(params).map(function(key){return key+'='+encodeURIComponent(params[key]);}).join('&');if(url.includes('?')){return url+'&'+keyValueString;}else{return url+'?'+keyValueString;}}}]);return SNHttpManager;}(_Lib_services_pure_service__WEBPACK_IMPORTED_MODULE_0__["PureService"]);/***/},/***/"./lib/services/index.js":/*!*******************************!*\
!*** ./lib/services/index.js ***!
\*******************************/ /*! exports provided: SNAlertManager, SNSessionManager, SNApiService, SNComponentManager, SNHttpManager, SNModelManager, SNSingletonManager, SNActionsManager, SNMigrationService, SNProtocolService, SNHistoryManager, SNPrivilegesManager, SNKeyManager, KEY_MODE_ROOT_KEY_NONE, ItemsKeyManager, SyncEvents, SNSyncManager, SYNC_MODE_DOWNLOAD_FIRST, DeviceAuthService, SNStorageManager, StorageEncryptionPolicies, StoragePersistencePolicies */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony import */var _Services_alert_manager__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Services/alert_manager */"./lib/services/alert_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNAlertManager",function(){return _Services_alert_manager__WEBPACK_IMPORTED_MODULE_0__["SNAlertManager"];});/* harmony import */var _Services_api_session_manager__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Services/api/session_manager */"./lib/services/api/session_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNSessionManager",function(){return _Services_api_session_manager__WEBPACK_IMPORTED_MODULE_1__["SNSessionManager"];});/* harmony import */var _Services_api_api_service__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! @Services/api/api_service */"./lib/services/api/api_service.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNApiService",function(){return _Services_api_api_service__WEBPACK_IMPORTED_MODULE_2__["SNApiService"];});/* harmony import */var _Services_component_manager__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! @Services/component_manager */"./lib/services/component_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNComponentManager",function(){return _Services_component_manager__WEBPACK_IMPORTED_MODULE_3__["SNComponentManager"];});/* harmony import */var _Services_http_manager__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(/*! @Services/http_manager */"./lib/services/http_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNHttpManager",function(){return _Services_http_manager__WEBPACK_IMPORTED_MODULE_4__["SNHttpManager"];});/* harmony import */var _Services_model_manager__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__(/*! @Services/model_manager */"./lib/services/model_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNModelManager",function(){return _Services_model_manager__WEBPACK_IMPORTED_MODULE_5__["SNModelManager"];});/* harmony import */var _Services_singleton_manager__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__(/*! @Services/singleton_manager */"./lib/services/singleton_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNSingletonManager",function(){return _Services_singleton_manager__WEBPACK_IMPORTED_MODULE_6__["SNSingletonManager"];});/* harmony import */var _Services_actions_manager__WEBPACK_IMPORTED_MODULE_7__=__webpack_require__(/*! @Services/actions_manager */"./lib/services/actions_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNActionsManager",function(){return _Services_actions_manager__WEBPACK_IMPORTED_MODULE_7__["SNActionsManager"];});/* harmony import */var _Lib_migration_service__WEBPACK_IMPORTED_MODULE_8__=__webpack_require__(/*! @Lib/migration/service */"./lib/migration/service.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNMigrationService",function(){return _Lib_migration_service__WEBPACK_IMPORTED_MODULE_8__["SNMigrationService"];});/* harmony import */var _Services_protocol_service__WEBPACK_IMPORTED_MODULE_9__=__webpack_require__(/*! @Services/protocol_service */"./lib/services/protocol_service.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNProtocolService",function(){return _Services_protocol_service__WEBPACK_IMPORTED_MODULE_9__["SNProtocolService"];});/* harmony import */var _Services_history_history_manager__WEBPACK_IMPORTED_MODULE_10__=__webpack_require__(/*! @Services/history/history_manager */"./lib/services/history/history_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNHistoryManager",function(){return _Services_history_history_manager__WEBPACK_IMPORTED_MODULE_10__["SNHistoryManager"];});/* harmony import */var _Services_privileges_privileges_manager__WEBPACK_IMPORTED_MODULE_11__=__webpack_require__(/*! @Services/privileges/privileges_manager */"./lib/services/privileges/privileges_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNPrivilegesManager",function(){return _Services_privileges_privileges_manager__WEBPACK_IMPORTED_MODULE_11__["SNPrivilegesManager"];});/* harmony import */var _Services_key_manager__WEBPACK_IMPORTED_MODULE_12__=__webpack_require__(/*! @Services/key_manager */"./lib/services/key_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNKeyManager",function(){return _Services_key_manager__WEBPACK_IMPORTED_MODULE_12__["SNKeyManager"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"KEY_MODE_ROOT_KEY_NONE",function(){return _Services_key_manager__WEBPACK_IMPORTED_MODULE_12__["KEY_MODE_ROOT_KEY_NONE"];});/* harmony import */var _Services_items_key_manager__WEBPACK_IMPORTED_MODULE_13__=__webpack_require__(/*! @Services/items_key_manager */"./lib/services/items_key_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"ItemsKeyManager",function(){return _Services_items_key_manager__WEBPACK_IMPORTED_MODULE_13__["ItemsKeyManager"];});/* harmony import */var _Services_sync_events__WEBPACK_IMPORTED_MODULE_14__=__webpack_require__(/*! @Services/sync/events */"./lib/services/sync/events.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SyncEvents",function(){return _Services_sync_events__WEBPACK_IMPORTED_MODULE_14__["SyncEvents"];});/* harmony import */var _Services_sync_sync_manager__WEBPACK_IMPORTED_MODULE_15__=__webpack_require__(/*! @Services/sync/sync_manager */"./lib/services/sync/sync_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNSyncManager",function(){return _Services_sync_sync_manager__WEBPACK_IMPORTED_MODULE_15__["SNSyncManager"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SYNC_MODE_DOWNLOAD_FIRST",function(){return _Services_sync_sync_manager__WEBPACK_IMPORTED_MODULE_15__["SYNC_MODE_DOWNLOAD_FIRST"];});/* harmony import */var _Services_device_auth_service__WEBPACK_IMPORTED_MODULE_16__=__webpack_require__(/*! @Services/device_auth/service */"./lib/services/device_auth/service.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"DeviceAuthService",function(){return _Services_device_auth_service__WEBPACK_IMPORTED_MODULE_16__["DeviceAuthService"];});/* harmony import */var _Services_storage_manager__WEBPACK_IMPORTED_MODULE_17__=__webpack_require__(/*! @Services/storage_manager */"./lib/services/storage_manager.js");/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"SNStorageManager",function(){return _Services_storage_manager__WEBPACK_IMPORTED_MODULE_17__["SNStorageManager"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"StorageEncryptionPolicies",function(){return _Services_storage_manager__WEBPACK_IMPORTED_MODULE_17__["StorageEncryptionPolicies"];});/* harmony reexport (safe) */__webpack_require__.d(__webpack_exports__,"StoragePersistencePolicies",function(){return _Services_storage_manager__WEBPACK_IMPORTED_MODULE_17__["StoragePersistencePolicies"];});/***/},/***/"./lib/services/items_key_manager.js":/*!*******************************************!*\
!*** ./lib/services/items_key_manager.js ***!
\*******************************************/ /*! exports provided: ItemsKeyManager */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"ItemsKeyManager",function(){return ItemsKeyManager;});/* harmony import */var _Lib_services_pure_service__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Lib/services/pure_service */"./lib/services/pure_service.js");/* harmony import */var _Lib_events__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Lib/events */"./lib/events.js");/* harmony import */var _Services_key_manager__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! @Services/key_manager */"./lib/services/key_manager.js");/* harmony import */var _Models__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! @Models */"./lib/models/index.js");/* harmony import */var _Lib_utils__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(/*! @Lib/utils */"./lib/utils.js");function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0)){_context6.next=4;break;}_context6.next=4;return regeneratorRuntime.awrap(this.modelManager.setItemsDirty(itemsKeys));case 4:case"end":return _context6.stop();}}},null,this);}/**
* When migrating from non-SNItemsKey architecture, many items will not have a relationship with any key object.
* For those items, we can be sure that only 1 key object will correspond to that protocol version.
* @returns The SNItemsKey object to decrypt items encrypted with previous protocol version.
*/},{key:"defaultItemsKeyForItemVersion",value:function defaultItemsKeyForItemVersion(version){return regeneratorRuntime.async(function defaultItemsKeyForItemVersion$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:return _context7.abrupt("return",this.allItemsKeys.find(function(key){return key.version===version;}));case 1:case"end":return _context7.stop();}}},null,this);}/**
* Creates a new random SNItemsKey to use for item encryption, and adds it to model management.
* Consumer must call sync.
*/},{key:"createNewDefaultItemsKey",value:function createNewDefaultItemsKey(){var rootKey,operatorVersion,itemsKey,currentDefault,payload;return regeneratorRuntime.async(function createNewDefaultItemsKey$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:_context8.next=2;return regeneratorRuntime.awrap(this.keyManager.getRootKey());case 2:rootKey=_context8.sent;operatorVersion=rootKey?rootKey.version:this.protocolService.getLatestVersion();_context8.next=6;return regeneratorRuntime.awrap(this.protocolService.operatorForVersion(operatorVersion).createItemsKey());case 6:itemsKey=_context8.sent;currentDefault=this.getDefaultItemsKey();if(!currentDefault){_context8.next=12;break;}currentDefault.content.isDefault=false;_context8.next=12;return regeneratorRuntime.awrap(this.modelManager.setItemDirty(currentDefault));case 12:itemsKey.content.isDefault=true;payload=itemsKey.payloadRepresentation({override:{dirty:true}});_context8.next=16;return regeneratorRuntime.awrap(this.modelManager.mapPayloadToLocalItem({payload:payload}));case 16:case"end":return _context8.stop();}}},null,this);}},{key:"allItemsKeys",get:function get(){return this.modelManager.itemsKeys;}}]);return ItemsKeyManager;}(_Lib_services_pure_service__WEBPACK_IMPORTED_MODULE_0__["PureService"]);/***/},/***/"./lib/services/key_manager.js":/*!*************************************!*\
!*** ./lib/services/key_manager.js ***!
\*************************************/ /*! exports provided: KEY_MODE_ROOT_KEY_NONE, KEY_MODE_ROOT_KEY_ONLY, KEY_MODE_ROOT_KEY_PLUS_WRAPPER, KEY_MODE_WRAPPER_ONLY, SNKeyManager */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"KEY_MODE_ROOT_KEY_NONE",function(){return KEY_MODE_ROOT_KEY_NONE;});/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"KEY_MODE_ROOT_KEY_ONLY",function(){return KEY_MODE_ROOT_KEY_ONLY;});/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"KEY_MODE_ROOT_KEY_PLUS_WRAPPER",function(){return KEY_MODE_ROOT_KEY_PLUS_WRAPPER;});/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"KEY_MODE_WRAPPER_ONLY",function(){return KEY_MODE_WRAPPER_ONLY;});/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"SNKeyManager",function(){return SNKeyManager;});/* harmony import */var _Lib_services_pure_service__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Lib/services/pure_service */"./lib/services/pure_service.js");/* harmony import */var _Lib_utils__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Lib/utils */"./lib/utils.js");/* harmony import */var _Payloads__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! @Payloads */"./lib/protocol/payloads/index.js");/* harmony import */var _Models_content_types__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! @Models/content_types */"./lib/models/content_types.js");/* harmony import */var _Lib_storage_keys__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(/*! @Lib/storage_keys */"./lib/storage_keys.js");/* harmony import */var _Protocol__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__(/*! @Protocol */"./lib/protocol/index.js");/* harmony import */var _Lib_services_storage_manager__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__(/*! @Lib/services/storage_manager */"./lib/services/storage_manager.js");function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i1&&_args10[1]!==undefined?_args10[1]:false;if(!item.errorDecrypting){_context10.next=3;break;}return _context10.abrupt("return");case 3:content=item.content;/**
* If another client removes an item's references, this client won't pick
* up the removal unless we remove everything not present in the current
* list of references
*/item.updateLocalRelationships();if(!(!content.references||item.deleted)){_context10.next=7;break;}return _context10.abrupt("return");case 7:/** Make copy, references will be modified in array */references=content.references.slice();referencesIds=references.map(function(ref){return ref.uuid;});includeBlanks=true;items=this.findItems(referencesIds,includeBlanks);_iteratorNormalCompletion6=true;_didIteratorError6=false;_iteratorError6=undefined;_context10.prev=14;_iterator6=items.entries()[Symbol.iterator]();case 16:if(_iteratorNormalCompletion6=(_step6=_iterator6.next()).done){_context10.next=30;break;}_step6$value=_slicedToArray(_step6.value,2),index=_step6$value[0],referencedItem=_step6$value[1];if(!referencedItem){_context10.next=25;break;}item.addItemAsRelationship(referencedItem);if(!markReferencesDirty){_context10.next=23;break;}_context10.next=23;return regeneratorRuntime.awrap(this.setItemDirty(referencedItem,true));case 23:_context10.next=27;break;case 25:referenceId=referencesIds[index];this.resolveRelationshipWhenItemAvailable({interestedItem:item,missingItemId:referenceId});case 27:_iteratorNormalCompletion6=true;_context10.next=16;break;case 30:_context10.next=36;break;case 32:_context10.prev=32;_context10.t0=_context10["catch"](14);_didIteratorError6=true;_iteratorError6=_context10.t0;case 36:_context10.prev=36;_context10.prev=37;if(!_iteratorNormalCompletion6&&_iterator6.return!=null){_iterator6.return();}case 39:_context10.prev=39;if(!_didIteratorError6){_context10.next=42;break;}throw _iteratorError6;case 42:return _context10.finish(39);case 43:return _context10.finish(36);case 44:case"end":return _context10.stop();}}},null,this,[[14,32,36,44],[37,,39,43]]);}/**
* @observers
*/ /* Notifies observers when an item has been created */},{key:"addCreationObserver",value:function addCreationObserver(observer){this.creationObservers.push(observer);return observer;}},{key:"removeCreationObserver",value:function removeCreationObserver(observer){lodash_remove__WEBPACK_IMPORTED_MODULE_0___default()(this.creationObservers,observer);}},{key:"notifyCreationObservers",value:function notifyCreationObservers(items,source,sourceKey){var _iteratorNormalCompletion7,_didIteratorError7,_iteratorError7,_iterator7,_step7,observer;return regeneratorRuntime.async(function notifyCreationObservers$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:_iteratorNormalCompletion7=true;_didIteratorError7=false;_iteratorError7=undefined;_context11.prev=3;_iterator7=this.creationObservers[Symbol.iterator]();case 5:if(_iteratorNormalCompletion7=(_step7=_iterator7.next()).done){_context11.next=12;break;}observer=_step7.value;_context11.next=9;return regeneratorRuntime.awrap(observer.callback({items:items,source:source,sourceKey:sourceKey}));case 9:_iteratorNormalCompletion7=true;_context11.next=5;break;case 12:_context11.next=18;break;case 14:_context11.prev=14;_context11.t0=_context11["catch"](3);_didIteratorError7=true;_iteratorError7=_context11.t0;case 18:_context11.prev=18;_context11.prev=19;if(!_iteratorNormalCompletion7&&_iterator7.return!=null){_iterator7.return();}case 21:_context11.prev=21;if(!_didIteratorError7){_context11.next=24;break;}throw _iteratorError7;case 24:return _context11.finish(21);case 25:return _context11.finish(18);case 26:case"end":return _context11.stop();}}},null,this,[[3,14,18,26],[19,,21,25]]);}/* Notifies observers when an item has been mapped from */},{key:"addMappingObserver",value:function addMappingObserver(types,callback){return this.addMappingObserverWithPriority({types:types,callback:callback,priority:1});}},{key:"addMappingObserverWithPriority",value:function addMappingObserverWithPriority(_ref15){var _this2=this;var priority=_ref15.priority,types=_ref15.types,callback=_ref15.callback;if(!Array.isArray(types)){types=[types];}var observer={types:types,priority:priority,callback:callback};this.mappingObservers.push(observer);return function(){lodash_pull__WEBPACK_IMPORTED_MODULE_1___default()(_this2.mappingObservers,observer);};}/* Note that this function is public, and can also be called manually (desktopManager uses it) */},{key:"notifyMappingObservers",value:function notifyMappingObservers(items,source,sourceKey){var _this3=this;var observers,_iteratorNormalCompletion8,_didIteratorError8,_iteratorError8,_loop,_iterator8,_step8;return regeneratorRuntime.async(function notifyMappingObservers$(_context13){while(1){switch(_context13.prev=_context13.next){case 0:observers=this.mappingObservers.sort(function(a,b){return a.priority0)){_context12.next=26;break;}_context12.next=26;return regeneratorRuntime.awrap(_this3._callMappingObserver(observer,allRelevantItems,validItems,deletedItems,source,sourceKey));case 26:case"end":return _context12.stop();}}},null,null,[[7,11,15,23],[16,,18,22]]);};_iterator8=observers[Symbol.iterator]();case 7:if(_iteratorNormalCompletion8=(_step8=_iterator8.next()).done){_context13.next=13;break;}_context13.next=10;return regeneratorRuntime.awrap(_loop());case 10:_iteratorNormalCompletion8=true;_context13.next=7;break;case 13:_context13.next=19;break;case 15:_context13.prev=15;_context13.t0=_context13["catch"](4);_didIteratorError8=true;_iteratorError8=_context13.t0;case 19:_context13.prev=19;_context13.prev=20;if(!_iteratorNormalCompletion8&&_iterator8.return!=null){_iterator8.return();}case 22:_context13.prev=22;if(!_didIteratorError8){_context13.next=25;break;}throw _iteratorError8;case 25:return _context13.finish(22);case 26:return _context13.finish(19);case 27:case"end":return _context13.stop();}}},null,this,[[4,15,19,27],[20,,22,26]]);}},{key:"_callMappingObserver",value:function _callMappingObserver(observer,allRelevantItems,validItems,deletedItems,source,sourceKey){var _this4=this;return regeneratorRuntime.async(function _callMappingObserver$(_context15){while(1){switch(_context15.prev=_context15.next){case 0:return _context15.abrupt("return",new Promise(function(resolve,reject){_this4.timeout(function _callee(){return regeneratorRuntime.async(function _callee$(_context14){while(1){switch(_context14.prev=_context14.next){case 0:_context14.prev=0;_context14.next=3;return regeneratorRuntime.awrap(observer.callback(allRelevantItems,validItems,deletedItems,source,sourceKey));case 3:_context14.next=8;break;case 5:_context14.prev=5;_context14.t0=_context14["catch"](0);console.error('Mapping observer exception',_context14.t0);case 8:_context14.prev=8;resolve();return _context14.finish(8);case 11:case"end":return _context14.stop();}}},null,null,[[0,5,8,11]]);});}));case 1:case"end":return _context15.stop();}}});}/**
* When a client sets an item as dirty, it means its values has changed,
* and everyone should know about it. Particularly extensions. For example,
* if you edit the title of a note, extensions won't be notified until
* the save sync completes. With this, they'll be notified immediately.
*/},{key:"setItemDirty",value:function setItemDirty(item){var dirty,updateClientDate,source,sourceKey,_args16=arguments;return regeneratorRuntime.async(function setItemDirty$(_context16){while(1){switch(_context16.prev=_context16.next){case 0:dirty=_args16.length>1&&_args16[1]!==undefined?_args16[1]:true;updateClientDate=_args16.length>2?_args16[2]:undefined;source=_args16.length>3?_args16[3]:undefined;sourceKey=_args16.length>4?_args16[4]:undefined;return _context16.abrupt("return",this.setItemsDirty([item],dirty,updateClientDate,source,sourceKey));case 5:case"end":return _context16.stop();}}},null,this);}},{key:"setItemsDirty",value:function setItemsDirty(items){var dirty,updateClientDate,source,sourceKey,_iteratorNormalCompletion10,_didIteratorError10,_iteratorError10,_iterator10,_step10,item,_args17=arguments;return regeneratorRuntime.async(function setItemsDirty$(_context17){while(1){switch(_context17.prev=_context17.next){case 0:dirty=_args17.length>1&&_args17[1]!==undefined?_args17[1]:true;updateClientDate=_args17.length>2?_args17[2]:undefined;source=_args17.length>3?_args17[3]:undefined;sourceKey=_args17.length>4?_args17[4]:undefined;_iteratorNormalCompletion10=true;_didIteratorError10=false;_iteratorError10=undefined;_context17.prev=7;_iterator10=items[Symbol.iterator]();case 9:if(_iteratorNormalCompletion10=(_step10=_iterator10.next()).done){_context17.next=17;break;}item=_step10.value;if(item.isItem){_context17.next=13;break;}throw'Attempting to dirty non-item object.';case 13:item.setDirty({dirty:dirty,updateClientDate:updateClientDate,authorized:true});case 14:_iteratorNormalCompletion10=true;_context17.next=9;break;case 17:_context17.next=23;break;case 19:_context17.prev=19;_context17.t0=_context17["catch"](7);_didIteratorError10=true;_iteratorError10=_context17.t0;case 23:_context17.prev=23;_context17.prev=24;if(!_iteratorNormalCompletion10&&_iterator10.return!=null){_iterator10.return();}case 26:_context17.prev=26;if(!_didIteratorError10){_context17.next=29;break;}throw _iteratorError10;case 29:return _context17.finish(26);case 30:return _context17.finish(23);case 31:return _context17.abrupt("return",this.mapItems({items:items,source:source||_Payloads__WEBPACK_IMPORTED_MODULE_6__["PayloadSources"].LocalDirted,sourceKey:sourceKey}));case 32:case"end":return _context17.stop();}}},null,this,[[7,19,23,31],[24,,26,30]]);}},{key:"duplicateItem",value:function duplicateItem(_ref16){var item,isConflict,payload,payloads,results,copy;return regeneratorRuntime.async(function duplicateItem$(_context18){while(1){switch(_context18.prev=_context18.next){case 0:item=_ref16.item,isConflict=_ref16.isConflict;if(item.isItem){_context18.next=3;break;}throw'Attempting to duplicate non-item object.';case 3:payload=Object(_Payloads__WEBPACK_IMPORTED_MODULE_6__["CreateMaxPayloadFromAnyObject"])({object:item});_context18.next=6;return regeneratorRuntime.awrap(Object(_Payloads__WEBPACK_IMPORTED_MODULE_6__["PayloadsByDuplicating"])({payload:payload,baseCollection:this.getMasterCollection(),isConflict:isConflict}));case 6:payloads=_context18.sent;_context18.next=9;return regeneratorRuntime.awrap(this.mapPayloadsToLocalItems({payloads:payloads}));case 9:results=_context18.sent;copy=results.find(function(p){return p.uuid===payloads[0].uuid;});return _context18.abrupt("return",copy);case 12:case"end":return _context18.stop();}}},null,this);}/** @public */},{key:"createItem",value:function createItem(_ref17){var contentType,content,add,needsSync,payload,item;return regeneratorRuntime.async(function createItem$(_context19){while(1){switch(_context19.prev=_context19.next){case 0:contentType=_ref17.contentType,content=_ref17.content,add=_ref17.add,needsSync=_ref17.needsSync;if(contentType){_context19.next=3;break;}throw'Attempting to create item with no contentType';case 3:_context19.t0=_Payloads__WEBPACK_IMPORTED_MODULE_6__["CreateMaxPayloadFromAnyObject"];_context19.next=6;return regeneratorRuntime.awrap(_Lib_uuid__WEBPACK_IMPORTED_MODULE_7__["Uuid"].GenerateUuid());case 6:_context19.t1=_context19.sent;_context19.t2=contentType;_context19.t3=content;_context19.t4={uuid:_context19.t1,content_type:_context19.t2,content:_context19.t3};_context19.t5={object:_context19.t4};payload=(0,_context19.t0)(_context19.t5);item=Object(_Models__WEBPACK_IMPORTED_MODULE_4__["CreateItemFromPayload"])(payload);if(!add){_context19.next=19;break;}_context19.next=16;return regeneratorRuntime.awrap(this.insertItem({item:item}));case 16:if(!needsSync){_context19.next=19;break;}_context19.next=19;return regeneratorRuntime.awrap(this.setItemDirty(item));case 19:return _context19.abrupt("return",item);case 20:case"end":return _context19.stop();}}},null,this);}/**
* Adds items to model management.
* @param globalOnly Whether the item should only be added to main .items
* array, and not individual item arrays like .notes,
* .tags, .components, etc.
*/},{key:"addItem",value:function addItem(item){var globalOnly,_args20=arguments;return regeneratorRuntime.async(function addItem$(_context20){while(1){switch(_context20.prev=_context20.next){case 0:globalOnly=_args20.length>1&&_args20[1]!==undefined?_args20[1]:false;return _context20.abrupt("return",this.addItems([item],globalOnly));case 2:case"end":return _context20.stop();}}},null,this);}},{key:"addItems",value:function addItems(items){var globalOnly,payloads,_args21=arguments;return regeneratorRuntime.async(function addItems$(_context21){while(1){switch(_context21.prev=_context21.next){case 0:globalOnly=_args21.length>1&&_args21[1]!==undefined?_args21[1]:false;console.warn('ModelManager.addItems is depracated. Use mapPayloadsToLocalItems instead.');payloads=items.map(function(item){return Object(_Payloads__WEBPACK_IMPORTED_MODULE_6__["CreateMaxPayloadFromAnyObject"])({object:item});});_context21.next=5;return regeneratorRuntime.awrap(this.mapPayloadsToLocalItems({payloads:payloads}));case 5:case"end":return _context21.stop();}}},null,this);}},{key:"getDirtyItems",value:function getDirtyItems(){return this.items.filter(function(item){// An item that has an error decrypting can be synced only if it is being deleted.
// Otherwise, we don't want to send corrupt content up to the server.
return item.dirty&&!item.dummy&&(!item.errorDecrypting||item.deleted);});}},{key:"clearDirtyItems",value:function clearDirtyItems(items){return regeneratorRuntime.async(function clearDirtyItems$(_context22){while(1){switch(_context22.prev=_context22.next){case 0:return _context22.abrupt("return",this.setItemsDirty(items,false));case 1:case"end":return _context22.stop();}}},null,this);}/* Used when changing encryption key */},{key:"setAllItemsDirty",value:function setAllItemsDirty(){var relevantItems;return regeneratorRuntime.async(function setAllItemsDirty$(_context23){while(1){switch(_context23.prev=_context23.next){case 0:relevantItems=this.allItems;_context23.next=3;return regeneratorRuntime.awrap(this.setItemsDirty(relevantItems,true));case 3:case"end":return _context23.stop();}}},null,this);}},{key:"setItemToBeDeleted",value:function setItemToBeDeleted(item){return regeneratorRuntime.async(function setItemToBeDeleted$(_context24){while(1){switch(_context24.prev=_context24.next){case 0:item.deleted=true;if(item.dummy){_context24.next=4;break;}_context24.next=4;return regeneratorRuntime.awrap(this.setItemDirty(item,true));case 4:_context24.next=6;return regeneratorRuntime.awrap(this.handleReferencesForItemDeletion(item));case 6:this.removeItemFromRespectiveArray(item);case 7:case"end":return _context24.stop();}}},null,this);}},{key:"handleReferencesForItemDeletion",value:function handleReferencesForItemDeletion(item){var _iteratorNormalCompletion11,_didIteratorError11,_iteratorError11,_iterator11,_step11,reference,relationship,referencingItems,_iteratorNormalCompletion12,_didIteratorError12,_iteratorError12,_iterator12,_step12,referencingItem;return regeneratorRuntime.async(function handleReferencesForItemDeletion$(_context25){while(1){switch(_context25.prev=_context25.next){case 0:if(item.errorDecrypting){_context25.next=32;break;}_iteratorNormalCompletion11=true;_didIteratorError11=false;_iteratorError11=undefined;_context25.prev=4;_iterator11=item.content.references[Symbol.iterator]();case 6:if(_iteratorNormalCompletion11=(_step11=_iterator11.next()).done){_context25.next=18;break;}reference=_step11.value;relationship=this.findItem(reference.uuid);if(!relationship){_context25.next=15;break;}item.removeItemAsRelationship(relationship);if(!relationship.hasRelationshipWithItem(item)){_context25.next=15;break;}relationship.removeItemAsRelationship(item);_context25.next=15;return regeneratorRuntime.awrap(this.setItemDirty(relationship,true));case 15:_iteratorNormalCompletion11=true;_context25.next=6;break;case 18:_context25.next=24;break;case 20:_context25.prev=20;_context25.t0=_context25["catch"](4);_didIteratorError11=true;_iteratorError11=_context25.t0;case 24:_context25.prev=24;_context25.prev=25;if(!_iteratorNormalCompletion11&&_iterator11.return!=null){_iterator11.return();}case 27:_context25.prev=27;if(!_didIteratorError11){_context25.next=30;break;}throw _iteratorError11;case 30:return _context25.finish(27);case 31:return _context25.finish(24);case 32:/** Handle indirect relationships */referencingItems=item.allReferencingItems;_iteratorNormalCompletion12=true;_didIteratorError12=false;_iteratorError12=undefined;_context25.prev=36;_iterator12=referencingItems[Symbol.iterator]();case 38:if(_iteratorNormalCompletion12=(_step12=_iterator12.next()).done){_context25.next=46;break;}referencingItem=_step12.value;referencingItem.removeItemAsRelationship(item);_context25.next=43;return regeneratorRuntime.awrap(this.setItemDirty(referencingItem,true));case 43:_iteratorNormalCompletion12=true;_context25.next=38;break;case 46:_context25.next=52;break;case 48:_context25.prev=48;_context25.t1=_context25["catch"](36);_didIteratorError12=true;_iteratorError12=_context25.t1;case 52:_context25.prev=52;_context25.prev=53;if(!_iteratorNormalCompletion12&&_iterator12.return!=null){_iterator12.return();}case 55:_context25.prev=55;if(!_didIteratorError12){_context25.next=58;break;}throw _iteratorError12;case 58:return _context25.finish(55);case 59:return _context25.finish(52);case 60:item.resetLocalReferencePointers();case 61:case"end":return _context25.stop();}}},null,this,[[4,20,24,32],[25,,27,31],[36,48,52,60],[53,,55,59]]);}},{key:"setItemsToBeDeleted",value:function setItemsToBeDeleted(items){var _iteratorNormalCompletion13,_didIteratorError13,_iteratorError13,_iterator13,_step13,item;return regeneratorRuntime.async(function setItemsToBeDeleted$(_context26){while(1){switch(_context26.prev=_context26.next){case 0:_iteratorNormalCompletion13=true;_didIteratorError13=false;_iteratorError13=undefined;_context26.prev=3;_iterator13=items[Symbol.iterator]();case 5:if(_iteratorNormalCompletion13=(_step13=_iterator13.next()).done){_context26.next=12;break;}item=_step13.value;_context26.next=9;return regeneratorRuntime.awrap(this.setItemToBeDeleted(item));case 9:_iteratorNormalCompletion13=true;_context26.next=5;break;case 12:_context26.next=18;break;case 14:_context26.prev=14;_context26.t0=_context26["catch"](3);_didIteratorError13=true;_iteratorError13=_context26.t0;case 18:_context26.prev=18;_context26.prev=19;if(!_iteratorNormalCompletion13&&_iterator13.return!=null){_iterator13.return();}case 21:_context26.prev=21;if(!_didIteratorError13){_context26.next=24;break;}throw _iteratorError13;case 24:return _context26.finish(21);case 25:return _context26.finish(18);case 26:case"end":return _context26.stop();}}},null,this,[[3,14,18,26],[19,,21,25]]);}},{key:"removeItemLocally",value:function removeItemLocally(item){return regeneratorRuntime.async(function removeItemLocally$(_context27){while(1){switch(_context27.prev=_context27.next){case 0:lodash_remove__WEBPACK_IMPORTED_MODULE_0___default()(this.items,{uuid:item.uuid});delete this.itemsHash[item.uuid];this.removeItemFromRespectiveArray(item);item.isBeingRemovedLocally();case 4:case"end":return _context27.stop();}}},null,this);}},{key:"removeItemFromRespectiveArray",value:function removeItemFromRespectiveArray(item){if(item.content_type===_Models__WEBPACK_IMPORTED_MODULE_4__["ContentTypes"].Tag){lodash_remove__WEBPACK_IMPORTED_MODULE_0___default()(this.tags,{uuid:item.uuid});}else if(item.content_type===_Models__WEBPACK_IMPORTED_MODULE_4__["ContentTypes"].Note){lodash_remove__WEBPACK_IMPORTED_MODULE_0___default()(this.notes,{uuid:item.uuid});}else if(item.content_type===_Models__WEBPACK_IMPORTED_MODULE_4__["ContentTypes"].Component){lodash_remove__WEBPACK_IMPORTED_MODULE_0___default()(this.components,{uuid:item.uuid});}else if(item.content_type===_Models__WEBPACK_IMPORTED_MODULE_4__["ContentTypes"].ItemsKey){lodash_remove__WEBPACK_IMPORTED_MODULE_0___default()(this.itemsKeys,{uuid:item.uuid});}}},{key:"alternateUuidForItem",value:function alternateUuidForItem(item){var payload,results,mapped;return regeneratorRuntime.async(function alternateUuidForItem$(_context28){while(1){switch(_context28.prev=_context28.next){case 0:if(item.isItem){_context28.next=2;break;}throw'Attempting to alternate uuid of non-item object';case 2:payload=Object(_Payloads__WEBPACK_IMPORTED_MODULE_6__["CreateMaxPayloadFromAnyObject"])({object:item});_context28.next=5;return regeneratorRuntime.awrap(Object(_Payloads__WEBPACK_IMPORTED_MODULE_6__["PayloadsByAlternatingUuid"])({payload:payload,baseCollection:this.getMasterCollection()}));case 5:results=_context28.sent;_context28.next=8;return regeneratorRuntime.awrap(this.mapPayloadsToLocalItems({payloads:results,source:_Payloads__WEBPACK_IMPORTED_MODULE_6__["PayloadSources"].LocalSaved}));case 8:mapped=_context28.sent;return _context28.abrupt("return",mapped[0]);case 10:case"end":return _context28.stop();}}},null,this);}/* Searching */},{key:"getItems",value:function getItems(contentType){if(Array.isArray(contentType)){return this.allItems.filter(function(item){return!item.dummy&&(contentType.includes(item.content_type)||contentType.includes('*'));});}var managed=this.managedItemsForContentType(contentType);return managed||this.getItems([contentType]);}},{key:"managedItemsForContentType",value:function managedItemsForContentType(contentType){if(contentType===_Models__WEBPACK_IMPORTED_MODULE_4__["ContentTypes"].Note){return this.notes;}else if(contentType===_Models__WEBPACK_IMPORTED_MODULE_4__["ContentTypes"].Component){return this.components;}else if(contentType===_Models__WEBPACK_IMPORTED_MODULE_4__["ContentTypes"].Tag){return this.tags;}return null;}},{key:"invalidItems",value:function invalidItems(){return this.allItems.filter(function(item){return item.errorDecrypting;});}},{key:"validItemsForContentType",value:function validItemsForContentType(contentType){var managed=this.managedItemsForContentType(contentType);var items=managed||this.allItems;return items.filter(function(item){return!item.errorDecrypting&&(Array.isArray(contentType)?contentType.includes(item.content_type):item.content_type===contentType);});}},{key:"findItem",value:function findItem(itemId){return this.itemsHash[itemId];}},{key:"findItems",value:function findItems(ids){var includeBlanks=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var results=[];var _iteratorNormalCompletion14=true;var _didIteratorError14=false;var _iteratorError14=undefined;try{for(var _iterator14=ids[Symbol.iterator](),_step14;!(_iteratorNormalCompletion14=(_step14=_iterator14.next()).done);_iteratorNormalCompletion14=true){var id=_step14.value;var item=this.itemsHash[id];if(item||includeBlanks){results.push(item);}}}catch(err){_didIteratorError14=true;_iteratorError14=err;}finally{try{if(!_iteratorNormalCompletion14&&_iterator14.return!=null){_iterator14.return();}}finally{if(_didIteratorError14){throw _iteratorError14;}}}return results;}},{key:"itemsMatchingPredicate",value:function itemsMatchingPredicate(predicate){return this.itemsMatchingPredicates([predicate]);}},{key:"itemsMatchingPredicates",value:function itemsMatchingPredicates(predicates){return this.filterItemsWithPredicates(this.allItems,predicates);}},{key:"filterItemsWithPredicates",value:function filterItemsWithPredicates(items,predicates){var results=items.filter(function(item){var _iteratorNormalCompletion15=true;var _didIteratorError15=false;var _iteratorError15=undefined;try{for(var _iterator15=predicates[Symbol.iterator](),_step15;!(_iteratorNormalCompletion15=(_step15=_iterator15.next()).done);_iteratorNormalCompletion15=true){var predicate=_step15.value;if(!item.satisfiesPredicate(predicate)){return false;}}}catch(err){_didIteratorError15=true;_iteratorError15=err;}finally{try{if(!_iteratorNormalCompletion15&&_iterator15.return!=null){_iterator15.return();}}finally{if(_didIteratorError15){throw _iteratorError15;}}}return true;});return results;}},{key:"importPayloads",value:function importPayloads(payloads){var delta,collection,items,_iteratorNormalCompletion16,_didIteratorError16,_iteratorError16,_iterator16,_step16,item;return regeneratorRuntime.async(function importPayloads$(_context29){while(1){switch(_context29.prev=_context29.next){case 0:delta=new _Payloads__WEBPACK_IMPORTED_MODULE_6__["DeltaFileImport"]({baseCollection:this.getMasterCollection(),applyCollection:new _Payloads__WEBPACK_IMPORTED_MODULE_6__["PayloadCollection"]({payloads:payloads,source:_Payloads__WEBPACK_IMPORTED_MODULE_6__["PayloadSources"].FileImport})});_context29.next=3;return regeneratorRuntime.awrap(delta.resultingCollection());case 3:collection=_context29.sent;_context29.next=6;return regeneratorRuntime.awrap(this.mapCollectionToLocalItems({collection:collection}));case 6:items=_context29.sent;_iteratorNormalCompletion16=true;_didIteratorError16=false;_iteratorError16=undefined;_context29.prev=10;_iterator16=items[Symbol.iterator]();case 12:if(_iteratorNormalCompletion16=(_step16=_iterator16.next()).done){_context29.next=20;break;}item=_step16.value;_context29.next=16;return regeneratorRuntime.awrap(this.setItemDirty(item,true,false));case 16:item.deleted=false;case 17:_iteratorNormalCompletion16=true;_context29.next=12;break;case 20:_context29.next=26;break;case 22:_context29.prev=22;_context29.t0=_context29["catch"](10);_didIteratorError16=true;_iteratorError16=_context29.t0;case 26:_context29.prev=26;_context29.prev=27;if(!_iteratorNormalCompletion16&&_iterator16.return!=null){_iterator16.return();}case 29:_context29.prev=29;if(!_didIteratorError16){_context29.next=32;break;}throw _iteratorError16;case 32:return _context29.finish(29);case 33:return _context29.finish(26);case 34:return _context29.abrupt("return",items);case 35:case"end":return _context29.stop();}}},null,this,[[10,22,26,34],[27,,29,33]]);}},{key:"noteCount",value:function noteCount(){return this.notes.filter(function(n){return!n.dummy;}).length;}},{key:"removeAllItemsFromMemory",value:function removeAllItemsFromMemory(){var _iteratorNormalCompletion17=true;var _didIteratorError17=false;var _iteratorError17=undefined;try{for(var _iterator17=this.items[Symbol.iterator](),_step17;!(_iteratorNormalCompletion17=(_step17=_iterator17.next()).done);_iteratorNormalCompletion17=true){var item=_step17.value;item.deleted=true;}}catch(err){_didIteratorError17=true;_iteratorError17=err;}finally{try{if(!_iteratorNormalCompletion17&&_iterator17.return!=null){_iterator17.return();}}finally{if(_didIteratorError17){throw _iteratorError17;}}}this.notifyMappingObservers(this.items);this.handleSignOut();}},{key:"findTag",value:function findTag(_ref18){var title=_ref18.title;return Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_3__["findInArray"])(this.tags,'title',title);}},{key:"findOrCreateTag",value:function findOrCreateTag(_ref19){var title,tag;return regeneratorRuntime.async(function findOrCreateTag$(_context30){while(1){switch(_context30.prev=_context30.next){case 0:title=_ref19.title;tag=this.findTag({title:title});if(tag){_context30.next=6;break;}_context30.next=5;return regeneratorRuntime.awrap(this.createItem({contentType:'Tag',content:{title:title},add:true,needsSync:true}));case 5:tag=_context30.sent;case 6:return _context30.abrupt("return",tag);case 7:case"end":return _context30.stop();}}},null,this);}},{key:"reorderTagLocation",value:function reorderTagLocation(tag){lodash_pull__WEBPACK_IMPORTED_MODULE_1___default()(this.tags,tag);this.tags.splice(lodash_sortedIndexBy__WEBPACK_IMPORTED_MODULE_2___default()(this.tags,tag,function(tag){if(tag.title)return tag.title.toLowerCase();else return'';}),0,tag);}},{key:"notesMatchingSmartTag",value:function notesMatchingSmartTag(tag){var contentTypePredicate=new _Models__WEBPACK_IMPORTED_MODULE_4__["SFPredicate"]('content_type','=','Note');var predicates=[contentTypePredicate,tag.content.predicate];if(!tag.content.isTrashTag){var notTrashedPredicate=new _Models__WEBPACK_IMPORTED_MODULE_4__["SFPredicate"]('content.trashed','=',false);predicates.push(notTrashedPredicate);}var results=this.itemsMatchingPredicates(predicates);return results;}},{key:"trashSmartTag",value:function trashSmartTag(){return this.systemSmartTags.find(function(tag){return tag.content.isTrashTag;});}},{key:"trashedItems",value:function trashedItems(){return this.notesMatchingSmartTag(this.trashSmartTag());}},{key:"emptyTrash",value:function emptyTrash(){var notes=this.trashedItems();var _iteratorNormalCompletion18=true;var _didIteratorError18=false;var _iteratorError18=undefined;try{for(var _iterator18=notes[Symbol.iterator](),_step18;!(_iteratorNormalCompletion18=(_step18=_iterator18.next()).done);_iteratorNormalCompletion18=true){var note=_step18.value;this.setItemToBeDeleted(note);}}catch(err){_didIteratorError18=true;_iteratorError18=err;}finally{try{if(!_iteratorNormalCompletion18&&_iterator18.return!=null){_iterator18.return();}}finally{if(_didIteratorError18){throw _iteratorError18;}}}}},{key:"buildSystemSmartTags",value:function buildSystemSmartTags(){this.systemSmartTags=_Models__WEBPACK_IMPORTED_MODULE_4__["SNSmartTag"].systemSmartTags();}},{key:"getSmartTagWithId",value:function getSmartTagWithId(id){return this.getSmartTags().find(function(candidate){return candidate.uuid===id;});}},{key:"getSmartTags",value:function getSmartTags(){var userTags=this.validItemsForContentType(_Models__WEBPACK_IMPORTED_MODULE_4__["ContentTypes"].SmartTag).sort(function(a,b){return a.content.title0);case 4:case"end":return _context8.stop();}}},null,this);}/**
* Whether the action requires present authentication.
*/},{key:"actionRequiresPrivilege",value:function actionRequiresPrivilege(action){var expiresAt,netCredentials;return regeneratorRuntime.async(function actionRequiresPrivilege$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:_context9.next=2;return regeneratorRuntime.awrap(this.getSessionExpirey());case 2:expiresAt=_context9.sent;if(!(expiresAt>new Date())){_context9.next=5;break;}return _context9.abrupt("return",false);case 5:_context9.next=7;return regeneratorRuntime.awrap(this.netCredentialsForAction(action));case 7:netCredentials=_context9.sent;return _context9.abrupt("return",netCredentials.length>0);case 9:case"end":return _context9.stop();}}},null,this);}},{key:"authenticateAction",value:function authenticateAction(action,credentialAuthMapping){var requiredCredentials,successfulCredentials,failedCredentials,_iteratorNormalCompletion2,_didIteratorError2,_iteratorError2,_iterator2,_step2,credential,passesAuth;return regeneratorRuntime.async(function authenticateAction$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:_context10.next=2;return regeneratorRuntime.awrap(this.netCredentialsForAction(action));case 2:requiredCredentials=_context10.sent;successfulCredentials=[];failedCredentials=[];_iteratorNormalCompletion2=true;_didIteratorError2=false;_iteratorError2=undefined;_context10.prev=8;_iterator2=requiredCredentials[Symbol.iterator]();case 10:if(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done){_context10.next=19;break;}credential=_step2.value;_context10.next=14;return regeneratorRuntime.awrap(this.verifyAuthenticationParameters(credential,credentialAuthMapping[credential]));case 14:passesAuth=_context10.sent;if(passesAuth){successfulCredentials.push(credential);}else{failedCredentials.push(credential);}case 16:_iteratorNormalCompletion2=true;_context10.next=10;break;case 19:_context10.next=25;break;case 21:_context10.prev=21;_context10.t0=_context10["catch"](8);_didIteratorError2=true;_iteratorError2=_context10.t0;case 25:_context10.prev=25;_context10.prev=26;if(!_iteratorNormalCompletion2&&_iterator2.return!=null){_iterator2.return();}case 28:_context10.prev=28;if(!_didIteratorError2){_context10.next=31;break;}throw _iteratorError2;case 31:return _context10.finish(28);case 32:return _context10.finish(25);case 33:return _context10.abrupt("return",{success:failedCredentials.length===0,successfulCredentials:successfulCredentials,failedCredentials:failedCredentials});case 34:case"end":return _context10.stop();}}},null,this,[[8,21,25,33],[26,,28,32]]);}},{key:"verifyAuthenticationParameters",value:function verifyAuthenticationParameters(credential,value){return regeneratorRuntime.async(function verifyAuthenticationParameters$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:if(!(credential===PrivilegeCredentials.AccountPassword)){_context11.next=4;break;}return _context11.abrupt("return",this.keyManager.validateAccountPassword(value));case 4:if(!(credential===PrivilegeCredentials.LocalPasscode)){_context11.next=6;break;}return _context11.abrupt("return",this.keyManager.validateLocalPasscode(value));case 6:case"end":return _context11.stop();}}},null,this);}},{key:"displayInfoForCredential",value:function displayInfoForCredential(credential){var metadata={};metadata[PrivilegeCredentials.AccountPassword]={label:"Account Password",prompt:"Please enter your account password."};metadata[PrivilegeCredentials.LocalPasscode]={label:"Local Passcode",prompt:"Please enter your local passcode."};return metadata[credential];}},{key:"displayInfoForAction",value:function displayInfoForAction(action){var metadata={};metadata[ProtectedActions.ManageExtensions]={label:"Manage Extensions"};metadata[ProtectedActions.ManageBackups]={label:"Download/Import Backups"};metadata[ProtectedActions.ViewProtectedNotes]={label:"View Protected Notes"};metadata[ProtectedActions.ManagePrivileges]={label:"Manage Privileges"};metadata[ProtectedActions.ManagePasscode]={label:"Manage Passcode"};metadata[ProtectedActions.DeleteNote]={label:"Delete Notes"};return metadata[action];}},{key:"getSessionLengthOptions",value:function getSessionLengthOptions(){return[{value:PRIVILEGE_SESSION_LENGTH_NONE,label:"Don't Remember"},{value:PRIVILEGE_SESSION_LENGTH_FIVE_MINUTES,label:"5 Minutes"},{value:PRIVILEGE_SESSION_LENGTH_ONE_HOUR,label:"1 Hour"},{value:PRIVILEGE_SESSION_LENGTH_ONE_WEEK,label:"1 Week"}];}}]);return SNPrivilegesManager;}(_Lib_services_pure_service__WEBPACK_IMPORTED_MODULE_0__["PureService"]);/***/},/***/"./lib/services/protocol_service.js":/*!******************************************!*\
!*** ./lib/services/protocol_service.js ***!
\******************************************/ /*! exports provided: SNProtocolService */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"SNProtocolService",function(){return SNProtocolService;});/* harmony import */var _Lib_services_pure_service__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Lib/services/pure_service */"./lib/services/pure_service.js");/* harmony import */var sncrypto__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! sncrypto */"../sncrypto/dist/sncrypto.js");/* harmony import */var sncrypto__WEBPACK_IMPORTED_MODULE_1___default=/*#__PURE__*/__webpack_require__.n(sncrypto__WEBPACK_IMPORTED_MODULE_1__);/* harmony import */var _Lib_uuid__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! @Lib/uuid */"./lib/uuid.js");/* harmony import */var _Payloads__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! @Payloads */"./lib/protocol/payloads/index.js");/* harmony import */var _Lib_utils__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(/*! @Lib/utils */"./lib/utils.js");/* harmony import */var _Protocol__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__(/*! @Protocol */"./lib/protocol/index.js");function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i5000){return this.crypto instanceof sncrypto__WEBPACK_IMPORTED_MODULE_1__["SNWebCrypto"];}else{return true;}}/**
* @returns The versions that this library supports.
*/},{key:"supportedVersions",value:function supportedVersions(){return[_Protocol__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V001,_Protocol__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V002,_Protocol__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V003,_Protocol__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V004];}},{key:"isVersionNewerThanLibraryVersion",value:function isVersionNewerThanLibraryVersion(version){var libraryVersion=this.getLatestVersion();return parseInt(version)>parseInt(libraryVersion);}},{key:"isProtocolVersionOutdated",value:function isProtocolVersionOutdated(version){// YYYY-MM-DD
var expirationDates={};expirationDates[_Protocol__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V001]=Date.parse('2018-01-01');expirationDates[_Protocol__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V002]=Date.parse('2020-01-01');var date=expirationDates[version];if(!date){// No expiration date, is active version
return false;}var expired=new Date()>date;return expired;}},{key:"costMinimumForVersion",value:function costMinimumForVersion(version){switch(version){case _Protocol__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V001:return _Protocol__WEBPACK_IMPORTED_MODULE_5__["SNProtocolOperator001"].pwCost();case _Protocol__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V002:return _Protocol__WEBPACK_IMPORTED_MODULE_5__["SNProtocolOperator002"].pwCost();case _Protocol__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V003:return _Protocol__WEBPACK_IMPORTED_MODULE_5__["SNProtocolOperator003"].pwCost();case _Protocol__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V004:return _Protocol__WEBPACK_IMPORTED_MODULE_5__["SNProtocolOperator004"].kdfIterations();default:throw"Unable to find cost minimum for version ".concat(version);}}},{key:"versionForPayload",value:function versionForPayload(payload){return payload.content.substring(0,_Protocol__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].VersionLength);}},{key:"createOperatorForLatestVersion",value:function createOperatorForLatestVersion(){return this.createOperatorForVersion(this.getLatestVersion());}},{key:"createOperatorForVersion",value:function createOperatorForVersion(version){if(version===_Protocol__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V001){return new _Protocol__WEBPACK_IMPORTED_MODULE_5__["SNProtocolOperator001"](this.crypto);}else if(version===_Protocol__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V002){return new _Protocol__WEBPACK_IMPORTED_MODULE_5__["SNProtocolOperator002"](this.crypto);}else if(version===_Protocol__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V003){return new _Protocol__WEBPACK_IMPORTED_MODULE_5__["SNProtocolOperator003"](this.crypto);}else if(version===_Protocol__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V004){return new _Protocol__WEBPACK_IMPORTED_MODULE_5__["SNProtocolOperator004"](this.crypto);}else if(version===_Protocol__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V000Base64Decrypted){return this.createOperatorForLatestVersion();}else{throw"Unable to find operator for version ".concat(version);}}},{key:"operatorForVersion",value:function operatorForVersion(version){var operatorKey=version;var operator=this.operators[operatorKey];if(!operator){operator=this.createOperatorForVersion(version);this.operators[operatorKey]=operator;}return operator;}},{key:"defaultOperator",value:function defaultOperator(){return this.operatorForVersion(this.getLatestVersion());}},{key:"computeRootKey",value:function computeRootKey(_ref2){var password,keyParams,version,operator;return regeneratorRuntime.async(function computeRootKey$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:password=_ref2.password,keyParams=_ref2.keyParams;version=keyParams.version;operator=this.operatorForVersion(version);return _context5.abrupt("return",operator.computeRootKey({password:password,keyParams:keyParams}));case 4:case"end":return _context5.stop();}}},null,this);}},{key:"createRootKey",value:function createRootKey(_ref3){var identifier,password,operator;return regeneratorRuntime.async(function createRootKey$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:identifier=_ref3.identifier,password=_ref3.password;operator=this.defaultOperator();return _context6.abrupt("return",operator.createRootKey({identifier:identifier,password:password}));case 3:case"end":return _context6.stop();}}},null,this);}},{key:"getRootKeyParams",value:function getRootKeyParams(){return regeneratorRuntime.async(function getRootKeyParams$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:return _context7.abrupt("return",this.keyManager.getRootKeyParams());case 1:case"end":return _context7.stop();}}},null,this);}},{key:"payloadContentFormatForIntent",value:function payloadContentFormatForIntent(_ref4){var key=_ref4.key,intent=_ref4.intent;if(!key){/** Decrypted */if(intent===_Protocol__WEBPACK_IMPORTED_MODULE_5__["EncryptionIntents"].LocalStorageDecrypted||intent===_Protocol__WEBPACK_IMPORTED_MODULE_5__["EncryptionIntents"].LocalStoragePreferEncrypted||intent===_Protocol__WEBPACK_IMPORTED_MODULE_5__["EncryptionIntents"].FileDecrypted||intent===_Protocol__WEBPACK_IMPORTED_MODULE_5__["EncryptionIntents"].FilePreferEncrypted){return _Payloads__WEBPACK_IMPORTED_MODULE_3__["PayloadFormats"].DecryptedBareObject;}else if(intent===_Protocol__WEBPACK_IMPORTED_MODULE_5__["EncryptionIntents"].Sync){return _Payloads__WEBPACK_IMPORTED_MODULE_3__["PayloadFormats"].DecryptedBase64String;}}else{/** Encrypted */if(intent===_Protocol__WEBPACK_IMPORTED_MODULE_5__["EncryptionIntents"].Sync||intent===_Protocol__WEBPACK_IMPORTED_MODULE_5__["EncryptionIntents"].FileEncrypted||intent===_Protocol__WEBPACK_IMPORTED_MODULE_5__["EncryptionIntents"].FilePreferEncrypted||intent===_Protocol__WEBPACK_IMPORTED_MODULE_5__["EncryptionIntents"].LocalStorageEncrypted||intent===_Protocol__WEBPACK_IMPORTED_MODULE_5__["EncryptionIntents"].LocalStoragePreferEncrypted){return _Payloads__WEBPACK_IMPORTED_MODULE_3__["PayloadFormats"].EncryptedString;}else{throw"Unhandled case in protocolService.payloadContentFormatForIntent.";}}}/**
* Generates parameters for a payload that are typically encrypted, and used for syncing or saving locally.
* Parameters are non-typed objects that can later by converted to objects.
* @param key Optional. The key to use to encrypt the payload. Will be looked up if not supplied.
* @returns A plain key/value object.
*/},{key:"payloadByEncryptingPayload",value:function payloadByEncryptingPayload(_ref5){var payload,key,intent,version,format,operator,encryptionParameters;return regeneratorRuntime.async(function payloadByEncryptingPayload$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:payload=_ref5.payload,key=_ref5.key,intent=_ref5.intent;if(!payload.errorDecrypting){_context8.next=3;break;}return _context8.abrupt("return",payload);case 3:if(!(!key&&!Object(_Protocol__WEBPACK_IMPORTED_MODULE_5__["isDecryptedIntent"])(intent))){_context8.next=7;break;}_context8.next=6;return regeneratorRuntime.awrap(this.keyManager.keyToUseForEncryptionOfPayload({payload:payload,intent:intent}));case 6:key=_context8.sent;case 7:if(!(!key&&Object(_Protocol__WEBPACK_IMPORTED_MODULE_5__["intentRequiresEncryption"])(intent))){_context8.next=9;break;}throw'Attempting to generate encrypted payload with no key.';case 9:if(!payload.isEncrypted){_context8.next=11;break;}throw'Attempting to encrypt already encrypted payload.';case 11:if(payload.content){_context8.next=13;break;}throw'Attempting to encrypt payload with no content.';case 13:if(payload.uuid){_context8.next=15;break;}throw'Attempting to encrypt payload with no uuid.';case 15:version=key?key.version:this.getLatestVersion();format=this.payloadContentFormatForIntent({key:key,intent:intent});operator=this.operatorForVersion(version);_context8.next=20;return regeneratorRuntime.awrap(operator.generateEncryptionParameters({payload:payload,key:key,format:format}));case 20:encryptionParameters=_context8.sent;if(encryptionParameters){_context8.next=23;break;}throw'Unable to generate encryption parameters';case 23:return _context8.abrupt("return",Object(_Payloads__WEBPACK_IMPORTED_MODULE_3__["CreateIntentPayloadFromObject"])({object:payload,override:encryptionParameters,intent:intent}));case 24:case"end":return _context8.stop();}}},null,this);}},{key:"payloadsByEncryptingPayloads",value:function payloadsByEncryptingPayloads(_ref6){var payloads,intent,results,_iteratorNormalCompletion,_didIteratorError,_iteratorError,_iterator,_step,payload,encryptedPayload;return regeneratorRuntime.async(function payloadsByEncryptingPayloads$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:payloads=_ref6.payloads,intent=_ref6.intent;results=[];_iteratorNormalCompletion=true;_didIteratorError=false;_iteratorError=undefined;_context9.prev=5;_iterator=payloads[Symbol.iterator]();case 7:if(_iteratorNormalCompletion=(_step=_iterator.next()).done){_context9.next=16;break;}payload=_step.value;_context9.next=11;return regeneratorRuntime.awrap(this.payloadByEncryptingPayload({payload:payload,intent:intent}));case 11:encryptedPayload=_context9.sent;results.push(encryptedPayload);case 13:_iteratorNormalCompletion=true;_context9.next=7;break;case 16:_context9.next=22;break;case 18:_context9.prev=18;_context9.t0=_context9["catch"](5);_didIteratorError=true;_iteratorError=_context9.t0;case 22:_context9.prev=22;_context9.prev=23;if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return();}case 25:_context9.prev=25;if(!_didIteratorError){_context9.next=28;break;}throw _iteratorError;case 28:return _context9.finish(25);case 29:return _context9.finish(22);case 30:return _context9.abrupt("return",results);case 31:case"end":return _context9.stop();}}},null,this,[[5,18,22,30],[23,,25,29]]);}/**
* Generates a new payload by decrypting the input payload.
* @param payload - The payload to decrypt.
* @param key - Optional. The key to use to decrypt the payload. If none is supplied, it will be automatically looked up.
*/},{key:"payloadByDecryptingPayload",value:function payloadByDecryptingPayload(_ref7){var payload,key,version,operator,encryptionParameters,decryptedParameters;return regeneratorRuntime.async(function payloadByDecryptingPayload$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:payload=_ref7.payload,key=_ref7.key;if(payload.content){_context10.next=3;break;}throw'Attempting to decrypt payload that has no content.';case 3:if(key){_context10.next=7;break;}_context10.next=6;return regeneratorRuntime.awrap(this.keyManager.keyToUseForDecryptionOfPayload({payload:payload}));case 6:key=_context10.sent;case 7:if(key){_context10.next=9;break;}return _context10.abrupt("return",Object(_Payloads__WEBPACK_IMPORTED_MODULE_3__["CreateMaxPayloadFromAnyObject"])({object:payload,override:{waitingForKey:true,errorDecrypting:true}}));case 9:version=this.versionForPayload(payload);operator=this.operatorForVersion(version);encryptionParameters=Object(_Payloads__WEBPACK_IMPORTED_MODULE_3__["CreateEncryptionParameters"])(payload);_context10.next=14;return regeneratorRuntime.awrap(operator.generateDecryptedParameters({encryptedParameters:encryptionParameters,key:key}));case 14:decryptedParameters=_context10.sent;return _context10.abrupt("return",Object(_Payloads__WEBPACK_IMPORTED_MODULE_3__["CreateMaxPayloadFromAnyObject"])({object:payload,override:decryptedParameters}));case 16:case"end":return _context10.stop();}}},null,this);}},{key:"payloadsByDecryptingPayloads",value:function payloadsByDecryptingPayloads(_ref8){var payloads,throws,decryptedPayloads,_iteratorNormalCompletion2,_didIteratorError2,_iteratorError2,_iterator2,_step2,encryptedPayload,isDecryptable,decryptedPayload,_override;return regeneratorRuntime.async(function payloadsByDecryptingPayloads$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:payloads=_ref8.payloads,throws=_ref8.throws;decryptedPayloads=[];_iteratorNormalCompletion2=true;_didIteratorError2=false;_iteratorError2=undefined;_context11.prev=5;_iterator2=payloads[Symbol.iterator]();case 7:if(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done){_context11.next=37;break;}encryptedPayload=_step2.value;if(encryptedPayload){_context11.next=12;break;}/** Keep in counts similar to out counts */decryptedPayloads.push(encryptedPayload);return _context11.abrupt("continue",34);case 12:if(encryptedPayload.isPayload){_context11.next=14;break;}throw'Attempting to decrypt non-payload object in payloadsByDecryptingPayloads.';case 14:if(!(encryptedPayload.deleted===true&&Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_4__["isNullOrUndefined"])(encryptedPayload.content))){_context11.next=17;break;}decryptedPayloads.push(encryptedPayload);return _context11.abrupt("continue",34);case 17:isDecryptable=Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_4__["isString"])(encryptedPayload.content);if(isDecryptable){_context11.next=21;break;}decryptedPayloads.push(encryptedPayload);return _context11.abrupt("continue",34);case 21:_context11.prev=21;_context11.next=24;return regeneratorRuntime.awrap(this.payloadByDecryptingPayload({payload:encryptedPayload}));case 24:decryptedPayload=_context11.sent;decryptedPayloads.push(decryptedPayload);_context11.next=34;break;case 28:_context11.prev=28;_context11.t0=_context11["catch"](21);decryptedPayloads.push(Object(_Payloads__WEBPACK_IMPORTED_MODULE_3__["CreateMaxPayloadFromAnyObject"])({object:encryptedPayload,override:(_override={},_defineProperty(_override,_Payloads__WEBPACK_IMPORTED_MODULE_3__["PayloadFields"].ErrorDecrypting,true),_defineProperty(_override,_Payloads__WEBPACK_IMPORTED_MODULE_3__["PayloadFields"].ErrorDecryptingChanged,!encryptedPayload.errorDecrypting),_override)}));if(!throws){_context11.next=33;break;}throw _context11.t0;case 33:console.error("Error decrypting payload",encryptedPayload,_context11.t0);case 34:_iteratorNormalCompletion2=true;_context11.next=7;break;case 37:_context11.next=43;break;case 39:_context11.prev=39;_context11.t1=_context11["catch"](5);_didIteratorError2=true;_iteratorError2=_context11.t1;case 43:_context11.prev=43;_context11.prev=44;if(!_iteratorNormalCompletion2&&_iterator2.return!=null){_iterator2.return();}case 46:_context11.prev=46;if(!_didIteratorError2){_context11.next=49;break;}throw _iteratorError2;case 49:return _context11.finish(46);case 50:return _context11.finish(43);case 51:return _context11.abrupt("return",decryptedPayloads);case 52:case"end":return _context11.stop();}}},null,this,[[5,39,43,51],[21,28],[44,,46,50]]);}/**
* If an item was attempting to decrypt, but failed, either because the keys
* for that item had not downloaded yet, or any other reason, it will be deferred
* item.errorDecrypting = true and possibly item.waitingForKey = true.
* Here we find such items, and attempt to decrypt them again.
*/},{key:"decryptErroredItems",value:function decryptErroredItems(){var items,payloads,decrypted;return regeneratorRuntime.async(function decryptErroredItems$(_context12){while(1){switch(_context12.prev=_context12.next){case 0:items=this.modelManager.allItems.filter(function(item){return item.waitingForKey||item.errorDecrypting;});if(!(items.length===0)){_context12.next=3;break;}return _context12.abrupt("return");case 3:payloads=items.map(function(item){return Object(_Payloads__WEBPACK_IMPORTED_MODULE_3__["CreateMaxPayloadFromAnyObject"])({object:item});});_context12.next=6;return regeneratorRuntime.awrap(this.payloadsByDecryptingPayloads({payloads:payloads}));case 6:decrypted=_context12.sent;_context12.next=9;return regeneratorRuntime.awrap(this.modelManager.mapPayloadsToLocalItems({payloads:decrypted}));case 9:case"end":return _context12.stop();}}},null,this);}},{key:"payloadsByDecryptingBackupFile",value:function payloadsByDecryptingBackupFile(_ref9){var data,password,keyParams,rawItems,encryptedPayloads,decryptedPayloads,key;return regeneratorRuntime.async(function payloadsByDecryptingBackupFile$(_context13){while(1){switch(_context13.prev=_context13.next){case 0:data=_ref9.data,password=_ref9.password;keyParams=data.keyParams||data.auth_params;rawItems=data.items;encryptedPayloads=rawItems.map(function(rawItem){return Object(_Payloads__WEBPACK_IMPORTED_MODULE_3__["CreateSourcedPayloadFromObject"])({object:rawItem,source:_Payloads__WEBPACK_IMPORTED_MODULE_3__["PayloadSources"].FileImport});});if(!keyParams){_context13.next=13;break;}_context13.next=7;return regeneratorRuntime.awrap(this.computeRootKey({password:password,keyParams:keyParams}));case 7:key=_context13.sent;_context13.next=10;return regeneratorRuntime.awrap(this.payloadsByDecryptingPayloads({payloads:encryptedPayloads,key:key}));case 10:decryptedPayloads=_context13.sent;_context13.next=14;break;case 13:decryptedPayloads=encryptedPayloads;case 14:return _context13.abrupt("return",decryptedPayloads);case 15:case"end":return _context13.stop();}}},null,this);}},{key:"payloadsByDecryptingRawPayload",value:function payloadsByDecryptingRawPayload(_ref10){var rawPayload,encryptedPayload;return regeneratorRuntime.async(function payloadsByDecryptingRawPayload$(_context14){while(1){switch(_context14.prev=_context14.next){case 0:rawPayload=_ref10.rawPayload;encryptedPayload=Object(_Payloads__WEBPACK_IMPORTED_MODULE_3__["CreateSourcedPayloadFromObject"])({object:rawPayload});return _context14.abrupt("return",this.payloadByDecryptingPayload({payload:encryptedPayload}));case 3:case"end":return _context14.stop();}}},null,this);}/**
* Compares two keys for equality
* @returns Boolean
*/},{key:"compareRootKeys",value:function compareRootKeys(keyA,keyB){return regeneratorRuntime.async(function compareRootKeys$(_context15){while(1){switch(_context15.prev=_context15.next){case 0:return _context15.abrupt("return",keyA.compare(keyB));case 1:case"end":return _context15.stop();}}});}},{key:"createKeyParams",value:function createKeyParams(keyParams){if(keyParams.isKeyParamsObject){throw'Attempting to create key params from non-raw value.';}/* 002 doesn't have version automatically, newer versions do. */if(!keyParams.version){keyParams.version=_Protocol__WEBPACK_IMPORTED_MODULE_5__["ProtocolVersions"].V002;}return Object(_Protocol__WEBPACK_IMPORTED_MODULE_5__["CreateKeyParams"])(keyParams);}/**
* Creates a JSON string representing the backup format of all items, or just subitems
* if supplied.
* @param {Array} subItems An optional array of items to create backup of.
* If not supplied, all items are backed up.
* @param {bool} returnIfEmpty Returns null if there are no items to make backup of.
*/},{key:"createBackupFile",value:function createBackupFile(){var _ref11,subItems,intent,returnIfEmpty,items,payloads,encryptedPayloads,data,keyParams,prettyPrint,_args16=arguments;return regeneratorRuntime.async(function createBackupFile$(_context16){while(1){switch(_context16.prev=_context16.next){case 0:_ref11=_args16.length>0&&_args16[0]!==undefined?_args16[0]:{},subItems=_ref11.subItems,intent=_ref11.intent,returnIfEmpty=_ref11.returnIfEmpty;items=subItems||this.modelManager.allItems;if(!(returnIfEmpty&&items.length===0)){_context16.next=4;break;}return _context16.abrupt("return",null);case 4:if(!intent){intent=_Protocol__WEBPACK_IMPORTED_MODULE_5__["EncryptionIntents"].FilePreferEncrypted;}payloads=items.map(function(item){return Object(_Payloads__WEBPACK_IMPORTED_MODULE_3__["CreateMaxPayloadFromAnyObject"])({object:item});});_context16.next=8;return regeneratorRuntime.awrap(this.payloadsByEncryptingPayloads({payloads:payloads,intent:intent}));case 8:encryptedPayloads=_context16.sent;data={items:encryptedPayloads};_context16.next=12;return regeneratorRuntime.awrap(this.keyManager.getRootKeyParams());case 12:keyParams=_context16.sent;if(keyParams&&intent!==_Protocol__WEBPACK_IMPORTED_MODULE_5__["EncryptionIntents"].FileDecrypted){data.keyParams=keyParams.getPortableValue();}prettyPrint=2;return _context16.abrupt("return",JSON.stringify(data,null,prettyPrint));case 16:case"end":return _context16.stop();}}},null,this);}}]);return SNProtocolService;}(_Lib_services_pure_service__WEBPACK_IMPORTED_MODULE_0__["PureService"]);/***/},/***/"./lib/services/pure_service.js":/*!**************************************!*\
!*** ./lib/services/pure_service.js ***!
\**************************************/ /*! exports provided: PureService */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"PureService",function(){return PureService;});/* harmony import */var lodash_pull__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! lodash/pull */"./node_modules/lodash/pull.js");/* harmony import */var lodash_pull__WEBPACK_IMPORTED_MODULE_0___default=/*#__PURE__*/__webpack_require__.n(lodash_pull__WEBPACK_IMPORTED_MODULE_0__);function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0)){_context4.next=4;break;}return _context4.abrupt("return",items[0]);case 4:if(this.syncManager.getLastSyncDate()){_context4.next=7;break;}_context4.next=7;return regeneratorRuntime.awrap(this.syncManager.sync());case 7:/** Check again */refreshedItems=this.validItemsMatchingPredicate(predicate);if(!(refreshedItems.length>0)){_context4.next=10;break;}return _context4.abrupt("return",refreshedItems[0]);case 10:/** Delete any items that are errored */errorDecrypting=this.modelManager.itemsMatchingPredicate(predicate).filter(function(item){return item.errorDecrypting;});_context4.next=13;return regeneratorRuntime.awrap(this.modelManager.setItemsToBeDeleted(errorDecrypting));case 13:_context4.t0=_Payloads_generator__WEBPACK_IMPORTED_MODULE_3__["CopyPayload"];_context4.t1=createPayload;_context4.next=17;return regeneratorRuntime.awrap(_Lib_uuid__WEBPACK_IMPORTED_MODULE_4__["Uuid"].GenerateUuid());case 17:_context4.t2=_context4.sent;_context4.t3={uuid:_context4.t2,dirty:true};_context4.t4={payload:_context4.t1,override:_context4.t3};dirtyPayload=(0,_context4.t0)(_context4.t4);_context4.next=23;return regeneratorRuntime.awrap(this.modelManager.mapPayloadToLocalItem({payload:dirtyPayload}));case 23:item=_context4.sent;_context4.next=26;return regeneratorRuntime.awrap(this.syncManager.sync());case 26:return _context4.abrupt("return",item);case 27:case"end":return _context4.stop();}}},null,this);}}]);return SNSingletonManager;}(_Lib_services_pure_service__WEBPACK_IMPORTED_MODULE_0__["PureService"]);/***/},/***/"./lib/services/storage_manager.js":/*!*****************************************!*\
!*** ./lib/services/storage_manager.js ***!
\*****************************************/ /*! exports provided: StoragePersistencePolicies, StorageEncryptionPolicies, StorageValueModes, ValueModesKeys, SNStorageManager */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"StoragePersistencePolicies",function(){return StoragePersistencePolicies;});/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"StorageEncryptionPolicies",function(){return StorageEncryptionPolicies;});/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"StorageValueModes",function(){return StorageValueModes;});/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"ValueModesKeys",function(){return ValueModesKeys;});/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"SNStorageManager",function(){return SNStorageManager;});/* harmony import */var _Lib_services_pure_service__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Lib/services/pure_service */"./lib/services/pure_service.js");/* harmony import */var _Protocol__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Protocol */"./lib/protocol/index.js");/* harmony import */var _Lib__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! @Lib */"./lib/index.js");/* harmony import */var _Payloads__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! @Payloads */"./lib/protocol/payloads/index.js");/* harmony import */var _Models_content_types__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(/*! @Models/content_types */"./lib/models/content_types.js");/* harmony import */var _Lib_utils__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__(/*! @Lib/utils */"./lib/utils.js");/* harmony import */var _Lib_uuid__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__(/*! @Lib/uuid */"./lib/uuid.js");function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0;}/** @public */},{key:"canDecryptWithKey",value:function canDecryptWithKey(key){var wrappedValue,decryptedPayload;return regeneratorRuntime.async(function canDecryptWithKey$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:wrappedValue=this.values[ValueModesKeys.Wrapped];_context6.next=3;return regeneratorRuntime.awrap(this.decryptWrappedValue({wrappedValue:wrappedValue,key:key,throws:false}));case 3:decryptedPayload=_context6.sent;return _context6.abrupt("return",!decryptedPayload.errorDecrypting);case 5:case"end":return _context6.stop();}}},null,this);}/** @private */},{key:"decryptWrappedValue",value:function decryptWrappedValue(_ref2){var wrappedValue,key,payload,decryptedPayload;return regeneratorRuntime.async(function decryptWrappedValue$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:wrappedValue=_ref2.wrappedValue,key=_ref2.key;if(wrappedValue.content_type){_context7.next=3;break;}throw'Attempting to decrypt nonexistent wrapped value';case 3:payload=Object(_Payloads__WEBPACK_IMPORTED_MODULE_3__["CreateMaxPayloadFromAnyObject"])({object:wrappedValue,override:{content_type:_Models_content_types__WEBPACK_IMPORTED_MODULE_4__["ContentTypes"].EncryptedStorage}});_context7.next=6;return regeneratorRuntime.awrap(this.protocolService.payloadByDecryptingPayload({payload:payload,key:key}));case 6:decryptedPayload=_context7.sent;return _context7.abrupt("return",decryptedPayload);case 8:case"end":return _context7.stop();}}},null,this);}/** @public */},{key:"decryptStorage",value:function decryptStorage(){var wrappedValue,decryptedPayload;return regeneratorRuntime.async(function decryptStorage$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:wrappedValue=this.values[ValueModesKeys.Wrapped];_context8.next=3;return regeneratorRuntime.awrap(this.decryptWrappedValue({wrappedValue:wrappedValue}));case 3:decryptedPayload=_context8.sent;if(!decryptedPayload.errorDecrypting){_context8.next=6;break;}throw'Unable to decrypt storage encryption';case 6:this.values[ValueModesKeys.Unwrapped]=Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_5__["Copy"])(decryptedPayload.content);delete this.values[ValueModesKeys.Wrapped];case 8:case"end":return _context8.stop();}}},null,this);}/**
* Generates a payload that can be persisted to disk,
* either as a plain object, or an encrypted item.
*/},{key:"generatePersistenceValue",value:function generatePersistenceValue(){var rawContent,valuesToWrap,payload,encryptedPayload;return regeneratorRuntime.async(function generatePersistenceValue$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:rawContent=Object.assign({},this.values);valuesToWrap=rawContent[ValueModesKeys.Unwrapped];_context9.t0=_Payloads__WEBPACK_IMPORTED_MODULE_3__["CreateMaxPayloadFromAnyObject"];_context9.next=5;return regeneratorRuntime.awrap(_Lib_uuid__WEBPACK_IMPORTED_MODULE_6__["Uuid"].GenerateUuid());case 5:_context9.t1=_context9.sent;_context9.t2=valuesToWrap;_context9.t3=_Models_content_types__WEBPACK_IMPORTED_MODULE_4__["ContentTypes"].EncryptedStorage;_context9.t4={uuid:_context9.t1,content:_context9.t2,content_type:_context9.t3};_context9.t5={object:_context9.t4};payload=(0,_context9.t0)(_context9.t5);_context9.next=13;return regeneratorRuntime.awrap(this.protocolService.payloadByEncryptingPayload({payload:payload,intent:_Protocol__WEBPACK_IMPORTED_MODULE_1__["EncryptionIntents"].LocalStoragePreferEncrypted}));case 13:encryptedPayload=_context9.sent;rawContent[ValueModesKeys.Wrapped]=encryptedPayload;rawContent[ValueModesKeys.Unwrapped]=null;return _context9.abrupt("return",rawContent);case 17:case"end":return _context9.stop();}}},null,this);}},{key:"repersistToDisk",value:function repersistToDisk(){var value;return regeneratorRuntime.async(function repersistToDisk$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:if(this.storagePersistable){_context10.next=2;break;}return _context10.abrupt("return");case 2:if(!(this.persistencePolicy===StoragePersistencePolicies.Ephemeral)){_context10.next=4;break;}return _context10.abrupt("return");case 4:_context10.next=6;return regeneratorRuntime.awrap(this.generatePersistenceValue());case 6:value=_context10.sent;return _context10.abrupt("return",this.persistAsValueToDisk(value));case 8:case"end":return _context10.stop();}}},null,this);}},{key:"setValue",value:function setValue(key,value){var mode,_args11=arguments;return regeneratorRuntime.async(function setValue$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:mode=_args11.length>2&&_args11[2]!==undefined?_args11[2]:StorageValueModes.Default;if(this.values){_context11.next=3;break;}throw'Attempting to set storage value before loading local storage.';case 3:this.values[this.domainKeyForMode(mode)][key]=value;return _context11.abrupt("return",this.repersistToDisk());case 5:case"end":return _context11.stop();}}},null,this);}},{key:"getValue",value:function getValue(key){var mode,_args12=arguments;return regeneratorRuntime.async(function getValue$(_context12){while(1){switch(_context12.prev=_context12.next){case 0:mode=_args12.length>1&&_args12[1]!==undefined?_args12[1]:StorageValueModes.Default;if(this.values){_context12.next=3;break;}throw'Attempting to access storage value before loading local storage.';case 3:if(this.values[this.domainKeyForMode(mode)]){_context12.next=5;break;}throw"Storage domain mode not available ".concat(mode," for key ").concat(key);case 5:return _context12.abrupt("return",this.values[this.domainKeyForMode(mode)][key]);case 6:case"end":return _context12.stop();}}},null,this);}},{key:"removeValue",value:function removeValue(key){var mode,_args13=arguments;return regeneratorRuntime.async(function removeValue$(_context13){while(1){switch(_context13.prev=_context13.next){case 0:mode=_args13.length>1&&_args13[1]!==undefined?_args13[1]:StorageValueModes.Default;if(this.values){_context13.next=3;break;}throw'Attempting to access storage value before loading local storage.';case 3:delete this.values[this.domainKeyForMode(mode)][key];return _context13.abrupt("return",this.repersistToDisk());case 5:case"end":return _context13.stop();}}},null,this);}/**
* Default persistence key. Platforms can override as needed.
*/},{key:"getPersistenceKey",value:function getPersistenceKey(){return Object(_Lib__WEBPACK_IMPORTED_MODULE_2__["namespacedKey"])(this.namespace,_Lib__WEBPACK_IMPORTED_MODULE_2__["StorageKeys"].StorageObject);}},{key:"defaultValuesObject",value:function defaultValuesObject(){var _ref3=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{},wrapped=_ref3.wrapped,unwrapped=_ref3.unwrapped,nonwrapped=_ref3.nonwrapped;return this.constructor.defaultValuesObject({wrapped:wrapped,unwrapped:unwrapped,nonwrapped:nonwrapped});}},{key:"domainKeyForMode",/** @private */value:function domainKeyForMode(mode){return this.constructor.domainKeyForMode(mode);}/**
* Clears simple values from storage only. Does not affect items.
*/},{key:"clear",value:function clear(){return regeneratorRuntime.async(function clear$(_context14){while(1){switch(_context14.prev=_context14.next){case 0:this.values=this.defaultValuesObject();_context14.next=3;return regeneratorRuntime.awrap(this.repersistToDisk());case 3:case"end":return _context14.stop();}}},null,this);}/**
* Payload Storage
*/},{key:"getAllRawPayloads",value:function getAllRawPayloads(){return regeneratorRuntime.async(function getAllRawPayloads$(_context15){while(1){switch(_context15.prev=_context15.next){case 0:return _context15.abrupt("return",this.deviceInterface.getAllRawDatabasePayloads());case 1:case"end":return _context15.stop();}}},null,this);}},{key:"savePayload",value:function savePayload(payload){return regeneratorRuntime.async(function savePayload$(_context16){while(1){switch(_context16.prev=_context16.next){case 0:return _context16.abrupt("return",this.savePayloads([payload]));case 1:case"end":return _context16.stop();}}},null,this);}},{key:"savePayloads",value:function savePayloads(decryptedPayloads){var deleted,nondeleted,_iteratorNormalCompletion,_didIteratorError,_iteratorError,_iterator,_step,payload,encrypted;return regeneratorRuntime.async(function savePayloads$(_context17){while(1){switch(_context17.prev=_context17.next){case 0:if(!(this.persistencePolicy===StoragePersistencePolicies.Ephemeral)){_context17.next=2;break;}return _context17.abrupt("return");case 2:deleted=[];nondeleted=[];_iteratorNormalCompletion=true;_didIteratorError=false;_iteratorError=undefined;_context17.prev=7;_iterator=decryptedPayloads[Symbol.iterator]();case 9:if(_iteratorNormalCompletion=(_step=_iterator.next()).done){_context17.next=22;break;}payload=_step.value;if(!payload.discardable){_context17.next=15;break;}/** If the payload is deleted and not dirty, remove it from db. */deleted.push(payload);_context17.next=19;break;case 15:_context17.next=17;return regeneratorRuntime.awrap(this.protocolService.payloadByEncryptingPayload({payload:payload,intent:this.encryptionPolicy===StorageEncryptionPolicies.Default?_Protocol__WEBPACK_IMPORTED_MODULE_1__["EncryptionIntents"].LocalStoragePreferEncrypted:_Protocol__WEBPACK_IMPORTED_MODULE_1__["EncryptionIntents"].LocalStorageDecrypted}));case 17:encrypted=_context17.sent;nondeleted.push(encrypted);case 19:_iteratorNormalCompletion=true;_context17.next=9;break;case 22:_context17.next=28;break;case 24:_context17.prev=24;_context17.t0=_context17["catch"](7);_didIteratorError=true;_iteratorError=_context17.t0;case 28:_context17.prev=28;_context17.prev=29;if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return();}case 31:_context17.prev=31;if(!_didIteratorError){_context17.next=34;break;}throw _iteratorError;case 34:return _context17.finish(31);case 35:return _context17.finish(28);case 36:if(!(deleted.length>0)){_context17.next=39;break;}_context17.next=39;return regeneratorRuntime.awrap(this.deletePayloads(deleted));case 39:_context17.next=41;return regeneratorRuntime.awrap(this.deviceInterface.saveRawDatabasePayloads(nondeleted));case 41:case"end":return _context17.stop();}}},null,this,[[7,24,28,36],[29,,31,35]]);}},{key:"deletePayloads",value:function deletePayloads(payloads){var _iteratorNormalCompletion2,_didIteratorError2,_iteratorError2,_iterator2,_step2,payload;return regeneratorRuntime.async(function deletePayloads$(_context18){while(1){switch(_context18.prev=_context18.next){case 0:_iteratorNormalCompletion2=true;_didIteratorError2=false;_iteratorError2=undefined;_context18.prev=3;_iterator2=payloads[Symbol.iterator]();case 5:if(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done){_context18.next=12;break;}payload=_step2.value;_context18.next=9;return regeneratorRuntime.awrap(this.deletePayloadWithId(payload.uuid));case 9:_iteratorNormalCompletion2=true;_context18.next=5;break;case 12:_context18.next=18;break;case 14:_context18.prev=14;_context18.t0=_context18["catch"](3);_didIteratorError2=true;_iteratorError2=_context18.t0;case 18:_context18.prev=18;_context18.prev=19;if(!_iteratorNormalCompletion2&&_iterator2.return!=null){_iterator2.return();}case 21:_context18.prev=21;if(!_didIteratorError2){_context18.next=24;break;}throw _iteratorError2;case 24:return _context18.finish(21);case 25:return _context18.finish(18);case 26:case"end":return _context18.stop();}}},null,this,[[3,14,18,26],[19,,21,25]]);}},{key:"deletePayloadWithId",value:function deletePayloadWithId(id){return regeneratorRuntime.async(function deletePayloadWithId$(_context19){while(1){switch(_context19.prev=_context19.next){case 0:return _context19.abrupt("return",this.deviceInterface.removeRawDatabasePayloadWithId(id));case 1:case"end":return _context19.stop();}}},null,this);}},{key:"clearAllPayloads",value:function clearAllPayloads(){return regeneratorRuntime.async(function clearAllPayloads$(_context20){while(1){switch(_context20.prev=_context20.next){case 0:return _context20.abrupt("return",this.deviceInterface.removeAllRawDatabasePayloads());case 1:case"end":return _context20.stop();}}},null,this);}/**
* General
*/},{key:"clearAllData",value:function clearAllData(){return regeneratorRuntime.async(function clearAllData$(_context21){while(1){switch(_context21.prev=_context21.next){case 0:return _context21.abrupt("return",Promise.all([this.clear(),this.clearAllPayloads()]));case 1:case"end":return _context21.stop();}}},null,this);}}],[{key:"defaultValuesObject",value:function defaultValuesObject(){var _ref5;var _ref4=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{},_ref4$wrapped=_ref4.wrapped,wrapped=_ref4$wrapped===void 0?{}:_ref4$wrapped,_ref4$unwrapped=_ref4.unwrapped,unwrapped=_ref4$unwrapped===void 0?{}:_ref4$unwrapped,_ref4$nonwrapped=_ref4.nonwrapped,nonwrapped=_ref4$nonwrapped===void 0?{}:_ref4$nonwrapped;return _ref5={},_defineProperty(_ref5,ValueModesKeys.Wrapped,wrapped),_defineProperty(_ref5,ValueModesKeys.Unwrapped,unwrapped),_defineProperty(_ref5,ValueModesKeys.Nonwrapped,nonwrapped),_ref5;}/** @private */},{key:"domainKeyForMode",value:function domainKeyForMode(mode){if(mode===StorageValueModes.Default){return ValueModesKeys.Unwrapped;}else if(mode===StorageValueModes.Nonwrapped){return ValueModesKeys.Nonwrapped;}else{throw'Invalid mode';}}}]);return SNStorageManager;}(_Lib_services_pure_service__WEBPACK_IMPORTED_MODULE_0__["PureService"]);/***/},/***/"./lib/services/sync/account/downloader.js":/*!*************************************************!*\
!*** ./lib/services/sync/account/downloader.js ***!
\*************************************************/ /*! exports provided: AccountDownloader */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"AccountDownloader",function(){return AccountDownloader;});/* harmony import */var _Payloads_generator__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Payloads/generator */"./lib/protocol/payloads/generator.js");/* harmony import */var _Lib_protocol_payloads_sources__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Lib/protocol/payloads/sources */"./lib/protocol/payloads/sources.js");function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;icurrent.lastSyncBegan;}else{/** If new item, it must be dirty to be synced */return true;}}}]);return AccountSyncResponseResolver;}();/***/},/***/"./lib/services/sync/events.js":/*!*************************************!*\
!*** ./lib/services/sync/events.js ***!
\*************************************/ /*! exports provided: SyncEvents */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"SyncEvents",function(){return SyncEvents;});var SyncEvents={/** A full sync can consist of many round-trips to the server */FullSyncCompleted:'sync:full-completed',/** A single sync is just one round-trip to the server completion */SingleSyncCompleted:'sync:single-completed',DownloadFirstSyncCompleted:'sync:initial-completed',SyncTakingTooLong:'sync:taking-too-long',SyncError:'sync:error',SyncException:'sync:sync-exception',InvalidSession:'sync:invalid-session',MajorDataChange:'major-data-change',LocalDataLoaded:'local-data-loaded',LocalDataIncrementalLoad:'local-data-incremental-load',EnterOutOfSync:'enter-out-of-sync',ExitOutOfSync:'exit-out-of-sync'};/***/},/***/"./lib/services/sync/offline/operation.js":/*!************************************************!*\
!*** ./lib/services/sync/offline/operation.js ***!
\************************************************/ /*! exports provided: OfflineSyncOperation */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"OfflineSyncOperation",function(){return OfflineSyncOperation;});/* harmony import */var _Payloads_generator__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Payloads/generator */"./lib/protocol/payloads/generator.js");/* harmony import */var _Services_sync_signals__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! @Services/sync/signals */"./lib/services/sync/signals.js");function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0&&_args9[0]!==undefined?_args9[0]:{},alternateUuids=_ref2.alternateUuids;if(!alternateUuids){_context9.next=29;break;}/** Make a copy of the array, as alternating uuid will affect array */_items=this.modelManager.allNondummyItems.filter(function(item){return!item.errorDecrypting;}).slice();_iteratorNormalCompletion=true;_didIteratorError=false;_iteratorError=undefined;_context9.prev=6;_iterator=_items[Symbol.iterator]();case 8:if(_iteratorNormalCompletion=(_step=_iterator.next()).done){_context9.next=15;break;}item=_step.value;_context9.next=12;return regeneratorRuntime.awrap(this.modelManager.alternateUuidForItem(item));case 12:_iteratorNormalCompletion=true;_context9.next=8;break;case 15:_context9.next=21;break;case 17:_context9.prev=17;_context9.t0=_context9["catch"](6);_didIteratorError=true;_iteratorError=_context9.t0;case 21:_context9.prev=21;_context9.prev=22;if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return();}case 24:_context9.prev=24;if(!_didIteratorError){_context9.next=27;break;}throw _iteratorError;case 27:return _context9.finish(24);case 28:return _context9.finish(21);case 29:items=this.modelManager.allNondummyItems;payloads=items.map(function(item){return Object(_Payloads_generator__WEBPACK_IMPORTED_MODULE_13__["CreateMaxPayloadFromAnyObject"])({object:item,override:{dirty:true}});});_context9.next=33;return regeneratorRuntime.awrap(this.modelManager.mapPayloadsToLocalItems({payloads:payloads}));case 33:_context9.next=35;return regeneratorRuntime.awrap(this.persistPayloads({decryptedPayloads:payloads}));case 35:case"end":return _context9.stop();}}},null,this,[[6,17,21,29],[22,,24,28]]);}/**
* @public
* If encryption status changes (esp. on mobile, where local storage encryption
* can be disabled), consumers may call this function to repersist all items to
* disk using latest encryption status.
*/},{key:"repersistAllItems",value:function repersistAllItems(){var items,payloads;return regeneratorRuntime.async(function repersistAllItems$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:items=this.modelManager.allItems;payloads=items.map(function(item){return Object(_Payloads_generator__WEBPACK_IMPORTED_MODULE_13__["CreateMaxPayloadFromAnyObject"])({object:item});});return _context10.abrupt("return",this.persistPayloads({decryptedPayloads:payloads}));case 3:case"end":return _context10.stop();}}},null,this);}/**
* Return the payloads that need local persistence, before beginning a sync.
* This way, if the application is closed before a sync request completes,
* pending data will be saved to disk, and synced the next time the app opens.
*/},{key:"popPayloadsNeedingPreSyncSave",value:function popPayloadsNeedingPreSyncSave(from){var lastPreSyncSave,payloads;return regeneratorRuntime.async(function popPayloadsNeedingPreSyncSave$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:lastPreSyncSave=this.state.lastPreSyncSaveDate;if(lastPreSyncSave){_context11.next=3;break;}return _context11.abrupt("return",from);case 3:/** dirtiedDate can be null if the payload was created as dirty */payloads=from.filter(function(candidate){return!candidate.dirtiedDate||candidate.dirtiedDate>lastPreSyncSave;});this.state.setLastPresaveSyncDate(new Date());return _context11.abrupt("return",payloads);case 6:case"end":return _context11.stop();}}},null,this);}},{key:"timingStrategyResolveOnNext",value:function timingStrategyResolveOnNext(){var _this4=this;return new Promise(function(resolve,reject){_this4.resolveQueue.push({resolve:resolve,reject:reject});});}},{key:"timingStrategyForceSpawnNew",value:function timingStrategyForceSpawnNew(options){var _this5=this;return new Promise(function(resolve,reject){_this5.spawnQueue.push({resolve:resolve,reject:reject,options:options});});}/**
* For timing strategy TIMING_STRATEGY_FORCE_SPAWN_NEW, we will execute a whole sync request
* and pop it from the queue.
*/},{key:"popSpawnQueue",value:function popSpawnQueue(){if(this.spawnQueue.length===0){return null;}var promise=this.spawnQueue[0];Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["removeFromIndex"])(this.spawnQueue,0);this.log('Syncing again from spawn queue');return this.sync(_objectSpread({timingStrategy:TIMING_STRATEGY_FORCE_SPAWN_NEW},promise.options)).then(function(){promise.resolve();}).catch(function(){promise.reject();});}/**
* @param timingStrategy TIMING_STRATEGY_RESOLVE_ON_NEXT | Default
* Promise will be resolved on the next sync requests after the current one completes.
* If there is no scheduled sync request, one will be scheduled.
*
* TIMING_STRATEGY_FORCE_SPAWN_NEW
* A new sync request is guarenteed to be generated for your request, no matter how long it takes.
* Promise will be resolved whenever this sync request is processed in the serial queue.
*
* @param mode SYNC_MODE_DEFAULT
* Performs a standard sync, uploading any dirty items and retrieving items.
* SYNC_MODE_DOWNLOAD_FIRST
* The first sync for an account, where we first want to download all remote items first
* before uploading any dirty items. This allows a consumer, for example, to download
* all data to see if user has an items key, and if not, only then create a new one.
* @param checkIntegrity Whether the server should compute and return an integrity hash.
*/},{key:"sync",value:function sync(){var _ref3,timingStrategy,mode,checkIntegrity,items,neverSyncedDeleted,decryptedPayloads,payloadsNeedingSave,inTimeResolveQueue,useStrategy,syncInProgress,databaseLoaded,beginDate,useMode,online,uploadPayloads,operation,_iteratorNormalCompletion2,_didIteratorError2,_iteratorError2,_iterator2,_step2,callback,_args12=arguments;return regeneratorRuntime.async(function sync$(_context12){while(1){switch(_context12.prev=_context12.next){case 0:_ref3=_args12.length>0&&_args12[0]!==undefined?_args12[0]:{},timingStrategy=_ref3.timingStrategy,mode=_ref3.mode,checkIntegrity=_ref3.checkIntegrity;if(!this.locked){_context12.next=4;break;}this.log('Sync Locked');return _context12.abrupt("return");case 4:_context12.next=6;return regeneratorRuntime.awrap(this.itemsNeedingSync());case 6:items=_context12.sent;/**
* Items that have never been synced and marked as deleted should not be
* uploaded to server, and instead deleted directly after sync completion.
*/neverSyncedDeleted=items.filter(function(item){return item.neverSynced&&item.deleted;});Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["subtractFromArray"])(items,neverSyncedDeleted);decryptedPayloads=items.map(function(item){return Object(_Payloads_generator__WEBPACK_IMPORTED_MODULE_13__["CreateMaxPayloadFromAnyObject"])({object:item});});_context12.next=12;return regeneratorRuntime.awrap(this.popPayloadsNeedingPreSyncSave(decryptedPayloads));case 12:payloadsNeedingSave=_context12.sent;_context12.next=15;return regeneratorRuntime.awrap(this.persistPayloads({decryptedPayloads:payloadsNeedingSave}));case 15:/** The resolve queue before we add any new elements to it below */inTimeResolveQueue=this.resolveQueue.slice();useStrategy=!Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["isNullOrUndefined"])(timingStrategy)?timingStrategy:TIMING_STRATEGY_RESOLVE_ON_NEXT;syncInProgress=this.opStatus.syncInProgress;databaseLoaded=this.databaseLoaded;if(!(syncInProgress||!databaseLoaded)){_context12.next=30;break;}this.log(syncInProgress?'Attempting to sync while existing sync in progress.':'Attempting to sync before local database has loaded.');if(!(useStrategy===TIMING_STRATEGY_RESOLVE_ON_NEXT)){_context12.next=25;break;}return _context12.abrupt("return",this.timingStrategyResolveOnNext());case 25:if(!(useStrategy===TIMING_STRATEGY_FORCE_SPAWN_NEW)){_context12.next=29;break;}return _context12.abrupt("return",this.timingStrategyForceSpawnNew({checkIntegrity:checkIntegrity}));case 29:throw"Unhandled timing strategy ".concat(useStrategy);case 30:/** Lock syncing immediately after checking in progress above */this.opStatus.setDidBegin();/**
* Marking items dirty after lastSyncBegan will cause them to sync again.
*/beginDate=new Date();_context12.next=34;return regeneratorRuntime.awrap(this.modelManager.setItemsProperties({items:items,properties:{lastSyncBegan:beginDate}}));case 34:useMode=!Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["isNullOrUndefined"])(mode)?mode:SYNC_MODE_DEFAULT;_context12.next=37;return regeneratorRuntime.awrap(this.sessionManager.online());case 37:online=_context12.sent;if(!(useMode===SYNC_MODE_DEFAULT)){_context12.next=46;break;}if(this.completedInitialSync){_context12.next=41;break;}throw'Attempting to default mode sync without having completed initial.';case 41:_context12.next=43;return regeneratorRuntime.awrap(this.protocolService.payloadsByEncryptingPayloads({payloads:decryptedPayloads,intent:online?_Protocol_intents__WEBPACK_IMPORTED_MODULE_14__["EncryptionIntents"].Sync:_Protocol_intents__WEBPACK_IMPORTED_MODULE_14__["EncryptionIntents"].LocalStorageDecrypted}));case 43:uploadPayloads=_context12.sent;_context12.next=47;break;case 46:if(useMode===SYNC_MODE_DOWNLOAD_FIRST){uploadPayloads=[];}case 47:if(!online){_context12.next=53;break;}_context12.next=50;return regeneratorRuntime.awrap(this.syncOnlineOperation({payloads:uploadPayloads,checkIntegrity:checkIntegrity}));case 50:operation=_context12.sent;_context12.next=56;break;case 53:_context12.next=55;return regeneratorRuntime.awrap(this.syncOfflineOperation({payloads:uploadPayloads}));case 55:operation=_context12.sent;case 56:_context12.next=58;return regeneratorRuntime.awrap(operation.run());case 58:this.opStatus.setDidEnd();/**
* For timing strategy TIMING_STRATEGY_RESOLVE_ON_NEXT.
* Execute any callbacks pulled before this sync request began.
*/_iteratorNormalCompletion2=true;_didIteratorError2=false;_iteratorError2=undefined;_context12.prev=62;for(_iterator2=inTimeResolveQueue[Symbol.iterator]();!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=true){callback=_step2.value;callback.resolve();}_context12.next=70;break;case 66:_context12.prev=66;_context12.t0=_context12["catch"](62);_didIteratorError2=true;_iteratorError2=_context12.t0;case 70:_context12.prev=70;_context12.prev=71;if(!_iteratorNormalCompletion2&&_iterator2.return!=null){_iterator2.return();}case 73:_context12.prev=73;if(!_didIteratorError2){_context12.next=76;break;}throw _iteratorError2;case 76:return _context12.finish(73);case 77:return _context12.finish(70);case 78:Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["subtractFromArray"])(this.resolveQueue,inTimeResolveQueue);if(!this.popSpawnQueue()&&this.resolveQueue.length>0){this.log('Syncing again from resolve queue');/** No need to await. */this.sync();}_context12.next=82;return regeneratorRuntime.awrap(this.handleSyncOperationCompletion({operation:operation}));case 82:_context12.next=84;return regeneratorRuntime.awrap(this.handleNeverSyncedDeleted(neverSyncedDeleted));case 84:if(!(useMode===SYNC_MODE_DOWNLOAD_FIRST)){_context12.next=91;break;}this.completedInitialSync=true;_context12.next=88;return regeneratorRuntime.awrap(this.notifyEvent(_Lib__WEBPACK_IMPORTED_MODULE_18__["SyncEvents"].DownloadFirstSyncCompleted));case 88:return _context12.abrupt("return",this.sync());case 91:_context12.next=93;return regeneratorRuntime.awrap(this.itemsNeedingSync());case 93:_context12.t1=_context12.sent.length;if(!(_context12.t1>0)){_context12.next=96;break;}return _context12.abrupt("return",this.sync());case 96:case"end":return _context12.stop();}}},null,this,[[62,66,70,78],[71,,73,77]]);}/**
* @private
*/},{key:"syncOnlineOperation",value:function syncOnlineOperation(_ref4){var _this6=this;var payloads,checkIntegrity,operation;return regeneratorRuntime.async(function syncOnlineOperation$(_context14){while(1){switch(_context14.prev=_context14.next){case 0:payloads=_ref4.payloads,checkIntegrity=_ref4.checkIntegrity;this.log('Syncing online user',payloads);_context14.t0=_Services_sync_account_operation__WEBPACK_IMPORTED_MODULE_7__["AccountSyncOperation"];_context14.t1=this.apiService;_context14.t2=payloads;_context14.t3=checkIntegrity;_context14.next=8;return regeneratorRuntime.awrap(this.getLastSyncToken());case 8:_context14.t4=_context14.sent;_context14.next=11;return regeneratorRuntime.awrap(this.getPaginationToken());case 11:_context14.t5=_context14.sent;_context14.t6=function receiver(signal,type){var response;return regeneratorRuntime.async(function receiver$(_context13){while(1){switch(_context13.prev=_context13.next){case 0:if(!(type===_Services_sync_signals__WEBPACK_IMPORTED_MODULE_17__["SIGNAL_TYPE_RESPONSE"])){_context13.next=11;break;}response=signal;if(!response.hasError){_context13.next=7;break;}_context13.next=5;return regeneratorRuntime.awrap(_this6.handleErrorServerResponse({operation:operation,response:response}));case 5:_context13.next=9;break;case 7:_context13.next=9;return regeneratorRuntime.awrap(_this6.handleSuccessServerResponse({operation:operation,response:response}));case 9:_context13.next=14;break;case 11:if(!(type===_Services_sync_signals__WEBPACK_IMPORTED_MODULE_17__["SIGNAL_TYPE_STATUS_CHANGED"])){_context13.next=14;break;}_context13.next=14;return regeneratorRuntime.awrap(_this6.handleStatusChange({operation:operation}));case 14:case"end":return _context13.stop();}}});};_context14.t7={apiService:_context14.t1,payloads:_context14.t2,checkIntegrity:_context14.t3,lastSyncToken:_context14.t4,paginationToken:_context14.t5,receiver:_context14.t6};operation=new _context14.t0(_context14.t7);return _context14.abrupt("return",operation);case 16:case"end":return _context14.stop();}}},null,this);}},{key:"syncOfflineOperation",value:function syncOfflineOperation(_ref5){var _this7=this;var payloads,operation;return regeneratorRuntime.async(function syncOfflineOperation$(_context16){while(1){switch(_context16.prev=_context16.next){case 0:payloads=_ref5.payloads;this.log('Syncing offline user',payloads);operation=new _Services_sync_offline_operation__WEBPACK_IMPORTED_MODULE_8__["OfflineSyncOperation"]({payloads:payloads,receiver:function receiver(signal,type){return regeneratorRuntime.async(function receiver$(_context15){while(1){switch(_context15.prev=_context15.next){case 0:if(!(type===_Services_sync_signals__WEBPACK_IMPORTED_MODULE_17__["SIGNAL_TYPE_RESPONSE"])){_context15.next=5;break;}_context15.next=3;return regeneratorRuntime.awrap(_this7.handleOfflineResponse(signal));case 3:_context15.next=8;break;case 5:if(!(type===_Services_sync_signals__WEBPACK_IMPORTED_MODULE_17__["SIGNAL_TYPE_STATUS_CHANGED"])){_context15.next=8;break;}_context15.next=8;return regeneratorRuntime.awrap(_this7.handleStatusChange({operation:operation}));case 8:case"end":return _context15.stop();}}});}});return _context16.abrupt("return",operation);case 4:case"end":return _context16.stop();}}},null,this);}},{key:"handleStatusChange",value:function handleStatusChange(_ref6){var operation,pendingUploadCount,totalUploadCount,completedUploadCount;return regeneratorRuntime.async(function handleStatusChange$(_context17){while(1){switch(_context17.prev=_context17.next){case 0:operation=_ref6.operation;pendingUploadCount=operation.pendingUploadCount();totalUploadCount=operation.totalUploadCount();completedUploadCount=totalUploadCount-pendingUploadCount;this.opStatus.setUploadStatus({completed:completedUploadCount,total:totalUploadCount});case 5:case"end":return _context17.stop();}}},null,this);}},{key:"handleOfflineResponse",value:function handleOfflineResponse(response){var decryptedPayloads;return regeneratorRuntime.async(function handleOfflineResponse$(_context18){while(1){switch(_context18.prev=_context18.next){case 0:this.log('Offline Sync Response',response);decryptedPayloads=response.payloads;_context18.next=4;return regeneratorRuntime.awrap(this.persistPayloads({decryptedPayloads:decryptedPayloads}));case 4:_context18.next=6;return regeneratorRuntime.awrap(this.modelManager.mapPayloadsToLocalItems({payloads:decryptedPayloads,source:_Payloads_sources__WEBPACK_IMPORTED_MODULE_11__["PayloadSources"].LocalSaved}));case 6:case"end":return _context18.stop();}}},null,this);}},{key:"handleErrorServerResponse",value:function handleErrorServerResponse(_ref7){var operation,response;return regeneratorRuntime.async(function handleErrorServerResponse$(_context19){while(1){switch(_context19.prev=_context19.next){case 0:operation=_ref7.operation,response=_ref7.response;this.log('Sync Error',response);if(response.status===INVALID_SESSION_RESPONSE_STATUS){this.notifyEvent(_Lib__WEBPACK_IMPORTED_MODULE_18__["SyncEvents"].InvalidSession);}this.opStatus.setError(response.error);this.notifyEvent(_Lib__WEBPACK_IMPORTED_MODULE_18__["SyncEvents"].SyncError,response.error);case 5:case"end":return _context19.stop();}}},null,this);}},{key:"handleSuccessServerResponse",value:function handleSuccessServerResponse(_ref8){var operation,response,decryptedPayloads,_iteratorNormalCompletion3,_didIteratorError3,_iteratorError3,_iterator3,_step3,payload,decrypted,masterCollection,resolver,collections,_iteratorNormalCompletion4,_didIteratorError4,_iteratorError4,_iterator4,_step4,collection,payloadsToPersist,payloadClass,clientHash;return regeneratorRuntime.async(function handleSuccessServerResponse$(_context20){while(1){switch(_context20.prev=_context20.next){case 0:operation=_ref8.operation,response=_ref8.response;if(!this._simulate_latency){_context20.next=4;break;}_context20.next=4;return regeneratorRuntime.awrap(Object(_Lib_utils__WEBPACK_IMPORTED_MODULE_0__["sleep"])(this._simulate_latency.latency));case 4:this.log('Online Sync Response',response);this.setLastSyncToken(response.lastSyncToken);this.setPaginationToken(response.paginationToken);this.opStatus.clearError();this.opStatus.setDownloadStatus({downloaded:response.allProcessedPayloads.length});decryptedPayloads=[];_iteratorNormalCompletion3=true;_didIteratorError3=false;_iteratorError3=undefined;_context20.prev=13;_iterator3=response.allProcessedPayloads[Symbol.iterator]();case 15:if(_iteratorNormalCompletion3=(_step3=_iterator3.next()).done){_context20.next=26;break;}payload=_step3.value;if(!(payload.deleted||!payload.fields().includes(_Payloads_fields__WEBPACK_IMPORTED_MODULE_10__["PayloadFields"].Content))){_context20.next=19;break;}return _context20.abrupt("continue",23);case 19:_context20.next=21;return regeneratorRuntime.awrap(this.protocolService.payloadByDecryptingPayload({payload:payload}));case 21:decrypted=_context20.sent;decryptedPayloads.push(decrypted);case 23:_iteratorNormalCompletion3=true;_context20.next=15;break;case 26:_context20.next=32;break;case 28:_context20.prev=28;_context20.t0=_context20["catch"](13);_didIteratorError3=true;_iteratorError3=_context20.t0;case 32:_context20.prev=32;_context20.prev=33;if(!_iteratorNormalCompletion3&&_iterator3.return!=null){_iterator3.return();}case 35:_context20.prev=35;if(!_didIteratorError3){_context20.next=38;break;}throw _iteratorError3;case 38:return _context20.finish(35);case 39:return _context20.finish(32);case 40:masterCollection=this.modelManager.getMasterCollection();resolver=new _Services_sync_account_response_resolver__WEBPACK_IMPORTED_MODULE_6__["AccountSyncResponseResolver"]({response:response,decryptedResponsePayloads:decryptedPayloads,payloadsSavedOrSaving:operation.payloadsSavedOrSaving,baseCollection:masterCollection});_context20.next=44;return regeneratorRuntime.awrap(resolver.collectionsByProcessingResponse());case 44:collections=_context20.sent;_iteratorNormalCompletion4=true;_didIteratorError4=false;_iteratorError4=undefined;_context20.prev=48;_iterator4=collections[Symbol.iterator]();case 50:if(_iteratorNormalCompletion4=(_step4=_iterator4.next()).done){_context20.next=62;break;}collection=_step4.value;_context20.next=54;return regeneratorRuntime.awrap(this.modelManager.mapCollectionToLocalItems({collection:collection}));case 54:payloadsToPersist=void 0;payloadClass=Object(_Payloads_generator__WEBPACK_IMPORTED_MODULE_13__["payloadClassForSource"])(collection.source);if(!payloadClass.fields().includes(_Payloads_fields__WEBPACK_IMPORTED_MODULE_10__["PayloadFields"].Content)){/** Before persisting, merge with current base value that has content field */payloadsToPersist=collection.allPayloads.map(function(payload){var base=masterCollection.findPayload(payload.uuid);return base.mergedWith(payload);});}else{payloadsToPersist=collection.allPayloads;}_context20.next=59;return regeneratorRuntime.awrap(this.persistPayloads({decryptedPayloads:payloadsToPersist}));case 59:_iteratorNormalCompletion4=true;_context20.next=50;break;case 62:_context20.next=68;break;case 64:_context20.prev=64;_context20.t1=_context20["catch"](48);_didIteratorError4=true;_iteratorError4=_context20.t1;case 68:_context20.prev=68;_context20.prev=69;if(!_iteratorNormalCompletion4&&_iterator4.return!=null){_iterator4.return();}case 71:_context20.prev=71;if(!_didIteratorError4){_context20.next=74;break;}throw _iteratorError4;case 74:return _context20.finish(71);case 75:return _context20.finish(68);case 76:_context20.next=78;return regeneratorRuntime.awrap(this.notifyEvent(_Lib__WEBPACK_IMPORTED_MODULE_18__["SyncEvents"].SingleSyncCompleted));case 78:if(!response.checkIntegrity){_context20.next=87;break;}_context20.next=81;return regeneratorRuntime.awrap(this.computeDataIntegrityHash());case 81:clientHash=_context20.sent;_context20.next=84;return regeneratorRuntime.awrap(this.state.setIntegrityHashes({clientHash:clientHash,serverHash:response.integrityHash}));case 84:if(this.state.needsSync&&operation.done){this.log('Syncing again from integrity check');this.sync({checkIntegrity:true,timingStrategy:TIMING_STRATEGY_FORCE_SPAWN_NEW});}_context20.next=89;break;case 87:_context20.next=89;return regeneratorRuntime.awrap(this.state.clearIntegrityHashes());case 89:case"end":return _context20.stop();}}},null,this,[[13,28,32,40],[33,,35,39],[48,64,68,76],[69,,71,75]]);}},{key:"handleSyncOperationCompletion",value:function handleSyncOperationCompletion(_ref9){var operation;return regeneratorRuntime.async(function handleSyncOperationCompletion$(_context21){while(1){switch(_context21.prev=_context21.next){case 0:operation=_ref9.operation;this.opStatus.reset();this.state.setLastSyncDate(new Date());if(operation.numberOfItemsInvolved>=this.majorChangeThreshold){this.notifyEvent(_Lib__WEBPACK_IMPORTED_MODULE_18__["SyncEvents"].MajorDataChange);}_context21.next=6;return regeneratorRuntime.awrap(this.notifyEvent(_Lib__WEBPACK_IMPORTED_MODULE_18__["SyncEvents"].FullSyncCompleted));case 6:case"end":return _context21.stop();}}},null,this);}/**
* @private
* Items that have never been synced and marked as deleted should be cleared
* as dirty, mapped, then removed from storage.
*/},{key:"handleNeverSyncedDeleted",value:function handleNeverSyncedDeleted(items){var payloads;return regeneratorRuntime.async(function handleNeverSyncedDeleted$(_context22){while(1){switch(_context22.prev=_context22.next){case 0:payloads=items.map(function(item){return item.payloadRepresentation({override:{dirty:false}});});_context22.next=3;return regeneratorRuntime.awrap(this.modelManager.mapPayloadsToLocalItems({payloads:payloads}));case 3:_context22.next=5;return regeneratorRuntime.awrap(this.persistPayloads({decryptedPayloads:payloads}));case 5:case"end":return _context22.stop();}}},null,this);}},{key:"persistPayloads",value:function persistPayloads(_ref10){var _ref10$decryptedPaylo,decryptedPayloads;return regeneratorRuntime.async(function persistPayloads$(_context23){while(1){switch(_context23.prev=_context23.next){case 0:_ref10$decryptedPaylo=_ref10.decryptedPayloads,decryptedPayloads=_ref10$decryptedPaylo===void 0?[]:_ref10$decryptedPaylo;if(!(decryptedPayloads.length===0)){_context23.next=3;break;}return _context23.abrupt("return");case 3:_context23.next=5;return regeneratorRuntime.awrap(this.storageManager.savePayloads(decryptedPayloads));case 5:case"end":return _context23.stop();}}},null,this);}/**
* Computes a hash of all items updated_at strings joined with a comma.
* The server will also do the same, to determine whether the client values match server values.
* @returns A SHA256 digest string (hex).
*/},{key:"computeDataIntegrityHash",value:function computeDataIntegrityHash(){var items,dates,string;return regeneratorRuntime.async(function computeDataIntegrityHash$(_context24){while(1){switch(_context24.prev=_context24.next){case 0:_context24.prev=0;items=this.modelManager.nonDeletedItems.sort(function(a,b){return b.updated_at-a.updated_at;});dates=items.map(function(item){return item.updatedAtTimestamp();});string=dates.join(',');return _context24.abrupt("return",this.protocolService.crypto.sha256(string));case 7:_context24.prev=7;_context24.t0=_context24["catch"](0);console.error("Error computing data integrity hash",_context24.t0);return _context24.abrupt("return",null);case 11:case"end":return _context24.stop();}}},null,this,[[0,7]]);}},{key:"handleSignOut",value:function handleSignOut(){return regeneratorRuntime.async(function handleSignOut$(_context25){while(1){switch(_context25.prev=_context25.next){case 0:this.state.reset();this.opStatus.reset();this.resolveQueue=[];this.spawnQueue=[];_context25.next=6;return regeneratorRuntime.awrap(this.clearSyncPositionTokens());case 6:case"end":return _context25.stop();}}},null,this);}/** Downloads all items and maps to lcoal items to attempt resolve out-of-sync state */},{key:"resolveOutOfSync",value:function resolveOutOfSync(){var downloader,payloads,delta,collection;return regeneratorRuntime.async(function resolveOutOfSync$(_context26){while(1){switch(_context26.prev=_context26.next){case 0:downloader=new _Services_sync_account_downloader__WEBPACK_IMPORTED_MODULE_5__["AccountDownloader"]({apiService:this.apiService,protocolService:this.protocolService,customEvent:'resolve-out-of-sync'});_context26.next=3;return regeneratorRuntime.awrap(downloader.run());case 3:payloads=_context26.sent;delta=new _Payloads_deltas__WEBPACK_IMPORTED_MODULE_9__["DeltaOutOfSync"]({baseCollection:this.modelManager.getMasterCollection(),applyCollection:new _Payloads_collection__WEBPACK_IMPORTED_MODULE_12__["PayloadCollection"]({payloads:payloads,source:_Payloads_sources__WEBPACK_IMPORTED_MODULE_11__["PayloadSources"].RemoteRetrieved})});_context26.next=7;return regeneratorRuntime.awrap(delta.resultingCollection());case 7:collection=_context26.sent;_context26.next=10;return regeneratorRuntime.awrap(this.modelManager.mapCollectionToLocalItems({collection:collection}));case 10:_context26.next=12;return regeneratorRuntime.awrap(this.persistPayloads({decryptedPayloads:collection.payloads}));case 12:return _context26.abrupt("return",this.sync({checkIntegrity:true}));case 13:case"end":return _context26.stop();}}},null,this);}},{key:"statelessDownloadAllItems",value:function statelessDownloadAllItems(){var _ref11,contentType,customEvent,downloader,payloads,_args27=arguments;return regeneratorRuntime.async(function statelessDownloadAllItems$(_context27){while(1){switch(_context27.prev=_context27.next){case 0:_ref11=_args27.length>0&&_args27[0]!==undefined?_args27[0]:{},contentType=_ref11.contentType,customEvent=_ref11.customEvent;downloader=new _Services_sync_account_downloader__WEBPACK_IMPORTED_MODULE_5__["AccountDownloader"]({apiService:this.apiService,protocolService:this.protocolService,contentType:contentType,customEvent:customEvent});_context27.next=4;return regeneratorRuntime.awrap(downloader.run());case 4:payloads=_context27.sent;return _context27.abrupt("return",payloads.map(function(payload){return Object(_Models_generator__WEBPACK_IMPORTED_MODULE_16__["CreateItemFromPayload"])(payload);}));case 6:case"end":return _context27.stop();}}},null,this);}/** @unit_testing */ // eslint-disable-next-line camelcase
},{key:"ut_setDatabaseLoaded",value:function ut_setDatabaseLoaded(loaded){this.databaseLoaded=loaded;}/** @unit_testing */ // eslint-disable-next-line camelcase
},{key:"ut_beginLatencySimulator",value:function ut_beginLatencySimulator(latency){this._simulate_latency={latency:latency||1000,enabled:true};}/** @unit_testing */ // eslint-disable-next-line camelcase
},{key:"ut_endLatencySimulator",value:function ut_endLatencySimulator(){this._simulate_latency=null;}}]);return SNSyncManager;}(_Services_pure_service__WEBPACK_IMPORTED_MODULE_1__["PureService"]);/***/},/***/"./lib/services/sync/sync_op_status.js":/*!*********************************************!*\
!*** ./lib/services/sync/sync_op_status.js ***!
\*********************************************/ /*! exports provided: SyncOpStatus */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"SyncOpStatus",function(){return SyncOpStatus;});/* harmony import */var _Lib__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Lib */"./lib/index.js");function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;iHEALTHY_SYNC_DURATION_THRESHOLD_S){_this.receiver(_Lib__WEBPACK_IMPORTED_MODULE_0__["SyncEvents"].SyncTakingTooLong);_this.stopTimingMonitor();}},TIMING_MONITOR_POLL_FREQUENCY_MS);}},{key:"stopTimingMonitor",value:function stopTimingMonitor(){if(this.interval.hasOwnProperty('cancel')){this.interval.cancel(this.timingMonitor);}else{clearInterval(this.timingMonitor);}this.timingMonitor=null;}},{key:"setError",value:function setError(error){this.error=error;}},{key:"clearError",value:function clearError(){this.error=null;}},{key:"reset",value:function reset(){this.downloaded=0;this.completedUpload=0;this.totalUpload=0;this.inProgress=false;this.syncing=false;}},{key:"syncInProgress",get:function get(){return this.syncing===true;}},{key:"secondsSinceSyncStart",get:function get(){return(new Date()-this.syncStart)/1000;}}]);return SyncOpStatus;}();/***/},/***/"./lib/services/sync/sync_state.js":/*!*****************************************!*\
!*** ./lib/services/sync/sync_state.js ***!
\*****************************************/ /*! exports provided: SyncState */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"SyncState",function(){return SyncState;});/* harmony import */var _Lib__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Lib */"./lib/index.js");function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i=this.maxDiscordance&&!this.outOfSync){this.outOfSync=true;this.receiver(_Lib__WEBPACK_IMPORTED_MODULE_0__["SyncEvents"].EnterOutOfSync);}}case 5:case"end":return _context.stop();}}},null,this);}},{key:"lastPreSyncSaveDate",get:function get(){return this._lastPreSyncSave;}},{key:"lastSyncDate",get:function get(){return this._lastSyncDate;}},{key:"needsSync",get:function get(){return this.discordance>0&&this.discordancedateB){return dateA;}else{return dateB;}}function uniqCombineObjArrays(arrayA,arrayB,equalityKeys){return lodash_uniqWith__WEBPACK_IMPORTED_MODULE_2___default()(arrayA.concat(arrayB),function(a,b){var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=equalityKeys[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var key=_step.value;if(a[key]!==b[key]){return false;}}}catch(err){_didIteratorError=true;_iteratorError=err;}finally{try{if(!_iteratorNormalCompletion&&_iterator.return!=null){_iterator.return();}}finally{if(_didIteratorError){throw _iteratorError;}}}return true;});}/** Returns the last element in the array. */function lastElement(array){return array[array.length-1];}/** Adds all items from otherArray into inArray, in-place. */function extendArray(inArray,otherArray){var _iteratorNormalCompletion2=true;var _didIteratorError2=false;var _iteratorError2=undefined;try{for(var _iterator2=otherArray[Symbol.iterator](),_step2;!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=true){var value=_step2.value;inArray.push(value);}}catch(err){_didIteratorError2=true;_iteratorError2=err;}finally{try{if(!_iteratorNormalCompletion2&&_iterator2.return!=null){_iterator2.return();}}finally{if(_didIteratorError2){throw _iteratorError2;}}}}/** Removes all items appearing in toSubtract from inArray, in-place */function subtractFromArray(inArray,toSubtract){var _iteratorNormalCompletion3=true;var _didIteratorError3=false;var _iteratorError3=undefined;try{for(var _iterator3=toSubtract[Symbol.iterator](),_step3;!(_iteratorNormalCompletion3=(_step3=_iterator3.next()).done);_iteratorNormalCompletion3=true){var value=_step3.value;inArray.splice(inArray.indexOf(value),1);}}catch(err){_didIteratorError3=true;_iteratorError3=err;}finally{try{if(!_iteratorNormalCompletion3&&_iterator3.return!=null){_iterator3.return();}}finally{if(_didIteratorError3){throw _iteratorError3;}}}}/** Removes an object from the array by value */function removeFromArray(array,value){array.splice(array.indexOf(value),1);}/** Returns a new array by removing all elements in subtract from array */function arrayByDifference(array,subtract){return array.filter(function(x){return!subtract.includes(x);}).concat(subtract.filter(function(x){return!array.includes(x);}));}/** Removes the value from the array at the given index, in-place. */function removeFromIndex(array,index){array.splice(index,1);}/** Removes the value from the array at the given index, in-place. */function arrayByRemovingFromIndex(array,index){var copy=array.slice();removeFromIndex(copy,index);return copy;}function omitInPlace(object,keys){if(!object){return object;}var _iteratorNormalCompletion4=true;var _didIteratorError4=false;var _iteratorError4=undefined;try{for(var _iterator4=keys[Symbol.iterator](),_step4;!(_iteratorNormalCompletion4=(_step4=_iterator4.next()).done);_iteratorNormalCompletion4=true){var key=_step4.value;delete object[key];}}catch(err){_didIteratorError4=true;_iteratorError4=err;}finally{try{if(!_iteratorNormalCompletion4&&_iterator4.return!=null){_iterator4.return();}}finally{if(_didIteratorError4){throw _iteratorError4;}}}return object;}/** Creates a new object by omitting `fields` from `object` */function omitByCopy(object,fields){var newObject=Object.assign({},object);/**
* Lodash's omit, which was previously used, seems to cause unexpected behavior
* when payload is an ES6 item class. So we instead manually omit each key.
*/var _iteratorNormalCompletion5=true;var _didIteratorError5=false;var _iteratorError5=undefined;try{for(var _iterator5=fields[Symbol.iterator](),_step5;!(_iteratorNormalCompletion5=(_step5=_iterator5.next()).done);_iteratorNormalCompletion5=true){var key=_step5.value;delete newObject[key];}}catch(err){_didIteratorError5=true;_iteratorError5=err;}finally{try{if(!_iteratorNormalCompletion5&&_iterator5.return!=null){_iterator5.return();}}finally{if(_didIteratorError5){throw _iteratorError5;}}}return newObject;}function isObject(value){if(value===null){return false;}return typeof value==='function'||_typeof(value)==='object';}function joinPaths(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}return args.map(function(part,i){if(i===0){return part.trim().replace(/[\/]*$/g,'');}else{return part.trim().replace(/(^[\/]*|[\/]*$)/g,'');}}).filter(function(x){return x.length;}).join('/');}/**
* lodash.merge will not merge a full array with an empty one.
* deepMerge will replace arrays wholesale
*/function deepMerge(a,b){if(!a||!b){throw'Attempting to deepMerge with null values';}function mergeCopyArrays(objValue,srcValue){if(lodash_isArray__WEBPACK_IMPORTED_MODULE_0___default()(objValue)){return srcValue;}}lodash_mergeWith__WEBPACK_IMPORTED_MODULE_1___default()(a,b,mergeCopyArrays);return a;}function Copy(object){return JSON.parse(JSON.stringify(object));}function deepMergeByCopy(a,b){if(!a||!b){throw'Attempting to deepMergeByCopy with null values';}function mergeCopyArrays(objValue,srcValue){if(lodash_isArray__WEBPACK_IMPORTED_MODULE_0___default()(objValue)){return srcValue;}}b=Copy(b);lodash_mergeWith__WEBPACK_IMPORTED_MODULE_1___default()(a,b,mergeCopyArrays);return a;}/** Picks fields from an object by copying rather than by value (which is how Lodash's pick works.) */function pickByCopy(object,keys){var result={};var _iteratorNormalCompletion6=true;var _didIteratorError6=false;var _iteratorError6=undefined;try{for(var _iterator6=keys[Symbol.iterator](),_step6;!(_iteratorNormalCompletion6=(_step6=_iterator6.next()).done);_iteratorNormalCompletion6=true){var key=_step6.value;result[key]=object[key];}}catch(err){_didIteratorError6=true;_iteratorError6=err;}finally{try{if(!_iteratorNormalCompletion6&&_iterator6.return!=null){_iterator6.return();}}finally{if(_didIteratorError6){throw _iteratorError6;}}}return Copy(result);}function deepFreeze(object){// Retrieve the property names defined on object
var propNames=Object.getOwnPropertyNames(object);// Freeze properties before freezing self
var _iteratorNormalCompletion7=true;var _didIteratorError7=false;var _iteratorError7=undefined;try{for(var _iterator7=propNames[Symbol.iterator](),_step7;!(_iteratorNormalCompletion7=(_step7=_iterator7.next()).done);_iteratorNormalCompletion7=true){var name=_step7.value;var value=object[name];object[name]=value&&_typeof(value)==="object"?deepFreeze(value):value;}}catch(err){_didIteratorError7=true;_iteratorError7=err;}finally{try{if(!_iteratorNormalCompletion7&&_iterator7.return!=null){_iterator7.return();}}finally{if(_didIteratorError7){throw _iteratorError7;}}}return Object.freeze(object);}function hasGetter(object,property){var descriptor=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(object),property);return descriptor&&!isNullOrUndefined(descriptor.get);}function sleep(milliseconds){return regeneratorRuntime.async(function sleep$(_context){while(1){switch(_context.prev=_context.next){case 0:console.warn("Sleeping for",milliseconds);return _context.abrupt("return",new Promise(function(resolve,reject){setTimeout(function(){resolve();},milliseconds);}));case 2:case"end":return _context.stop();}}});}/* WEBPACK VAR INJECTION */}).call(this,__webpack_require__(/*! ./../node_modules/webpack/buildin/global.js */"./node_modules/webpack/buildin/global.js"));/***/},/***/"./lib/uuid.js":/*!*********************!*\
!*** ./lib/uuid.js ***!
\*********************/ /*! exports provided: Uuid */ /***/function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);/* harmony export (binding) */__webpack_require__.d(__webpack_exports__,"Uuid",function(){return Uuid;});/* harmony import */var _Lib_utils__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! @Lib/utils */"./lib/utils.js");function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i-1;}module.exports=arrayIncludes;/***/},/***/"./node_modules/lodash/_arrayIncludesWith.js":/*!***************************************************!*\
!*** ./node_modules/lodash/_arrayIncludesWith.js ***!
\***************************************************/ /*! no static exports found */ /***/function(module,exports){/**
* This function is like `arrayIncludes` except that it accepts a comparator.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @param {Function} comparator The comparator invoked per element.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/function arrayIncludesWith(array,value,comparator){var index=-1,length=array==null?0:array.length;while(++index0&&predicate(value)){if(depth>1){// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value,depth-1,predicate,isStrict,result);}else{arrayPush(result,value);}}else if(!isStrict){result[result.length]=value;}}return result;}module.exports=baseFlatten;/***/},/***/"./node_modules/lodash/_baseFor.js":/*!*****************************************!*\
!*** ./node_modules/lodash/_baseFor.js ***!
\*****************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var createBaseFor=__webpack_require__(/*! ./_createBaseFor */"./node_modules/lodash/_createBaseFor.js");/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/var baseFor=createBaseFor();module.exports=baseFor;/***/},/***/"./node_modules/lodash/_baseForOwn.js":/*!********************************************!*\
!*** ./node_modules/lodash/_baseForOwn.js ***!
\********************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseFor=__webpack_require__(/*! ./_baseFor */"./node_modules/lodash/_baseFor.js"),keys=__webpack_require__(/*! ./keys */"./node_modules/lodash/keys.js");/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/function baseForOwn(object,iteratee){return object&&baseFor(object,iteratee,keys);}module.exports=baseForOwn;/***/},/***/"./node_modules/lodash/_baseGet.js":/*!*****************************************!*\
!*** ./node_modules/lodash/_baseGet.js ***!
\*****************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var castPath=__webpack_require__(/*! ./_castPath */"./node_modules/lodash/_castPath.js"),toKey=__webpack_require__(/*! ./_toKey */"./node_modules/lodash/_toKey.js");/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/function baseGet(object,path){path=castPath(path,object);var index=0,length=path.length;while(object!=null&&index-1){if(seen!==array){splice.call(seen,fromIndex,1);}splice.call(array,fromIndex,1);}}return array;}module.exports=basePullAll;/***/},/***/"./node_modules/lodash/_basePullAt.js":/*!********************************************!*\
!*** ./node_modules/lodash/_basePullAt.js ***!
\********************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseUnset=__webpack_require__(/*! ./_baseUnset */"./node_modules/lodash/_baseUnset.js"),isIndex=__webpack_require__(/*! ./_isIndex */"./node_modules/lodash/_isIndex.js");/** Used for built-in method references. */var arrayProto=Array.prototype;/** Built-in value references. */var splice=arrayProto.splice;/**
* The base implementation of `_.pullAt` without support for individual
* indexes or capturing the removed elements.
*
* @private
* @param {Array} array The array to modify.
* @param {number[]} indexes The indexes of elements to remove.
* @returns {Array} Returns `array`.
*/function basePullAt(array,indexes){var length=array?indexes.length:0,lastIndex=length-1;while(length--){var index=indexes[length];if(length==lastIndex||index!==previous){var previous=index;if(isIndex(index)){splice.call(array,index,1);}else{baseUnset(array,index);}}}return array;}module.exports=basePullAt;/***/},/***/"./node_modules/lodash/_baseRest.js":/*!******************************************!*\
!*** ./node_modules/lodash/_baseRest.js ***!
\******************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var identity=__webpack_require__(/*! ./identity */"./node_modules/lodash/identity.js"),overRest=__webpack_require__(/*! ./_overRest */"./node_modules/lodash/_overRest.js"),setToString=__webpack_require__(/*! ./_setToString */"./node_modules/lodash/_setToString.js");/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/function baseRest(func,start){return setToString(overRest(func,start,identity),func+'');}module.exports=baseRest;/***/},/***/"./node_modules/lodash/_baseSetToString.js":/*!*************************************************!*\
!*** ./node_modules/lodash/_baseSetToString.js ***!
\*************************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var constant=__webpack_require__(/*! ./constant */"./node_modules/lodash/constant.js"),defineProperty=__webpack_require__(/*! ./_defineProperty */"./node_modules/lodash/_defineProperty.js"),identity=__webpack_require__(/*! ./identity */"./node_modules/lodash/identity.js");/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/var baseSetToString=!defineProperty?identity:function(func,string){return defineProperty(func,'toString',{'configurable':true,'enumerable':false,'value':constant(string),'writable':true});};module.exports=baseSetToString;/***/},/***/"./node_modules/lodash/_baseSlice.js":/*!*******************************************!*\
!*** ./node_modules/lodash/_baseSlice.js ***!
\*******************************************/ /*! no static exports found */ /***/function(module,exports){/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/function baseSlice(array,start,end){var index=-1,length=array.length;if(start<0){start=-start>length?0:length+start;}end=end>length?length:end;if(end<0){end+=length;}length=start>end?0:end-start>>>0;start>>>=0;var result=Array(length);while(++index=LARGE_ARRAY_SIZE){var set=iteratee?null:createSet(array);if(set){return setToArray(set);}isCommon=false;includes=cacheHas;seen=new SetCache();}else{seen=iteratee?[]:result;}outer:while(++index1?sources[length-1]:undefined,guard=length>2?sources[2]:undefined;customizer=assigner.length>3&&typeof customizer=='function'?(length--,customizer):undefined;if(guard&&isIterateeCall(sources[0],sources[1],guard)){customizer=length<3?undefined:customizer;length=1;}object=Object(object);while(++index-1?iterable[iteratee?collection[index]:index]:undefined;};}module.exports=createFind;/***/},/***/"./node_modules/lodash/_createSet.js":/*!*******************************************!*\
!*** ./node_modules/lodash/_createSet.js ***!
\*******************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var Set=__webpack_require__(/*! ./_Set */"./node_modules/lodash/_Set.js"),noop=__webpack_require__(/*! ./noop */"./node_modules/lodash/noop.js"),setToArray=__webpack_require__(/*! ./_setToArray */"./node_modules/lodash/_setToArray.js");/** Used as references for various `Number` constants. */var INFINITY=1/0;/**
* Creates a set object of `values`.
*
* @private
* @param {Array} values The values to add to the set.
* @returns {Object} Returns the new set.
*/var createSet=!(Set&&1/setToArray(new Set([,-0]))[1]==INFINITY)?noop:function(values){return new Set(values);};module.exports=createSet;/***/},/***/"./node_modules/lodash/_customOmitClone.js":/*!*************************************************!*\
!*** ./node_modules/lodash/_customOmitClone.js ***!
\*************************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var isPlainObject=__webpack_require__(/*! ./isPlainObject */"./node_modules/lodash/isPlainObject.js");/**
* Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
* objects.
*
* @private
* @param {*} value The value to inspect.
* @param {string} key The key of the property to inspect.
* @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
*/function customOmitClone(value){return isPlainObject(value)?undefined:value;}module.exports=customOmitClone;/***/},/***/"./node_modules/lodash/_defineProperty.js":/*!************************************************!*\
!*** ./node_modules/lodash/_defineProperty.js ***!
\************************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var getNative=__webpack_require__(/*! ./_getNative */"./node_modules/lodash/_getNative.js");var defineProperty=function(){try{var func=getNative(Object,'defineProperty');func({},'',{});return func;}catch(e){}}();module.exports=defineProperty;/***/},/***/"./node_modules/lodash/_equalArrays.js":/*!*********************************************!*\
!*** ./node_modules/lodash/_equalArrays.js ***!
\*********************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var SetCache=__webpack_require__(/*! ./_SetCache */"./node_modules/lodash/_SetCache.js"),arraySome=__webpack_require__(/*! ./_arraySome */"./node_modules/lodash/_arraySome.js"),cacheHas=__webpack_require__(/*! ./_cacheHas */"./node_modules/lodash/_cacheHas.js");/** Used to compose bitmasks for value comparisons. */var COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2;/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/function equalArrays(array,other,bitmask,customizer,equalFunc,stack){var isPartial=bitmask&COMPARE_PARTIAL_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength)){return false;}// Assume cyclic values are equal.
var stacked=stack.get(array);if(stacked&&stack.get(other)){return stacked==other;}var index=-1,result=true,seen=bitmask&COMPARE_UNORDERED_FLAG?new SetCache():undefined;stack.set(array,other);stack.set(other,array);// Ignore non-index properties.
while(++index-1&&value%1==0&&value-1;}module.exports=listCacheHas;/***/},/***/"./node_modules/lodash/_listCacheSet.js":/*!**********************************************!*\
!*** ./node_modules/lodash/_listCacheSet.js ***!
\**********************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var assocIndexOf=__webpack_require__(/*! ./_assocIndexOf */"./node_modules/lodash/_assocIndexOf.js");/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);if(index<0){++this.size;data.push([key,value]);}else{data[index][1]=value;}return this;}module.exports=listCacheSet;/***/},/***/"./node_modules/lodash/_mapCacheClear.js":/*!***********************************************!*\
!*** ./node_modules/lodash/_mapCacheClear.js ***!
\***********************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var Hash=__webpack_require__(/*! ./_Hash */"./node_modules/lodash/_Hash.js"),ListCache=__webpack_require__(/*! ./_ListCache */"./node_modules/lodash/_ListCache.js"),Map=__webpack_require__(/*! ./_Map */"./node_modules/lodash/_Map.js");/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/function mapCacheClear(){this.size=0;this.__data__={'hash':new Hash(),'map':new(Map||ListCache)(),'string':new Hash()};}module.exports=mapCacheClear;/***/},/***/"./node_modules/lodash/_mapCacheDelete.js":/*!************************************************!*\
!*** ./node_modules/lodash/_mapCacheDelete.js ***!
\************************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var getMapData=__webpack_require__(/*! ./_getMapData */"./node_modules/lodash/_getMapData.js");/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/function mapCacheDelete(key){var result=getMapData(this,key)['delete'](key);this.size-=result?1:0;return result;}module.exports=mapCacheDelete;/***/},/***/"./node_modules/lodash/_mapCacheGet.js":/*!*********************************************!*\
!*** ./node_modules/lodash/_mapCacheGet.js ***!
\*********************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var getMapData=__webpack_require__(/*! ./_getMapData */"./node_modules/lodash/_getMapData.js");/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/function mapCacheGet(key){return getMapData(this,key).get(key);}module.exports=mapCacheGet;/***/},/***/"./node_modules/lodash/_mapCacheHas.js":/*!*********************************************!*\
!*** ./node_modules/lodash/_mapCacheHas.js ***!
\*********************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var getMapData=__webpack_require__(/*! ./_getMapData */"./node_modules/lodash/_getMapData.js");/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/function mapCacheHas(key){return getMapData(this,key).has(key);}module.exports=mapCacheHas;/***/},/***/"./node_modules/lodash/_mapCacheSet.js":/*!*********************************************!*\
!*** ./node_modules/lodash/_mapCacheSet.js ***!
\*********************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var getMapData=__webpack_require__(/*! ./_getMapData */"./node_modules/lodash/_getMapData.js");/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/function mapCacheSet(key,value){var data=getMapData(this,key),size=data.size;data.set(key,value);this.size+=data.size==size?0:1;return this;}module.exports=mapCacheSet;/***/},/***/"./node_modules/lodash/_mapToArray.js":/*!********************************************!*\
!*** ./node_modules/lodash/_mapToArray.js ***!
\********************************************/ /*! no static exports found */ /***/function(module,exports){/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/function mapToArray(map){var index=-1,result=Array(map.size);map.forEach(function(value,key){result[++index]=[key,value];});return result;}module.exports=mapToArray;/***/},/***/"./node_modules/lodash/_matchesStrictComparable.js":/*!*********************************************************!*\
!*** ./node_modules/lodash/_matchesStrictComparable.js ***!
\*********************************************************/ /*! no static exports found */ /***/function(module,exports){/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/function matchesStrictComparable(key,srcValue){return function(object){if(object==null){return false;}return object[key]===srcValue&&(srcValue!==undefined||key in Object(object));};}module.exports=matchesStrictComparable;/***/},/***/"./node_modules/lodash/_memoizeCapped.js":/*!***********************************************!*\
!*** ./node_modules/lodash/_memoizeCapped.js ***!
\***********************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var memoize=__webpack_require__(/*! ./memoize */"./node_modules/lodash/memoize.js");/** Used as the maximum memoize cache size. */var MAX_MEMOIZE_SIZE=500;/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/function memoizeCapped(func){var result=memoize(func,function(key){if(cache.size===MAX_MEMOIZE_SIZE){cache.clear();}return key;});var cache=result.cache;return result;}module.exports=memoizeCapped;/***/},/***/"./node_modules/lodash/_nativeCreate.js":/*!**********************************************!*\
!*** ./node_modules/lodash/_nativeCreate.js ***!
\**********************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var getNative=__webpack_require__(/*! ./_getNative */"./node_modules/lodash/_getNative.js");/* Built-in method references that are verified to be native. */var nativeCreate=getNative(Object,'create');module.exports=nativeCreate;/***/},/***/"./node_modules/lodash/_nativeKeys.js":/*!********************************************!*\
!*** ./node_modules/lodash/_nativeKeys.js ***!
\********************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var overArg=__webpack_require__(/*! ./_overArg */"./node_modules/lodash/_overArg.js");/* Built-in method references for those with the same name as other `lodash` methods. */var nativeKeys=overArg(Object.keys,Object);module.exports=nativeKeys;/***/},/***/"./node_modules/lodash/_nativeKeysIn.js":/*!**********************************************!*\
!*** ./node_modules/lodash/_nativeKeysIn.js ***!
\**********************************************/ /*! no static exports found */ /***/function(module,exports){/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/function nativeKeysIn(object){var result=[];if(object!=null){for(var key in Object(object)){result.push(key);}}return result;}module.exports=nativeKeysIn;/***/},/***/"./node_modules/lodash/_nodeUtil.js":/*!******************************************!*\
!*** ./node_modules/lodash/_nodeUtil.js ***!
\******************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){/* WEBPACK VAR INJECTION */(function(module){function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}var freeGlobal=__webpack_require__(/*! ./_freeGlobal */"./node_modules/lodash/_freeGlobal.js");/** Detect free variable `exports`. */var freeExports=(false?undefined:_typeof(exports))=='object'&&exports&&!exports.nodeType&&exports;/** Detect free variable `module`. */var freeModule=freeExports&&(false?undefined:_typeof(module))=='object'&&module&&!module.nodeType&&module;/** Detect the popular CommonJS extension `module.exports`. */var moduleExports=freeModule&&freeModule.exports===freeExports;/** Detect free variable `process` from Node.js. */var freeProcess=moduleExports&&freeGlobal.process;/** Used to access faster Node.js helpers. */var nodeUtil=function(){try{// Use `util.types` for Node.js 10+.
var types=freeModule&&freeModule.require&&freeModule.require('util').types;if(types){return types;}// Legacy `process.binding('util')` for Node.js < 10.
return freeProcess&&freeProcess.binding&&freeProcess.binding('util');}catch(e){}}();module.exports=nodeUtil;/* WEBPACK VAR INJECTION */}).call(this,__webpack_require__(/*! ./../webpack/buildin/module.js */"./node_modules/webpack/buildin/module.js")(module));/***/},/***/"./node_modules/lodash/_objectToString.js":/*!************************************************!*\
!*** ./node_modules/lodash/_objectToString.js ***!
\************************************************/ /*! no static exports found */ /***/function(module,exports){/** Used for built-in method references. */var objectProto=Object.prototype;/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/var nativeObjectToString=objectProto.toString;/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/function objectToString(value){return nativeObjectToString.call(value);}module.exports=objectToString;/***/},/***/"./node_modules/lodash/_overArg.js":/*!*****************************************!*\
!*** ./node_modules/lodash/_overArg.js ***!
\*****************************************/ /*! no static exports found */ /***/function(module,exports){/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/function overArg(func,transform){return function(arg){return func(transform(arg));};}module.exports=overArg;/***/},/***/"./node_modules/lodash/_overRest.js":/*!******************************************!*\
!*** ./node_modules/lodash/_overRest.js ***!
\******************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var apply=__webpack_require__(/*! ./_apply */"./node_modules/lodash/_apply.js");/* Built-in method references for those with the same name as other `lodash` methods. */var nativeMax=Math.max;/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/function overRest(func,start,transform){start=nativeMax(start===undefined?func.length-1:start,0);return function(){var args=arguments,index=-1,length=nativeMax(args.length-start,0),array=Array(length);while(++index0){if(++count>=HOT_COUNT){return arguments[0];}}else{count=0;}return func.apply(undefined,arguments);};}module.exports=shortOut;/***/},/***/"./node_modules/lodash/_stackClear.js":/*!********************************************!*\
!*** ./node_modules/lodash/_stackClear.js ***!
\********************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var ListCache=__webpack_require__(/*! ./_ListCache */"./node_modules/lodash/_ListCache.js");/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/function stackClear(){this.__data__=new ListCache();this.size=0;}module.exports=stackClear;/***/},/***/"./node_modules/lodash/_stackDelete.js":/*!*********************************************!*\
!*** ./node_modules/lodash/_stackDelete.js ***!
\*********************************************/ /*! no static exports found */ /***/function(module,exports){/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/function stackDelete(key){var data=this.__data__,result=data['delete'](key);this.size=data.size;return result;}module.exports=stackDelete;/***/},/***/"./node_modules/lodash/_stackGet.js":/*!******************************************!*\
!*** ./node_modules/lodash/_stackGet.js ***!
\******************************************/ /*! no static exports found */ /***/function(module,exports){/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/function stackGet(key){return this.__data__.get(key);}module.exports=stackGet;/***/},/***/"./node_modules/lodash/_stackHas.js":/*!******************************************!*\
!*** ./node_modules/lodash/_stackHas.js ***!
\******************************************/ /*! no static exports found */ /***/function(module,exports){/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/function stackHas(key){return this.__data__.has(key);}module.exports=stackHas;/***/},/***/"./node_modules/lodash/_stackSet.js":/*!******************************************!*\
!*** ./node_modules/lodash/_stackSet.js ***!
\******************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var ListCache=__webpack_require__(/*! ./_ListCache */"./node_modules/lodash/_ListCache.js"),Map=__webpack_require__(/*! ./_Map */"./node_modules/lodash/_Map.js"),MapCache=__webpack_require__(/*! ./_MapCache */"./node_modules/lodash/_MapCache.js");/** Used as the size to enable large array optimizations. */var LARGE_ARRAY_SIZE=200;/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/function stackSet(key,value){var data=this.__data__;if(data instanceof ListCache){var pairs=data.__data__;if(!Map||pairs.length [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/function constant(value){return function(){return value;};}module.exports=constant;/***/},/***/"./node_modules/lodash/eq.js":/*!***********************************!*\
!*** ./node_modules/lodash/eq.js ***!
\***********************************/ /*! no static exports found */ /***/function(module,exports){/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/function eq(value,other){return value===other||value!==value&&other!==other;}module.exports=eq;/***/},/***/"./node_modules/lodash/find.js":/*!*************************************!*\
!*** ./node_modules/lodash/find.js ***!
\*************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var createFind=__webpack_require__(/*! ./_createFind */"./node_modules/lodash/_createFind.js"),findIndex=__webpack_require__(/*! ./findIndex */"./node_modules/lodash/findIndex.js");/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.find(users, function(o) { return o.age < 40; });
* // => object for 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.find(users, { 'age': 1, 'active': true });
* // => object for 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.find(users, ['active', false]);
* // => object for 'fred'
*
* // The `_.property` iteratee shorthand.
* _.find(users, 'active');
* // => object for 'barney'
*/var find=createFind(findIndex);module.exports=find;/***/},/***/"./node_modules/lodash/findIndex.js":/*!******************************************!*\
!*** ./node_modules/lodash/findIndex.js ***!
\******************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseFindIndex=__webpack_require__(/*! ./_baseFindIndex */"./node_modules/lodash/_baseFindIndex.js"),baseIteratee=__webpack_require__(/*! ./_baseIteratee */"./node_modules/lodash/_baseIteratee.js"),toInteger=__webpack_require__(/*! ./toInteger */"./node_modules/lodash/toInteger.js");/* Built-in method references for those with the same name as other `lodash` methods. */var nativeMax=Math.max;/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/function findIndex(array,predicate,fromIndex){var length=array==null?0:array.length;if(!length){return-1;}var index=fromIndex==null?0:toInteger(fromIndex);if(index<0){index=nativeMax(length+index,0);}return baseFindIndex(array,baseIteratee(predicate,3),index);}module.exports=findIndex;/***/},/***/"./node_modules/lodash/flatten.js":/*!****************************************!*\
!*** ./node_modules/lodash/flatten.js ***!
\****************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseFlatten=__webpack_require__(/*! ./_baseFlatten */"./node_modules/lodash/_baseFlatten.js");/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/function flatten(array){var length=array==null?0:array.length;return length?baseFlatten(array,1):[];}module.exports=flatten;/***/},/***/"./node_modules/lodash/get.js":/*!************************************!*\
!*** ./node_modules/lodash/get.js ***!
\************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseGet=__webpack_require__(/*! ./_baseGet */"./node_modules/lodash/_baseGet.js");/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/function get(object,path,defaultValue){var result=object==null?undefined:baseGet(object,path);return result===undefined?defaultValue:result;}module.exports=get;/***/},/***/"./node_modules/lodash/hasIn.js":/*!**************************************!*\
!*** ./node_modules/lodash/hasIn.js ***!
\**************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseHasIn=__webpack_require__(/*! ./_baseHasIn */"./node_modules/lodash/_baseHasIn.js"),hasPath=__webpack_require__(/*! ./_hasPath */"./node_modules/lodash/_hasPath.js");/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/function hasIn(object,path){return object!=null&&hasPath(object,path,baseHasIn);}module.exports=hasIn;/***/},/***/"./node_modules/lodash/identity.js":/*!*****************************************!*\
!*** ./node_modules/lodash/identity.js ***!
\*****************************************/ /*! no static exports found */ /***/function(module,exports){/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/function identity(value){return value;}module.exports=identity;/***/},/***/"./node_modules/lodash/isArguments.js":/*!********************************************!*\
!*** ./node_modules/lodash/isArguments.js ***!
\********************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseIsArguments=__webpack_require__(/*! ./_baseIsArguments */"./node_modules/lodash/_baseIsArguments.js"),isObjectLike=__webpack_require__(/*! ./isObjectLike */"./node_modules/lodash/isObjectLike.js");/** Used for built-in method references. */var objectProto=Object.prototype;/** Used to check objects for own properties. */var hasOwnProperty=objectProto.hasOwnProperty;/** Built-in value references. */var propertyIsEnumerable=objectProto.propertyIsEnumerable;/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/var isArguments=baseIsArguments(function(){return arguments;}())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,'callee')&&!propertyIsEnumerable.call(value,'callee');};module.exports=isArguments;/***/},/***/"./node_modules/lodash/isArray.js":/*!****************************************!*\
!*** ./node_modules/lodash/isArray.js ***!
\****************************************/ /*! no static exports found */ /***/function(module,exports){/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/var isArray=Array.isArray;module.exports=isArray;/***/},/***/"./node_modules/lodash/isArrayLike.js":/*!********************************************!*\
!*** ./node_modules/lodash/isArrayLike.js ***!
\********************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var isFunction=__webpack_require__(/*! ./isFunction */"./node_modules/lodash/isFunction.js"),isLength=__webpack_require__(/*! ./isLength */"./node_modules/lodash/isLength.js");/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/function isArrayLike(value){return value!=null&&isLength(value.length)&&!isFunction(value);}module.exports=isArrayLike;/***/},/***/"./node_modules/lodash/isArrayLikeObject.js":/*!**************************************************!*\
!*** ./node_modules/lodash/isArrayLikeObject.js ***!
\**************************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var isArrayLike=__webpack_require__(/*! ./isArrayLike */"./node_modules/lodash/isArrayLike.js"),isObjectLike=__webpack_require__(/*! ./isObjectLike */"./node_modules/lodash/isObjectLike.js");/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/function isArrayLikeObject(value){return isObjectLike(value)&&isArrayLike(value);}module.exports=isArrayLikeObject;/***/},/***/"./node_modules/lodash/isBuffer.js":/*!*****************************************!*\
!*** ./node_modules/lodash/isBuffer.js ***!
\*****************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){/* WEBPACK VAR INJECTION */(function(module){function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}var root=__webpack_require__(/*! ./_root */"./node_modules/lodash/_root.js"),stubFalse=__webpack_require__(/*! ./stubFalse */"./node_modules/lodash/stubFalse.js");/** Detect free variable `exports`. */var freeExports=(false?undefined:_typeof(exports))=='object'&&exports&&!exports.nodeType&&exports;/** Detect free variable `module`. */var freeModule=freeExports&&(false?undefined:_typeof(module))=='object'&&module&&!module.nodeType&&module;/** Detect the popular CommonJS extension `module.exports`. */var moduleExports=freeModule&&freeModule.exports===freeExports;/** Built-in value references. */var Buffer=moduleExports?root.Buffer:undefined;/* Built-in method references for those with the same name as other `lodash` methods. */var nativeIsBuffer=Buffer?Buffer.isBuffer:undefined;/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/var isBuffer=nativeIsBuffer||stubFalse;module.exports=isBuffer;/* WEBPACK VAR INJECTION */}).call(this,__webpack_require__(/*! ./../webpack/buildin/module.js */"./node_modules/webpack/buildin/module.js")(module));/***/},/***/"./node_modules/lodash/isFunction.js":/*!*******************************************!*\
!*** ./node_modules/lodash/isFunction.js ***!
\*******************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseGetTag=__webpack_require__(/*! ./_baseGetTag */"./node_modules/lodash/_baseGetTag.js"),isObject=__webpack_require__(/*! ./isObject */"./node_modules/lodash/isObject.js");/** `Object#toString` result references. */var asyncTag='[object AsyncFunction]',funcTag='[object Function]',genTag='[object GeneratorFunction]',proxyTag='[object Proxy]';/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/function isFunction(value){if(!isObject(value)){return false;}// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag=baseGetTag(value);return tag==funcTag||tag==genTag||tag==asyncTag||tag==proxyTag;}module.exports=isFunction;/***/},/***/"./node_modules/lodash/isLength.js":/*!*****************************************!*\
!*** ./node_modules/lodash/isLength.js ***!
\*****************************************/ /*! no static exports found */ /***/function(module,exports){/** Used as references for various `Number` constants. */var MAX_SAFE_INTEGER=9007199254740991;/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/function isLength(value){return typeof value=='number'&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER;}module.exports=isLength;/***/},/***/"./node_modules/lodash/isMap.js":/*!**************************************!*\
!*** ./node_modules/lodash/isMap.js ***!
\**************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseIsMap=__webpack_require__(/*! ./_baseIsMap */"./node_modules/lodash/_baseIsMap.js"),baseUnary=__webpack_require__(/*! ./_baseUnary */"./node_modules/lodash/_baseUnary.js"),nodeUtil=__webpack_require__(/*! ./_nodeUtil */"./node_modules/lodash/_nodeUtil.js");/* Node.js helper references. */var nodeIsMap=nodeUtil&&nodeUtil.isMap;/**
* Checks if `value` is classified as a `Map` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
* @example
*
* _.isMap(new Map);
* // => true
*
* _.isMap(new WeakMap);
* // => false
*/var isMap=nodeIsMap?baseUnary(nodeIsMap):baseIsMap;module.exports=isMap;/***/},/***/"./node_modules/lodash/isObject.js":/*!*****************************************!*\
!*** ./node_modules/lodash/isObject.js ***!
\*****************************************/ /*! no static exports found */ /***/function(module,exports){function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/function isObject(value){var type=_typeof(value);return value!=null&&(type=='object'||type=='function');}module.exports=isObject;/***/},/***/"./node_modules/lodash/isObjectLike.js":/*!*********************************************!*\
!*** ./node_modules/lodash/isObjectLike.js ***!
\*********************************************/ /*! no static exports found */ /***/function(module,exports){function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/function isObjectLike(value){return value!=null&&_typeof(value)=='object';}module.exports=isObjectLike;/***/},/***/"./node_modules/lodash/isPlainObject.js":/*!**********************************************!*\
!*** ./node_modules/lodash/isPlainObject.js ***!
\**********************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseGetTag=__webpack_require__(/*! ./_baseGetTag */"./node_modules/lodash/_baseGetTag.js"),getPrototype=__webpack_require__(/*! ./_getPrototype */"./node_modules/lodash/_getPrototype.js"),isObjectLike=__webpack_require__(/*! ./isObjectLike */"./node_modules/lodash/isObjectLike.js");/** `Object#toString` result references. */var objectTag='[object Object]';/** Used for built-in method references. */var funcProto=Function.prototype,objectProto=Object.prototype;/** Used to resolve the decompiled source of functions. */var funcToString=funcProto.toString;/** Used to check objects for own properties. */var hasOwnProperty=objectProto.hasOwnProperty;/** Used to infer the `Object` constructor. */var objectCtorString=funcToString.call(Object);/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/function isPlainObject(value){if(!isObjectLike(value)||baseGetTag(value)!=objectTag){return false;}var proto=getPrototype(value);if(proto===null){return true;}var Ctor=hasOwnProperty.call(proto,'constructor')&&proto.constructor;return typeof Ctor=='function'&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString;}module.exports=isPlainObject;/***/},/***/"./node_modules/lodash/isSet.js":/*!**************************************!*\
!*** ./node_modules/lodash/isSet.js ***!
\**************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseIsSet=__webpack_require__(/*! ./_baseIsSet */"./node_modules/lodash/_baseIsSet.js"),baseUnary=__webpack_require__(/*! ./_baseUnary */"./node_modules/lodash/_baseUnary.js"),nodeUtil=__webpack_require__(/*! ./_nodeUtil */"./node_modules/lodash/_nodeUtil.js");/* Node.js helper references. */var nodeIsSet=nodeUtil&&nodeUtil.isSet;/**
* Checks if `value` is classified as a `Set` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
* @example
*
* _.isSet(new Set);
* // => true
*
* _.isSet(new WeakSet);
* // => false
*/var isSet=nodeIsSet?baseUnary(nodeIsSet):baseIsSet;module.exports=isSet;/***/},/***/"./node_modules/lodash/isSymbol.js":/*!*****************************************!*\
!*** ./node_modules/lodash/isSymbol.js ***!
\*****************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}var baseGetTag=__webpack_require__(/*! ./_baseGetTag */"./node_modules/lodash/_baseGetTag.js"),isObjectLike=__webpack_require__(/*! ./isObjectLike */"./node_modules/lodash/isObjectLike.js");/** `Object#toString` result references. */var symbolTag='[object Symbol]';/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/function isSymbol(value){return _typeof(value)=='symbol'||isObjectLike(value)&&baseGetTag(value)==symbolTag;}module.exports=isSymbol;/***/},/***/"./node_modules/lodash/isTypedArray.js":/*!*********************************************!*\
!*** ./node_modules/lodash/isTypedArray.js ***!
\*********************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseIsTypedArray=__webpack_require__(/*! ./_baseIsTypedArray */"./node_modules/lodash/_baseIsTypedArray.js"),baseUnary=__webpack_require__(/*! ./_baseUnary */"./node_modules/lodash/_baseUnary.js"),nodeUtil=__webpack_require__(/*! ./_nodeUtil */"./node_modules/lodash/_nodeUtil.js");/* Node.js helper references. */var nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray;/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/var isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;module.exports=isTypedArray;/***/},/***/"./node_modules/lodash/keys.js":/*!*************************************!*\
!*** ./node_modules/lodash/keys.js ***!
\*************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var arrayLikeKeys=__webpack_require__(/*! ./_arrayLikeKeys */"./node_modules/lodash/_arrayLikeKeys.js"),baseKeys=__webpack_require__(/*! ./_baseKeys */"./node_modules/lodash/_baseKeys.js"),isArrayLike=__webpack_require__(/*! ./isArrayLike */"./node_modules/lodash/isArrayLike.js");/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object);}module.exports=keys;/***/},/***/"./node_modules/lodash/keysIn.js":/*!***************************************!*\
!*** ./node_modules/lodash/keysIn.js ***!
\***************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var arrayLikeKeys=__webpack_require__(/*! ./_arrayLikeKeys */"./node_modules/lodash/_arrayLikeKeys.js"),baseKeysIn=__webpack_require__(/*! ./_baseKeysIn */"./node_modules/lodash/_baseKeysIn.js"),isArrayLike=__webpack_require__(/*! ./isArrayLike */"./node_modules/lodash/isArrayLike.js");/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/function keysIn(object){return isArrayLike(object)?arrayLikeKeys(object,true):baseKeysIn(object);}module.exports=keysIn;/***/},/***/"./node_modules/lodash/last.js":/*!*************************************!*\
!*** ./node_modules/lodash/last.js ***!
\*************************************/ /*! no static exports found */ /***/function(module,exports){/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/function last(array){var length=array==null?0:array.length;return length?array[length-1]:undefined;}module.exports=last;/***/},/***/"./node_modules/lodash/map.js":/*!************************************!*\
!*** ./node_modules/lodash/map.js ***!
\************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var arrayMap=__webpack_require__(/*! ./_arrayMap */"./node_modules/lodash/_arrayMap.js"),baseIteratee=__webpack_require__(/*! ./_baseIteratee */"./node_modules/lodash/_baseIteratee.js"),baseMap=__webpack_require__(/*! ./_baseMap */"./node_modules/lodash/_baseMap.js"),isArray=__webpack_require__(/*! ./isArray */"./node_modules/lodash/isArray.js");/**
* Creates an array of values by running each element in `collection` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
* `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
* `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
* `template`, `trim`, `trimEnd`, `trimStart`, and `words`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
* function square(n) {
* return n * n;
* }
*
* _.map([4, 8], square);
* // => [16, 64]
*
* _.map({ 'a': 4, 'b': 8 }, square);
* // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
*/function map(collection,iteratee){var func=isArray(collection)?arrayMap:baseMap;return func(collection,baseIteratee(iteratee,3));}module.exports=map;/***/},/***/"./node_modules/lodash/memoize.js":/*!****************************************!*\
!*** ./node_modules/lodash/memoize.js ***!
\****************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var MapCache=__webpack_require__(/*! ./_MapCache */"./node_modules/lodash/_MapCache.js");/** Error message constants. */var FUNC_ERROR_TEXT='Expected a function';/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/function memoize(func,resolver){if(typeof func!='function'||resolver!=null&&typeof resolver!='function'){throw new TypeError(FUNC_ERROR_TEXT);}var memoized=function memoized(){var args=arguments,key=resolver?resolver.apply(this,args):args[0],cache=memoized.cache;if(cache.has(key)){return cache.get(key);}var result=func.apply(this,args);memoized.cache=cache.set(key,result)||cache;return result;};memoized.cache=new(memoize.Cache||MapCache)();return memoized;}// Expose `MapCache`.
memoize.Cache=MapCache;module.exports=memoize;/***/},/***/"./node_modules/lodash/merge.js":/*!**************************************!*\
!*** ./node_modules/lodash/merge.js ***!
\**************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseMerge=__webpack_require__(/*! ./_baseMerge */"./node_modules/lodash/_baseMerge.js"),createAssigner=__webpack_require__(/*! ./_createAssigner */"./node_modules/lodash/_createAssigner.js");/**
* This method is like `_.assign` except that it recursively merges own and
* inherited enumerable string keyed properties of source objects into the
* destination object. Source properties that resolve to `undefined` are
* skipped if a destination value exists. Array and plain object properties
* are merged recursively. Other objects and value types are overridden by
* assignment. Source objects are applied from left to right. Subsequent
* sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var object = {
* 'a': [{ 'b': 2 }, { 'd': 4 }]
* };
*
* var other = {
* 'a': [{ 'c': 3 }, { 'e': 5 }]
* };
*
* _.merge(object, other);
* // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
*/var merge=createAssigner(function(object,source,srcIndex){baseMerge(object,source,srcIndex);});module.exports=merge;/***/},/***/"./node_modules/lodash/mergeWith.js":/*!******************************************!*\
!*** ./node_modules/lodash/mergeWith.js ***!
\******************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseMerge=__webpack_require__(/*! ./_baseMerge */"./node_modules/lodash/_baseMerge.js"),createAssigner=__webpack_require__(/*! ./_createAssigner */"./node_modules/lodash/_createAssigner.js");/**
* This method is like `_.merge` except that it accepts `customizer` which
* is invoked to produce the merged values of the destination and source
* properties. If `customizer` returns `undefined`, merging is handled by the
* method instead. The `customizer` is invoked with six arguments:
* (objValue, srcValue, key, object, source, stack).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} customizer The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* function customizer(objValue, srcValue) {
* if (_.isArray(objValue)) {
* return objValue.concat(srcValue);
* }
* }
*
* var object = { 'a': [1], 'b': [2] };
* var other = { 'a': [3], 'b': [4] };
*
* _.mergeWith(object, other, customizer);
* // => { 'a': [1, 3], 'b': [2, 4] }
*/var mergeWith=createAssigner(function(object,source,srcIndex,customizer){baseMerge(object,source,srcIndex,customizer);});module.exports=mergeWith;/***/},/***/"./node_modules/lodash/noop.js":/*!*************************************!*\
!*** ./node_modules/lodash/noop.js ***!
\*************************************/ /*! no static exports found */ /***/function(module,exports){/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/function noop(){// No operation performed.
}module.exports=noop;/***/},/***/"./node_modules/lodash/omit.js":/*!*************************************!*\
!*** ./node_modules/lodash/omit.js ***!
\*************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var arrayMap=__webpack_require__(/*! ./_arrayMap */"./node_modules/lodash/_arrayMap.js"),baseClone=__webpack_require__(/*! ./_baseClone */"./node_modules/lodash/_baseClone.js"),baseUnset=__webpack_require__(/*! ./_baseUnset */"./node_modules/lodash/_baseUnset.js"),castPath=__webpack_require__(/*! ./_castPath */"./node_modules/lodash/_castPath.js"),copyObject=__webpack_require__(/*! ./_copyObject */"./node_modules/lodash/_copyObject.js"),customOmitClone=__webpack_require__(/*! ./_customOmitClone */"./node_modules/lodash/_customOmitClone.js"),flatRest=__webpack_require__(/*! ./_flatRest */"./node_modules/lodash/_flatRest.js"),getAllKeysIn=__webpack_require__(/*! ./_getAllKeysIn */"./node_modules/lodash/_getAllKeysIn.js");/** Used to compose bitmasks for cloning. */var CLONE_DEEP_FLAG=1,CLONE_FLAT_FLAG=2,CLONE_SYMBOLS_FLAG=4;/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable property paths of `object` that are not omitted.
*
* **Note:** This method is considerably slower than `_.pick`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
*/var omit=flatRest(function(object,paths){var result={};if(object==null){return result;}var isDeep=false;paths=arrayMap(paths,function(path){path=castPath(path,object);isDeep||(isDeep=path.length>1);return path;});copyObject(object,getAllKeysIn(object),result);if(isDeep){result=baseClone(result,CLONE_DEEP_FLAG|CLONE_FLAT_FLAG|CLONE_SYMBOLS_FLAG,customOmitClone);}var length=paths.length;while(length--){baseUnset(result,paths[length]);}return result;});module.exports=omit;/***/},/***/"./node_modules/lodash/property.js":/*!*****************************************!*\
!*** ./node_modules/lodash/property.js ***!
\*****************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseProperty=__webpack_require__(/*! ./_baseProperty */"./node_modules/lodash/_baseProperty.js"),basePropertyDeep=__webpack_require__(/*! ./_basePropertyDeep */"./node_modules/lodash/_basePropertyDeep.js"),isKey=__webpack_require__(/*! ./_isKey */"./node_modules/lodash/_isKey.js"),toKey=__webpack_require__(/*! ./_toKey */"./node_modules/lodash/_toKey.js");/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/function property(path){return isKey(path)?baseProperty(toKey(path)):basePropertyDeep(path);}module.exports=property;/***/},/***/"./node_modules/lodash/pull.js":/*!*************************************!*\
!*** ./node_modules/lodash/pull.js ***!
\*************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseRest=__webpack_require__(/*! ./_baseRest */"./node_modules/lodash/_baseRest.js"),pullAll=__webpack_require__(/*! ./pullAll */"./node_modules/lodash/pullAll.js");/**
* Removes all given values from `array` using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
* to remove elements from an array by predicate.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {...*} [values] The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = ['a', 'b', 'c', 'a', 'b', 'c'];
*
* _.pull(array, 'a', 'c');
* console.log(array);
* // => ['b', 'b']
*/var pull=baseRest(pullAll);module.exports=pull;/***/},/***/"./node_modules/lodash/pullAll.js":/*!****************************************!*\
!*** ./node_modules/lodash/pullAll.js ***!
\****************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var basePullAll=__webpack_require__(/*! ./_basePullAll */"./node_modules/lodash/_basePullAll.js");/**
* This method is like `_.pull` except that it accepts an array of values to remove.
*
* **Note:** Unlike `_.difference`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = ['a', 'b', 'c', 'a', 'b', 'c'];
*
* _.pullAll(array, ['a', 'c']);
* console.log(array);
* // => ['b', 'b']
*/function pullAll(array,values){return array&&array.length&&values&&values.length?basePullAll(array,values):array;}module.exports=pullAll;/***/},/***/"./node_modules/lodash/remove.js":/*!***************************************!*\
!*** ./node_modules/lodash/remove.js ***!
\***************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseIteratee=__webpack_require__(/*! ./_baseIteratee */"./node_modules/lodash/_baseIteratee.js"),basePullAt=__webpack_require__(/*! ./_basePullAt */"./node_modules/lodash/_basePullAt.js");/**
* Removes all elements from `array` that `predicate` returns truthy for
* and returns an array of the removed elements. The predicate is invoked
* with three arguments: (value, index, array).
*
* **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
* to pull elements from an array by value.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = [1, 2, 3, 4];
* var evens = _.remove(array, function(n) {
* return n % 2 == 0;
* });
*
* console.log(array);
* // => [1, 3]
*
* console.log(evens);
* // => [2, 4]
*/function remove(array,predicate){var result=[];if(!(array&&array.length)){return result;}var index=-1,indexes=[],length=array.length;predicate=baseIteratee(predicate,3);while(++index 0
*
* // The `_.property` iteratee shorthand.
* _.sortedIndexBy(objects, { 'x': 4 }, 'x');
* // => 0
*/function sortedIndexBy(array,value,iteratee){return baseSortedIndexBy(array,value,baseIteratee(iteratee,2));}module.exports=sortedIndexBy;/***/},/***/"./node_modules/lodash/stubArray.js":/*!******************************************!*\
!*** ./node_modules/lodash/stubArray.js ***!
\******************************************/ /*! no static exports found */ /***/function(module,exports){/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/function stubArray(){return[];}module.exports=stubArray;/***/},/***/"./node_modules/lodash/stubFalse.js":/*!******************************************!*\
!*** ./node_modules/lodash/stubFalse.js ***!
\******************************************/ /*! no static exports found */ /***/function(module,exports){/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/function stubFalse(){return false;}module.exports=stubFalse;/***/},/***/"./node_modules/lodash/toFinite.js":/*!*****************************************!*\
!*** ./node_modules/lodash/toFinite.js ***!
\*****************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var toNumber=__webpack_require__(/*! ./toNumber */"./node_modules/lodash/toNumber.js");/** Used as references for various `Number` constants. */var INFINITY=1/0,MAX_INTEGER=1.7976931348623157e+308;/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/function toFinite(value){if(!value){return value===0?value:0;}value=toNumber(value);if(value===INFINITY||value===-INFINITY){var sign=value<0?-1:1;return sign*MAX_INTEGER;}return value===value?value:0;}module.exports=toFinite;/***/},/***/"./node_modules/lodash/toInteger.js":/*!******************************************!*\
!*** ./node_modules/lodash/toInteger.js ***!
\******************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var toFinite=__webpack_require__(/*! ./toFinite */"./node_modules/lodash/toFinite.js");/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/function toInteger(value){var result=toFinite(value),remainder=result%1;return result===result?remainder?result-remainder:result:0;}module.exports=toInteger;/***/},/***/"./node_modules/lodash/toNumber.js":/*!*****************************************!*\
!*** ./node_modules/lodash/toNumber.js ***!
\*****************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var isObject=__webpack_require__(/*! ./isObject */"./node_modules/lodash/isObject.js"),isSymbol=__webpack_require__(/*! ./isSymbol */"./node_modules/lodash/isSymbol.js");/** Used as references for various `Number` constants. */var NAN=0/0;/** Used to match leading and trailing whitespace. */var reTrim=/^\s+|\s+$/g;/** Used to detect bad signed hexadecimal string values. */var reIsBadHex=/^[-+]0x[0-9a-f]+$/i;/** Used to detect binary string values. */var reIsBinary=/^0b[01]+$/i;/** Used to detect octal string values. */var reIsOctal=/^0o[0-7]+$/i;/** Built-in method references without a dependency on `root`. */var freeParseInt=parseInt;/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/function toNumber(value){if(typeof value=='number'){return value;}if(isSymbol(value)){return NAN;}if(isObject(value)){var other=typeof value.valueOf=='function'?value.valueOf():value;value=isObject(other)?other+'':other;}if(typeof value!='string'){return value===0?value:+value;}value=value.replace(reTrim,'');var isBinary=reIsBinary.test(value);return isBinary||reIsOctal.test(value)?freeParseInt(value.slice(2),isBinary?2:8):reIsBadHex.test(value)?NAN:+value;}module.exports=toNumber;/***/},/***/"./node_modules/lodash/toPlainObject.js":/*!**********************************************!*\
!*** ./node_modules/lodash/toPlainObject.js ***!
\**********************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var copyObject=__webpack_require__(/*! ./_copyObject */"./node_modules/lodash/_copyObject.js"),keysIn=__webpack_require__(/*! ./keysIn */"./node_modules/lodash/keysIn.js");/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/function toPlainObject(value){return copyObject(value,keysIn(value));}module.exports=toPlainObject;/***/},/***/"./node_modules/lodash/toString.js":/*!*****************************************!*\
!*** ./node_modules/lodash/toString.js ***!
\*****************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseToString=__webpack_require__(/*! ./_baseToString */"./node_modules/lodash/_baseToString.js");/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/function toString(value){return value==null?'':baseToString(value);}module.exports=toString;/***/},/***/"./node_modules/lodash/uniq.js":/*!*************************************!*\
!*** ./node_modules/lodash/uniq.js ***!
\*************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseUniq=__webpack_require__(/*! ./_baseUniq */"./node_modules/lodash/_baseUniq.js");/**
* Creates a duplicate-free version of an array, using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons, in which only the first occurrence of each element
* is kept. The order of result values is determined by the order they occur
* in the array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniq([2, 1, 2]);
* // => [2, 1]
*/function uniq(array){return array&&array.length?baseUniq(array):[];}module.exports=uniq;/***/},/***/"./node_modules/lodash/uniqWith.js":/*!*****************************************!*\
!*** ./node_modules/lodash/uniqWith.js ***!
\*****************************************/ /*! no static exports found */ /***/function(module,exports,__webpack_require__){var baseUniq=__webpack_require__(/*! ./_baseUniq */"./node_modules/lodash/_baseUniq.js");/**
* This method is like `_.uniq` except that it accepts `comparator` which
* is invoked to compare elements of `array`. The order of result values is
* determined by the order they occur in the array.The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.uniqWith(objects, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
*/function uniqWith(array,comparator){comparator=typeof comparator=='function'?comparator:undefined;return array&&array.length?baseUniq(array,undefined,comparator):[];}module.exports=uniqWith;/***/},/***/"./node_modules/webpack/buildin/global.js":/*!***********************************!*\
!*** (webpack)/buildin/global.js ***!
\***********************************/ /*! no static exports found */ /***/function(module,exports){function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj;};}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};}return _typeof(obj);}var g;// This works in non-strict mode
g=function(){return this;}();try{// This works if eval is allowed (see CSP)
g=g||new Function("return this")();}catch(e){// This works if the window reference is available
if((typeof window==="undefined"?"undefined":_typeof(window))==="object")g=window;}// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports=g;/***/},/***/"./node_modules/webpack/buildin/module.js":/*!***********************************!*\
!*** (webpack)/buildin/module.js ***!
\***********************************/ /*! no static exports found */ /***/function(module,exports){module.exports=function(module){if(!module.webpackPolyfill){module.deprecate=function(){};module.paths=[];// module.parent = undefined by default
if(!module.children)module.children=[];Object.defineProperty(module,"loaded",{enumerable:true,get:function get(){return module.l;}});Object.defineProperty(module,"id",{enumerable:true,get:function get(){return module.i;}});module.webpackPolyfill=1;}return module;};/***/}/******/}));});
/***/ }),
/***/ "./app/assets/javascripts/app.js":
/*!***************************************!*\
!*** ./app/assets/javascripts/app.js ***!
\***************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _routes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./routes */ "./app/assets/javascripts/routes.js");
/* harmony import */ var _application__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./application */ "./app/assets/javascripts/application.js");
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./state */ "./app/assets/javascripts/state.js");
/* harmony import */ var _controllers__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controllers */ "./app/assets/javascripts/controllers/index.js");
/* harmony import */ var _directives_functional__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./directives/functional */ "./app/assets/javascripts/directives/functional/index.js");
/* harmony import */ var _directives_views__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./directives/views */ "./app/assets/javascripts/directives/views/index.js");
/* harmony import */ var _filters__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./filters */ "./app/assets/javascripts/filters/index.js");
/* harmony import */ var _services__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./services */ "./app/assets/javascripts/services/index.js");
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('app', ['ngSanitize']); // Config
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('app').config(_routes__WEBPACK_IMPORTED_MODULE_1__["configRoutes"]).constant('appVersion', "3.5.0"); // Controllers
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('app').directive('root', function () {
return new _controllers__WEBPACK_IMPORTED_MODULE_4__["Root"]();
}).directive('tagsPanel', function () {
return new _controllers__WEBPACK_IMPORTED_MODULE_4__["TagsPanel"]();
}).directive('notesPanel', function () {
return new _controllers__WEBPACK_IMPORTED_MODULE_4__["NotesPanel"]();
}).directive('editorPanel', function () {
return new _controllers__WEBPACK_IMPORTED_MODULE_4__["EditorPanel"]();
}).directive('footer', function () {
return new _controllers__WEBPACK_IMPORTED_MODULE_4__["Footer"]();
}).directive('lockScreen', function () {
return new _controllers__WEBPACK_IMPORTED_MODULE_4__["LockScreen"]();
}); // Directives - Functional
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('app').directive('snAutofocus', ['$timeout', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["autofocus"]]).directive('clickOutside', ['$document', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["clickOutside"]]).directive('delayHide', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["delayHide"]).directive('elemReady', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["elemReady"]).directive('fileChange', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["fileChange"]).directive('infiniteScroll', ['$rootScope', '$window', '$timeout', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["infiniteScroll"]]).directive('lowercase', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["lowercase"]).directive('selectOnClick', ['$window', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["selectOnClick"]]).directive('snEnter', _directives_functional__WEBPACK_IMPORTED_MODULE_5__["snEnter"]); // Directives - Views
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('app').directive('accountMenu', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["AccountMenu"]();
}).directive('actionsMenu', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["ActionsMenu"]();
}).directive('componentModal', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["ComponentModal"]();
}).directive('componentView', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["ComponentView"]();
}) // .directive(
// 'componentView',
// ($rootScope, componentManager, desktopManager, $timeout) =>
// new ComponentView($rootScope, componentManager, desktopManager, $timeout)
// )
.directive('conflictResolutionModal', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["ConflictResolutionModal"]();
}).directive('editorMenu', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["EditorMenu"]();
}).directive('inputModal', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["InputModal"]();
}).directive('menuRow', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["MenuRow"]();
}).directive('panelResizer', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["PanelResizer"]();
}).directive('passwordWizard', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["PasswordWizard"]();
}).directive('permissionsModal', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["PermissionsModal"]();
}).directive('privilegesAuthModal', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["PrivilegesAuthModal"]();
}).directive('privilegesManagementModal', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["PrivilegesManagementModal"]();
}).directive('revisionPreviewModal', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["RevisionPreviewModal"]();
}).directive('sessionHistoryMenu', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["SessionHistoryMenu"]();
}).directive('syncResolutionMenu', function () {
return new _directives_views__WEBPACK_IMPORTED_MODULE_6__["SyncResolutionMenu"]();
}); // Filters
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('app').filter('trusted', ['$sce', _filters__WEBPACK_IMPORTED_MODULE_7__["trusted"]]); // Services
angular__WEBPACK_IMPORTED_MODULE_0___default.a.module('app').service('appState', _state__WEBPACK_IMPORTED_MODULE_3__["AppState"]).service('application', _application__WEBPACK_IMPORTED_MODULE_2__["Application"]).service('archiveManager', _services__WEBPACK_IMPORTED_MODULE_8__["ArchiveManager"]).service('desktopManager', _services__WEBPACK_IMPORTED_MODULE_8__["DesktopManager"]).service('godService', _services__WEBPACK_IMPORTED_MODULE_8__["GodService"]).service('keyboardManager', _services__WEBPACK_IMPORTED_MODULE_8__["KeyboardManager"]).service('lockManager', _services__WEBPACK_IMPORTED_MODULE_8__["LockManager"]).service('nativeExtManager', _services__WEBPACK_IMPORTED_MODULE_8__["NativeExtManager"]).service('preferencesManager', _services__WEBPACK_IMPORTED_MODULE_8__["PreferencesManager"]).service('statusManager', _services__WEBPACK_IMPORTED_MODULE_8__["StatusManager"]).service('storageManager', StorageManager).service('themeManager', _services__WEBPACK_IMPORTED_MODULE_8__["ThemeManager"]);
/***/ }),
/***/ "./app/assets/javascripts/application.js":
/*!***********************************************!*\
!*** ./app/assets/javascripts/application.js ***!
\***********************************************/
/*! exports provided: Application */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Application", function() { return Application; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js");
/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var _services_alertManager__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/services/alertManager */ "./app/assets/javascripts/services/alertManager.js");
/* harmony import */ var _web_device_interface__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/web_device_interface */ "./app/assets/javascripts/web_device_interface.js");
var Application =
/*#__PURE__*/
function (_SNApplication) {
Application.$inject = ["$compile", "$timeout", "$rootScope"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_5___default()(Application, _SNApplication);
/* @ngInject */
function Application($compile, $timeout, $rootScope) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Application);
var deviceInterface = new _web_device_interface__WEBPACK_IMPORTED_MODULE_10__["WebDeviceInterface"]({
timeout: $timeout
});
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(Application).call(this, {
environment: snjs__WEBPACK_IMPORTED_MODULE_6__["Environments"].Web,
platform: Object(snjs__WEBPACK_IMPORTED_MODULE_6__["platformFromString"])(Object(_utils__WEBPACK_IMPORTED_MODULE_8__["getPlatformString"])()),
namespace: '',
host: window._default_sync_server,
deviceInterface: deviceInterface,
swapClasses: [{
swap: snjs__WEBPACK_IMPORTED_MODULE_6__["SNAlertManager"],
with: _services_alertManager__WEBPACK_IMPORTED_MODULE_9__["AlertManager"]
}]
}));
_this.$compile = $compile;
_this.$rootScope = $rootScope;
deviceInterface.setApplication(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_4___default()(_this));
_this.overrideComponentManagerFunctions();
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Application, [{
key: "overrideComponentManagerFunctions",
value: function overrideComponentManagerFunctions() {
function openModalComponent(component) {
var scope = this.$rootScope.$new(true);
scope.component = component;
var el = this.$compile("")(scope);
angular__WEBPACK_IMPORTED_MODULE_7___default.a.element(document.body).append(el);
}
function presentPermissionsDialog(dialog) {
var scope = this.$rootScope.$new(true);
scope.permissionsString = dialog.permissionsString;
scope.component = dialog.component;
scope.callback = dialog.callback;
var el = this.$compile("")(scope);
angular__WEBPACK_IMPORTED_MODULE_7___default.a.element(document.body).append(el);
}
this.componentManager.openModalComponent = openModalComponent.bind(this);
this.componentManager.presentPermissionsDialog = presentPermissionsDialog.bind(this);
}
}]);
return Application;
}(snjs__WEBPACK_IMPORTED_MODULE_6__["SNApplication"]);
/***/ }),
/***/ "./app/assets/javascripts/controllers/abstract/pure_ctrl.js":
/*!******************************************************************!*\
!*** ./app/assets/javascripts/controllers/abstract/pure_ctrl.js ***!
\******************************************************************/
/*! exports provided: PureCtrl */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PureCtrl", function() { return PureCtrl; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
var PureCtrl =
/*#__PURE__*/
function () {
function PureCtrl($scope, $timeout, application, appState) {
var _this = this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, PureCtrl);
if (!$scope || !$timeout || !application || !appState) {
throw 'Invalid PureCtrl construction.';
}
this.$scope = $scope;
this.$timeout = $timeout;
this.appState = appState;
this.application = application;
this.state = {};
this.props = {};
this.addAppStateObserver();
this.addAppEventObserver();
$scope.$on('$destroy', function () {
_this.unsubApp();
_this.unsubState();
});
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(PureCtrl, [{
key: "setState",
value: function () {
var _setState = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(state) {
var _this2 = this;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", new Promise(function (resolve) {
_this2.$timeout(function () {
_this2.state = Object.freeze(Object.assign({}, _this2.state, state));
resolve();
});
}));
case 1:
case "end":
return _context.stop();
}
}
}, _callee);
}));
function setState(_x) {
return _setState.apply(this, arguments);
}
return setState;
}()
}, {
key: "initProps",
value: function initProps(props) {
if (Object.keys(this.props).length > 0) {
throw 'Already init-ed props.';
}
this.props = Object.freeze(Object.assign({}, this.props, props));
}
}, {
key: "addAppStateObserver",
value: function addAppStateObserver() {
var _this3 = this;
this.unsubState = this.appState.addObserver(function (eventName, data) {
_this3.onAppStateEvent(eventName, data);
});
}
}, {
key: "addAppEventObserver",
value: function addAppEventObserver() {
var _this4 = this;
this.unsubApp = this.application.addEventObserver(function (eventName) {
_this4.onApplicationEvent(eventName);
});
}
}, {
key: "onApplicationEvent",
value: function onApplicationEvent(eventName) {
/** Optional override */
}
}, {
key: "onAppStateEvent",
value: function onAppStateEvent(eventName, data) {
/** Optional override */
}
}]);
return PureCtrl;
}();
/***/ }),
/***/ "./app/assets/javascripts/controllers/constants.js":
/*!*********************************************************!*\
!*** ./app/assets/javascripts/controllers/constants.js ***!
\*********************************************************/
/*! exports provided: PANEL_NAME_NOTES, PANEL_NAME_TAGS */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PANEL_NAME_NOTES", function() { return PANEL_NAME_NOTES; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PANEL_NAME_TAGS", function() { return PANEL_NAME_TAGS; });
var PANEL_NAME_NOTES = 'notes';
var PANEL_NAME_TAGS = 'tags';
/***/ }),
/***/ "./app/assets/javascripts/controllers/editor.js":
/*!******************************************************!*\
!*** ./app/assets/javascripts/controllers/editor.js ***!
\******************************************************/
/*! exports provided: EditorPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EditorPanel", function() { return EditorPanel; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js");
/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var lodash_find__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! lodash/find */ "./node_modules/lodash/find.js");
/* harmony import */ var lodash_find__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(lodash_find__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var _services_keyboardManager__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/services/keyboardManager */ "./app/assets/javascripts/services/keyboardManager.js");
/* harmony import */ var _editor_pug__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! %/editor.pug */ "./app/assets/templates/editor.pug");
/* harmony import */ var _editor_pug__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(_editor_pug__WEBPACK_IMPORTED_MODULE_14__);
/* harmony import */ var _Controllers__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @Controllers */ "./app/assets/javascripts/controllers/index.js");
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! @/state */ "./app/assets/javascripts/state.js");
/* harmony import */ var _strings__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! @/strings */ "./app/assets/javascripts/strings.js");
/* harmony import */ var _services_preferencesManager__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! @/services/preferencesManager */ "./app/assets/javascripts/services/preferencesManager.js");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var NOTE_PREVIEW_CHAR_LIMIT = 80;
var MINIMUM_STATUS_DURATION = 400;
var SAVE_TIMEOUT_DEBOUNCE = 350;
var SAVE_TIMEOUT_NO_DEBOUNCE = 100;
var EDITOR_DEBOUNCE = 200;
var AppDataKeys = {
Pinned: 'pinned',
Locked: 'locked',
Archived: 'archived',
PrefersPlainEditor: 'prefersPlainEditor'
};
var ElementIds = {
NoteTextEditor: 'note-text-editor',
NoteTitleEditor: 'note-title-editor',
EditorContent: 'editor-content',
NoteTagsComponentContainer: 'note-tags-component-container'
};
var Fonts = {
DesktopMonospaceFamily: "Menlo,Consolas,'DejaVu Sans Mono',monospace",
WebMonospaceFamily: "monospace",
SansSerifFamily: "inherit"
};
var EditorCtrl =
/*#__PURE__*/
function (_PureCtrl) {
EditorCtrl.$inject = ["$scope", "$timeout", "$rootScope", "application", "appState", "desktopManager", "keyboardManager", "preferencesManager"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default()(EditorCtrl, _PureCtrl);
/* @ngInject */
function EditorCtrl($scope, $timeout, $rootScope, application, appState, desktopManager, keyboardManager, preferencesManager) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, EditorCtrl);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(EditorCtrl).call(this, $scope, $timeout, application, appState));
_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default()(_this), "editorMenuOnSelect", function (component) {
if (!component || component.area === 'editor-editor') {
/** If plain editor or other editor */
_this.setMenuState('showEditorMenu', false);
var editor = component;
if (_this.state.selectedEditor && editor !== _this.state.selectedEditor) {
_this.disassociateComponentWithCurrentNote(_this.state.selectedEditor);
}
if (editor) {
var prefersPlain = _this.state.note.getAppDataItem(AppDataKeys.PrefersPlainEditor) === true;
if (prefersPlain) {
_this.state.note.setAppDataItem(AppDataKeys.PrefersPlainEditor, false);
_this.application.setItemNeedsSync({
item: _this.state.note
});
}
_this.associateComponentWithCurrentNote(editor);
} else {
/** Note prefers plain editor */
if (!_this.state.note.getAppDataItem(AppDataKeys.PrefersPlainEditor)) {
_this.state.note.setAppDataItem(AppDataKeys.PrefersPlainEditor, true);
_this.application.setItemNeedsSync({
item: _this.state.note
});
}
_this.reloadFont();
}
_this.setState({
selectedEditor: editor
});
} else if (component.area === 'editor-stack') {
_this.toggleStackComponentForCurrentItem(component);
}
/** Dirtying can happen above */
_this.application.sync();
});
_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default()(_this), "onPanelResizeFinish", function (width, left, isMaxWidth) {
if (isMaxWidth) {
_this.preferencesManager.setUserPrefValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_18__["PrefKeys"].EditorWidth, null);
} else {
if (width !== undefined && width !== null) {
_this.preferencesManager.setUserPrefValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_18__["PrefKeys"].EditorWidth, width);
_this.leftResizeControl.setWidth(width);
}
}
if (left !== undefined && left !== null) {
_this.preferencesManager.setUserPrefValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_18__["PrefKeys"].EditorLeft, left);
_this.rightResizeControl.setLeft(left);
}
_this.preferencesManager.syncUserPreferences();
});
_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default()(_this), "onEditorLoad", function (editor) {
_this.desktopManager.redoSearch();
});
_this.$rootScope = $rootScope;
_this.desktopManager = desktopManager;
_this.keyboardManager = keyboardManager;
_this.preferencesManager = preferencesManager;
_this.state = {
componentStack: [],
editorDebounce: EDITOR_DEBOUNCE,
isDesktop: Object(_utils__WEBPACK_IMPORTED_MODULE_12__["isDesktopApplication"])(),
spellcheck: true,
mutable: {
tagsString: ''
}
};
_this.leftResizeControl = {};
_this.rightResizeControl = {};
_this.addSyncStatusObserver();
_this.registerKeyboardShortcuts();
application.onUnlock(function () {
_this.streamItems();
_this.registerComponentHandler();
});
/** Used by .pug template */
_this.prefKeyMonospace = _services_preferencesManager__WEBPACK_IMPORTED_MODULE_18__["PrefKeys"].EditorMonospaceEnabled;
_this.prefKeySpellcheck = _services_preferencesManager__WEBPACK_IMPORTED_MODULE_18__["PrefKeys"].EditorSpellcheck;
_this.prefKeyMarginResizers = _services_preferencesManager__WEBPACK_IMPORTED_MODULE_18__["PrefKeys"].EditorResizersEnabled;
return _this;
}
/** @override */
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(EditorCtrl, [{
key: "onAppStateEvent",
value: function onAppStateEvent(eventName, data) {
if (eventName === _state__WEBPACK_IMPORTED_MODULE_16__["AppStateEvents"].NoteChanged) {
this.handleNoteSelectionChange(this.appState.getSelectedNote(), data.previousNote);
} else if (eventName === _state__WEBPACK_IMPORTED_MODULE_16__["AppStateEvents"].PreferencesChanged) {
this.loadPreferences();
}
}
/** @override */
}, {
key: "onApplicationEvent",
value: function onApplicationEvent(eventName) {
if (!this.state.note) {
return;
}
if (eventName === snjs__WEBPACK_IMPORTED_MODULE_10__["ApplicationEvents"].HighLatencySync) {
this.setState({
syncTakingTooLong: true
});
} else if (eventName === snjs__WEBPACK_IMPORTED_MODULE_10__["ApplicationEvents"].CompletedSync) {
this.setState({
syncTakingTooLong: false
});
if (this.state.note.dirty) {
/** if we're still dirty, don't change status, a sync is likely upcoming. */
} else {
var saved = this.state.note.updated_at > this.state.note.lastSyncBegan;
var isInErrorState = this.state.saveError;
if (isInErrorState || saved) {
this.showAllChangesSavedStatus();
}
}
} else if (eventName === snjs__WEBPACK_IMPORTED_MODULE_10__["ApplicationEvents"].FailedSync) {
/**
* Only show error status in editor if the note is dirty.
* Otherwise, it means the originating sync came from somewhere else
* and we don't want to display an error here.
*/
if (this.state.note.dirty) {
this.showErrorStatus();
}
}
}
}, {
key: "streamItems",
value: function streamItems() {
var _this2 = this;
this.application.streamItems({
contentType: snjs__WEBPACK_IMPORTED_MODULE_10__["ContentTypes"].Note,
stream: function () {
var _stream = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(_ref) {
var items, source, matchingNote;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
items = _ref.items, source = _ref.source;
if (_this2.state.note) {
_context.next = 3;
break;
}
return _context.abrupt("return");
case 3:
if (!(_this2.state.note.deleted || _this2.state.note.content.trashed)) {
_context.next = 5;
break;
}
return _context.abrupt("return");
case 5:
if (Object(snjs__WEBPACK_IMPORTED_MODULE_10__["isPayloadSourceRetrieved"])(source)) {
_context.next = 7;
break;
}
return _context.abrupt("return");
case 7:
matchingNote = items.find(function (item) {
return item.uuid === _this2.state.note.uuid;
});
if (matchingNote) {
_context.next = 10;
break;
}
return _context.abrupt("return");
case 10:
_this2.reloadTagsString();
case 11:
case "end":
return _context.stop();
}
}
}, _callee);
}));
function stream(_x) {
return _stream.apply(this, arguments);
}
return stream;
}()
});
this.application.streamItems({
contentType: snjs__WEBPACK_IMPORTED_MODULE_10__["ContentTypes"].Tag,
stream: function () {
var _stream2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(_ref2) {
var items, source, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, tag;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
items = _ref2.items, source = _ref2.source;
if (_this2.state.note) {
_context2.next = 3;
break;
}
return _context2.abrupt("return");
case 3:
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
_context2.prev = 6;
_iterator = items[Symbol.iterator]();
case 8:
if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
_context2.next = 16;
break;
}
tag = _step.value;
if (!(!_this2.state.note.savedTagsString || tag.deleted || tag.hasRelationshipWithItem(_this2.state.note))) {
_context2.next = 13;
break;
}
_this2.reloadTagsString();
return _context2.abrupt("break", 16);
case 13:
_iteratorNormalCompletion = true;
_context2.next = 8;
break;
case 16:
_context2.next = 22;
break;
case 18:
_context2.prev = 18;
_context2.t0 = _context2["catch"](6);
_didIteratorError = true;
_iteratorError = _context2.t0;
case 22:
_context2.prev = 22;
_context2.prev = 23;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 25:
_context2.prev = 25;
if (!_didIteratorError) {
_context2.next = 28;
break;
}
throw _iteratorError;
case 28:
return _context2.finish(25);
case 29:
return _context2.finish(22);
case 30:
case "end":
return _context2.stop();
}
}
}, _callee2, null, [[6, 18, 22, 30], [23,, 25, 29]]);
}));
function stream(_x2) {
return _stream2.apply(this, arguments);
}
return stream;
}()
});
this.application.streamItems({
contentType: snjs__WEBPACK_IMPORTED_MODULE_10__["ContentTypes"].Component,
stream: function () {
var _stream3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(_ref3) {
var items, source, editors, editor;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
items = _ref3.items, source = _ref3.source;
if (_this2.state.note) {
_context3.next = 3;
break;
}
return _context3.abrupt("return");
case 3:
/** Reload componentStack in case new ones were added or removed */
_this2.reloadComponentStackArray();
/** Observe editor changes to see if the current note should update its editor */
editors = items.filter(function (item) {
return item.isEditor();
});
if (!(editors.length === 0)) {
_context3.next = 7;
break;
}
return _context3.abrupt("return");
case 7:
/** Find the most recent editor for note */
editor = _this2.editorForNote(_this2.state.note);
_this2.setState({
selectedEditor: editor
});
if (!editor) {
_this2.reloadFont();
}
case 10:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
function stream(_x3) {
return _stream3.apply(this, arguments);
}
return stream;
}()
});
}
}, {
key: "handleNoteSelectionChange",
value: function () {
var _handleNoteSelectionChange = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(note, previousNote) {
var associatedEditor;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
this.setState({
note: this.appState.getSelectedNote(),
showExtensions: false,
showOptionsMenu: false,
altKeyDown: false,
noteStatus: null
});
if (note) {
_context4.next = 3;
break;
}
return _context4.abrupt("return");
case 3:
associatedEditor = this.editorForNote(note);
if (associatedEditor && associatedEditor !== this.state.selectedEditor) {
/**
* Setting note to not ready will remove the editor from view in a flash,
* so we only want to do this if switching between external editors
*/
this.setState({
noteReady: false,
selectedEditor: associatedEditor
});
} else if (!associatedEditor) {
/** No editor */
this.setState({
selectedEditor: null
});
}
_context4.next = 7;
return this.setState({
noteReady: true
});
case 7:
this.reloadTagsString();
this.loadPreferences();
if (note.dummy) {
this.focusEditor();
}
if (previousNote && previousNote !== note) {
if (previousNote.dummy) {
this.performNoteDeletion(previousNote);
}
}
this.reloadComponentContext();
case 12:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function handleNoteSelectionChange(_x4, _x5) {
return _handleNoteSelectionChange.apply(this, arguments);
}
return handleNoteSelectionChange;
}()
}, {
key: "addSyncStatusObserver",
value: function addSyncStatusObserver() {
/** @todo */
// this.syncStatusObserver = syncManager.
// registerSyncStatusObserver((status) => {
// if (status.localError) {
// this.$timeout(() => {
// this.showErrorStatus({
// message: "Offline Saving Issue",
// desc: "Changes not saved"
// });
// }, 500);
// }
// });
}
}, {
key: "editorForNote",
value: function editorForNote(note) {
return this.application.componentManager.editorForNote(note);
}
}, {
key: "setMenuState",
value: function setMenuState(menu, state) {
this.setState(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()({}, menu, state));
this.closeAllMenus({
exclude: menu
});
}
}, {
key: "toggleMenu",
value: function toggleMenu(menu) {
this.setMenuState(menu, !this.state[menu]);
}
}, {
key: "closeAllMenus",
value: function closeAllMenus() {
var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
exclude = _ref4.exclude;
var allMenus = ['showOptionsMenu', 'showEditorMenu', 'showExtensions', 'showSessionHistory'];
var menuState = {};
for (var _i = 0, _allMenus = allMenus; _i < _allMenus.length; _i++) {
var candidate = _allMenus[_i];
if (candidate !== exclude) {
menuState[candidate] = false;
}
}
this.setState(menuState);
}
}, {
key: "hasAvailableExtensions",
value: function hasAvailableExtensions() {
return this.application.actionsManager.extensionsInContextOfItem(this.state.note).length > 0;
}
}, {
key: "performFirefoxPinnedTabFix",
value: function performFirefoxPinnedTabFix() {
/**
* For Firefox pinned tab issue:
* When a new browser session is started, and SN is in a pinned tab,
* SN is unusable until the tab is reloaded.
*/
if (document.hidden) {
window.location.reload();
}
}
}, {
key: "saveNote",
value: function saveNote(_ref5) {
var _this3 = this;
var bypassDebouncer = _ref5.bypassDebouncer,
updateClientModified = _ref5.updateClientModified,
dontUpdatePreviews = _ref5.dontUpdatePreviews;
this.performFirefoxPinnedTabFix();
var note = this.state.note;
note.dummy = false;
if (note.deleted) {
this.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_17__["STRING_DELETED_NOTE"]
});
return;
}
if (!this.application.findItem({
uuid: note.uuid
})) {
this.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_17__["STRING_INVALID_NOTE"]
});
return;
}
this.showSavingStatus();
if (!dontUpdatePreviews) {
var text = note.text || '';
var truncate = text.length > NOTE_PREVIEW_CHAR_LIMIT;
var substring = text.substring(0, NOTE_PREVIEW_CHAR_LIMIT);
var previewPlain = substring + (truncate ? _strings__WEBPACK_IMPORTED_MODULE_17__["STRING_ELLIPSES"] : '');
note.content.preview_plain = previewPlain;
note.content.preview_html = null;
}
this.application.setItemNeedsSync({
item: note,
updateUserModifiedDate: updateClientModified
});
if (this.saveTimeout) {
this.$timeout.cancel(this.saveTimeout);
}
var noDebounce = bypassDebouncer || this.application.noAccount();
var syncDebouceMs = noDebounce ? SAVE_TIMEOUT_NO_DEBOUNCE : SAVE_TIMEOUT_DEBOUNCE;
this.saveTimeout = this.$timeout(function () {
_this3.application.sync();
}, syncDebouceMs);
}
}, {
key: "showSavingStatus",
value: function showSavingStatus() {
this.setStatus({
message: "Saving..."
}, false);
}
}, {
key: "showAllChangesSavedStatus",
value: function showAllChangesSavedStatus() {
this.setState({
saveError: false,
syncTakingTooLong: false
});
var status = "All changes saved";
if (this.application.noAccount()) {
status += " (offline)";
}
this.setStatus({
message: status
});
}
}, {
key: "showErrorStatus",
value: function showErrorStatus(error) {
if (!error) {
error = {
message: "Sync Unreachable",
desc: "Changes saved offline"
};
}
this.setState({
saveError: true,
syncTakingTooLong: false
});
this.setStatus(error);
}
}, {
key: "setStatus",
value: function setStatus(status) {
var _this4 = this;
var wait = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var waitForMs;
if (!this.state.noteStatus || !this.state.noteStatus.date) {
waitForMs = 0;
} else {
waitForMs = MINIMUM_STATUS_DURATION - (new Date() - this.state.noteStatus.date);
}
if (!wait || waitForMs < 0) {
waitForMs = 0;
}
if (this.statusTimeout) {
this.$timeout.cancel(this.statusTimeout);
}
this.statusTimeout = this.$timeout(function () {
status.date = new Date();
_this4.setState({
noteStatus: status
});
}, waitForMs);
}
}, {
key: "contentChanged",
value: function contentChanged() {
this.saveNote({
updateClientModified: true
});
}
}, {
key: "onTitleEnter",
value: function onTitleEnter($event) {
$event.target.blur();
this.onTitleChange();
this.focusEditor();
}
}, {
key: "onTitleChange",
value: function onTitleChange() {
this.saveNote({
dontUpdatePreviews: true,
updateClientModified: true
});
}
}, {
key: "focusEditor",
value: function focusEditor() {
var element = document.getElementById(ElementIds.NoteTextEditor);
if (element) {
this.lastEditorFocusEventSource = _state__WEBPACK_IMPORTED_MODULE_16__["EventSources"].Script;
element.focus();
}
}
}, {
key: "focusTitle",
value: function focusTitle() {
document.getElementById(ElementIds.NoteTitleEditor).focus();
}
}, {
key: "clickedTextArea",
value: function clickedTextArea() {
this.setMenuState('showOptionsMenu', false);
}
}, {
key: "onNameFocus",
value: function onNameFocus() {
this.editingName = true;
}
}, {
key: "onContentFocus",
value: function onContentFocus() {
this.appState.editorDidFocus(this.lastEditorFocusEventSource);
this.lastEditorFocusEventSource = null;
}
}, {
key: "onNameBlur",
value: function onNameBlur() {
this.editingName = false;
}
}, {
key: "selectedMenuItem",
value: function selectedMenuItem(hide) {
if (hide) {
this.setMenuState('showOptionsMenu', false);
}
}
}, {
key: "deleteNote",
value: function () {
var _deleteNote = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5(permanently) {
var _this5 = this;
var run, requiresPrivilege;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
if (!this.state.note.dummy) {
_context5.next = 3;
break;
}
this.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_17__["STRING_DELETE_PLACEHOLDER_ATTEMPT"]
});
return _context5.abrupt("return");
case 3:
run = function run() {
if (_this5.state.note.locked) {
_this5.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_17__["STRING_DELETE_LOCKED_ATTEMPT"]
});
return;
}
var title = _this5.state.note.safeTitle().length ? "'".concat(_this5.state.note.title, "'") : "this note";
var text = Object(_strings__WEBPACK_IMPORTED_MODULE_17__["StringDeleteNote"])({
title: title,
permanently: permanently
});
_this5.application.alertManager.confirm({
text: text,
destructive: true,
onConfirm: function onConfirm() {
if (permanently) {
_this5.performNoteDeletion(_this5.state.note);
} else {
_this5.state.note.content.trashed = true;
_this5.saveNote({
bypassDebouncer: true,
dontUpdatePreviews: true
});
}
_this5.appState.setSelectedNote(null);
_this5.setMenuState('showOptionsMenu', false);
}
});
};
_context5.next = 6;
return this.application.privilegesManager.actionRequiresPrivilege(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].DeleteNote);
case 6:
requiresPrivilege = _context5.sent;
if (requiresPrivilege) {
this.godService.presentPrivilegesModal(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].DeleteNote, function () {
run();
});
} else {
run();
}
case 8:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function deleteNote(_x6) {
return _deleteNote.apply(this, arguments);
}
return deleteNote;
}()
}, {
key: "performNoteDeletion",
value: function performNoteDeletion(note) {
this.application.deleteItem({
item: note
});
if (note === this.state.note) {
this.setState({
note: null
});
}
if (note.dummy) {
this.application.deleteItemLocally({
item: note
});
return;
}
this.application.sync();
}
}, {
key: "restoreTrashedNote",
value: function restoreTrashedNote() {
this.state.note.content.trashed = false;
this.saveNote({
bypassDebouncer: true,
dontUpdatePreviews: true
});
this.appState.setSelectedNote(null);
}
}, {
key: "deleteNotePermanantely",
value: function deleteNotePermanantely() {
this.deleteNote(true);
}
}, {
key: "getTrashCount",
value: function getTrashCount() {
return this.application.getTrashedItems().length;
}
}, {
key: "emptyTrash",
value: function emptyTrash() {
var _this6 = this;
var count = this.getTrashCount();
this.application.alertManager.confirm({
text: Object(_strings__WEBPACK_IMPORTED_MODULE_17__["StringEmptyTrash"])({
count: count
}),
destructive: true,
onConfirm: function onConfirm() {
_this6.application.emptyTrash();
_this6.application.sync();
}
});
}
}, {
key: "togglePin",
value: function togglePin() {
this.state.note.setAppDataItem(AppDataKeys.Pinned, !this.state.note.pinned);
this.saveNote({
bypassDebouncer: true,
dontUpdatePreviews: true
});
}
}, {
key: "toggleLockNote",
value: function toggleLockNote() {
this.state.note.setAppDataItem(AppDataKeys.Locked, !this.state.note.locked);
this.saveNote({
bypassDebouncer: true,
dontUpdatePreviews: true
});
}
}, {
key: "toggleProtectNote",
value: function toggleProtectNote() {
var _this7 = this;
this.state.note.content.protected = !this.state.note.content.protected;
this.saveNote({
bypassDebouncer: true,
dontUpdatePreviews: true
});
/** Show privileges manager if protection is not yet set up */
this.application.privilegesManager.actionHasPrivilegesConfigured(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ViewProtectedNotes).then(function (configured) {
if (!configured) {
_this7.godService.presentPrivilegesManagementModal();
}
});
}
}, {
key: "toggleNotePreview",
value: function toggleNotePreview() {
this.state.note.content.hidePreview = !this.state.note.content.hidePreview;
this.saveNote({
bypassDebouncer: true,
dontUpdatePreviews: true
});
}
}, {
key: "toggleArchiveNote",
value: function toggleArchiveNote() {
this.state.note.setAppDataItem(AppDataKeys.Archived, !this.state.note.archived);
this.saveNote({
bypassDebouncer: true,
dontUpdatePreviews: true
});
}
}, {
key: "reloadTagsString",
value: function reloadTagsString() {
this.setState({
mutable: _objectSpread({}, this.state.mutable, {
tagsString: this.state.note.tagsString()
})
});
}
}, {
key: "addTag",
value: function addTag(tag) {
var strings = this.state.note.tags.map(function (currentTag) {
return currentTag.title;
});
strings.push(tag.title);
this.saveTags({
strings: strings
});
}
}, {
key: "removeTag",
value: function removeTag(tag) {
var strings = this.state.note.tags.map(function (currentTag) {
return currentTag.title;
}).filter(function (title) {
return title !== tag.title;
});
this.saveTags({
strings: strings
});
}
}, {
key: "saveTags",
value: function () {
var _saveTags = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee6() {
var _ref6,
strings,
toRemove,
_iteratorNormalCompletion2,
_didIteratorError2,
_iteratorError2,
_iterator2,
_step2,
tag,
_i2,
_toRemove,
tagToRemove,
tags,
_iteratorNormalCompletion3,
_didIteratorError3,
_iteratorError3,
_iterator3,
_step3,
tagString,
existingRelationship,
_i3,
_tags,
_tag,
_args6 = arguments;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
_ref6 = _args6.length > 0 && _args6[0] !== undefined ? _args6[0] : {}, strings = _ref6.strings;
if (!(!strings && this.state.mutable.tagsString === this.state.note.tagsString())) {
_context6.next = 3;
break;
}
return _context6.abrupt("return");
case 3:
if (!strings) {
strings = this.state.mutable.tagsString.split('#').filter(function (string) {
return string.length > 0;
}).map(function (string) {
return string.trim();
});
}
this.state.note.dummy = false;
toRemove = [];
_iteratorNormalCompletion2 = true;
_didIteratorError2 = false;
_iteratorError2 = undefined;
_context6.prev = 9;
for (_iterator2 = this.state.note.tags[Symbol.iterator](); !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
tag = _step2.value;
if (strings.indexOf(tag.title) === -1) {
toRemove.push(tag);
}
}
_context6.next = 17;
break;
case 13:
_context6.prev = 13;
_context6.t0 = _context6["catch"](9);
_didIteratorError2 = true;
_iteratorError2 = _context6.t0;
case 17:
_context6.prev = 17;
_context6.prev = 18;
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
case 20:
_context6.prev = 20;
if (!_didIteratorError2) {
_context6.next = 23;
break;
}
throw _iteratorError2;
case 23:
return _context6.finish(20);
case 24:
return _context6.finish(17);
case 25:
for (_i2 = 0, _toRemove = toRemove; _i2 < _toRemove.length; _i2++) {
tagToRemove = _toRemove[_i2];
tagToRemove.removeItemAsRelationship(this.state.note);
}
this.application.setItemsNeedsSync({
items: toRemove
});
tags = [];
_iteratorNormalCompletion3 = true;
_didIteratorError3 = false;
_iteratorError3 = undefined;
_context6.prev = 31;
_iterator3 = strings[Symbol.iterator]();
case 33:
if (_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done) {
_context6.next = 45;
break;
}
tagString = _step3.value;
existingRelationship = lodash_find__WEBPACK_IMPORTED_MODULE_11___default()(this.state.note.tags, {
title: tagString
});
if (existingRelationship) {
_context6.next = 42;
break;
}
_context6.t1 = tags;
_context6.next = 40;
return this.application.findOrCreateTag({
title: tagString
});
case 40:
_context6.t2 = _context6.sent;
_context6.t1.push.call(_context6.t1, _context6.t2);
case 42:
_iteratorNormalCompletion3 = true;
_context6.next = 33;
break;
case 45:
_context6.next = 51;
break;
case 47:
_context6.prev = 47;
_context6.t3 = _context6["catch"](31);
_didIteratorError3 = true;
_iteratorError3 = _context6.t3;
case 51:
_context6.prev = 51;
_context6.prev = 52;
if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
_iterator3.return();
}
case 54:
_context6.prev = 54;
if (!_didIteratorError3) {
_context6.next = 57;
break;
}
throw _iteratorError3;
case 57:
return _context6.finish(54);
case 58:
return _context6.finish(51);
case 59:
for (_i3 = 0, _tags = tags; _i3 < _tags.length; _i3++) {
_tag = _tags[_i3];
_tag.addItemAsRelationship(this.state.note);
}
this.application.saveItems({
items: tags
});
this.reloadTagsString();
case 62:
case "end":
return _context6.stop();
}
}
}, _callee6, this, [[9, 13, 17, 25], [18,, 20, 24], [31, 47, 51, 59], [52,, 54, 58]]);
}));
function saveTags() {
return _saveTags.apply(this, arguments);
}
return saveTags;
}()
}, {
key: "loadPreferences",
value: function loadPreferences() {
var monospaceEnabled = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_18__["PrefKeys"].EditorMonospaceEnabled, true);
var spellcheck = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_18__["PrefKeys"].EditorSpellcheck, true);
var marginResizersEnabled = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_18__["PrefKeys"].EditorResizersEnabled, true);
this.setState({
monospaceEnabled: monospaceEnabled,
spellcheck: spellcheck,
marginResizersEnabled: marginResizersEnabled
});
if (!document.getElementById(ElementIds.EditorContent)) {
/** Elements have not yet loaded due to ng-if around wrapper */
return;
}
this.reloadFont();
if (this.state.marginResizersEnabled) {
var width = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_18__["PrefKeys"].EditorWidth, null);
if (width != null) {
this.leftResizeControl.setWidth(width);
this.rightResizeControl.setWidth(width);
}
var left = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_18__["PrefKeys"].EditorLeft, null);
if (left != null) {
this.leftResizeControl.setLeft(left);
this.rightResizeControl.setLeft(left);
}
}
}
}, {
key: "reloadFont",
value: function reloadFont() {
var editor = document.getElementById(ElementIds.NoteTextEditor);
if (!editor) {
return;
}
if (this.state.monospaceEnabled) {
if (this.state.isDesktop) {
editor.style.fontFamily = Fonts.DesktopMonospaceFamily;
} else {
editor.style.fontFamily = Fonts.WebMonospaceFamily;
}
} else {
editor.style.fontFamily = Fonts.SansSerifFamily;
}
}
}, {
key: "toggleKey",
value: function () {
var _toggleKey = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee7(key) {
var _this8 = this;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
this[key] = !this[key];
this.preferencesManager.setUserPrefValue(key, this[key], true);
this.reloadFont();
if (!(key === _services_preferencesManager__WEBPACK_IMPORTED_MODULE_18__["PrefKeys"].EditorSpellcheck)) {
_context7.next = 10;
break;
}
_context7.next = 6;
return this.setState({
noteReady: false
});
case 6:
this.setState({
noteReady: true
});
this.reloadFont();
_context7.next = 11;
break;
case 10:
if (key === _services_preferencesManager__WEBPACK_IMPORTED_MODULE_18__["PrefKeys"].EditorResizersEnabled && this[key] === true) {
this.$timeout(function () {
_this8.leftResizeControl.flash();
_this8.rightResizeControl.flash();
});
}
case 11:
case "end":
return _context7.stop();
}
}
}, _callee7, this);
}));
function toggleKey(_x7) {
return _toggleKey.apply(this, arguments);
}
return toggleKey;
}()
/** @components */
}, {
key: "registerComponentHandler",
value: function registerComponentHandler() {
var _this9 = this;
this.application.componentManager.registerHandler({
identifier: 'editor',
areas: ['note-tags', 'editor-stack', 'editor-editor'],
activationHandler: function activationHandler(component) {
if (component.area === 'note-tags') {
_this9.setState({
tagsComponent: component.active ? component : null
});
} else if (component.area === 'editor-editor') {
if (component === _this9.state.selectedEditor && !component.active) {
_this9.setState({
selectedEditor: null
});
} else if (_this9.state.selectedEditor) {
if (_this9.state.selectedEditor.active && _this9.state.note) {
if (component.isExplicitlyEnabledForItem(_this9.state.note) && !_this9.state.selectedEditor.isExplicitlyEnabledForItem(_this9.state.note)) {
_this9.setState({
selectedEditor: component
});
}
}
} else if (_this9.state.note) {
var enableable = component.isExplicitlyEnabledForItem(_this9.state.note) || component.isDefaultEditor();
if (component.active && enableable) {
_this9.setState({
selectedEditor: component
});
} else {
/**
* Not a candidate, and no qualified editor.
* Disable the current editor.
*/
_this9.setState({
selectedEditor: null
});
}
}
} else if (component.area === 'editor-stack') {
_this9.reloadComponentContext();
}
},
contextRequestHandler: function contextRequestHandler(component) {
if (component === _this9.state.selectedEditor || component === _this9.state.tagsComponent || _this9.state.componentStack.includes(component)) {
return _this9.state.note;
}
},
focusHandler: function focusHandler(component, focused) {
if (component.isEditor() && focused) {
_this9.closeAllMenus();
}
},
actionHandler: function actionHandler(component, action, data) {
if (action === 'set-size') {
var setSize = function setSize(element, size) {
var widthString = typeof size.width === 'string' ? size.width : "".concat(data.width, "px");
var heightString = typeof size.height === 'string' ? size.height : "".concat(data.height, "px");
element.setAttribute('style', "width: ".concat(widthString, "; height: ").concat(heightString, ";"));
};
if (data.type === 'container') {
if (component.area === 'note-tags') {
var container = document.getElementById(ElementIds.NoteTagsComponentContainer);
setSize(container, data);
}
}
} else if (action === 'associate-item') {
if (data.item.content_type === 'Tag') {
var tag = _this9.application.findItem({
uuid: data.item.uuid
});
_this9.addTag(tag);
}
} else if (action === 'deassociate-item') {
var _tag2 = _this9.application.findItem({
uuid: data.item.uuid
});
_this9.removeTag(_tag2);
} else if (action === 'save-items') {
var includesNote = data.items.map(function (item) {
return item.uuid;
}).includes(_this9.state.note.uuid);
if (includesNote) {
_this9.showSavingStatus();
}
}
}
});
}
}, {
key: "reloadComponentStackArray",
value: function reloadComponentStackArray() {
var components = this.application.componentManager.componentsForArea('editor-stack').sort(function (a, b) {
return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1;
});
this.setState({
componentStack: components
});
}
}, {
key: "reloadComponentContext",
value: function reloadComponentContext() {
this.reloadComponentStackArray();
if (this.state.note) {
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = this.state.componentStack[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var component = _step4.value;
if (component.active) {
this.application.componentManager.setComponentHidden(component, !component.isExplicitlyEnabledForItem(this.state.note));
}
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
}
this.application.componentManager.contextItemDidChangeInArea('note-tags');
this.application.componentManager.contextItemDidChangeInArea('editor-stack');
this.application.componentManager.contextItemDidChangeInArea('editor-editor');
}
}, {
key: "toggleStackComponentForCurrentItem",
value: function toggleStackComponentForCurrentItem(component) {
if (component.hidden || !component.active) {
this.application.componentManager.setComponentHidden(component, false);
this.associateComponentWithCurrentNote(component);
if (!component.active) {
this.application.componentManager.activateComponent(component);
}
this.application.componentManager.contextItemDidChangeInArea('editor-stack');
} else {
this.application.componentManager.setComponentHidden(component, true);
this.disassociateComponentWithCurrentNote(component);
}
}
}, {
key: "disassociateComponentWithCurrentNote",
value: function disassociateComponentWithCurrentNote(component) {
var _this10 = this;
component.associatedItemIds = component.associatedItemIds.filter(function (id) {
return id !== _this10.state.note.uuid;
});
if (!component.disassociatedItemIds.includes(this.state.note.uuid)) {
component.disassociatedItemIds.push(this.state.note.uuid);
}
this.application.saveItem({
item: component
});
}
}, {
key: "associateComponentWithCurrentNote",
value: function associateComponentWithCurrentNote(component) {
var _this11 = this;
component.disassociatedItemIds = component.disassociatedItemIds.filter(function (id) {
return id !== _this11.state.note.uuid;
});
if (!component.associatedItemIds.includes(this.state.note.uuid)) {
component.associatedItemIds.push(this.state.note.uuid);
}
this.application.saveItem({
item: component
});
}
}, {
key: "registerKeyboardShortcuts",
value: function registerKeyboardShortcuts() {
var _this12 = this;
this.altKeyObserver = this.keyboardManager.addKeyObserver({
modifiers: [_services_keyboardManager__WEBPACK_IMPORTED_MODULE_13__["KeyboardModifiers"].Alt],
onKeyDown: function onKeyDown() {
_this12.setState({
altKeyDown: true
});
},
onKeyUp: function onKeyUp() {
_this12.setState({
altKeyDown: false
});
}
});
this.trashKeyObserver = this.keyboardManager.addKeyObserver({
key: _services_keyboardManager__WEBPACK_IMPORTED_MODULE_13__["KeyboardKeys"].Backspace,
notElementIds: [ElementIds.NoteTextEditor, ElementIds.NoteTitleEditor],
modifiers: [_services_keyboardManager__WEBPACK_IMPORTED_MODULE_13__["KeyboardModifiers"].Meta],
onKeyDown: function onKeyDown() {
_this12.deleteNote();
}
});
this.deleteKeyObserver = this.keyboardManager.addKeyObserver({
key: _services_keyboardManager__WEBPACK_IMPORTED_MODULE_13__["KeyboardKeys"].Backspace,
modifiers: [_services_keyboardManager__WEBPACK_IMPORTED_MODULE_13__["KeyboardModifiers"].Meta, _services_keyboardManager__WEBPACK_IMPORTED_MODULE_13__["KeyboardModifiers"].Shift, _services_keyboardManager__WEBPACK_IMPORTED_MODULE_13__["KeyboardModifiers"].Alt],
onKeyDown: function onKeyDown(event) {
event.preventDefault();
_this12.deleteNote(true);
}
});
}
}, {
key: "onSystemEditorLoad",
value: function onSystemEditorLoad() {
var _this13 = this;
if (this.loadedTabListener) {
return;
}
this.loadedTabListener = true;
/**
* Insert 4 spaces when a tab key is pressed,
* only used when inside of the text editor.
* If the shift key is pressed first, this event is
* not fired.
*/
var editor = document.getElementById(ElementIds.NoteTextEditor);
this.tabObserver = this.keyboardManager.addKeyObserver({
element: editor,
key: _services_keyboardManager__WEBPACK_IMPORTED_MODULE_13__["KeyboardKeys"].Tab,
onKeyDown: function onKeyDown(event) {
if (_this13.state.note.locked || event.shiftKey) {
return;
}
event.preventDefault();
/** Using document.execCommand gives us undo support */
var insertSuccessful = document.execCommand('insertText', false, '\t');
if (!insertSuccessful) {
/** document.execCommand works great on Chrome/Safari but not Firefox */
var start = editor.selectionStart;
var end = editor.selectionEnd;
var spaces = ' ';
/** Insert 4 spaces */
editor.value = editor.value.substring(0, start) + spaces + editor.value.substring(end);
/** Place cursor 4 spaces away from where the tab key was pressed */
editor.selectionStart = editor.selectionEnd = start + 4;
}
var note = _this13.state.note;
note.text = editor.value;
_this13.setState({
note: note
});
_this13.saveNote({
bypassDebouncer: true
});
}
});
/**
* Handles when the editor is destroyed,
* (and not when our controller is destroyed.)
*/
angular__WEBPACK_IMPORTED_MODULE_9___default.a.element(editor).on('$destroy', function () {
if (_this13.tabObserver) {
_this13.keyboardManager.removeKeyObserver(_this13.tabObserver);
_this13.loadedTabListener = false;
}
});
}
}]);
return EditorCtrl;
}(_Controllers__WEBPACK_IMPORTED_MODULE_15__["PureCtrl"]);
var EditorPanel = function EditorPanel() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, EditorPanel);
this.restrict = 'E';
this.scope = {};
this.template = _editor_pug__WEBPACK_IMPORTED_MODULE_14___default.a;
this.replace = true;
this.controller = EditorCtrl;
this.controllerAs = 'self';
this.bindToController = true;
};
/***/ }),
/***/ "./app/assets/javascripts/controllers/footer.js":
/*!******************************************************!*\
!*** ./app/assets/javascripts/controllers/footer.js ***!
\******************************************************/
/*! exports provided: Footer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Footer", function() { return Footer; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js");
/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _footer_pug__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! %/footer.pug */ "./app/assets/templates/footer.pug");
/* harmony import */ var _footer_pug__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_footer_pug__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/state */ "./app/assets/javascripts/state.js");
/* harmony import */ var _strings__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/strings */ "./app/assets/javascripts/strings.js");
/* harmony import */ var _Controllers__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @Controllers */ "./app/assets/javascripts/controllers/index.js");
var FooterCtrl =
/*#__PURE__*/
function (_PureCtrl) {
FooterCtrl.$inject = ["$scope", "$rootScope", "$timeout", "application", "appState", "nativeExtManager", "statusManager", "godService"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default()(FooterCtrl, _PureCtrl);
/* @ngInject */
function FooterCtrl($scope, $rootScope, $timeout, application, appState, nativeExtManager, statusManager, godService) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, FooterCtrl);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(FooterCtrl).call(this, $scope, $timeout, application, appState));
_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default()(_this), "toggleSyncResolutionMenu", function () {
_this.showSyncResolution = !_this.showSyncResolution;
});
_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default()(_this), "closeAccountMenu", function () {
_this.showAccountMenu = false;
});
_this.$rootScope = $rootScope;
_this.nativeExtManager = nativeExtManager;
_this.statusManager = statusManager;
_this.godService = godService;
_this.rooms = [];
_this.themesWithIcons = [];
_this.showSyncResolution = false;
_this.addRootScopeListeners();
_this.statusManager.addStatusObserver(function (string) {
_this.$timeout(function () {
_this.arbitraryStatusMessage = string;
});
});
application.onUnlock(function () {
_this.application.hasPasscode().then(function (value) {
_this.hasPasscode = value;
});
_this.godService.checkForSecurityUpdate().then(function (available) {
_this.securityUpdateAvailable = available;
});
_this.user = _this.application.getUser();
_this.updateOfflineStatus();
_this.addAppEventObserver();
_this.findErrors();
_this.streamItems();
_this.registerComponentHandler();
});
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(FooterCtrl, [{
key: "addRootScopeListeners",
value: function addRootScopeListeners() {
var _this2 = this;
this.$rootScope.$on("security-update-status-changed", function () {
_this2.securityUpdateAvailable = _this2.godService.securityUpdateAvailable;
});
this.$rootScope.$on("reload-ext-data", function () {
_this2.reloadExtendedData();
});
this.$rootScope.$on("new-update-available", function () {
_this2.$timeout(function () {
_this2.onNewUpdateAvailable();
});
});
}
/** @override */
}, {
key: "onAppStateEvent",
value: function onAppStateEvent(eventName, data) {
var _this3 = this;
if (eventName === _state__WEBPACK_IMPORTED_MODULE_12__["AppStateEvents"].EditorFocused) {
if (data.eventSource === _state__WEBPACK_IMPORTED_MODULE_12__["EventSources"].UserInteraction) {
this.closeAllRooms();
this.closeAccountMenu();
}
} else if (eventName === _state__WEBPACK_IMPORTED_MODULE_12__["AppStateEvents"].BeganBackupDownload) {
this.backupStatus = this.statusManager.addStatusFromString("Saving local backup...");
} else if (eventName === _state__WEBPACK_IMPORTED_MODULE_12__["AppStateEvents"].EndedBackupDownload) {
if (data.success) {
this.backupStatus = this.statusManager.replaceStatusWithString(this.backupStatus, "Successfully saved backup.");
} else {
this.backupStatus = this.statusManager.replaceStatusWithString(this.backupStatus, "Unable to save local backup.");
}
this.$timeout(function () {
_this3.backupStatus = _this3.statusManager.removeStatus(_this3.backupStatus);
}, 2000);
}
}
/** @override */
}, {
key: "onApplicationEvent",
value: function onApplicationEvent(eventName) {
if (eventName === snjs__WEBPACK_IMPORTED_MODULE_10__["ApplicationEvents"].LoadedLocalData) {
if (this.offline && this.application.getNoteCount() === 0) {
this.showAccountMenu = true;
}
} else if (eventName === snjs__WEBPACK_IMPORTED_MODULE_10__["ApplicationEvents"].EnteredOutOfSync) {
this.outOfSync = true;
} else if (eventName === snjs__WEBPACK_IMPORTED_MODULE_10__["ApplicationEvents"].ExitedOutOfSync) {
this.outOfSync = false;
} else if (eventName === snjs__WEBPACK_IMPORTED_MODULE_10__["ApplicationEvents"].CompletedSync) {
this.syncUpdated();
this.findErrors();
this.updateOfflineStatus();
} else if (eventName === snjs__WEBPACK_IMPORTED_MODULE_10__["ApplicationEvents"].FailedSync) {
this.findErrors();
this.updateOfflineStatus();
}
}
}, {
key: "streamItems",
value: function streamItems() {
var _this4 = this;
this.application.streamItems({
contentType: snjs__WEBPACK_IMPORTED_MODULE_10__["ContentTypes"].Component,
stream: function () {
var _stream = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_this4.rooms = _this4.application.getItems({
contentType: snjs__WEBPACK_IMPORTED_MODULE_10__["ContentTypes"].Component
}).filter(function (candidate) {
return candidate.area === 'rooms' && !candidate.deleted;
});
if (_this4.queueExtReload) {
_this4.queueExtReload = false;
_this4.reloadExtendedData();
}
case 2:
case "end":
return _context.stop();
}
}
}, _callee);
}));
function stream() {
return _stream.apply(this, arguments);
}
return stream;
}()
});
this.application.streamItems({
contentType: 'SN|Theme',
stream: function () {
var _stream2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var themes, differ;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
themes = _this4.application.getDisplayableItems({
contentType: snjs__WEBPACK_IMPORTED_MODULE_10__["ContentTypes"].Theme
}).filter(function (candidate) {
return !candidate.deleted && candidate.content.package_info && candidate.content.package_info.dock_icon;
}).sort(function (a, b) {
return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1;
});
differ = themes.length !== _this4.themesWithIcons.length;
_this4.themesWithIcons = themes;
if (differ) {
_this4.reloadDockShortcuts();
}
case 4:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
function stream() {
return _stream2.apply(this, arguments);
}
return stream;
}()
});
}
}, {
key: "registerComponentHandler",
value: function registerComponentHandler() {
var _this5 = this;
this.application.componentManager.registerHandler({
identifier: "roomBar",
areas: ["rooms", "modal"],
activationHandler: function activationHandler(component) {},
actionHandler: function actionHandler(component, action, data) {
if (action === "set-size") {
component.setLastSize(data);
}
},
focusHandler: function focusHandler(component, focused) {
if (component.isEditor() && focused) {
_this5.closeAllRooms();
_this5.closeAccountMenu();
}
}
});
}
}, {
key: "reloadExtendedData",
value: function reloadExtendedData() {
var _this6 = this;
if (this.reloadInProgress) {
return;
}
this.reloadInProgress = true;
/**
* A reload consists of opening the extensions manager,
* then closing it after a short delay.
*/
var extWindow = this.rooms.find(function (room) {
return room.package_info.identifier === _this6.nativeExtManager.extManagerId;
});
if (!extWindow) {
this.queueExtReload = true;
this.reloadInProgress = false;
return;
}
this.selectRoom(extWindow);
this.$timeout(function () {
_this6.selectRoom(extWindow);
_this6.reloadInProgress = false;
_this6.$rootScope.$broadcast('ext-reload-complete');
}, 2000);
}
}, {
key: "updateOfflineStatus",
value: function updateOfflineStatus() {
this.offline = this.application.noAccount();
}
}, {
key: "openSecurityUpdate",
value: function openSecurityUpdate() {
this.godService.presentPasswordWizard('upgrade-security');
}
}, {
key: "findErrors",
value: function findErrors() {
this.error = this.application.getSyncStatus().error;
}
}, {
key: "accountMenuPressed",
value: function accountMenuPressed() {
this.showAccountMenu = !this.showAccountMenu;
this.closeAllRooms();
}
}, {
key: "lockApp",
value: function lockApp() {
this.$rootScope.lockApplication();
}
}, {
key: "refreshData",
value: function refreshData() {
var _this7 = this;
this.isRefreshing = true;
this.application.sync({
timingStrategy: snjs__WEBPACK_IMPORTED_MODULE_10__["TIMING_STRATEGY_FORCE_SPAWN_NEW"],
checkIntegrity: true
}).then(function (response) {
_this7.$timeout(function () {
_this7.isRefreshing = false;
}, 200);
if (response && response.error) {
_this7.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_13__["STRING_GENERIC_SYNC_ERROR"]
});
} else {
_this7.syncUpdated();
}
});
}
}, {
key: "syncUpdated",
value: function syncUpdated() {
this.lastSyncDate = Object(_utils__WEBPACK_IMPORTED_MODULE_9__["dateToLocalizedString"])(new Date());
}
}, {
key: "onNewUpdateAvailable",
value: function onNewUpdateAvailable() {
this.newUpdateAvailable = true;
}
}, {
key: "clickedNewUpdateAnnouncement",
value: function clickedNewUpdateAnnouncement() {
this.newUpdateAvailable = false;
this.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_13__["STRING_NEW_UPDATE_READY"]
});
}
}, {
key: "reloadDockShortcuts",
value: function reloadDockShortcuts() {
var shortcuts = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.themesWithIcons[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var theme = _step.value;
var name = theme.content.package_info.name;
var icon = theme.content.package_info.dock_icon;
if (!icon) {
continue;
}
shortcuts.push({
name: name,
component: theme,
icon: icon
});
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
this.dockShortcuts = shortcuts.sort(function (a, b) {
/** Circles first, then images */
var aType = a.icon.type;
var bType = b.icon.type;
if (aType === bType) {
return 0;
} else if (aType === 'circle' && bType === 'svg') {
return -1;
} else if (bType === 'circle' && aType === 'svg') {
return 1;
}
});
}
}, {
key: "initSvgForShortcut",
value: function initSvgForShortcut(shortcut) {
var id = 'dock-svg-' + shortcut.component.uuid;
var element = document.getElementById(id);
var parser = new DOMParser();
var svg = shortcut.component.content.package_info.dock_icon.source;
var doc = parser.parseFromString(svg, 'image/svg+xml');
element.appendChild(doc.documentElement);
}
}, {
key: "selectShortcut",
value: function selectShortcut(shortcut) {
this.application.componentManager.toggleComponent(shortcut.component);
}
}, {
key: "onRoomDismiss",
value: function onRoomDismiss(room) {
room.showRoom = false;
}
}, {
key: "closeAllRooms",
value: function closeAllRooms() {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = this.rooms[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var room = _step2.value;
room.showRoom = false;
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
}
}, {
key: "selectRoom",
value: function () {
var _selectRoom = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(room) {
var _this8 = this;
var run, requiresPrivilege;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
run = function run() {
_this8.$timeout(function () {
room.showRoom = !room.showRoom;
});
};
if (room.showRoom) {
_context3.next = 8;
break;
}
_context3.next = 4;
return this.application.privilegesManager.actionRequiresPrivilege(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManageExtensions);
case 4:
requiresPrivilege = _context3.sent;
if (requiresPrivilege) {
this.godService.presentPrivilegesModal(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManageExtensions, run);
} else {
run();
}
_context3.next = 9;
break;
case 8:
run();
case 9:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function selectRoom(_x) {
return _selectRoom.apply(this, arguments);
}
return selectRoom;
}()
}, {
key: "clickOutsideAccountMenu",
value: function clickOutsideAccountMenu() {
if (this.godService.authenticationInProgress()) {
return;
}
this.showAccountMenu = false;
}
}]);
return FooterCtrl;
}(_Controllers__WEBPACK_IMPORTED_MODULE_14__["PureCtrl"]);
var Footer = function Footer() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, Footer);
this.restrict = 'E';
this.scope = {};
this.template = _footer_pug__WEBPACK_IMPORTED_MODULE_11___default.a;
this.controller = FooterCtrl;
this.replace = true;
this.controllerAs = 'ctrl';
this.bindToController = true;
};
/***/ }),
/***/ "./app/assets/javascripts/controllers/index.js":
/*!*****************************************************!*\
!*** ./app/assets/javascripts/controllers/index.js ***!
\*****************************************************/
/*! exports provided: PureCtrl, EditorPanel, Footer, NotesPanel, TagsPanel, Root, LockScreen */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _abstract_pure_ctrl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./abstract/pure_ctrl */ "./app/assets/javascripts/controllers/abstract/pure_ctrl.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PureCtrl", function() { return _abstract_pure_ctrl__WEBPACK_IMPORTED_MODULE_0__["PureCtrl"]; });
/* harmony import */ var _editor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./editor */ "./app/assets/javascripts/controllers/editor.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EditorPanel", function() { return _editor__WEBPACK_IMPORTED_MODULE_1__["EditorPanel"]; });
/* harmony import */ var _footer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./footer */ "./app/assets/javascripts/controllers/footer.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Footer", function() { return _footer__WEBPACK_IMPORTED_MODULE_2__["Footer"]; });
/* harmony import */ var _notes_notes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./notes/notes */ "./app/assets/javascripts/controllers/notes/notes.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NotesPanel", function() { return _notes_notes__WEBPACK_IMPORTED_MODULE_3__["NotesPanel"]; });
/* harmony import */ var _tags__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./tags */ "./app/assets/javascripts/controllers/tags.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TagsPanel", function() { return _tags__WEBPACK_IMPORTED_MODULE_4__["TagsPanel"]; });
/* harmony import */ var _root__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./root */ "./app/assets/javascripts/controllers/root.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Root", function() { return _root__WEBPACK_IMPORTED_MODULE_5__["Root"]; });
/* harmony import */ var _lockScreen__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./lockScreen */ "./app/assets/javascripts/controllers/lockScreen.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LockScreen", function() { return _lockScreen__WEBPACK_IMPORTED_MODULE_6__["LockScreen"]; });
/***/ }),
/***/ "./app/assets/javascripts/controllers/lockScreen.js":
/*!**********************************************************!*\
!*** ./app/assets/javascripts/controllers/lockScreen.js ***!
\**********************************************************/
/*! exports provided: LockScreen */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LockScreen", function() { return LockScreen; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _lock_screen_pug__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! %/lock-screen.pug */ "./app/assets/templates/lock-screen.pug");
/* harmony import */ var _lock_screen_pug__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_lock_screen_pug__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/state */ "./app/assets/javascripts/state.js");
/* harmony import */ var _abstract_pure_ctrl__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./abstract/pure_ctrl */ "./app/assets/javascripts/controllers/abstract/pure_ctrl.js");
var ELEMENT_ID_PASSCODE_INPUT = 'passcode-input';
var LockScreenCtrl =
/*#__PURE__*/
function (_PureCtrl) {
LockScreenCtrl.$inject = ["$scope", "$timeout", "application", "appState"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6___default()(LockScreenCtrl, _PureCtrl);
/* @ngInject */
function LockScreenCtrl($scope, $timeout, application, appState) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, LockScreenCtrl);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(LockScreenCtrl).call(this, $scope, $timeout, application, appState));
_this.formData = {};
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(LockScreenCtrl, [{
key: "$onInit",
value: function $onInit() {
var _this2 = this;
this.puppet.focusInput = function () {
_this2.passcodeInput.focus();
};
}
}, {
key: "onAppStateEvent",
/** @override */
value: function () {
var _onAppStateEvent = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(eventName, data) {
var input;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (eventName === _state__WEBPACK_IMPORTED_MODULE_8__["AppStateEvents"].WindowDidFocus) {
input = this.passcodeInput;
if (input) {
input.focus();
}
}
case 1:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function onAppStateEvent(_x, _x2) {
return _onAppStateEvent.apply(this, arguments);
}
return onAppStateEvent;
}()
}, {
key: "submitPasscodeForm",
value: function () {
var _submitPasscodeForm = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2($event) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!(!this.formData.passcode || this.formData.passcode.length === 0)) {
_context2.next = 2;
break;
}
return _context2.abrupt("return");
case 2:
this.passcodeInput.blur();
this.onValue()(this.formData.passcode);
case 4:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function submitPasscodeForm(_x3) {
return _submitPasscodeForm.apply(this, arguments);
}
return submitPasscodeForm;
}()
}, {
key: "forgotPasscode",
value: function forgotPasscode() {
this.formData.showRecovery = true;
}
}, {
key: "beginDeleteData",
value: function beginDeleteData() {
var _this3 = this;
this.application.alertManager.confirm({
text: "Are you sure you want to clear all local data?",
destructive: true,
onConfirm: function () {
var _onConfirm = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return _this3.application.signOut();
case 2:
_context3.next = 4;
return _this3.application.restart();
case 4:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
function onConfirm() {
return _onConfirm.apply(this, arguments);
}
return onConfirm;
}()
});
}
}, {
key: "passcodeInput",
get: function get() {
return document.getElementById(ELEMENT_ID_PASSCODE_INPUT);
}
}]);
return LockScreenCtrl;
}(_abstract_pure_ctrl__WEBPACK_IMPORTED_MODULE_9__["PureCtrl"]);
var LockScreen = function LockScreen() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, LockScreen);
this.restrict = 'E';
this.template = _lock_screen_pug__WEBPACK_IMPORTED_MODULE_7___default.a;
this.controller = LockScreenCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
onValue: '&',
puppet: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/controllers/notes/note_utils.js":
/*!****************************************************************!*\
!*** ./app/assets/javascripts/controllers/notes/note_utils.js ***!
\****************************************************************/
/*! exports provided: SORT_KEY_CREATED_AT, SORT_KEY_UPDATED_AT, SORT_KEY_CLIENT_UPDATED_AT, SORT_KEY_TITLE, filterAndSortNotes, filterNotes, sortNotes */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SORT_KEY_CREATED_AT", function() { return SORT_KEY_CREATED_AT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SORT_KEY_UPDATED_AT", function() { return SORT_KEY_UPDATED_AT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SORT_KEY_CLIENT_UPDATED_AT", function() { return SORT_KEY_CLIENT_UPDATED_AT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SORT_KEY_TITLE", function() { return SORT_KEY_TITLE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filterAndSortNotes", function() { return filterAndSortNotes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "filterNotes", function() { return filterNotes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sortNotes", function() { return sortNotes; });
var SORT_KEY_CREATED_AT = 'created_at';
var SORT_KEY_UPDATED_AT = 'updated_at';
var SORT_KEY_CLIENT_UPDATED_AT = 'client_updated_at';
var SORT_KEY_TITLE = 'title';
function filterAndSortNotes(_ref) {
var notes = _ref.notes,
selectedTag = _ref.selectedTag,
showArchived = _ref.showArchived,
hidePinned = _ref.hidePinned,
filterText = _ref.filterText,
sortBy = _ref.sortBy,
reverse = _ref.reverse;
var filtered = filterNotes({
notes: notes,
selectedTag: selectedTag,
showArchived: showArchived,
hidePinned: hidePinned,
filterText: filterText
});
var sorted = sortNotes({
notes: filtered,
sortBy: sortBy,
reverse: reverse
});
return sorted;
}
function filterNotes(_ref2) {
var notes = _ref2.notes,
selectedTag = _ref2.selectedTag,
showArchived = _ref2.showArchived,
hidePinned = _ref2.hidePinned,
filterText = _ref2.filterText;
return notes.filter(function (note) {
var canShowArchived = showArchived;
var canShowPinned = !hidePinned;
var isTrash = selectedTag.content.isTrashTag;
if (!isTrash && note.content.trashed) {
return false;
}
var isSmartTag = selectedTag.isSmartTag();
if (isSmartTag) {
canShowArchived = canShowArchived || selectedTag.content.isArchiveTag || isTrash;
}
if (note.archived && !canShowArchived || note.pinned && !canShowPinned) {
return false;
}
return noteMatchesQuery({
note: note,
query: filterText
});
});
}
function noteMatchesQuery(_ref3) {
var note = _ref3.note,
query = _ref3.query;
if (query.length === 0) {
return true;
}
var title = note.safeTitle().toLowerCase();
var text = note.safeText().toLowerCase();
var lowercaseText = query.toLowerCase();
var quotedText = stringBetweenQuotes(lowercaseText);
if (quotedText) {
return title.includes(quotedText) || text.includes(quotedText);
}
if (stringIsUuid(lowercaseText)) {
return note.uuid === lowercaseText;
}
var words = lowercaseText.split(" ");
var matchesTitle = words.every(function (word) {
return title.indexOf(word) >= 0;
});
var matchesBody = words.every(function (word) {
return text.indexOf(word) >= 0;
});
return matchesTitle || matchesBody;
}
function stringBetweenQuotes(text) {
var matches = text.match(/"(.*?)"/);
return matches ? matches[1] : null;
}
function stringIsUuid(text) {
var matches = text.match(/\b[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}\b/); // eslint-disable-next-line no-unneeded-ternary
return matches ? true : false;
}
function sortNotes(_ref4) {
var _ref4$notes = _ref4.notes,
notes = _ref4$notes === void 0 ? [] : _ref4$notes,
sortBy = _ref4.sortBy,
reverse = _ref4.reverse;
var sortValueFn = function sortValueFn(a, b) {
var pinCheck = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (a.dummy) {
return -1;
}
if (b.dummy) {
return 1;
}
if (!pinCheck) {
if (a.pinned && b.pinned) {
return sortValueFn(a, b, true);
}
if (a.pinned) {
return -1;
}
if (b.pinned) {
return 1;
}
}
var aValue = a[sortBy] || '';
var bValue = b[sortBy] || '';
var vector = 1;
if (reverse) {
vector *= -1;
}
if (sortBy === SORT_KEY_TITLE) {
aValue = aValue.toLowerCase();
bValue = bValue.toLowerCase();
if (aValue.length === 0 && bValue.length === 0) {
return 0;
} else if (aValue.length === 0 && bValue.length !== 0) {
return 1 * vector;
} else if (aValue.length !== 0 && bValue.length === 0) {
return -1 * vector;
} else {
vector *= -1;
}
}
if (aValue > bValue) {
return -1 * vector;
} else if (aValue < bValue) {
return 1 * vector;
}
return 0;
};
var result = notes.sort(function (a, b) {
return sortValueFn(a, b);
});
return result;
}
/***/ }),
/***/ "./app/assets/javascripts/controllers/notes/notes.js":
/*!***********************************************************!*\
!*** ./app/assets/javascripts/controllers/notes/notes.js ***!
\***********************************************************/
/*! exports provided: NotesPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NotesPanel", function() { return NotesPanel; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js");
/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _notes_pug__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! %/notes.pug */ "./app/assets/templates/notes.pug");
/* harmony import */ var _notes_pug__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_notes_pug__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_12__);
/* harmony import */ var _Controllers__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @Controllers */ "./app/assets/javascripts/controllers/index.js");
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @/state */ "./app/assets/javascripts/state.js");
/* harmony import */ var _services_keyboardManager__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @/services/keyboardManager */ "./app/assets/javascripts/services/keyboardManager.js");
/* harmony import */ var _services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! @/services/preferencesManager */ "./app/assets/javascripts/services/preferencesManager.js");
/* harmony import */ var _controllers_constants__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! @/controllers/constants */ "./app/assets/javascripts/controllers/constants.js");
/* harmony import */ var _note_utils__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./note_utils */ "./app/assets/javascripts/controllers/notes/note_utils.js");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
/**
* This is the height of a note cell with nothing but the title,
* which *is* a display option
*/
var MIN_NOTE_CELL_HEIGHT = 51.0;
var DEFAULT_LIST_NUM_NOTES = 20;
var ELEMENT_ID_SEARCH_BAR = 'search-bar';
var ELEMENT_ID_SCROLL_CONTAINER = 'notes-scrollable';
var NotesCtrl =
/*#__PURE__*/
function (_PureCtrl) {
NotesCtrl.$inject = ["$scope", "$timeout", "$rootScope", "application", "appState", "desktopManager", "keyboardManager", "preferencesManager"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default()(NotesCtrl, _PureCtrl);
/* @ngInject */
function NotesCtrl($scope, $timeout, $rootScope, application, appState, desktopManager, keyboardManager, preferencesManager) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, NotesCtrl);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(NotesCtrl).call(this, $scope, $timeout, application, appState));
_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default()(_this), "onPanelResize", function (newWidth, lastLeft, isAtMaxWidth, isCollapsed) {
_this.preferencesManager.setUserPrefValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PrefKeys"].NotesPanelWidth, newWidth);
_this.preferencesManager.syncUserPreferences();
_this.appState.panelDidResize({
name: _controllers_constants__WEBPACK_IMPORTED_MODULE_17__["PANEL_NAME_NOTES"],
collapsed: isCollapsed
});
});
_this.$rootScope = $rootScope;
_this.application = application;
_this.appState = appState;
_this.desktopManager = desktopManager;
_this.keyboardManager = keyboardManager;
_this.preferencesManager = preferencesManager;
_this.state = {
notes: [],
renderedNotes: [],
selectedNote: null,
tag: null,
sortBy: null,
showArchived: null,
hidePinned: null,
sortReverse: null,
panelTitle: null,
mutable: {
showMenu: false
},
noteFilter: {
text: ''
}
};
_this.panelController = {};
window.onresize = function (event) {
_this.resetPagination({
keepCurrentIfLarger: true
});
};
_this.resetPagination();
_this.registerKeyboardShortcuts();
angular__WEBPACK_IMPORTED_MODULE_10___default.a.element(document).ready(function () {
_this.reloadPreferences();
});
application.onUnlock(function () {
_this.streamNotesAndTags();
_this.reloadPreferences();
});
return _this;
}
/** @override */
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(NotesCtrl, [{
key: "onAppStateEvent",
value: function onAppStateEvent(eventName, data) {
if (eventName === _state__WEBPACK_IMPORTED_MODULE_14__["AppStateEvents"].TagChanged) {
this.handleTagChange(this.appState.getSelectedTag(), data.previousTag);
} else if (eventName === _state__WEBPACK_IMPORTED_MODULE_14__["AppStateEvents"].NoteChanged) {
this.handleNoteSelection(this.appState.getSelectedNote());
} else if (eventName === _state__WEBPACK_IMPORTED_MODULE_14__["AppStateEvents"].PreferencesChanged) {
this.reloadPreferences();
this.reloadNotes();
} else if (eventName === _state__WEBPACK_IMPORTED_MODULE_14__["AppStateEvents"].EditorFocused) {
this.setShowMenuFalse();
}
}
/** @override */
}, {
key: "onApplicationEvent",
value: function onApplicationEvent(eventName) {
var _this2 = this;
if (eventName === snjs__WEBPACK_IMPORTED_MODULE_12__["ApplicationEvents"].SignedIn) {
/** Delete dummy note if applicable */
if (this.state.selectedNote && this.state.selectedNote.dummy) {
this.application.deleteItemLocally({
item: this.state.selectedNote
});
this.selectNote(null).then(function () {
_this2.reloadNotes();
});
/**
* We want to see if the user will download any items from the server.
* If the next sync completes and our notes are still 0,
* we need to create a dummy.
*/
this.createDummyOnSynCompletionIfNoNotes = true;
}
} else if (eventName === snjs__WEBPACK_IMPORTED_MODULE_12__["ApplicationEvents"].CompletedSync) {
if (this.createDummyOnSynCompletionIfNoNotes && this.state.notes.length === 0) {
this.createDummyOnSynCompletionIfNoNotes = false;
this.createNewNote();
}
}
}
}, {
key: "streamNotesAndTags",
value: function streamNotesAndTags() {
var _this3 = this;
this.application.streamItems({
contentType: [snjs__WEBPACK_IMPORTED_MODULE_12__["ContentTypes"].Note, snjs__WEBPACK_IMPORTED_MODULE_12__["ContentTypes"].Tag],
stream: function () {
var _stream = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(_ref) {
var items, selectedNote, discarded, notIncluded, notes, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, note;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
items = _ref.items;
_context.next = 3;
return _this3.reloadNotes();
case 3:
selectedNote = _this3.state.selectedNote;
if (selectedNote) {
discarded = selectedNote.deleted || selectedNote.content.trashed;
notIncluded = !_this3.state.notes.includes(selectedNote);
if (notIncluded || discarded) {
_this3.selectNextOrCreateNew();
}
} else {
_this3.selectFirstNote();
}
/** Note has changed values, reset its flags */
notes = items.filter(function (item) {
return item.content_type === snjs__WEBPACK_IMPORTED_MODULE_12__["ContentTypes"].Note;
});
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
_context.prev = 9;
for (_iterator = notes[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
note = _step.value;
_this3.loadFlagsForNote(note);
note.cachedCreatedAtString = note.createdAtString();
note.cachedUpdatedAtString = note.updatedAtString();
}
_context.next = 17;
break;
case 13:
_context.prev = 13;
_context.t0 = _context["catch"](9);
_didIteratorError = true;
_iteratorError = _context.t0;
case 17:
_context.prev = 17;
_context.prev = 18;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 20:
_context.prev = 20;
if (!_didIteratorError) {
_context.next = 23;
break;
}
throw _iteratorError;
case 23:
return _context.finish(20);
case 24:
return _context.finish(17);
case 25:
case "end":
return _context.stop();
}
}
}, _callee, null, [[9, 13, 17, 25], [18,, 20, 24]]);
}));
function stream(_x) {
return _stream.apply(this, arguments);
}
return stream;
}()
});
}
}, {
key: "handleTagChange",
value: function () {
var _handleTagChange = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(tag, previousTag) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!(this.state.selectedNote && this.state.selectedNote.dummy)) {
_context2.next = 5;
break;
}
this.application.deleteItemLocally({
item: this.state.selectedNote
});
if (previousTag) {
lodash__WEBPACK_IMPORTED_MODULE_9___default.a.remove(previousTag.notes, this.state.selectedNote);
}
_context2.next = 5;
return this.selectNote(null);
case 5:
_context2.next = 7;
return this.setState({
tag: tag
});
case 7:
this.resetScrollPosition();
this.setShowMenuFalse();
this.setNoteFilterText('');
this.desktopManager.searchText();
this.resetPagination();
_context2.next = 14;
return this.reloadNotes();
case 14:
if (this.state.notes.length > 0) {
this.selectFirstNote();
} else if (this.application.isDatabaseLoaded()) {
if (!tag.isSmartTag() || tag.content.isAllTag) {
this.createNewNote();
} else if (this.state.selectedNote && !this.state.notes.includes(this.state.selectedNote)) {
this.selectNote(null);
}
}
case 15:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function handleTagChange(_x2, _x3) {
return _handleTagChange.apply(this, arguments);
}
return handleTagChange;
}()
}, {
key: "resetScrollPosition",
value: function resetScrollPosition() {
var scrollable = document.getElementById(ELEMENT_ID_SCROLL_CONTAINER);
if (scrollable) {
scrollable.scrollTop = 0;
scrollable.scrollLeft = 0;
}
}
/**
* @template
* @internal
*/
}, {
key: "selectNote",
value: function () {
var _selectNote = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(note) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
this.appState.setSelectedNote(note);
case 1:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function selectNote(_x4) {
return _selectNote.apply(this, arguments);
}
return selectNote;
}()
}, {
key: "removeNoteFromList",
value: function () {
var _removeNoteFromList = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(note) {
var notes;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
notes = this.state.notes;
lodash__WEBPACK_IMPORTED_MODULE_9___default.a.pull(notes, note);
_context4.next = 4;
return this.setState({
notes: notes,
renderedNotes: notes.slice(0, this.notesToDisplay)
});
case 4:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function removeNoteFromList(_x5) {
return _removeNoteFromList.apply(this, arguments);
}
return removeNoteFromList;
}()
}, {
key: "reloadNotes",
value: function () {
var _reloadNotes = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5() {
var notes, _iteratorNormalCompletion2, _didIteratorError2, _iteratorError2, _iterator2, _step2, note;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
if (this.state.tag) {
_context5.next = 2;
break;
}
return _context5.abrupt("return");
case 2:
notes = Object(_note_utils__WEBPACK_IMPORTED_MODULE_18__["filterAndSortNotes"])({
notes: this.state.tag.notes,
selectedTag: this.state.tag,
showArchived: this.state.showArchived,
hidePinned: this.state.hidePinned,
filterText: this.state.noteFilter.text,
sortBy: this.state.sortBy,
reverse: this.state.sortReverse
});
_iteratorNormalCompletion2 = true;
_didIteratorError2 = false;
_iteratorError2 = undefined;
_context5.prev = 6;
for (_iterator2 = notes[Symbol.iterator](); !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
note = _step2.value;
if (note.errorDecrypting) {
this.loadFlagsForNote(note);
}
note.shouldShowTags = this.shouldShowTagsForNote(note);
}
_context5.next = 14;
break;
case 10:
_context5.prev = 10;
_context5.t0 = _context5["catch"](6);
_didIteratorError2 = true;
_iteratorError2 = _context5.t0;
case 14:
_context5.prev = 14;
_context5.prev = 15;
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
case 17:
_context5.prev = 17;
if (!_didIteratorError2) {
_context5.next = 20;
break;
}
throw _iteratorError2;
case 20:
return _context5.finish(17);
case 21:
return _context5.finish(14);
case 22:
_context5.next = 24;
return this.setState({
notes: notes,
renderedNotes: notes.slice(0, this.notesToDisplay)
});
case 24:
this.reloadPanelTitle();
case 25:
case "end":
return _context5.stop();
}
}
}, _callee5, this, [[6, 10, 14, 22], [15,, 17, 21]]);
}));
function reloadNotes() {
return _reloadNotes.apply(this, arguments);
}
return reloadNotes;
}()
}, {
key: "setShowMenuFalse",
value: function setShowMenuFalse() {
this.setState({
mutable: _objectSpread({}, this.state.mutable, {
showMenu: false
})
});
}
}, {
key: "handleNoteSelection",
value: function () {
var _handleNoteSelection = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee6(note) {
var previousNote;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
if (!(this.state.selectedNote === note)) {
_context6.next = 2;
break;
}
return _context6.abrupt("return");
case 2:
previousNote = this.state.selectedNote;
if (previousNote && previousNote.dummy) {
this.application.deleteItemLocally({
item: previousNote
});
this.removeNoteFromList(previousNote);
}
_context6.next = 6;
return this.setState({
selectedNote: note
});
case 6:
if (note) {
_context6.next = 8;
break;
}
return _context6.abrupt("return");
case 8:
this.selectedIndex = Math.max(0, this.displayableNotes().indexOf(note));
if (note.content.conflict_of) {
note.content.conflict_of = null;
this.application.saveItem({
item: note
});
}
if (this.isFiltering()) {
this.desktopManager.searchText(this.state.noteFilter.text);
}
case 11:
case "end":
return _context6.stop();
}
}
}, _callee6, this);
}));
function handleNoteSelection(_x6) {
return _handleNoteSelection.apply(this, arguments);
}
return handleNoteSelection;
}()
}, {
key: "reloadPreferences",
value: function reloadPreferences() {
var viewOptions = {};
var prevSortValue = this.state.sortBy;
var sortBy = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PrefKeys"].SortNotesBy, _note_utils__WEBPACK_IMPORTED_MODULE_18__["SORT_KEY_CREATED_AT"]);
if (sortBy === _note_utils__WEBPACK_IMPORTED_MODULE_18__["SORT_KEY_UPDATED_AT"]) {
/** Use client_updated_at instead */
sortBy = _note_utils__WEBPACK_IMPORTED_MODULE_18__["SORT_KEY_CLIENT_UPDATED_AT"];
}
viewOptions.sortBy = sortBy;
viewOptions.sortReverse = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PrefKeys"].SortNotesReverse, false);
viewOptions.showArchived = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PrefKeys"].NotesShowArchived, false);
viewOptions.hidePinned = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PrefKeys"].NotesHidePinned, false);
viewOptions.hideNotePreview = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PrefKeys"].NotesHideNotePreview, false);
viewOptions.hideDate = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PrefKeys"].NotesHideDate, false);
viewOptions.hideTags = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PrefKeys"].NotesHideTags, false);
this.setState(_objectSpread({}, viewOptions));
if (prevSortValue && prevSortValue !== sortBy) {
this.selectFirstNote();
}
var width = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PrefKeys"].NotesPanelWidth);
if (width) {
this.panelController.setWidth(width);
if (this.panelController.isCollapsed()) {
this.appState.panelDidResize({
name: _controllers_constants__WEBPACK_IMPORTED_MODULE_17__["PANEL_NAME_NOTES"],
collapsed: this.panelController.isCollapsed()
});
}
}
}
}, {
key: "paginate",
value: function paginate() {
this.notesToDisplay += this.pageSize;
this.reloadNotes();
if (this.searchSubmitted) {
this.desktopManager.searchText(this.state.noteFilter.text);
}
}
}, {
key: "resetPagination",
value: function resetPagination() {
var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
keepCurrentIfLarger = _ref2.keepCurrentIfLarger;
var clientHeight = document.documentElement.clientHeight;
this.pageSize = Math.ceil(clientHeight / MIN_NOTE_CELL_HEIGHT);
if (this.pageSize === 0) {
this.pageSize = DEFAULT_LIST_NUM_NOTES;
}
if (keepCurrentIfLarger && this.notesToDisplay > this.pageSize) {
return;
}
this.notesToDisplay = this.pageSize;
}
}, {
key: "reloadPanelTitle",
value: function reloadPanelTitle() {
var title;
if (this.isFiltering()) {
var resultCount = this.state.notes.length;
title = "".concat(resultCount, " search results");
} else if (this.state.tag) {
title = "".concat(this.state.tag.title);
}
this.setState({
panelTitle: title
});
}
}, {
key: "optionsSubtitle",
value: function optionsSubtitle() {
var base = "";
if (this.state.sortBy === 'created_at') {
base += " Date Added";
} else if (this.state.sortBy === 'client_updated_at') {
base += " Date Modified";
} else if (this.state.sortBy === 'title') {
base += " Title";
}
if (this.state.showArchived) {
base += " | + Archived";
}
if (this.state.hidePinned) {
base += " | – Pinned";
}
if (this.state.sortReverse) {
base += " | Reversed";
}
return base;
}
}, {
key: "loadFlagsForNote",
value: function loadFlagsForNote(note) {
var flags = [];
if (note.pinned) {
flags.push({
text: "Pinned",
class: 'info'
});
}
if (note.archived) {
flags.push({
text: "Archived",
class: 'warning'
});
}
if (note.content.protected) {
flags.push({
text: "Protected",
class: 'success'
});
}
if (note.locked) {
flags.push({
text: "Locked",
class: 'neutral'
});
}
if (note.content.trashed) {
flags.push({
text: "Deleted",
class: 'danger'
});
}
if (note.content.conflict_of) {
flags.push({
text: "Conflicted Copy",
class: 'danger'
});
}
if (note.errorDecrypting) {
flags.push({
text: "Missing Keys",
class: 'danger'
});
}
if (note.deleted) {
flags.push({
text: "Deletion Pending Sync",
class: 'danger'
});
}
note.flags = flags;
return flags;
}
}, {
key: "displayableNotes",
value: function displayableNotes() {
return this.state.notes;
}
}, {
key: "getFirstNonProtectedNote",
value: function getFirstNonProtectedNote() {
var displayableNotes = this.displayableNotes();
var index = 0;
var note = displayableNotes[index];
while (note && note.content.protected) {
index++;
if (index >= displayableNotes.length) {
break;
}
note = displayableNotes[index];
}
return note;
}
}, {
key: "selectFirstNote",
value: function selectFirstNote() {
var note = this.getFirstNonProtectedNote();
if (note) {
this.selectNote(note);
}
}
}, {
key: "selectNextNote",
value: function selectNextNote() {
var displayableNotes = this.displayableNotes();
var currentIndex = displayableNotes.indexOf(this.state.selectedNote);
if (currentIndex + 1 < displayableNotes.length) {
this.selectNote(displayableNotes[currentIndex + 1]);
}
}
}, {
key: "selectNextOrCreateNew",
value: function selectNextOrCreateNew() {
var note = this.getFirstNonProtectedNote();
if (note) {
this.selectNote(note);
} else if (!this.state.tag || !this.state.tag.isSmartTag()) {
this.createNewNote();
} else {
this.selectNote(null);
}
}
}, {
key: "selectPreviousNote",
value: function selectPreviousNote() {
var displayableNotes = this.displayableNotes();
var currentIndex = displayableNotes.indexOf(this.state.selectedNote);
if (currentIndex - 1 >= 0) {
this.selectNote(displayableNotes[currentIndex - 1]);
return true;
} else {
return false;
}
}
}, {
key: "createNewNote",
value: function () {
var _createNewNote = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee7() {
var selectedTag, title, newNote;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
selectedTag = this.appState.getSelectedTag();
if (selectedTag) {
_context7.next = 3;
break;
}
throw 'Attempting to create note with no selected tag';
case 3:
if (!(this.state.selectedNote && this.state.selectedNote.dummy)) {
_context7.next = 5;
break;
}
return _context7.abrupt("return");
case 5:
title = "Note" + (this.state.notes ? " " + (this.state.notes.length + 1) : "");
_context7.next = 8;
return this.application.createItem({
contentType: snjs__WEBPACK_IMPORTED_MODULE_12__["ContentTypes"].Note,
content: {
text: '',
title: title
},
add: true
});
case 8:
newNote = _context7.sent;
newNote.client_updated_at = new Date();
newNote.dummy = true;
this.application.setItemNeedsSync({
item: newNote
});
if (!selectedTag.isSmartTag()) {
selectedTag.addItemAsRelationship(newNote);
this.application.setItemNeedsSync({
item: selectedTag
});
}
this.selectNote(newNote);
case 14:
case "end":
return _context7.stop();
}
}
}, _callee7, this);
}));
function createNewNote() {
return _createNewNote.apply(this, arguments);
}
return createNewNote;
}()
}, {
key: "isFiltering",
value: function isFiltering() {
return this.state.noteFilter.text && this.state.noteFilter.text.length > 0;
}
}, {
key: "setNoteFilterText",
value: function () {
var _setNoteFilterText = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee8(text) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
_context8.next = 2;
return this.setState({
noteFilter: _objectSpread({}, this.state.noteFilter, {
text: text
})
});
case 2:
case "end":
return _context8.stop();
}
}
}, _callee8, this);
}));
function setNoteFilterText(_x7) {
return _setNoteFilterText.apply(this, arguments);
}
return setNoteFilterText;
}()
}, {
key: "clearFilterText",
value: function () {
var _clearFilterText = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee9() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
_context9.next = 2;
return this.setNoteFilterText('');
case 2:
this.onFilterEnter();
this.filterTextChanged();
this.resetPagination();
case 5:
case "end":
return _context9.stop();
}
}
}, _callee9, this);
}));
function clearFilterText() {
return _clearFilterText.apply(this, arguments);
}
return clearFilterText;
}()
}, {
key: "filterTextChanged",
value: function () {
var _filterTextChanged = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee10() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
if (this.searchSubmitted) {
this.searchSubmitted = false;
}
_context10.next = 3;
return this.reloadNotes();
case 3:
if (!this.state.notes.includes(this.state.selectedNote)) {
this.selectFirstNote();
}
case 4:
case "end":
return _context10.stop();
}
}
}, _callee10, this);
}));
function filterTextChanged() {
return _filterTextChanged.apply(this, arguments);
}
return filterTextChanged;
}()
}, {
key: "onFilterEnter",
value: function onFilterEnter() {
/**
* For Desktop, performing a search right away causes
* input to lose focus. We wait until user explicity hits
* enter before highlighting desktop search results.
*/
this.searchSubmitted = true;
this.desktopManager.searchText(this.state.noteFilter.text);
}
}, {
key: "selectedMenuItem",
value: function selectedMenuItem() {
this.setShowMenuFalse();
}
}, {
key: "togglePrefKey",
value: function togglePrefKey(key) {
this.preferencesManager.setUserPrefValue(key, !this.state[key]);
this.preferencesManager.syncUserPreferences();
}
}, {
key: "selectedSortByCreated",
value: function selectedSortByCreated() {
this.setSortBy(_note_utils__WEBPACK_IMPORTED_MODULE_18__["SORT_KEY_CREATED_AT"]);
}
}, {
key: "selectedSortByUpdated",
value: function selectedSortByUpdated() {
this.setSortBy(_note_utils__WEBPACK_IMPORTED_MODULE_18__["SORT_KEY_CLIENT_UPDATED_AT"]);
}
}, {
key: "selectedSortByTitle",
value: function selectedSortByTitle() {
this.setSortBy(_note_utils__WEBPACK_IMPORTED_MODULE_18__["SORT_KEY_TITLE"]);
}
}, {
key: "toggleReverseSort",
value: function toggleReverseSort() {
this.selectedMenuItem();
this.preferencesManager.setUserPrefValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PrefKeys"].SortNotesReverse, !this.state.sortReverse);
this.preferencesManager.syncUserPreferences();
}
}, {
key: "setSortBy",
value: function setSortBy(type) {
this.preferencesManager.setUserPrefValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_16__["PrefKeys"].SortNotesBy, type);
this.preferencesManager.syncUserPreferences();
}
}, {
key: "shouldShowTagsForNote",
value: function shouldShowTagsForNote(note) {
if (this.state.hideTags || note.content.protected) {
return false;
}
if (this.state.tag.content.isAllTag) {
return note.tags && note.tags.length > 0;
}
if (this.state.tag.isSmartTag()) {
return true;
}
/**
* Inside a tag, only show tags string if
* note contains tags other than this.state.tag
*/
return note.tags && note.tags.length > 1;
}
}, {
key: "getSearchBar",
value: function getSearchBar() {
return document.getElementById(ELEMENT_ID_SEARCH_BAR);
}
}, {
key: "registerKeyboardShortcuts",
value: function registerKeyboardShortcuts() {
var _this4 = this;
/**
* In the browser we're not allowed to override cmd/ctrl + n, so we have to
* use Control modifier as well. These rules don't apply to desktop, but
* probably better to be consistent.
*/
this.newNoteKeyObserver = this.keyboardManager.addKeyObserver({
key: 'n',
modifiers: [_services_keyboardManager__WEBPACK_IMPORTED_MODULE_15__["KeyboardModifiers"].Meta, _services_keyboardManager__WEBPACK_IMPORTED_MODULE_15__["KeyboardModifiers"].Ctrl],
onKeyDown: function onKeyDown(event) {
event.preventDefault();
_this4.createNewNote();
}
});
this.nextNoteKeyObserver = this.keyboardManager.addKeyObserver({
key: _services_keyboardManager__WEBPACK_IMPORTED_MODULE_15__["KeyboardKeys"].Down,
elements: [document.body, this.getSearchBar()],
onKeyDown: function onKeyDown(event) {
var searchBar = _this4.getSearchBar();
if (searchBar === document.activeElement) {
searchBar.blur();
}
_this4.selectNextNote();
}
});
this.nextNoteKeyObserver = this.keyboardManager.addKeyObserver({
key: _services_keyboardManager__WEBPACK_IMPORTED_MODULE_15__["KeyboardKeys"].Up,
element: document.body,
onKeyDown: function onKeyDown(event) {
_this4.selectPreviousNote();
}
});
this.searchKeyObserver = this.keyboardManager.addKeyObserver({
key: "f",
modifiers: [_services_keyboardManager__WEBPACK_IMPORTED_MODULE_15__["KeyboardModifiers"].Meta, _services_keyboardManager__WEBPACK_IMPORTED_MODULE_15__["KeyboardModifiers"].Shift],
onKeyDown: function onKeyDown(event) {
var searchBar = _this4.getSearchBar();
if (searchBar) {
searchBar.focus();
}
;
}
});
}
}]);
return NotesCtrl;
}(_Controllers__WEBPACK_IMPORTED_MODULE_13__["PureCtrl"]);
var NotesPanel = function NotesPanel() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, NotesPanel);
this.scope = {};
this.template = _notes_pug__WEBPACK_IMPORTED_MODULE_11___default.a;
this.replace = true;
this.controller = NotesCtrl;
this.controllerAs = 'self';
this.bindToController = true;
};
/***/ }),
/***/ "./app/assets/javascripts/controllers/root.js":
/*!****************************************************!*\
!*** ./app/assets/javascripts/controllers/root.js ***!
\****************************************************/
/*! exports provided: Root */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Root", function() { return Root; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var _root_pug__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! %/root.pug */ "./app/assets/templates/root.pug");
/* harmony import */ var _root_pug__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_root_pug__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/state */ "./app/assets/javascripts/state.js");
/* harmony import */ var _controllers_constants__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/controllers/constants */ "./app/assets/javascripts/controllers/constants.js");
/* harmony import */ var _strings__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/strings */ "./app/assets/javascripts/strings.js");
/* harmony import */ var _abstract_pure_ctrl__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./abstract/pure_ctrl */ "./app/assets/javascripts/controllers/abstract/pure_ctrl.js");
var RootCtrl =
/*#__PURE__*/
function (_PureCtrl) {
RootCtrl.$inject = ["$location", "$scope", "$rootScope", "$timeout", "application", "appState", "desktopManager", "lockManager", "preferencesManager", "themeManager", "statusManager"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6___default()(RootCtrl, _PureCtrl);
/* @ngInject */
function RootCtrl($location, $scope, $rootScope, $timeout, application, appState, desktopManager, lockManager, preferencesManager
/** Unused below, required to load globally */
, themeManager, statusManager) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, RootCtrl);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(RootCtrl).call(this, $scope, $timeout, application, appState));
_this.$location = $location;
_this.$rootScope = $rootScope;
_this.desktopManager = desktopManager;
_this.lockManager = lockManager;
_this.statusManager = statusManager;
_this.themeManager = themeManager;
_this.platformString = Object(_utils__WEBPACK_IMPORTED_MODULE_8__["getPlatformString"])();
_this.state = {
needsUnlock: true,
appClass: ''
};
_this.loadApplication();
_this.addDragDropHandlers();
application.onUnlock(function () {
_this.handleAutoSignInFromParams();
});
_this.lockScreenPuppet = {
focusInput: function focusInput() {}
};
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(RootCtrl, [{
key: "watchLockscreenValue",
value: function () {
var _watchLockscreenValue = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var _this2 = this;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", new Promise(function (resolve) {
var onLockscreenValue = function onLockscreenValue(value) {
resolve(new snjs__WEBPACK_IMPORTED_MODULE_7__["ChallengeResponse"]({
challenge: snjs__WEBPACK_IMPORTED_MODULE_7__["Challenges"].LocalPasscode,
value: value
}));
};
_this2.setState({
onLockscreenValue: onLockscreenValue
});
}));
case 1:
case "end":
return _context.stop();
}
}
}, _callee);
}));
function watchLockscreenValue() {
return _watchLockscreenValue.apply(this, arguments);
}
return watchLockscreenValue;
}()
}, {
key: "loadApplication",
value: function () {
var _loadApplication = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3() {
var _this3 = this;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return this.application.prepareForLaunch({
callbacks: {
requiresChallengeResponses: function () {
var _requiresChallengeResponses = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(challenges) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (challenges.includes(snjs__WEBPACK_IMPORTED_MODULE_7__["Challenges"].LocalPasscode)) {
_this3.setState({
needsUnlock: true
});
}
return _context2.abrupt("return", _this3.watchLockscreenValue());
case 2:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
function requiresChallengeResponses(_x) {
return _requiresChallengeResponses.apply(this, arguments);
}
return requiresChallengeResponses;
}(),
handleChallengeFailures: function handleChallengeFailures(responses) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = responses[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var response = _step.value;
if (response.challenge === snjs__WEBPACK_IMPORTED_MODULE_7__["Challenges"].LocalPasscode) {
_this3.application.alertManager.alert({
text: "Invalid passcode. Please try again.",
onClose: function onClose() {
_this3.lockScreenPuppet.focusInput();
}
});
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
}
});
case 2:
_context3.next = 4;
return this.application.launch();
case 4:
this.setState({
needsUnlock: false
});
this.application.componentManager.setDesktopManager(this.desktopManager);
this.application.registerService(this.themeManager); // this.addSyncStatusObserver();
// this.addSyncEventHandler();
case 7:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function loadApplication() {
return _loadApplication.apply(this, arguments);
}
return loadApplication;
}()
}, {
key: "onUpdateAvailable",
value: function onUpdateAvailable() {
this.$rootScope.$broadcast('new-update-available');
}
}, {
key: "onAppStateEvent",
/** @override */
value: function () {
var _onAppStateEvent = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(eventName, data) {
var appClass;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (!(eventName === _state__WEBPACK_IMPORTED_MODULE_10__["AppStateEvents"].PanelResized)) {
_context4.next = 9;
break;
}
if (data.panel === _controllers_constants__WEBPACK_IMPORTED_MODULE_11__["PANEL_NAME_NOTES"]) {
this.notesCollapsed = data.collapsed;
}
if (data.panel === _controllers_constants__WEBPACK_IMPORTED_MODULE_11__["PANEL_NAME_TAGS"]) {
this.tagsCollapsed = data.collapsed;
}
appClass = "";
if (this.notesCollapsed) {
appClass += "collapsed-notes";
}
if (this.tagsCollapsed) {
appClass += " collapsed-tags";
}
this.setState({
appClass: appClass
});
_context4.next = 14;
break;
case 9:
if (!(eventName === _state__WEBPACK_IMPORTED_MODULE_10__["AppStateEvents"].WindowDidFocus)) {
_context4.next = 14;
break;
}
_context4.next = 12;
return this.application.isPasscodeLocked();
case 12:
if (_context4.sent) {
_context4.next = 14;
break;
}
this.application.sync();
case 14:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function onAppStateEvent(_x2, _x3) {
return _onAppStateEvent.apply(this, arguments);
}
return onAppStateEvent;
}() // addSyncStatusObserver() {
// this.syncStatusObserver = syncManager.registerSyncStatusObserver((status) => {
// if (status.retrievedCount > 20) {
// const text = `Downloading ${status.retrievedCount} items. Keep app open.`;
// this.syncStatus = this.statusManager.replaceStatusWithString(
// this.syncStatus,
// text
// );
// this.showingDownloadStatus = true;
// } else if (this.showingDownloadStatus) {
// this.showingDownloadStatus = false;
// const text = "Download Complete.";
// this.syncStatus = this.statusManager.replaceStatusWithString(
// this.syncStatus,
// text
// );
// setTimeout(() => {
// this.syncStatus = this.statusManager.removeStatus(this.syncStatus);
// }, 2000);
// } else if (status.total > 20) {
// this.uploadSyncStatus = this.statusManager.replaceStatusWithString(
// this.uploadSyncStatus,
// `Syncing ${status.current}/${status.total} items...`
// );
// } else if (this.uploadSyncStatus) {
// this.uploadSyncStatus = this.statusManager.removeStatus(
// this.uploadSyncStatus
// );
// }
// });
// }
// addSyncEventHandler() {
// let lastShownDate;
// syncManager.addEventHandler((syncEvent, data) => {
// this.$rootScope.$broadcast(
// syncEvent,
// data || {}
// );
// if (syncEvent === 'sync-session-invalid') {
// /** Don't show repeatedly; at most 30 seconds in between */
// const SHOW_INTERVAL = 30;
// const lastShownSeconds = (new Date() - lastShownDate) / 1000;
// if (!lastShownDate || lastShownSeconds > SHOW_INTERVAL) {
// lastShownDate = new Date();
// setTimeout(() => {
// this.alertManager.alert({
// text: STRING_SESSION_EXPIRED
// });
// }, 500);
// }
// } else if (syncEvent === 'sync-exception') {
// this.alertManager.alert({
// text: StringSyncException(data)
// });
// }
// });
// }
// loadLocalData() {
// const encryptionEnabled = this.application.getUser || this.application.hasPasscode();
// this.syncStatus = this.statusManager.addStatusFromString(
// encryptionEnabled ? "Decrypting items..." : "Loading items..."
// );
// const incrementalCallback = (current, total) => {
// const notesString = `${current}/${total} items...`;
// const status = encryptionEnabled
// ? `Decrypting ${notesString}`
// : `Loading ${notesString}`;
// this.syncStatus = this.statusManager.replaceStatusWithString(
// this.syncStatus,
// status
// );
// };
// syncManager.loadLocalItems({ incrementalCallback }).then(() => {
// this.$timeout(() => {
// this.$rootScope.$broadcast("initial-data-loaded");
// this.syncStatus = this.statusManager.replaceStatusWithString(
// this.syncStatus,
// "Syncing..."
// );
// syncManager.sync({
// checkIntegrity: true
// }).then(() => {
// this.syncStatus = this.statusManager.removeStatus(this.syncStatus);
// });
// });
// });
// }
}, {
key: "addDragDropHandlers",
value: function addDragDropHandlers() {
var _this4 = this;
/**
* Disable dragging and dropping of files (but allow text) into main SN interface.
* both 'dragover' and 'drop' are required to prevent dropping of files.
* This will not prevent extensions from receiving drop events.
*/
window.addEventListener('dragover', function (event) {
if (event.dataTransfer.files.length > 0) {
event.preventDefault();
}
}, false);
window.addEventListener('drop', function (event) {
if (event.dataTransfer.files.length > 0) {
event.preventDefault();
_this4.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_12__["STRING_DEFAULT_FILE_ERROR"]
});
}
}, false);
}
}, {
key: "handleAutoSignInFromParams",
value: function handleAutoSignInFromParams() {
var _this5 = this;
var urlParam = function urlParam(key) {
return _this5.$location.search()[key];
};
var autoSignInFromParams =
/*#__PURE__*/
function () {
var _ref = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5() {
var server, email, pw;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
server = urlParam('server');
email = urlParam('email');
pw = urlParam('pw');
if (_this5.application.getUser()) {
_context5.next = 21;
break;
}
_context5.next = 6;
return _this5.application.getHost();
case 6:
_context5.t1 = _context5.sent;
_context5.t2 = server;
_context5.t0 = _context5.t1 === _context5.t2;
if (!_context5.t0) {
_context5.next = 11;
break;
}
_context5.t0 = _this5.application.getUser().email === email;
case 11:
if (!_context5.t0) {
_context5.next = 15;
break;
}
return _context5.abrupt("return");
case 15:
_context5.next = 17;
return _this5.application.signOut();
case 17:
_context5.next = 19;
return _this5.application.restart();
case 19:
_context5.next = 24;
break;
case 21:
_context5.next = 23;
return _this5.application.setHost(server);
case 23:
_this5.application.signIn({
email: email,
password: pw
});
case 24:
case "end":
return _context5.stop();
}
}
}, _callee5);
}));
return function autoSignInFromParams() {
return _ref.apply(this, arguments);
};
}();
if (urlParam('server')) {
autoSignInFromParams();
}
}
}]);
return RootCtrl;
}(_abstract_pure_ctrl__WEBPACK_IMPORTED_MODULE_13__["PureCtrl"]);
var Root = function Root() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, Root);
this.template = _root_pug__WEBPACK_IMPORTED_MODULE_9___default.a;
this.controller = RootCtrl;
this.replace = true;
this.controllerAs = 'self';
this.bindToController = true;
};
/***/ }),
/***/ "./app/assets/javascripts/controllers/tags.js":
/*!****************************************************!*\
!*** ./app/assets/javascripts/controllers/tags.js ***!
\****************************************************/
/*! exports provided: TagsPanel */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TagsPanel", function() { return TagsPanel; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js");
/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _tags_pug__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! %/tags.pug */ "./app/assets/templates/tags.pug");
/* harmony import */ var _tags_pug__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(_tags_pug__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/state */ "./app/assets/javascripts/state.js");
/* harmony import */ var _controllers_constants__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/controllers/constants */ "./app/assets/javascripts/controllers/constants.js");
/* harmony import */ var _services_preferencesManager__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/services/preferencesManager */ "./app/assets/javascripts/services/preferencesManager.js");
/* harmony import */ var _strings__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @/strings */ "./app/assets/javascripts/strings.js");
/* harmony import */ var _Controllers__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @Controllers */ "./app/assets/javascripts/controllers/index.js");
var TagsPanelCtrl =
/*#__PURE__*/
function (_PureCtrl) {
TagsPanelCtrl.$inject = ["$scope", "$rootScope", "$timeout", "application", "appState", "preferencesManager"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default()(TagsPanelCtrl, _PureCtrl);
/* @ngInject */
function TagsPanelCtrl($scope, $rootScope, $timeout, application, appState, preferencesManager) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, TagsPanelCtrl);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(TagsPanelCtrl).call(this, $scope, $timeout, application, appState));
_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_8___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_6___default()(_this), "onPanelResize", function (newWidth, lastLeft, isAtMaxWidth, isCollapsed) {
_this.preferencesManager.setUserPrefValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_13__["PrefKeys"].TagsPanelWidth, newWidth, true);
_this.appState.panelDidResize({
name: _controllers_constants__WEBPACK_IMPORTED_MODULE_12__["PANEL_NAME_TAGS"],
collapsed: isCollapsed
});
});
_this.$rootScope = $rootScope;
_this.preferencesManager = preferencesManager;
_this.panelController = {};
_this.loadPreferences();
_this.registerComponentHandler();
_this.state = {
smartTags: [],
noteCounts: {}
};
application.onUnlock(function () {
_this.beginStreamingItems();
var smartTags = _this.application.getSmartTags();
_this.setState({
smartTags: smartTags
});
_this.selectTag(smartTags[0]);
});
application.onSync(function () {
_this.reloadNoteCounts();
});
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(TagsPanelCtrl, [{
key: "beginStreamingItems",
value: function beginStreamingItems() {
var _this2 = this;
this.application.streamItems({
contentType: snjs__WEBPACK_IMPORTED_MODULE_9__["ContentTypes"].Tag,
stream: function () {
var _stream = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(_ref) {
var items, selectedTag;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
items = _ref.items;
_context.next = 3;
return _this2.setState({
tags: _this2.application.getItems({
contentType: snjs__WEBPACK_IMPORTED_MODULE_9__["ContentTypes"].Tag
}),
smartTags: _this2.application.getSmartTags()
});
case 3:
_this2.reloadNoteCounts();
if (_this2.state.selectedTag) {
/** If the selected tag has been deleted, revert to All view. */
selectedTag = items.find(function (tag) {
return tag.uuid === _this2.state.selectedTag.uuid;
});
if (selectedTag && selectedTag.deleted) {
_this2.selectTag(_this2.state.smartTags[0]);
}
}
case 5:
case "end":
return _context.stop();
}
}
}, _callee);
}));
function stream(_x) {
return _stream.apply(this, arguments);
}
return stream;
}()
});
}
/** @override */
}, {
key: "onAppStateEvent",
value: function onAppStateEvent(eventName, data) {
if (eventName === _state__WEBPACK_IMPORTED_MODULE_11__["AppStateEvents"].PreferencesChanged) {
this.loadPreferences();
} else if (eventName === _state__WEBPACK_IMPORTED_MODULE_11__["AppStateEvents"].TagChanged) {
this.setState({
selectedTag: this.appState.getSelectedTag()
});
}
}
}, {
key: "reloadNoteCounts",
value: function reloadNoteCounts() {
var allTags = [];
if (this.state.tags) {
allTags = allTags.concat(this.state.tags);
}
if (this.state.smartTags) {
allTags = allTags.concat(this.state.smartTags);
}
var noteCounts = {};
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = allTags[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var tag = _step.value;
var validNotes = snjs__WEBPACK_IMPORTED_MODULE_9__["SNNote"].filterDummyNotes(tag.notes).filter(function (note) {
return !note.archived && !note.content.trashed;
});
noteCounts[tag.uuid] = validNotes.length;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
this.setState({
noteCounts: noteCounts
});
}
}, {
key: "loadPreferences",
value: function loadPreferences() {
var width = this.preferencesManager.getValue(_services_preferencesManager__WEBPACK_IMPORTED_MODULE_13__["PrefKeys"].TagsPanelWidth);
if (width) {
this.panelController.setWidth(width);
if (this.panelController.isCollapsed()) {
this.appState.panelDidResize({
name: _controllers_constants__WEBPACK_IMPORTED_MODULE_12__["PANEL_NAME_TAGS"],
collapsed: this.panelController.isCollapsed()
});
}
}
}
}, {
key: "registerComponentHandler",
value: function registerComponentHandler() {
var _this3 = this;
this.application.componentManager.registerHandler({
identifier: 'tags',
areas: ['tags-list'],
activationHandler: function activationHandler(component) {
_this3.component = component;
},
contextRequestHandler: function contextRequestHandler(component) {
return null;
},
actionHandler: function actionHandler(component, action, data) {
if (action === 'select-item') {
if (data.item.content_type === 'Tag') {
var tag = _this3.application.findItem({
uuid: data.item.uuid
});
if (tag) {
_this3.selectTag(tag);
}
} else if (data.item.content_type === 'SN|SmartTag') {
var smartTag = new snjs__WEBPACK_IMPORTED_MODULE_9__["SNSmartTag"](data.item);
_this3.selectTag(smartTag);
}
} else if (action === 'clear-selection') {
_this3.selectTag(_this3.state.smartTags[0]);
}
}
});
}
}, {
key: "selectTag",
value: function () {
var _selectTag = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(tag) {
var _this4 = this;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (tag.isSmartTag()) {
Object.defineProperty(tag, 'notes', {
get: function get() {
return _this4.application.getNotesMatchingSmartTag({
smartTag: tag
});
}
});
}
if (tag.content.conflict_of) {
tag.content.conflict_of = null;
this.application.saveItem({
item: tag
});
}
this.appState.setSelectedTag(tag);
case 3:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function selectTag(_x2) {
return _selectTag.apply(this, arguments);
}
return selectTag;
}()
}, {
key: "clickedAddNewTag",
value: function () {
var _clickedAddNewTag = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3() {
var newTag;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!this.state.editingTag) {
_context3.next = 2;
break;
}
return _context3.abrupt("return");
case 2:
_context3.next = 4;
return this.application.createItem({
contentType: snjs__WEBPACK_IMPORTED_MODULE_9__["ContentTypes"].Tag
});
case 4:
newTag = _context3.sent;
this.setState({
previousTag: this.state.selectedTag,
selectedTag: newTag,
editingTag: newTag,
newTag: newTag
});
/** @todo Should not be accessing internal function */
/** Rely on local state instead of adding to global state */
this.application.modelManager.insertItems({
items: [newTag]
});
case 7:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function clickedAddNewTag() {
return _clickedAddNewTag.apply(this, arguments);
}
return clickedAddNewTag;
}()
}, {
key: "tagTitleDidChange",
value: function tagTitleDidChange(tag) {
this.setState({
editingTag: tag
});
}
}, {
key: "saveTag",
value: function () {
var _saveTag = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4($event, tag) {
var matchingTag, alreadyExists;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
$event.target.blur();
_context4.next = 3;
return this.setState({
editingTag: null
});
case 3:
if (!(!tag.title || tag.title.length === 0)) {
_context4.next = 7;
break;
}
if (this.state.editingTag) {
tag.title = this.editingOriginalName;
this.editingOriginalName = null;
} else if (this.state.newTag) {
/** @todo Should not be accessing internal function */
/** Rely on local state instead of adding to global state */
this.application.modelManager.removeItemLocally(tag);
this.setState({
selectedTag: this.state.previousTag
});
}
this.setState({
newTag: null
});
return _context4.abrupt("return");
case 7:
this.editingOriginalName = null;
matchingTag = this.application.findTag({
title: tag.title
});
alreadyExists = matchingTag && matchingTag !== tag;
if (!(this.state.newTag === tag && alreadyExists)) {
_context4.next = 15;
break;
}
this.application.alertManager.alert({
text: "A tag with this name already exists."
});
/** @todo Should not be accessing internal function */
/** Rely on local state instead of adding to global state */
this.application.modelManager.removeItemLocally(tag);
this.setState({
newTag: null
});
return _context4.abrupt("return");
case 15:
this.application.saveItem({
item: tag
});
this.selectTag(tag);
this.setState({
newTag: null
});
case 18:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function saveTag(_x3, _x4) {
return _saveTag.apply(this, arguments);
}
return saveTag;
}()
}, {
key: "selectedRenameTag",
value: function () {
var _selectedRenameTag = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5($event, tag) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
this.editingOriginalName = tag.title;
_context5.next = 3;
return this.setState({
editingTag: tag
});
case 3:
document.getElementById('tag-' + tag.uuid).focus();
case 4:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function selectedRenameTag(_x5, _x6) {
return _selectedRenameTag.apply(this, arguments);
}
return selectedRenameTag;
}()
}, {
key: "selectedDeleteTag",
value: function selectedDeleteTag(tag) {
this.removeTag(tag);
this.selectTag(this.state.smartTags[0]);
}
}, {
key: "removeTag",
value: function removeTag(tag) {
var _this5 = this;
this.application.alertManager.confirm({
text: _strings__WEBPACK_IMPORTED_MODULE_14__["STRING_DELETE_TAG"],
destructive: true,
onConfirm: function onConfirm() {
_this5.application.deleteItem({
item: tag
});
}
});
}
}]);
return TagsPanelCtrl;
}(_Controllers__WEBPACK_IMPORTED_MODULE_15__["PureCtrl"]);
var TagsPanel = function TagsPanel() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, TagsPanel);
this.restrict = 'E';
this.scope = {};
this.template = _tags_pug__WEBPACK_IMPORTED_MODULE_10___default.a;
this.replace = true;
this.controller = TagsPanelCtrl;
this.controllerAs = 'self';
this.bindToController = true;
};
/***/ }),
/***/ "./app/assets/javascripts/database.js":
/*!********************************************!*\
!*** ./app/assets/javascripts/database.js ***!
\********************************************/
/*! exports provided: Database */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Database", function() { return Database; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
var Database =
/*#__PURE__*/
function () {
function Database() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, Database);
this.locked = true;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(Database, [{
key: "setApplication",
value: function setApplication(application) {
this.alertManager = application.alertManager;
}
}, {
key: "displayOfflineAlert",
value: function displayOfflineAlert() {
var message = "There was an issue loading your offline database. This could happen for two reasons:";
message += "\n\n1. You're in a private window in your browser. We can't save your data without access to the local database. Please use a non-private window.";
message += "\n\n2. You have two windows of the app open at the same time. Please close any other app instances and reload the page.";
this.alertManager.alert({
text: message
});
}
}, {
key: "setLocked",
value: function setLocked(locked) {
this.locked = locked;
}
}, {
key: "openDatabase",
value: function () {
var _openDatabase = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var _this = this;
var _ref,
onUpgradeNeeded,
request,
_args = arguments;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_ref = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}, onUpgradeNeeded = _ref.onUpgradeNeeded;
if (!this.locked) {
_context.next = 3;
break;
}
throw 'Attempting to open locked database';
case 3:
request = window.indexedDB.open('standardnotes', 1);
return _context.abrupt("return", new Promise(function (resolve, reject) {
request.onerror = function (event) {
if (event.target.errorCode) {
_this.alertManager.alert({
text: 'Offline database issue: ' + event.target.errorCode
});
} else {
_this.displayOfflineAlert();
}
console.error('Offline database issue:', event);
resolve(null);
};
request.onsuccess = function (event) {
var db = event.target.result;
db.onversionchange = function (event) {
db.close();
};
db.onerror = function (errorEvent) {
console.error('Database error: ' + errorEvent.target.errorCode);
};
resolve(db);
};
request.onblocked = function (event) {
console.error('Request blocked error:', event.target.errorCode);
};
request.onupgradeneeded = function (event) {
var db = event.target.result;
db.onversionchange = function (event) {
db.close();
}; // Create an objectStore for this database
var objectStore = db.createObjectStore('items', {
keyPath: 'uuid'
});
objectStore.createIndex('uuid', 'uuid', {
unique: true
});
objectStore.transaction.oncomplete = function (event) {
// Ready to store values in the newly created objectStore.
if (db.version === 1 && onUpgradeNeeded) {
onUpgradeNeeded();
}
};
};
}));
case 5:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function openDatabase() {
return _openDatabase.apply(this, arguments);
}
return openDatabase;
}()
}, {
key: "getAllPayloads",
value: function () {
var _getAllPayloads = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var db, objectStore, payloads;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.openDatabase();
case 2:
db = _context2.sent;
objectStore = db.transaction('items').objectStore('items');
payloads = [];
return _context2.abrupt("return", new Promise(function (resolve) {
objectStore.openCursor().onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
payloads.push(cursor.value);
cursor.continue();
} else {
resolve(payloads);
}
};
}));
case 6:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function getAllPayloads() {
return _getAllPayloads.apply(this, arguments);
}
return getAllPayloads;
}()
}, {
key: "savePayload",
value: function () {
var _savePayload = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(payload) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
this.savePayloads([payload]);
case 1:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function savePayload(_x) {
return _savePayload.apply(this, arguments);
}
return savePayload;
}()
}, {
key: "savePayloads",
value: function () {
var _savePayloads = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee6(payloads) {
var _this2 = this;
var showGenericError, db, transaction;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
showGenericError = function showGenericError(error) {
_this2.alertManager.alert({
text: "Unable to save changes locally due to an unknown system issue. Issue Code: ".concat(error.code, " Issue Name: ").concat(error.name, ".")
});
};
if (!(payloads.length === 0)) {
_context6.next = 3;
break;
}
return _context6.abrupt("return");
case 3:
_context6.next = 5;
return this.openDatabase();
case 5:
db = _context6.sent;
transaction = db.transaction('items', 'readwrite');
return _context6.abrupt("return", new Promise(
/*#__PURE__*/
function () {
var _ref2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5(resolve, reject) {
var payloadObjectStore, putPayload, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, payload;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
transaction.oncomplete = function (event) {};
transaction.onerror = function (event) {
console.error('Transaction error:', event.target.errorCode);
showGenericError(event.target.error);
};
transaction.onblocked = function (event) {
console.error('Transaction blocked error:', event.target.errorCode);
showGenericError(event.target.error);
};
transaction.onabort = function (event) {
console.error('Offline saving aborted:', event);
var error = event.target.error;
if (error.name === 'QuotaExceededError') {
this.alertManager.alert({
text: 'Unable to save changes locally because your device is out of space. Please free up some disk space and try again, otherwise, your data may end up in an inconsistent state.'
});
} else {
showGenericError(error);
}
reject(error);
};
payloadObjectStore = transaction.objectStore('items');
putPayload =
/*#__PURE__*/
function () {
var _ref3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(payload) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
return _context4.abrupt("return", new Promise(function (resolve, reject) {
var request = payloadObjectStore.put(payload);
request.onerror = function (event) {
console.error('DB put error:', event.target.error);
resolve();
};
request.onsuccess = resolve;
}));
case 1:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
return function putPayload(_x5) {
return _ref3.apply(this, arguments);
};
}();
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
_context5.prev = 9;
_iterator = payloads[Symbol.iterator]();
case 11:
if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
_context5.next = 18;
break;
}
payload = _step.value;
_context5.next = 15;
return putPayload(payload);
case 15:
_iteratorNormalCompletion = true;
_context5.next = 11;
break;
case 18:
_context5.next = 24;
break;
case 20:
_context5.prev = 20;
_context5.t0 = _context5["catch"](9);
_didIteratorError = true;
_iteratorError = _context5.t0;
case 24:
_context5.prev = 24;
_context5.prev = 25;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 27:
_context5.prev = 27;
if (!_didIteratorError) {
_context5.next = 30;
break;
}
throw _iteratorError;
case 30:
return _context5.finish(27);
case 31:
return _context5.finish(24);
case 32:
resolve();
case 33:
case "end":
return _context5.stop();
}
}
}, _callee5, null, [[9, 20, 24, 32], [25,, 27, 31]]);
}));
return function (_x3, _x4) {
return _ref2.apply(this, arguments);
};
}()));
case 8:
case "end":
return _context6.stop();
}
}
}, _callee6, this);
}));
function savePayloads(_x2) {
return _savePayloads.apply(this, arguments);
}
return savePayloads;
}()
}, {
key: "deletePayload",
value: function () {
var _deletePayload = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee7(uuid) {
var db, request;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
_context7.next = 2;
return this.openDatabase();
case 2:
db = _context7.sent;
request = db.transaction('items', 'readwrite').objectStore('items').delete(uuid);
return _context7.abrupt("return", new Promise(function (resolve, reject) {
request.onsuccess = function (event) {
resolve();
};
request.onerror = function (event) {
// eslint-disable-next-line prefer-promise-reject-errors
reject();
};
}));
case 5:
case "end":
return _context7.stop();
}
}
}, _callee7, this);
}));
function deletePayload(_x6) {
return _deletePayload.apply(this, arguments);
}
return deletePayload;
}()
}, {
key: "clearAllPayloads",
value: function () {
var _clearAllPayloads = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee8() {
var deleteRequest;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
deleteRequest = window.indexedDB.deleteDatabase('standardnotes');
return _context8.abrupt("return", new Promise(function (resolve, reject) {
deleteRequest.onerror = function (event) {
console.error('Error deleting database.');
resolve();
};
deleteRequest.onsuccess = function (event) {
resolve();
};
deleteRequest.onblocked = function (event) {
console.error('Delete request blocked');
this.alertManager.alert({
text: 'Your browser is blocking Standard Notes from deleting the local database. Make sure there are no other open windows of this app and try again. If the issue persists, please manually delete app data to sign out.'
});
resolve();
};
}));
case 2:
case "end":
return _context8.stop();
}
}
}, _callee8);
}));
function clearAllPayloads() {
return _clearAllPayloads.apply(this, arguments);
}
return clearAllPayloads;
}()
}]);
return Database;
}();
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/autofocus.js":
/*!*******************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/autofocus.js ***!
\*******************************************************************/
/*! exports provided: autofocus */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "autofocus", function() { return autofocus; });
autofocus.$inject = ["$timeout"];
/* @ngInject */
function autofocus($timeout) {
return {
restrict: 'A',
scope: {
shouldFocus: '='
},
link: function link($scope, $element) {
$timeout(function () {
if ($scope.shouldFocus) {
$element[0].focus();
}
});
}
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/click-outside.js":
/*!***********************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/click-outside.js ***!
\***********************************************************************/
/*! exports provided: clickOutside */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clickOutside", function() { return clickOutside; });
clickOutside.$inject = ["$document"];
/* @ngInject */
function clickOutside($document) {
return {
restrict: 'A',
replace: false,
link: function link($scope, $element, attrs) {
var didApplyClickOutside = false;
$element.bind('click', function (e) {
didApplyClickOutside = false;
if (attrs.isOpen) {
e.stopPropagation();
}
});
$document.bind('click', function () {
// Ignore click if on SKAlert
if (event.target.closest(".sk-modal")) {
return;
}
if (!didApplyClickOutside) {
$scope.$apply(attrs.clickOutside);
didApplyClickOutside = true;
}
});
}
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/delay-hide.js":
/*!********************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/delay-hide.js ***!
\********************************************************************/
/*! exports provided: delayHide */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "delayHide", function() { return delayHide; });
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_0__);
delayHide.$inject = ["$timeout"];
/* @ngInject */
function delayHide($timeout) {
return {
restrict: 'A',
scope: {
show: '=',
delay: '@'
},
link: function link(scope, elem, attrs) {
showElement(false); // This is where all the magic happens!
// Whenever the scope variable updates we simply
// show if it evaluates to 'true' and hide if 'false'
scope.$watch('show', function (newVal) {
newVal ? showSpinner() : hideSpinner();
});
function showSpinner() {
if (scope.hidePromise) {
$timeout.cancel(scope.hidePromise);
scope.hidePromise = null;
}
showElement(true);
}
function hideSpinner() {
scope.hidePromise = $timeout(showElement.bind(this, false), getDelay());
}
function showElement(show) {
show ? elem.css({
display: ''
}) : elem.css({
display: 'none'
});
}
function getDelay() {
var delay = parseInt(scope.delay);
return angular__WEBPACK_IMPORTED_MODULE_0___default.a.isNumber(delay) ? delay : 200;
}
}
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/elemReady.js":
/*!*******************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/elemReady.js ***!
\*******************************************************************/
/*! exports provided: elemReady */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "elemReady", function() { return elemReady; });
elemReady.$inject = ["$parse"];
/* @ngInject */
function elemReady($parse) {
return {
restrict: 'A',
link: function link($scope, elem, attrs) {
elem.ready(function () {
$scope.$apply(function () {
var func = $parse(attrs.elemReady);
func($scope);
});
});
}
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/file-change.js":
/*!*********************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/file-change.js ***!
\*********************************************************************/
/*! exports provided: fileChange */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fileChange", function() { return fileChange; });
/* @ngInject */
function fileChange() {
return {
restrict: 'A',
scope: {
handler: '&'
},
link: function link(scope, element) {
element.on('change', function (event) {
scope.$apply(function () {
scope.handler({
files: event.target.files
});
});
});
}
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/index.js":
/*!***************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/index.js ***!
\***************************************************************/
/*! exports provided: autofocus, clickOutside, delayHide, elemReady, fileChange, infiniteScroll, lowercase, selectOnClick, snEnter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _autofocus__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./autofocus */ "./app/assets/javascripts/directives/functional/autofocus.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "autofocus", function() { return _autofocus__WEBPACK_IMPORTED_MODULE_0__["autofocus"]; });
/* harmony import */ var _click_outside__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./click-outside */ "./app/assets/javascripts/directives/functional/click-outside.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "clickOutside", function() { return _click_outside__WEBPACK_IMPORTED_MODULE_1__["clickOutside"]; });
/* harmony import */ var _delay_hide__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./delay-hide */ "./app/assets/javascripts/directives/functional/delay-hide.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "delayHide", function() { return _delay_hide__WEBPACK_IMPORTED_MODULE_2__["delayHide"]; });
/* harmony import */ var _elemReady__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./elemReady */ "./app/assets/javascripts/directives/functional/elemReady.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "elemReady", function() { return _elemReady__WEBPACK_IMPORTED_MODULE_3__["elemReady"]; });
/* harmony import */ var _file_change__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./file-change */ "./app/assets/javascripts/directives/functional/file-change.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "fileChange", function() { return _file_change__WEBPACK_IMPORTED_MODULE_4__["fileChange"]; });
/* harmony import */ var _infiniteScroll__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./infiniteScroll */ "./app/assets/javascripts/directives/functional/infiniteScroll.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "infiniteScroll", function() { return _infiniteScroll__WEBPACK_IMPORTED_MODULE_5__["infiniteScroll"]; });
/* harmony import */ var _lowercase__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./lowercase */ "./app/assets/javascripts/directives/functional/lowercase.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "lowercase", function() { return _lowercase__WEBPACK_IMPORTED_MODULE_6__["lowercase"]; });
/* harmony import */ var _selectOnClick__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./selectOnClick */ "./app/assets/javascripts/directives/functional/selectOnClick.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "selectOnClick", function() { return _selectOnClick__WEBPACK_IMPORTED_MODULE_7__["selectOnClick"]; });
/* harmony import */ var _snEnter__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./snEnter */ "./app/assets/javascripts/directives/functional/snEnter.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "snEnter", function() { return _snEnter__WEBPACK_IMPORTED_MODULE_8__["snEnter"]; });
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/infiniteScroll.js":
/*!************************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/infiniteScroll.js ***!
\************************************************************************/
/*! exports provided: infiniteScroll */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "infiniteScroll", function() { return infiniteScroll; });
infiniteScroll.$inject = ["$rootScope", "$window", "$timeout"];
/* @ngInject */
function infiniteScroll($rootScope, $window, $timeout) {
return {
link: function link(scope, elem, attrs) {
var offset = parseInt(attrs.threshold) || 0;
var e = elem[0];
elem.on('scroll', function () {
if (scope.$eval(attrs.canLoad) && e.scrollTop + e.offsetHeight >= e.scrollHeight - offset) {
scope.$apply(attrs.infiniteScroll);
}
});
}
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/lowercase.js":
/*!*******************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/lowercase.js ***!
\*******************************************************************/
/*! exports provided: lowercase */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lowercase", function() { return lowercase; });
/* @ngInject */
function lowercase() {
return {
require: 'ngModel',
link: function link(scope, element, attrs, modelCtrl) {
var lowercase = function lowercase(inputValue) {
if (inputValue === undefined) inputValue = '';
var lowercased = inputValue.toLowerCase();
if (lowercased !== inputValue) {
modelCtrl.$setViewValue(lowercased);
modelCtrl.$render();
}
return lowercased;
};
modelCtrl.$parsers.push(lowercase);
lowercase(scope[attrs.ngModel]);
}
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/selectOnClick.js":
/*!***********************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/selectOnClick.js ***!
\***********************************************************************/
/*! exports provided: selectOnClick */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "selectOnClick", function() { return selectOnClick; });
selectOnClick.$inject = ["$window"];
/* @ngInject */
function selectOnClick($window) {
return {
restrict: 'A',
link: function link(scope, element, attrs) {
element.on('focus', function () {
if (!$window.getSelection().toString()) {
/** Required for mobile Safari */
this.setSelectionRange(0, this.value.length);
}
});
}
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/functional/snEnter.js":
/*!*****************************************************************!*\
!*** ./app/assets/javascripts/directives/functional/snEnter.js ***!
\*****************************************************************/
/*! exports provided: snEnter */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "snEnter", function() { return snEnter; });
/* @ngInject */
function snEnter() {
return function (scope, element, attrs) {
element.bind('keydown keypress', function (event) {
if (event.which === 13) {
scope.$apply(function () {
scope.$eval(attrs.snEnter, {
event: event
});
});
event.preventDefault();
}
});
};
}
/***/ }),
/***/ "./app/assets/javascripts/directives/views/accountMenu.js":
/*!****************************************************************!*\
!*** ./app/assets/javascripts/directives/views/accountMenu.js ***!
\****************************************************************/
/*! exports provided: AccountMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AccountMenu", function() { return AccountMenu; });
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var _directives_account_menu_pug__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! %/directives/account-menu.pug */ "./app/assets/templates/directives/account-menu.pug");
/* harmony import */ var _directives_account_menu_pug__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(_directives_account_menu_pug__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_10__);
/* harmony import */ var _Controllers__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @Controllers */ "./app/assets/javascripts/controllers/index.js");
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/state */ "./app/assets/javascripts/state.js");
/* harmony import */ var _strings__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/strings */ "./app/assets/javascripts/strings.js");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var ELEMENT_ID_IMPORT_PASSWORD_INPUT = 'import-password-request';
var ELEMENT_NAME_AUTH_EMAIL = 'email';
var ELEMENT_NAME_AUTH_PASSWORD = 'password';
var ELEMENT_NAME_AUTH_PASSWORD_CONF = 'password_conf';
var AccountMenuCtrl =
/*#__PURE__*/
function (_PureCtrl) {
AccountMenuCtrl.$inject = ["$scope", "$rootScope", "$timeout", "appVersion", "application", "appState", "archiveManager", "godService", "lockManager"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default()(AccountMenuCtrl, _PureCtrl);
/* @ngInject */
function AccountMenuCtrl($scope, $rootScope, $timeout, appVersion, application, appState, archiveManager, godService, lockManager) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default()(this, AccountMenuCtrl);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_5___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6___default()(AccountMenuCtrl).call(this, $scope, $timeout, application, appState));
_this.$rootScope = $rootScope;
_this.appState = appState;
_this.application = application;
_this.archiveManager = archiveManager;
_this.godService = godService;
_this.lockManager = lockManager;
_this.state = {
appVersion: 'v' + (window.electronAppVersion || appVersion),
passcodeAutoLockOptions: _this.lockManager.getAutoLockIntervalOptions(),
formData: {
mergeLocal: true,
ephemeral: false
},
mutable: {}
};
application.onUnlock(
/*#__PURE__*/
_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.t0 = _this;
_context.next = 3;
return _this.refreshedCredentialState();
case 3:
_context.t1 = _context.sent;
_context.t0.setState.call(_context.t0, _context.t1);
_this.loadHost();
_this.checkForSecurityUpdate();
_this.reloadAutoLockInterval();
_this.loadBackupsAvailability();
case 9:
case "end":
return _context.stop();
}
}
}, _callee);
})));
application.onCredentialChange(
/*#__PURE__*/
_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee2() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.t0 = _this;
_context2.next = 3;
return _this.refreshedCredentialState();
case 3:
_context2.t1 = _context2.sent;
_context2.t0.setState.call(_context2.t0, _context2.t1);
case 5:
case "end":
return _context2.stop();
}
}
}, _callee2);
})));
_this.syncStatus = _this.application.getSyncStatus();
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4___default()(AccountMenuCtrl, [{
key: "refreshedCredentialState",
value: function () {
var _refreshedCredentialState = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee3() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.t0 = this.application.getUser();
_context3.t1 = !this.application.isEphemeralSession();
_context3.next = 4;
return this.application.hasPasscode();
case 4:
_context3.t2 = _context3.sent;
return _context3.abrupt("return", {
user: _context3.t0,
canAddPasscode: _context3.t1,
hasPasscode: _context3.t2
});
case 6:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function refreshedCredentialState() {
return _refreshedCredentialState.apply(this, arguments);
}
return refreshedCredentialState;
}()
}, {
key: "$onInit",
value: function $onInit() {
this.initProps({
closeFunction: this.closeFunction
});
}
}, {
key: "close",
value: function close() {
var _this2 = this;
this.$timeout(function () {
_this2.props.closeFunction()();
});
}
}, {
key: "loadHost",
value: function () {
var _loadHost = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee4() {
var host;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return this.application.getHost();
case 2:
host = _context4.sent;
this.setState({
server: host,
formData: _objectSpread({}, this.state.formData, {
url: host
})
});
case 4:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function loadHost() {
return _loadHost.apply(this, arguments);
}
return loadHost;
}()
}, {
key: "checkForSecurityUpdate",
value: function () {
var _checkForSecurityUpdate = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee5() {
var available;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_context5.next = 2;
return this.godService.checkForSecurityUpdate();
case 2:
available = _context5.sent;
this.setState({
securityUpdateAvailable: available
});
case 4:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function checkForSecurityUpdate() {
return _checkForSecurityUpdate.apply(this, arguments);
}
return checkForSecurityUpdate;
}()
}, {
key: "loadBackupsAvailability",
value: function () {
var _loadBackupsAvailability = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee6() {
var hasUser, hasPasscode, encryptedAvailable, encryptionStatusString;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
encryptionStatusString = function _ref3() {
if (hasUser) {
return _strings__WEBPACK_IMPORTED_MODULE_13__["STRING_E2E_ENABLED"];
} else if (hasPasscode) {
return _strings__WEBPACK_IMPORTED_MODULE_13__["STRING_LOCAL_ENC_ENABLED"];
} else {
return _strings__WEBPACK_IMPORTED_MODULE_13__["STRING_ENC_NOT_ENABLED"];
}
};
_context6.t0 = _utils__WEBPACK_IMPORTED_MODULE_8__["isNullOrUndefined"];
_context6.next = 4;
return this.application.getUser();
case 4:
_context6.t1 = _context6.sent;
hasUser = !(0, _context6.t0)(_context6.t1);
_context6.next = 8;
return this.application.hasPasscode();
case 8:
hasPasscode = _context6.sent;
encryptedAvailable = hasUser || hasPasscode;
this.setState({
encryptionStatusString: encryptionStatusString(),
encryptionEnabled: encryptedAvailable,
mutable: _objectSpread({}, this.state.mutable, {
backupEncrypted: encryptedAvailable
})
});
case 11:
case "end":
return _context6.stop();
}
}
}, _callee6, this);
}));
function loadBackupsAvailability() {
return _loadBackupsAvailability.apply(this, arguments);
}
return loadBackupsAvailability;
}()
}, {
key: "submitMfaForm",
value: function submitMfaForm() {
this.login();
}
}, {
key: "blurAuthFields",
value: function blurAuthFields() {
var names = [ELEMENT_NAME_AUTH_EMAIL, ELEMENT_NAME_AUTH_PASSWORD, ELEMENT_NAME_AUTH_PASSWORD_CONF];
for (var _i = 0, _names = names; _i < _names.length; _i++) {
var name = _names[_i];
var element = document.getElementsByName(name)[0];
if (element) {
element.blur();
}
}
}
}, {
key: "submitAuthForm",
value: function submitAuthForm() {
if (!this.state.formData.email || !this.state.formData.user_password) {
return;
}
this.blurAuthFields();
if (this.state.formData.showLogin) {
this.login();
} else {
this.register();
}
}
}, {
key: "setFormDataState",
value: function () {
var _setFormDataState = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee7(formData) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
return _context7.abrupt("return", this.setState({
formData: _objectSpread({}, this.state.formData, {}, formData)
}));
case 1:
case "end":
return _context7.stop();
}
}
}, _callee7, this);
}));
function setFormDataState(_x) {
return _setFormDataState.apply(this, arguments);
}
return setFormDataState;
}()
}, {
key: "login",
value: function () {
var _login = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee8() {
var response, hasError, error;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
_context8.next = 2;
return this.setFormDataState({
status: _strings__WEBPACK_IMPORTED_MODULE_13__["STRING_GENERATING_LOGIN_KEYS"],
authenticating: true
});
case 2:
_context8.next = 4;
return this.application.signIn({
email: this.state.formData.email,
password: this.state.formData.user_password,
strict: this.state.formData.strictSignin,
ephemeral: this.state.formData.ephemeral,
mfaKeyPath: this.state.formData.mfa.payload.mfa_key,
mfaCode: this.state.formData.userMfaCode,
mergeLocal: this.state.formData.mergeLocal
});
case 4:
response = _context8.sent;
hasError = !response || response.error;
if (hasError) {
_context8.next = 10;
break;
}
_context8.next = 9;
return this.onAuthSuccess();
case 9:
return _context8.abrupt("return");
case 10:
_context8.next = 12;
return this.setFormDataState({
status: null
});
case 12:
error = response ? response.error : {
message: "An unknown error occured."
};
if (!(error.tag === 'mfa-required' || error.tag === 'mfa-invalid')) {
_context8.next = 18;
break;
}
_context8.next = 16;
return this.setFormDataState({
showLogin: false,
mfa: error
});
case 16:
_context8.next = 21;
break;
case 18:
_context8.next = 20;
return this.setFormDataState({
showLogin: true,
mfa: null
});
case 20:
if (error.message) {
this.application.alertManager.alert({
text: error.message
});
}
case 21:
_context8.next = 23;
return this.setFormDataState({
authenticating: false
});
case 23:
case "end":
return _context8.stop();
}
}
}, _callee8, this);
}));
function login() {
return _login.apply(this, arguments);
}
return login;
}()
}, {
key: "register",
value: function () {
var _register = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee9() {
var confirmation, response, error;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
confirmation = this.state.formData.password_conf;
if (!(confirmation !== this.state.formData.user_password)) {
_context9.next = 4;
break;
}
this.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_13__["STRING_NON_MATCHING_PASSWORDS"]
});
return _context9.abrupt("return");
case 4:
_context9.next = 6;
return this.setFormDataState({
confirmPassword: false,
status: _strings__WEBPACK_IMPORTED_MODULE_13__["STRING_GENERATING_REGISTER_KEYS"],
authenticating: true
});
case 6:
_context9.next = 8;
return this.application.register({
email: this.state.formData.email,
password: this.state.formData.user_password,
ephemeral: this.state.formData.ephemeral,
mergeLocal: this.state.formData.mergeLocal
});
case 8:
response = _context9.sent;
if (!(!response || response.error)) {
_context9.next = 18;
break;
}
_context9.next = 12;
return this.setFormDataState({
status: null
});
case 12:
error = response ? response.error : {
message: "An unknown error occured."
};
_context9.next = 15;
return this.setFormDataState({
authenticating: false
});
case 15:
this.application.alertManager.alert({
text: error.message
});
_context9.next = 21;
break;
case 18:
_context9.next = 20;
return this.onAuthSuccess();
case 20:
this.application.sync();
case 21:
case "end":
return _context9.stop();
}
}
}, _callee9, this);
}));
function register() {
return _register.apply(this, arguments);
}
return register;
}()
}, {
key: "mergeLocalChanged",
value: function mergeLocalChanged() {
var _this3 = this;
if (!this.state.formData.mergeLocal) {
this.application.alertManager.confirm({
text: _strings__WEBPACK_IMPORTED_MODULE_13__["STRING_ACCOUNT_MENU_UNCHECK_MERGE"],
destructive: true,
onCancel: function onCancel() {
_this3.setFormDataState({
mergeLocal: true
});
}
});
}
}
}, {
key: "onAuthSuccess",
value: function () {
var _onAuthSuccess = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee10() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
if (!this.state.formData.mergeLocal) {
_context10.next = 4;
break;
}
this.$rootScope.$broadcast('major-data-change');
_context10.next = 4;
return this.rewriteDatabase({
alternateUuids: true
});
case 4:
_context10.next = 6;
return this.setFormDataState({
authenticating: false
});
case 6:
this.close();
case 7:
case "end":
return _context10.stop();
}
}
}, _callee10, this);
}));
function onAuthSuccess() {
return _onAuthSuccess.apply(this, arguments);
}
return onAuthSuccess;
}()
}, {
key: "openPasswordWizard",
value: function openPasswordWizard(type) {
this.close();
this.godService.presentPasswordWizard(type);
}
}, {
key: "openPrivilegesModal",
value: function () {
var _openPrivilegesModal = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee11() {
var _this4 = this;
var run, needsPrivilege;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee11$(_context11) {
while (1) {
switch (_context11.prev = _context11.next) {
case 0:
this.close();
run = function run() {
_this4.godService.presentPrivilegesManagementModal();
};
_context11.next = 4;
return this.application.privilegesManager.actionRequiresPrivilege(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManagePrivileges);
case 4:
needsPrivilege = _context11.sent;
if (needsPrivilege) {
this.godService.presentPrivilegesModal(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManagePrivileges, function () {
run();
});
} else {
run();
}
case 6:
case "end":
return _context11.stop();
}
}
}, _callee11, this);
}));
function openPrivilegesModal() {
return _openPrivilegesModal.apply(this, arguments);
}
return openPrivilegesModal;
}()
/**
* Allows IndexedDB unencrypted logs to be deleted
* `clearAllPayloads` will remove data from backing store,
* but not from working memory See:
* https://github.com/standardnotes/desktop/issues/131
*/
}, {
key: "rewriteDatabase",
value: function () {
var _rewriteDatabase = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee12() {
var _ref4,
alternateUuids,
_args12 = arguments;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee12$(_context12) {
while (1) {
switch (_context12.prev = _context12.next) {
case 0:
_ref4 = _args12.length > 0 && _args12[0] !== undefined ? _args12[0] : {}, alternateUuids = _ref4.alternateUuids;
_context12.next = 3;
return this.application.destroyDatabase();
case 3:
_context12.next = 5;
return this.application.markAllItemsAsNeedingSync({
alternateUuids: alternateUuids
});
case 5:
case "end":
return _context12.stop();
}
}
}, _callee12, this);
}));
function rewriteDatabase() {
return _rewriteDatabase.apply(this, arguments);
}
return rewriteDatabase;
}()
}, {
key: "destroyLocalData",
value: function destroyLocalData() {
var _this5 = this;
this.application.alertManager.confirm({
text: _strings__WEBPACK_IMPORTED_MODULE_13__["STRING_SIGN_OUT_CONFIRMATION"],
destructive: true,
onConfirm: function () {
var _onConfirm = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee13() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee13$(_context13) {
while (1) {
switch (_context13.prev = _context13.next) {
case 0:
_context13.next = 2;
return _this5.application.signOut();
case 2:
window.location.reload();
case 3:
case "end":
return _context13.stop();
}
}
}, _callee13);
}));
function onConfirm() {
return _onConfirm.apply(this, arguments);
}
return onConfirm;
}()
});
}
}, {
key: "submitImportPassword",
value: function () {
var _submitImportPassword = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee14() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee14$(_context14) {
while (1) {
switch (_context14.prev = _context14.next) {
case 0:
_context14.next = 2;
return this.performImport(this.state.importData.data, this.state.importData.password);
case 2:
case "end":
return _context14.stop();
}
}
}, _callee14, this);
}));
function submitImportPassword() {
return _submitImportPassword.apply(this, arguments);
}
return submitImportPassword;
}()
}, {
key: "readFile",
value: function () {
var _readFile = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee15(file) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee15$(_context15) {
while (1) {
switch (_context15.prev = _context15.next) {
case 0:
return _context15.abrupt("return", new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onload = function (e) {
try {
var data = JSON.parse(e.target.result);
resolve(data);
} catch (e) {
this.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_13__["STRING_INVALID_IMPORT_FILE"]
});
}
};
reader.readAsText(file);
}));
case 1:
case "end":
return _context15.stop();
}
}
}, _callee15);
}));
function readFile(_x2) {
return _readFile.apply(this, arguments);
}
return readFile;
}()
/**
* @template
*/
}, {
key: "importFileSelected",
value: function () {
var _importFileSelected = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee17(files) {
var _this6 = this;
var run, needsPrivilege;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee17$(_context17) {
while (1) {
switch (_context17.prev = _context17.next) {
case 0:
run =
/*#__PURE__*/
function () {
var _ref5 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee16() {
var file, data, element;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee16$(_context16) {
while (1) {
switch (_context16.prev = _context16.next) {
case 0:
file = files[0];
_context16.next = 3;
return _this6.readFile(file);
case 3:
data = _context16.sent;
if (data) {
_context16.next = 6;
break;
}
return _context16.abrupt("return");
case 6:
if (!data.auth_params) {
_context16.next = 13;
break;
}
_context16.next = 9;
return _this6.setState({
importData: _objectSpread({}, _this6.state.importData, {
requestPassword: true,
data: data
})
});
case 9:
element = document.getElementById(ELEMENT_ID_IMPORT_PASSWORD_INPUT);
if (element) {
element.scrollIntoView(false);
}
_context16.next = 15;
break;
case 13:
_context16.next = 15;
return _this6.performImport(data, null);
case 15:
case "end":
return _context16.stop();
}
}
}, _callee16);
}));
return function run() {
return _ref5.apply(this, arguments);
};
}();
_context17.next = 3;
return this.application.privilegesManager.actionRequiresPrivilege(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManageBackups);
case 3:
needsPrivilege = _context17.sent;
if (needsPrivilege) {
this.godService.presentPrivilegesModal(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManageBackups, run);
} else {
run();
}
case 5:
case "end":
return _context17.stop();
}
}
}, _callee17, this);
}));
function importFileSelected(_x3) {
return _importFileSelected.apply(this, arguments);
}
return importFileSelected;
}()
}, {
key: "performImport",
value: function () {
var _performImport = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee18(data, password) {
var errorCount, message;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee18$(_context18) {
while (1) {
switch (_context18.prev = _context18.next) {
case 0:
_context18.next = 2;
return this.setState({
importData: _objectSpread({}, this.state.importData, {
loading: true
})
});
case 2:
_context18.next = 4;
return this.importJSONData(data, password);
case 4:
errorCount = _context18.sent;
this.setState({
importData: null
});
if (errorCount > 0) {
message = Object(_strings__WEBPACK_IMPORTED_MODULE_13__["StringImportError"])({
errorCount: errorCount
});
this.application.alertManager.alert({
text: message
});
} else {
this.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_13__["STRING_IMPORT_SUCCESS"]
});
}
case 7:
case "end":
return _context18.stop();
}
}
}, _callee18, this);
}));
function performImport(_x4, _x5) {
return _performImport.apply(this, arguments);
}
return performImport;
}()
}, {
key: "importJSONData",
value: function () {
var _importJSONData = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee19(data, password) {
var _ref6, affectedItems, errorCount, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, item;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee19$(_context19) {
while (1) {
switch (_context19.prev = _context19.next) {
case 0:
_context19.next = 2;
return this.application.importData({
data: data.items,
password: password
});
case 2:
_ref6 = _context19.sent;
affectedItems = _ref6.affectedItems;
errorCount = _ref6.errorCount;
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
_context19.prev = 8;
for (_iterator = affectedItems[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
item = _step.value;
/**
* Don't want to activate any components during import process in
* case of exceptions breaking up the import proccess
*/
if (item.content_type === 'SN|Component') {
item.active = false;
}
}
_context19.next = 16;
break;
case 12:
_context19.prev = 12;
_context19.t0 = _context19["catch"](8);
_didIteratorError = true;
_iteratorError = _context19.t0;
case 16:
_context19.prev = 16;
_context19.prev = 17;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 19:
_context19.prev = 19;
if (!_didIteratorError) {
_context19.next = 22;
break;
}
throw _iteratorError;
case 22:
return _context19.finish(19);
case 23:
return _context19.finish(16);
case 24:
return _context19.abrupt("return", errorCount);
case 25:
case "end":
return _context19.stop();
}
}
}, _callee19, this, [[8, 12, 16, 24], [17,, 19, 23]]);
}));
function importJSONData(_x6, _x7) {
return _importJSONData.apply(this, arguments);
}
return importJSONData;
}()
}, {
key: "downloadDataArchive",
value: function () {
var _downloadDataArchive = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee20() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee20$(_context20) {
while (1) {
switch (_context20.prev = _context20.next) {
case 0:
this.archiveManager.downloadBackup(this.state.mutable.backupEncrypted);
case 1:
case "end":
return _context20.stop();
}
}
}, _callee20, this);
}));
function downloadDataArchive() {
return _downloadDataArchive.apply(this, arguments);
}
return downloadDataArchive;
}()
}, {
key: "notesAndTagsCount",
value: function notesAndTagsCount() {
return this.application.getItems({
contentType: ['Note', 'Tag']
}).length;
}
}, {
key: "encryptionStatusForNotes",
value: function encryptionStatusForNotes() {
var length = this.notesAndTagsCount();
return length + "/" + length + " notes and tags encrypted";
}
}, {
key: "reloadAutoLockInterval",
value: function () {
var _reloadAutoLockInterval = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee21() {
var interval;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee21$(_context21) {
while (1) {
switch (_context21.prev = _context21.next) {
case 0:
_context21.next = 2;
return this.lockManager.getAutoLockInterval();
case 2:
interval = _context21.sent;
this.setState({
selectedAutoLockInterval: interval
});
case 4:
case "end":
return _context21.stop();
}
}
}, _callee21, this);
}));
function reloadAutoLockInterval() {
return _reloadAutoLockInterval.apply(this, arguments);
}
return reloadAutoLockInterval;
}()
}, {
key: "selectAutoLockInterval",
value: function () {
var _selectAutoLockInterval = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee23(interval) {
var _this7 = this;
var run, needsPrivilege;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee23$(_context23) {
while (1) {
switch (_context23.prev = _context23.next) {
case 0:
run =
/*#__PURE__*/
function () {
var _ref7 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee22() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee22$(_context22) {
while (1) {
switch (_context22.prev = _context22.next) {
case 0:
_context22.next = 2;
return _this7.lockManager.setAutoLockInterval(interval);
case 2:
_this7.reloadAutoLockInterval();
case 3:
case "end":
return _context22.stop();
}
}
}, _callee22);
}));
return function run() {
return _ref7.apply(this, arguments);
};
}();
_context23.next = 3;
return this.application.privilegesManager.actionRequiresPrivilege(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManagePasscode);
case 3:
needsPrivilege = _context23.sent;
if (needsPrivilege) {
this.godService.presentPrivilegesModal(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManagePasscode, function () {
run();
});
} else {
run();
}
case 5:
case "end":
return _context23.stop();
}
}
}, _callee23, this);
}));
function selectAutoLockInterval(_x8) {
return _selectAutoLockInterval.apply(this, arguments);
}
return selectAutoLockInterval;
}()
}, {
key: "addPasscodeClicked",
value: function addPasscodeClicked() {
this.setFormDataState({
showPasscodeForm: true
});
}
}, {
key: "submitPasscodeForm",
value: function submitPasscodeForm() {
var _this8 = this;
var passcode = this.state.formData.passcode;
if (passcode !== this.state.formData.confirmPasscode) {
this.application.alertManager.alert({
text: _strings__WEBPACK_IMPORTED_MODULE_13__["STRING_NON_MATCHING_PASSCODES"]
});
return;
}
var func = this.state.formData.changingPasscode ? this.application.changePasscode.bind(this.application) : this.application.setPasscode.bind(this.application);
func(passcode,
/*#__PURE__*/
_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee24() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee24$(_context24) {
while (1) {
switch (_context24.prev = _context24.next) {
case 0:
_context24.next = 2;
return _this8.setFormDataState({
passcode: null,
confirmPasscode: null,
showPasscodeForm: false
});
case 2:
_context24.t0 = _utils__WEBPACK_IMPORTED_MODULE_8__["isNullOrUndefined"];
_context24.next = 5;
return _this8.application.getUser();
case 5:
_context24.t1 = _context24.sent;
if (!(0, _context24.t0)(_context24.t1)) {
_context24.next = 9;
break;
}
_this8.$rootScope.$broadcast('major-data-change');
_this8.rewriteDatabase();
case 9:
case "end":
return _context24.stop();
}
}
}, _callee24);
})));
}
}, {
key: "changePasscodePressed",
value: function () {
var _changePasscodePressed = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee25() {
var _this9 = this;
var run, needsPrivilege;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee25$(_context25) {
while (1) {
switch (_context25.prev = _context25.next) {
case 0:
run = function run() {
_this9.state.formData.changingPasscode = true;
_this9.addPasscodeClicked();
};
_context25.next = 3;
return this.application.privilegesManager.actionRequiresPrivilege(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManagePasscode);
case 3:
needsPrivilege = _context25.sent;
if (needsPrivilege) {
this.godService.presentPrivilegesModal(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManagePasscode, run);
} else {
run();
}
case 5:
case "end":
return _context25.stop();
}
}
}, _callee25, this);
}));
function changePasscodePressed() {
return _changePasscodePressed.apply(this, arguments);
}
return changePasscodePressed;
}()
}, {
key: "removePasscodePressed",
value: function () {
var _removePasscodePressed = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee27() {
var _this10 = this;
var run;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee27$(_context27) {
while (1) {
switch (_context27.prev = _context27.next) {
case 0:
run =
/*#__PURE__*/
function () {
var _ref9 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee26() {
var signedIn, message;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee26$(_context26) {
while (1) {
switch (_context26.prev = _context26.next) {
case 0:
_context26.t0 = _utils__WEBPACK_IMPORTED_MODULE_8__["isNullOrUndefined"];
_context26.next = 3;
return _this10.application.getUser();
case 3:
_context26.t1 = _context26.sent;
signedIn = !(0, _context26.t0)(_context26.t1);
message = _strings__WEBPACK_IMPORTED_MODULE_13__["STRING_REMOVE_PASSCODE_CONFIRMATION"];
if (!signedIn) {
message += _strings__WEBPACK_IMPORTED_MODULE_13__["STRING_REMOVE_PASSCODE_OFFLINE_ADDENDUM"];
}
_this10.application.alertManager.confirm({
text: message,
destructive: true,
onConfirm: function onConfirm() {
_this10.application.removePasscode();
}
});
case 8:
case "end":
return _context26.stop();
}
}
}, _callee26);
}));
return function run() {
return _ref9.apply(this, arguments);
};
}();
this.godService.presentPrivilegesModal(snjs__WEBPACK_IMPORTED_MODULE_10__["ProtectedActions"].ManagePasscode, run);
case 2:
case "end":
return _context27.stop();
}
}
}, _callee27, this);
}));
function removePasscodePressed() {
return _removePasscodePressed.apply(this, arguments);
}
return removePasscodePressed;
}()
}, {
key: "isDesktopApplication",
value: function isDesktopApplication() {
return Object(_utils__WEBPACK_IMPORTED_MODULE_8__["isDesktopApplication"])();
}
}]);
return AccountMenuCtrl;
}(_Controllers__WEBPACK_IMPORTED_MODULE_11__["PureCtrl"]);
var AccountMenu = function AccountMenu() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default()(this, AccountMenu);
this.restrict = 'E';
this.template = _directives_account_menu_pug__WEBPACK_IMPORTED_MODULE_9___default.a;
this.controller = AccountMenuCtrl;
this.controllerAs = 'self';
this.bindToController = true;
this.scope = {
closeFunction: '&'
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/actionsMenu.js":
/*!****************************************************************!*\
!*** ./app/assets/javascripts/directives/views/actionsMenu.js ***!
\****************************************************************/
/*! exports provided: ActionsMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionsMenu", function() { return ActionsMenu; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _directives_actions_menu_pug__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! %/directives/actions-menu.pug */ "./app/assets/templates/directives/actions-menu.pug");
/* harmony import */ var _directives_actions_menu_pug__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_directives_actions_menu_pug__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _Controllers__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @Controllers */ "./app/assets/javascripts/controllers/index.js");
var ActionsMenuCtrl =
/*#__PURE__*/
function (_PureCtrl) {
ActionsMenuCtrl.$inject = ["$scope", "$timeout", "application", "appState", "godService"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6___default()(ActionsMenuCtrl, _PureCtrl);
/* @ngInject */
function ActionsMenuCtrl($scope, $timeout, application, appState, godService) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, ActionsMenuCtrl);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(ActionsMenuCtrl).call(this, $scope, $timeout, application, appState));
_this.godService = godService;
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(ActionsMenuCtrl, [{
key: "$onInit",
value: function $onInit() {
this.initProps({
item: this.item
});
this.loadExtensions();
}
}, {
key: "loadExtensions",
value: function () {
var _loadExtensions = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var extensions, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, extension;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
extensions = this.application.actionsManager.getExtensions().sort(function (a, b) {
return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1;
});
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
_context.prev = 4;
_iterator = extensions[Symbol.iterator]();
case 6:
if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
_context.next = 15;
break;
}
extension = _step.value;
extension.loading = true;
_context.next = 11;
return this.application.actionsManager.loadExtensionInContextOfItem(extension, this.props.item);
case 11:
extension.loading = false;
case 12:
_iteratorNormalCompletion = true;
_context.next = 6;
break;
case 15:
_context.next = 21;
break;
case 17:
_context.prev = 17;
_context.t0 = _context["catch"](4);
_didIteratorError = true;
_iteratorError = _context.t0;
case 21:
_context.prev = 21;
_context.prev = 22;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 24:
_context.prev = 24;
if (!_didIteratorError) {
_context.next = 27;
break;
}
throw _iteratorError;
case 27:
return _context.finish(24);
case 28:
return _context.finish(21);
case 29:
this.setState({
extensions: extensions
});
case 30:
case "end":
return _context.stop();
}
}
}, _callee, this, [[4, 17, 21, 29], [22,, 24, 28]]);
}));
function loadExtensions() {
return _loadExtensions.apply(this, arguments);
}
return loadExtensions;
}()
}, {
key: "executeAction",
value: function () {
var _executeAction = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(action, extension) {
var result;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!(action.verb === 'nested')) {
_context2.next = 3;
break;
}
if (!action.subrows) {
action.subrows = this.subRowsForAction(action, extension);
} else {
action.subrows = null;
}
return _context2.abrupt("return");
case 3:
action.running = true;
_context2.next = 6;
return this.application.actionsManager.executeAction(action, extension, this.props.item);
case 6:
result = _context2.sent;
if (!action.error) {
_context2.next = 9;
break;
}
return _context2.abrupt("return");
case 9:
action.running = false;
this.handleActionResult(action, result);
_context2.next = 13;
return this.application.actionsManager.loadExtensionInContextOfItem(extension, this.props.item);
case 13:
this.setState({
extensions: this.state.extensions
});
case 14:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function executeAction(_x, _x2) {
return _executeAction.apply(this, arguments);
}
return executeAction;
}()
}, {
key: "handleActionResult",
value: function handleActionResult(action, result) {
switch (action.verb) {
case 'render':
{
var item = result.item;
this.godService.presentRevisionPreviewModal(item.uuid, item.content);
}
}
}
}, {
key: "subRowsForAction",
value: function subRowsForAction(parentAction, extension) {
var _this2 = this;
if (!parentAction.subactions) {
return null;
}
return parentAction.subactions.map(function (subaction) {
return {
onClick: function onClick() {
_this2.executeAction(subaction, extension, parentAction);
},
label: subaction.label,
subtitle: subaction.desc,
spinnerClass: subaction.running ? 'info' : null
};
});
}
}]);
return ActionsMenuCtrl;
}(_Controllers__WEBPACK_IMPORTED_MODULE_8__["PureCtrl"]);
var ActionsMenu = function ActionsMenu() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, ActionsMenu);
this.restrict = 'E';
this.template = _directives_actions_menu_pug__WEBPACK_IMPORTED_MODULE_7___default.a;
this.replace = true;
this.controller = ActionsMenuCtrl;
this.controllerAs = 'self';
this.bindToController = true;
this.scope = {
item: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/componentModal.js":
/*!*******************************************************************!*\
!*** ./app/assets/javascripts/directives/views/componentModal.js ***!
\*******************************************************************/
/*! exports provided: ComponentModalCtrl, ComponentModal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ComponentModalCtrl", function() { return ComponentModalCtrl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ComponentModal", function() { return ComponentModal; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _directives_component_modal_pug__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! %/directives/component-modal.pug */ "./app/assets/templates/directives/component-modal.pug");
/* harmony import */ var _directives_component_modal_pug__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_directives_component_modal_pug__WEBPACK_IMPORTED_MODULE_2__);
var ComponentModalCtrl =
/*#__PURE__*/
function () {
ComponentModalCtrl.$inject = ["$scope", "$element"];
/* @ngInject */
function ComponentModalCtrl($scope, $element) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ComponentModalCtrl);
this.$element = $element;
this.$scope = $scope;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(ComponentModalCtrl, [{
key: "dismiss",
value: function dismiss(callback) {
this.$element.remove();
this.$scope.$destroy();
if (this.onDismiss && this.onDismiss()) {
this.onDismiss()(this.component);
}
callback && callback();
}
}]);
return ComponentModalCtrl;
}();
var ComponentModal = function ComponentModal() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ComponentModal);
this.restrict = 'E';
this.template = _directives_component_modal_pug__WEBPACK_IMPORTED_MODULE_2___default.a;
this.controller = ComponentModalCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
show: '=',
component: '=',
callback: '=',
onDismiss: '&'
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/componentView.js":
/*!******************************************************************!*\
!*** ./app/assets/javascripts/directives/views/componentView.js ***!
\******************************************************************/
/*! exports provided: ComponentView */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ComponentView", function() { return ComponentView; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _directives_component_view_pug__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! %/directives/component-view.pug */ "./app/assets/templates/directives/component-view.pug");
/* harmony import */ var _directives_component_view_pug__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_directives_component_view_pug__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../utils */ "./app/assets/javascripts/utils.js");
/**
* The maximum amount of time we'll wait for a component
* to load before displaying error
*/
var MAX_LOAD_THRESHOLD = 4000;
var VISIBILITY_CHANGE_LISTENER_KEY = 'visibilitychange';
var ComponentViewCtrl =
/*#__PURE__*/
function () {
ComponentViewCtrl.$inject = ["$scope", "$rootScope", "$timeout", "application", "desktopManager", "themeManager"];
/* @ngInject */
function ComponentViewCtrl($scope, $rootScope, $timeout, application, desktopManager, themeManager) {
var _this = this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, ComponentViewCtrl);
this.$rootScope = $rootScope;
this.$timeout = $timeout;
this.application = application;
this.themeManager = themeManager;
this.desktopManager = desktopManager;
this.componentValid = true;
$scope.$watch('ctrl.component', function (component, prevComponent) {
_this.componentValueDidSet(component, prevComponent);
});
$scope.$on('ext-reload-complete', function () {
_this.reloadStatus(false);
});
$scope.$on('$destroy', function () {
_this.destroy();
});
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(ComponentViewCtrl, [{
key: "$onInit",
value: function $onInit() {
this.registerComponentHandlers();
this.registerPackageUpdateObserver();
}
}, {
key: "registerPackageUpdateObserver",
value: function registerPackageUpdateObserver() {
var _this2 = this;
this.updateObserver = this.desktopManager.registerUpdateObserver(function (component) {
if (component === _this2.component && component.active) {
_this2.reloadComponent();
}
});
}
}, {
key: "registerComponentHandlers",
value: function registerComponentHandlers() {
var _this3 = this;
this.themeHandlerIdentifier = 'component-view-' + Math.random();
this.application.componentManager.registerHandler({
identifier: this.themeHandlerIdentifier,
areas: ['themes'],
activationHandler: function activationHandler(component) {}
});
this.identifier = 'component-view-' + Math.random();
this.application.componentManager.registerHandler({
identifier: this.identifier,
areas: [this.component.area],
activationHandler: function activationHandler(component) {
if (component !== _this3.component) {
return;
}
_this3.$timeout(function () {
_this3.handleActivation();
});
},
actionHandler: function actionHandler(component, action, data) {
if (action === 'set-size') {
_this3.application.componentManager.handleSetSizeEvent(component, data);
}
}
});
}
}, {
key: "onVisibilityChange",
value: function onVisibilityChange() {
if (document.visibilityState === 'hidden') {
return;
}
if (this.issueLoading) {
this.reloadComponent();
}
}
}, {
key: "reloadComponent",
value: function () {
var _reloadComponent = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
this.componentValid = false;
_context.next = 3;
return this.application.componentManager.reloadComponent(this.component);
case 3:
this.reloadStatus();
case 4:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function reloadComponent() {
return _reloadComponent.apply(this, arguments);
}
return reloadComponent;
}()
}, {
key: "reloadStatus",
value: function reloadStatus() {
var _this4 = this;
var doManualReload = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
this.reloading = true;
var component = this.component;
var previouslyValid = this.componentValid;
var offlineRestricted = component.offlineOnly && !Object(_utils__WEBPACK_IMPORTED_MODULE_5__["isDesktopApplication"])();
var hasUrlError = function () {
if (Object(_utils__WEBPACK_IMPORTED_MODULE_5__["isDesktopApplication"])()) {
return !component.local_url && !component.hasValidHostedUrl();
} else {
return !component.hasValidHostedUrl();
}
}();
this.expired = component.valid_until && component.valid_until <= new Date();
if (!component.lockReadonly) {
component.readonly = this.expired;
}
this.componentValid = !offlineRestricted && !hasUrlError;
if (!this.componentValid) {
this.loading = false;
}
if (offlineRestricted) {
this.error = 'offline-restricted';
} else if (hasUrlError) {
this.error = 'url-missing';
} else {
this.error = null;
}
if (this.componentValid !== previouslyValid) {
if (this.componentValid) {
this.application.componentManager.reloadComponent(component, true);
}
}
if (this.expired && doManualReload) {
this.$rootScope.$broadcast('reload-ext-dat');
}
this.$timeout(function () {
_this4.reloading = false;
}, 500);
}
}, {
key: "handleActivation",
value: function handleActivation() {
var _this5 = this;
if (!this.component.active) {
return;
}
var iframe = this.application.componentManager.iframeForComponent(this.component);
if (!iframe) {
return;
}
this.loading = true;
if (this.loadTimeout) {
this.$timeout.cancel(this.loadTimeout);
}
this.loadTimeout = this.$timeout(function () {
_this5.handleIframeLoadTimeout();
}, MAX_LOAD_THRESHOLD);
iframe.onload = function (event) {
_this5.handleIframeLoad(iframe);
};
}
}, {
key: "handleIframeLoadTimeout",
value: function () {
var _handleIframeLoadTimeout = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (this.loading) {
this.loading = false;
this.issueLoading = true;
if (!this.didAttemptReload) {
this.didAttemptReload = true;
this.reloadComponent();
} else {
document.addEventListener(VISIBILITY_CHANGE_LISTENER_KEY, this.onVisibilityChange.bind(this));
}
}
case 1:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function handleIframeLoadTimeout() {
return _handleIframeLoadTimeout.apply(this, arguments);
}
return handleIframeLoadTimeout;
}()
}, {
key: "handleIframeLoad",
value: function () {
var _handleIframeLoad = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(iframe) {
var _this6 = this;
var desktopError, avoidFlickerTimeout;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
desktopError = false;
if (Object(_utils__WEBPACK_IMPORTED_MODULE_5__["isDesktopApplication"])()) {
try {
/** Accessing iframe.contentWindow.origin only allowed in desktop app. */
if (!iframe.contentWindow.origin || iframe.contentWindow.origin === 'null') {
desktopError = true;
}
} catch (e) {}
}
this.$timeout.cancel(this.loadTimeout);
_context3.next = 5;
return this.application.componentManager.registerComponentWindow(this.component, iframe.contentWindow);
case 5:
avoidFlickerTimeout = 7;
this.$timeout(function () {
_this6.loading = false; // eslint-disable-next-line no-unneeded-ternary
_this6.issueLoading = desktopError ? true : false;
_this6.onLoad && _this6.onLoad(_this6.component);
}, avoidFlickerTimeout);
case 7:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function handleIframeLoad(_x) {
return _handleIframeLoad.apply(this, arguments);
}
return handleIframeLoad;
}()
}, {
key: "componentValueDidSet",
value: function componentValueDidSet(component, prevComponent) {
var dontSync = true;
if (prevComponent && component !== prevComponent) {
this.application.componentManager.deactivateComponent(prevComponent, dontSync);
}
if (component) {
this.application.componentManager.activateComponent(component, dontSync);
this.reloadStatus();
}
}
}, {
key: "disableActiveTheme",
value: function disableActiveTheme() {
this.themeManager.deactivateAllThemes();
}
}, {
key: "getUrl",
value: function getUrl() {
var url = this.application.componentManager.urlForComponent(this.component);
this.component.runningLocally = url === this.component.local_url;
return url;
}
}, {
key: "destroy",
value: function destroy() {
this.application.componentManager.deregisterHandler(this.themeHandlerIdentifier);
this.application.componentManager.deregisterHandler(this.identifier);
if (this.component && !this.manualDealloc) {
var dontSync = true;
this.application.componentManager.deactivateComponent(this.component, dontSync);
}
this.desktopManager.deregisterUpdateObserver(this.updateObserver);
document.removeEventListener(VISIBILITY_CHANGE_LISTENER_KEY, this.onVisibilityChange.bind(this));
}
}]);
return ComponentViewCtrl;
}();
var ComponentView = function ComponentView() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, ComponentView);
this.restrict = 'E';
this.template = _directives_component_view_pug__WEBPACK_IMPORTED_MODULE_4___default.a;
this.scope = {
component: '=',
onLoad: '=?',
manualDealloc: '=?'
};
this.controller = ComponentViewCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/conflictResolutionModal.js":
/*!****************************************************************************!*\
!*** ./app/assets/javascripts/directives/views/conflictResolutionModal.js ***!
\****************************************************************************/
/*! exports provided: ConflictResolutionModal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ConflictResolutionModal", function() { return ConflictResolutionModal; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _directives_conflict_resolution_modal_pug__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! %/directives/conflict-resolution-modal.pug */ "./app/assets/templates/directives/conflict-resolution-modal.pug");
/* harmony import */ var _directives_conflict_resolution_modal_pug__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_directives_conflict_resolution_modal_pug__WEBPACK_IMPORTED_MODULE_2__);
var ConflictResolutionCtrl =
/*#__PURE__*/
function () {
ConflictResolutionCtrl.$inject = ["$element", "archiveManager", "application"];
/* @ngInject */
function ConflictResolutionCtrl($element, archiveManager, application) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ConflictResolutionCtrl);
this.$element = $element;
this.application = application;
this.archiveManager = archiveManager;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(ConflictResolutionCtrl, [{
key: "$onInit",
value: function $onInit() {
this.contentType = this.item1.content_type;
this.item1Content = this.createContentString(this.item1);
this.item2Content = this.createContentString(this.item2);
}
}, {
key: "createContentString",
value: function createContentString(item) {
var data = Object.assign({
created_at: item.created_at,
updated_at: item.updated_at
}, item.content);
return JSON.stringify(data, null, 2);
}
}, {
key: "keepItem1",
value: function keepItem1() {
var _this = this;
this.application.alertManager.confirm({
text: "Are you sure you want to delete the item on the right?",
destructive: true,
onConfirm: function onConfirm() {
_this.application.deleteItem({
item: _this.item2
});
_this.triggerCallback();
_this.dismiss();
}
});
}
}, {
key: "keepItem2",
value: function keepItem2() {
var _this2 = this;
this.application.alertManager.confirm({
text: "Are you sure you want to delete the item on the left?",
destructive: true,
onConfirm: function onConfirm() {
_this2.application.deleteItem({
item: _this2.item1
});
_this2.triggerCallback();
_this2.dismiss();
}
});
}
}, {
key: "keepBoth",
value: function keepBoth() {
this.triggerCallback();
this.dismiss();
}
}, {
key: "export",
value: function _export() {
this.archiveManager.downloadBackupOfItems([this.item1, this.item2], true);
}
}, {
key: "triggerCallback",
value: function triggerCallback() {
this.callback && this.callback();
}
}, {
key: "dismiss",
value: function dismiss() {
this.$element.remove();
}
}]);
return ConflictResolutionCtrl;
}();
var ConflictResolutionModal = function ConflictResolutionModal() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ConflictResolutionModal);
this.restrict = 'E';
this.template = _directives_conflict_resolution_modal_pug__WEBPACK_IMPORTED_MODULE_2___default.a;
this.controller = ConflictResolutionCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
item1: '=',
item2: '=',
callback: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/editorMenu.js":
/*!***************************************************************!*\
!*** ./app/assets/javascripts/directives/views/editorMenu.js ***!
\***************************************************************/
/*! exports provided: EditorMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EditorMenu", function() { return EditorMenu; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var _directives_editor_menu_pug__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! %/directives/editor-menu.pug */ "./app/assets/templates/directives/editor-menu.pug");
/* harmony import */ var _directives_editor_menu_pug__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_directives_editor_menu_pug__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _Controllers__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @Controllers */ "./app/assets/javascripts/controllers/index.js");
var EditorMenuCtrl =
/*#__PURE__*/
function (_PureCtrl) {
EditorMenuCtrl.$inject = ["$scope", "$timeout", "application", "appState"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(EditorMenuCtrl, _PureCtrl);
/* @ngInject */
function EditorMenuCtrl($scope, $timeout, application, appState) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, EditorMenuCtrl);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(EditorMenuCtrl).call(this, $scope, $timeout, application, appState));
_this.state = {
isDesktop: Object(_utils__WEBPACK_IMPORTED_MODULE_5__["isDesktopApplication"])()
};
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(EditorMenuCtrl, [{
key: "$onInit",
value: function $onInit() {
var editors = this.application.componentManager.componentsForArea('editor-editor').sort(function (a, b) {
return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1;
});
var defaultEditor = editors.filter(function (e) {
return e.isDefaultEditor();
})[0];
this.setState({
editors: editors,
defaultEditor: defaultEditor
});
}
}, {
key: "selectComponent",
value: function selectComponent(component) {
var _this2 = this;
if (component) {
if (component.content.conflict_of) {
component.content.conflict_of = null;
this.application.saveItem({
item: component
});
}
}
this.$timeout(function () {
_this2.callback()(component);
});
}
}, {
key: "toggleDefaultForEditor",
value: function toggleDefaultForEditor(editor) {
if (this.defaultEditor === editor) {
this.removeEditorDefault(editor);
} else {
this.makeEditorDefault(editor);
}
}
}, {
key: "offlineAvailableForComponent",
value: function offlineAvailableForComponent(component) {
return component.local_url && this.state.isDesktop;
}
}, {
key: "makeEditorDefault",
value: function makeEditorDefault(component) {
var currentDefault = this.application.componentManager.componentsForArea('editor-editor').filter(function (e) {
return e.isDefaultEditor();
})[0];
if (currentDefault) {
currentDefault.setAppDataItem('defaultEditor', false);
this.application.setItemsNeedsSync({
item: currentDefault
});
}
component.setAppDataItem('defaultEditor', true);
this.application.saveItem({
item: component
});
this.setState({
defaultEditor: component
});
}
}, {
key: "removeEditorDefault",
value: function removeEditorDefault(component) {
component.setAppDataItem('defaultEditor', false);
this.application.saveItem({
item: component
});
this.setState({
defaultEditor: null
});
}
}, {
key: "shouldDisplayRunningLocallyLabel",
value: function shouldDisplayRunningLocallyLabel(component) {
if (!component.runningLocally) {
return false;
}
if (component === this.selectedEditor) {
return true;
} else {
return false;
}
}
}]);
return EditorMenuCtrl;
}(_Controllers__WEBPACK_IMPORTED_MODULE_7__["PureCtrl"]);
var EditorMenu = function EditorMenu() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, EditorMenu);
this.restrict = 'E';
this.template = _directives_editor_menu_pug__WEBPACK_IMPORTED_MODULE_6___default.a;
this.controller = EditorMenuCtrl;
this.controllerAs = 'self';
this.bindToController = true;
this.scope = {
callback: '&',
selectedEditor: '=',
currentItem: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/index.js":
/*!**********************************************************!*\
!*** ./app/assets/javascripts/directives/views/index.js ***!
\**********************************************************/
/*! exports provided: AccountMenu, ActionsMenu, ComponentModal, ComponentView, ConflictResolutionModal, EditorMenu, InputModal, MenuRow, PanelResizer, PasswordWizard, PermissionsModal, PrivilegesAuthModal, PrivilegesManagementModal, RevisionPreviewModal, SessionHistoryMenu, SyncResolutionMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _accountMenu__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./accountMenu */ "./app/assets/javascripts/directives/views/accountMenu.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AccountMenu", function() { return _accountMenu__WEBPACK_IMPORTED_MODULE_0__["AccountMenu"]; });
/* harmony import */ var _actionsMenu__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./actionsMenu */ "./app/assets/javascripts/directives/views/actionsMenu.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ActionsMenu", function() { return _actionsMenu__WEBPACK_IMPORTED_MODULE_1__["ActionsMenu"]; });
/* harmony import */ var _componentModal__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./componentModal */ "./app/assets/javascripts/directives/views/componentModal.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ComponentModal", function() { return _componentModal__WEBPACK_IMPORTED_MODULE_2__["ComponentModal"]; });
/* harmony import */ var _componentView__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./componentView */ "./app/assets/javascripts/directives/views/componentView.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ComponentView", function() { return _componentView__WEBPACK_IMPORTED_MODULE_3__["ComponentView"]; });
/* harmony import */ var _conflictResolutionModal__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./conflictResolutionModal */ "./app/assets/javascripts/directives/views/conflictResolutionModal.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ConflictResolutionModal", function() { return _conflictResolutionModal__WEBPACK_IMPORTED_MODULE_4__["ConflictResolutionModal"]; });
/* harmony import */ var _editorMenu__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./editorMenu */ "./app/assets/javascripts/directives/views/editorMenu.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EditorMenu", function() { return _editorMenu__WEBPACK_IMPORTED_MODULE_5__["EditorMenu"]; });
/* harmony import */ var _inputModal__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./inputModal */ "./app/assets/javascripts/directives/views/inputModal.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InputModal", function() { return _inputModal__WEBPACK_IMPORTED_MODULE_6__["InputModal"]; });
/* harmony import */ var _menuRow__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./menuRow */ "./app/assets/javascripts/directives/views/menuRow.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MenuRow", function() { return _menuRow__WEBPACK_IMPORTED_MODULE_7__["MenuRow"]; });
/* harmony import */ var _panelResizer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./panelResizer */ "./app/assets/javascripts/directives/views/panelResizer.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PanelResizer", function() { return _panelResizer__WEBPACK_IMPORTED_MODULE_8__["PanelResizer"]; });
/* harmony import */ var _passwordWizard__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./passwordWizard */ "./app/assets/javascripts/directives/views/passwordWizard.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PasswordWizard", function() { return _passwordWizard__WEBPACK_IMPORTED_MODULE_9__["PasswordWizard"]; });
/* harmony import */ var _permissionsModal__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./permissionsModal */ "./app/assets/javascripts/directives/views/permissionsModal.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PermissionsModal", function() { return _permissionsModal__WEBPACK_IMPORTED_MODULE_10__["PermissionsModal"]; });
/* harmony import */ var _privilegesAuthModal__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./privilegesAuthModal */ "./app/assets/javascripts/directives/views/privilegesAuthModal.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrivilegesAuthModal", function() { return _privilegesAuthModal__WEBPACK_IMPORTED_MODULE_11__["PrivilegesAuthModal"]; });
/* harmony import */ var _privilegesManagementModal__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./privilegesManagementModal */ "./app/assets/javascripts/directives/views/privilegesManagementModal.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrivilegesManagementModal", function() { return _privilegesManagementModal__WEBPACK_IMPORTED_MODULE_12__["PrivilegesManagementModal"]; });
/* harmony import */ var _revisionPreviewModal__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./revisionPreviewModal */ "./app/assets/javascripts/directives/views/revisionPreviewModal.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RevisionPreviewModal", function() { return _revisionPreviewModal__WEBPACK_IMPORTED_MODULE_13__["RevisionPreviewModal"]; });
/* harmony import */ var _sessionHistoryMenu__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./sessionHistoryMenu */ "./app/assets/javascripts/directives/views/sessionHistoryMenu.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SessionHistoryMenu", function() { return _sessionHistoryMenu__WEBPACK_IMPORTED_MODULE_14__["SessionHistoryMenu"]; });
/* harmony import */ var _syncResolutionMenu__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./syncResolutionMenu */ "./app/assets/javascripts/directives/views/syncResolutionMenu.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SyncResolutionMenu", function() { return _syncResolutionMenu__WEBPACK_IMPORTED_MODULE_15__["SyncResolutionMenu"]; });
/***/ }),
/***/ "./app/assets/javascripts/directives/views/inputModal.js":
/*!***************************************************************!*\
!*** ./app/assets/javascripts/directives/views/inputModal.js ***!
\***************************************************************/
/*! exports provided: InputModal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InputModal", function() { return InputModal; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _directives_input_modal_pug__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! %/directives/input-modal.pug */ "./app/assets/templates/directives/input-modal.pug");
/* harmony import */ var _directives_input_modal_pug__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_directives_input_modal_pug__WEBPACK_IMPORTED_MODULE_2__);
var InputModalCtrl =
/*#__PURE__*/
function () {
InputModalCtrl.$inject = ["$scope", "$element"];
/* @ngInject */
function InputModalCtrl($scope, $element) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, InputModalCtrl);
this.$element = $element;
this.formData = {};
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(InputModalCtrl, [{
key: "dismiss",
value: function dismiss() {
this.$element.remove();
this.$scope.$destroy();
}
}, {
key: "submit",
value: function submit() {
this.callback()(this.formData.input);
this.dismiss();
}
}]);
return InputModalCtrl;
}();
var InputModal = function InputModal() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, InputModal);
this.restrict = 'E';
this.template = _directives_input_modal_pug__WEBPACK_IMPORTED_MODULE_2___default.a;
this.controller = InputModalCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
type: '=',
title: '=',
message: '=',
placeholder: '=',
callback: '&'
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/menuRow.js":
/*!************************************************************!*\
!*** ./app/assets/javascripts/directives/views/menuRow.js ***!
\************************************************************/
/*! exports provided: MenuRow */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MenuRow", function() { return MenuRow; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _directives_menu_row_pug__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! %/directives/menu-row.pug */ "./app/assets/templates/directives/menu-row.pug");
/* harmony import */ var _directives_menu_row_pug__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_directives_menu_row_pug__WEBPACK_IMPORTED_MODULE_2__);
var MenuRowCtrl =
/*#__PURE__*/
function () {
function MenuRowCtrl() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, MenuRowCtrl);
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(MenuRowCtrl, [{
key: "onClick",
value: function onClick($event) {
if (this.disabled) {
return;
}
$event.stopPropagation();
this.action();
}
}, {
key: "clickAccessoryButton",
value: function clickAccessoryButton($event) {
if (this.disabled) {
return;
}
$event.stopPropagation();
this.buttonAction();
}
}]);
return MenuRowCtrl;
}();
var MenuRow = function MenuRow() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, MenuRow);
this.restrict = 'E';
this.transclude = true;
this.template = _directives_menu_row_pug__WEBPACK_IMPORTED_MODULE_2___default.a;
this.controller = MenuRowCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
action: '&',
buttonAction: '&',
buttonClass: '=',
buttonText: '=',
desc: '=',
disabled: '=',
circle: '=',
circleAlign: '=',
faded: '=',
hasButton: '=',
label: '=',
spinnerClass: '=',
stylekitClass: '=',
subRows: '=',
subtitle: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/panelResizer.js":
/*!*****************************************************************!*\
!*** ./app/assets/javascripts/directives/views/panelResizer.js ***!
\*****************************************************************/
/*! exports provided: PanelResizer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PanelResizer", function() { return PanelResizer; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _directives_panel_resizer_pug__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! %/directives/panel-resizer.pug */ "./app/assets/templates/directives/panel-resizer.pug");
/* harmony import */ var _directives_panel_resizer_pug__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_directives_panel_resizer_pug__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
var PanelSides = {
Right: 'right',
Left: 'left'
};
var MouseEvents = {
Move: 'mousemove',
Down: 'mousedown',
Up: 'mouseup'
};
var CssClasses = {
Hoverable: 'hoverable',
AlwaysVisible: 'always-visible',
Dragging: 'dragging',
NoSelection: 'no-selection',
Collapsed: 'collapsed',
AnimateOpacity: 'animate-opacity'
};
var WINDOW_EVENT_RESIZE = 'resize';
var PanelResizerCtrl =
/*#__PURE__*/
function () {
PanelResizerCtrl.$inject = ["$compile", "$element", "$scope", "$timeout"];
/* @ngInject */
function PanelResizerCtrl($compile, $element, $scope, $timeout) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, PanelResizerCtrl);
this.$compile = $compile;
this.$element = $element;
this.$scope = $scope;
this.$timeout = $timeout;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(PanelResizerCtrl, [{
key: "$onInit",
value: function $onInit() {
this.configureControl();
this.configureDefaults();
this.addDoubleClickHandler();
this.reloadDefaultValues();
this.addMouseDownListener();
this.addMouseMoveListener();
this.addMouseUpListener();
}
}, {
key: "configureControl",
value: function configureControl() {
var _this = this;
this.control.setWidth = function (value) {
_this.setWidth(value, true);
};
this.control.setLeft = function (value) {
_this.setLeft(value);
};
this.control.flash = function () {
_this.flash();
};
this.control.isCollapsed = function () {
return _this.isCollapsed();
};
}
}, {
key: "configureDefaults",
value: function configureDefaults() {
this.panel = document.getElementById(this.panelId);
if (!this.panel) {
console.error('Panel not found for', this.panelId);
}
this.resizerColumn = this.$element[0];
this.currentMinWidth = this.minWidth || this.resizerColumn.offsetWidth;
this.pressed = false;
this.startWidth = this.panel.scrollWidth;
this.lastDownX = 0;
this.collapsed = false;
this.lastWidth = this.startWidth;
this.startLeft = this.panel.offsetLeft;
this.lastLeft = this.startLeft;
this.appFrame = null;
this.widthBeforeLastDblClick = 0;
if (this.property === PanelSides.Right) {
this.configureRightPanel();
}
if (this.alwaysVisible) {
this.resizerColumn.classList.add(CssClasses.AlwaysVisible);
}
if (this.hoverable) {
this.resizerColumn.classList.add(CssClasses.Hoverable);
}
}
}, {
key: "configureRightPanel",
value: function configureRightPanel() {
var _this2 = this;
var handleResize = Object(_utils__WEBPACK_IMPORTED_MODULE_4__["debounce"])(function (event) {
_this2.reloadDefaultValues();
_this2.handleWidthEvent();
_this2.$timeout(function () {
_this2.finishSettingWidth();
});
}, 250);
window.addEventListener(WINDOW_EVENT_RESIZE, handleResize);
this.$scope.$on('$destroy', function () {
window.removeEventListener(WINDOW_EVENT_RESIZE, handleResize);
});
}
}, {
key: "getParentRect",
value: function getParentRect() {
return this.panel.parentNode.getBoundingClientRect();
}
}, {
key: "reloadDefaultValues",
value: function reloadDefaultValues() {
this.startWidth = this.isAtMaxWidth() ? this.getParentRect().width : this.panel.scrollWidth;
this.lastWidth = this.startWidth;
this.appFrame = document.getElementById('app').getBoundingClientRect();
}
}, {
key: "addDoubleClickHandler",
value: function addDoubleClickHandler() {
var _this3 = this;
this.resizerColumn.ondblclick = function () {
_this3.$timeout(function () {
var preClickCollapseState = _this3.isCollapsed();
if (preClickCollapseState) {
_this3.setWidth(_this3.widthBeforeLastDblClick || _this3.defaultWidth);
} else {
_this3.widthBeforeLastDblClick = _this3.lastWidth;
_this3.setWidth(_this3.currentMinWidth);
}
_this3.finishSettingWidth();
var newCollapseState = !preClickCollapseState;
_this3.onResizeFinish()(_this3.lastWidth, _this3.lastLeft, _this3.isAtMaxWidth(), newCollapseState);
});
};
}
}, {
key: "addMouseDownListener",
value: function addMouseDownListener() {
var _this4 = this;
this.resizerColumn.addEventListener(MouseEvents.Down, function (event) {
_this4.addInvisibleOverlay();
_this4.pressed = true;
_this4.lastDownX = event.clientX;
_this4.startWidth = _this4.panel.scrollWidth;
_this4.startLeft = _this4.panel.offsetLeft;
_this4.panel.classList.add(CssClasses.NoSelection);
if (_this4.hoverable) {
_this4.resizerColumn.classList.add(CssClasses.Dragging);
}
});
}
}, {
key: "addMouseMoveListener",
value: function addMouseMoveListener() {
var _this5 = this;
document.addEventListener(MouseEvents.Move, function (event) {
if (!_this5.pressed) {
return;
}
event.preventDefault();
if (_this5.property && _this5.property === PanelSides.Left) {
_this5.handleLeftEvent(event);
} else {
_this5.handleWidthEvent(event);
}
});
}
}, {
key: "handleWidthEvent",
value: function handleWidthEvent(event) {
var x;
if (event) {
x = event.clientX;
} else {
/** Coming from resize event */
x = 0;
this.lastDownX = 0;
}
var deltaX = x - this.lastDownX;
var newWidth = this.startWidth + deltaX;
this.setWidth(newWidth, false);
if (this.onResize()) {
this.onResize()(this.lastWidth, this.panel);
}
}
}, {
key: "handleLeftEvent",
value: function handleLeftEvent(event) {
var panelRect = this.panel.getBoundingClientRect();
var x = event.clientX || panelRect.x;
var deltaX = x - this.lastDownX;
var newLeft = this.startLeft + deltaX;
if (newLeft < 0) {
newLeft = 0;
deltaX = -this.startLeft;
}
var parentRect = this.getParentRect();
var newWidth = this.startWidth - deltaX;
if (newWidth < this.currentMinWidth) {
newWidth = this.currentMinWidth;
}
if (newWidth > parentRect.width) {
newWidth = parentRect.width;
}
if (newLeft + newWidth > parentRect.width) {
newLeft = parentRect.width - newWidth;
}
this.setLeft(newLeft, false);
this.setWidth(newWidth, false);
}
}, {
key: "addMouseUpListener",
value: function addMouseUpListener() {
var _this6 = this;
document.addEventListener(MouseEvents.Up, function (event) {
_this6.removeInvisibleOverlay();
if (_this6.pressed) {
_this6.pressed = false;
_this6.resizerColumn.classList.remove(CssClasses.Dragging);
_this6.panel.classList.remove(CssClasses.NoSelection);
var isMaxWidth = _this6.isAtMaxWidth();
if (_this6.onResizeFinish) {
_this6.onResizeFinish()(_this6.lastWidth, _this6.lastLeft, isMaxWidth, _this6.isCollapsed());
}
_this6.finishSettingWidth();
}
});
}
}, {
key: "isAtMaxWidth",
value: function isAtMaxWidth() {
return Math.round(this.lastWidth + this.lastLeft) === Math.round(this.getParentRect().width);
}
}, {
key: "isCollapsed",
value: function isCollapsed() {
return this.lastWidth <= this.currentMinWidth;
}
}, {
key: "setWidth",
value: function setWidth(width, finish) {
if (width < this.currentMinWidth) {
width = this.currentMinWidth;
}
var parentRect = this.getParentRect();
if (width > parentRect.width) {
width = parentRect.width;
}
var maxWidth = this.appFrame.width - this.panel.getBoundingClientRect().x;
if (width > maxWidth) {
width = maxWidth;
}
if (Math.round(width + this.lastLeft) === Math.round(parentRect.width)) {
this.panel.style.width = "calc(100% - ".concat(this.lastLeft, "px)");
this.panel.style.flexBasis = "calc(100% - ".concat(this.lastLeft, "px)");
} else {
this.panel.style.flexBasis = width + 'px';
this.panel.style.width = width + 'px';
}
this.lastWidth = width;
if (finish) {
this.finishSettingWidth();
}
}
}, {
key: "setLeft",
value: function setLeft(left) {
this.panel.style.left = left + 'px';
this.lastLeft = left;
}
}, {
key: "finishSettingWidth",
value: function finishSettingWidth() {
if (!this.collapsable) {
return;
}
this.collapsed = this.isCollapsed();
if (this.collapsed) {
this.resizerColumn.classList.add(CssClasses.Collapsed);
} else {
this.resizerColumn.classList.remove(CssClasses.Collapsed);
}
}
/**
* If an iframe is displayed adjacent to our panel, and the mouse exits over the iframe,
* document[onmouseup] is not triggered because the document is no longer the same over
* the iframe. We add an invisible overlay while resizing so that the mouse context
* remains in our main document.
*/
}, {
key: "addInvisibleOverlay",
value: function addInvisibleOverlay() {
if (this.overlay) {
return;
}
this.overlay = this.$compile("")(this.$scope);
angular__WEBPACK_IMPORTED_MODULE_2___default.a.element(document.body).prepend(this.overlay);
}
}, {
key: "removeInvisibleOverlay",
value: function removeInvisibleOverlay() {
if (this.overlay) {
this.overlay.remove();
this.overlay = null;
}
}
}, {
key: "flash",
value: function flash() {
var _this7 = this;
var FLASH_DURATION = 3000;
this.resizerColumn.classList.add(CssClasses.AnimateOpacity);
this.$timeout(function () {
_this7.resizerColumn.classList.remove(CssClasses.AnimateOpacity);
}, FLASH_DURATION);
}
}]);
return PanelResizerCtrl;
}();
var PanelResizer = function PanelResizer() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, PanelResizer);
this.restrict = 'E';
this.template = _directives_panel_resizer_pug__WEBPACK_IMPORTED_MODULE_3___default.a;
this.controller = PanelResizerCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
alwaysVisible: '=',
collapsable: '=',
control: '=',
defaultWidth: '=',
hoverable: '=',
index: '=',
minWidth: '=',
onResize: '&',
onResizeFinish: '&',
panelId: '=',
property: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/passwordWizard.js":
/*!*******************************************************************!*\
!*** ./app/assets/javascripts/directives/views/passwordWizard.js ***!
\*******************************************************************/
/*! exports provided: PasswordWizard */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PasswordWizard", function() { return PasswordWizard; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _directives_password_wizard_pug__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! %/directives/password-wizard.pug */ "./app/assets/templates/directives/password-wizard.pug");
/* harmony import */ var _directives_password_wizard_pug__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_directives_password_wizard_pug__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _strings__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/strings */ "./app/assets/javascripts/strings.js");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../utils */ "./app/assets/javascripts/utils.js");
var DEFAULT_CONTINUE_TITLE = "Continue";
var Steps = {
IntroStep: 0,
BackupStep: 1,
SignoutStep: 2,
PasswordStep: 3,
SyncStep: 4,
FinishStep: 5
};
var PasswordWizardCtrl =
/*#__PURE__*/
function () {
PasswordWizardCtrl.$inject = ["$element", "$scope", "$timeout", "archiveManager"];
/* @ngInject */
function PasswordWizardCtrl($element, $scope, $timeout, archiveManager) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, PasswordWizardCtrl);
this.$element = $element;
this.$timeout = $timeout;
this.$scope = $scope;
this.archiveManager = archiveManager;
this.registerWindowUnloadStopper();
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(PasswordWizardCtrl, [{
key: "$onInit",
value: function $onInit() {
this.syncStatus = this.application.getSyncStatus();
this.formData = {};
this.configureDefaults();
}
}, {
key: "configureDefaults",
value: function configureDefaults() {
if (this.type === 'change-pw') {
this.title = "Change Password";
this.changePassword = true;
} else if (this.type === 'upgrade-security') {
this.title = "Account Update";
this.securityUpdate = true;
}
this.continueTitle = DEFAULT_CONTINUE_TITLE;
this.step = Steps.IntroStep;
}
/** Confirms with user before closing tab */
}, {
key: "registerWindowUnloadStopper",
value: function registerWindowUnloadStopper() {
window.onbeforeunload = function (e) {
return true;
};
this.$scope.$on("$destroy", function () {
window.onbeforeunload = null;
});
}
}, {
key: "titleForStep",
value: function titleForStep(step) {
switch (step) {
case Steps.BackupStep:
return "Download a backup of your data";
case Steps.SignoutStep:
return "Sign out of all your devices";
case Steps.PasswordStep:
return this.changePassword ? "Password information" : "Enter your current password";
case Steps.SyncStep:
return "Encrypt and sync data with new keys";
case Steps.FinishStep:
return "Sign back in to your devices";
default:
return null;
}
}
}, {
key: "nextStep",
value: function () {
var _nextStep = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var _this = this;
var next, preprocessor;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!(this.lockContinue || this.isContinuing)) {
_context.next = 2;
break;
}
return _context.abrupt("return");
case 2:
this.isContinuing = true;
if (!(this.step === Steps.FinishStep)) {
_context.next = 6;
break;
}
this.dismiss();
return _context.abrupt("return");
case 6:
next = function next() {
_this.step++;
_this.initializeStep(_this.step);
_this.isContinuing = false;
};
preprocessor = this.preprocessorForStep(this.step);
if (!preprocessor) {
_context.next = 13;
break;
}
_context.next = 11;
return preprocessor().then(next).catch(function () {
_this.isContinuing = false;
});
case 11:
_context.next = 14;
break;
case 13:
next();
case 14:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function nextStep() {
return _nextStep.apply(this, arguments);
}
return nextStep;
}()
}, {
key: "preprocessorForStep",
value: function preprocessorForStep(step) {
var _this2 = this;
if (step === Steps.PasswordStep) {
return (
/*#__PURE__*/
_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var success;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_this2.showSpinner = true;
_this2.continueTitle = "Generating Keys...";
_context2.next = 4;
return _this2.validateCurrentPassword();
case 4:
success = _context2.sent;
_this2.showSpinner = false;
_this2.continueTitle = DEFAULT_CONTINUE_TITLE;
return _context2.abrupt("return", success);
case 8:
case "end":
return _context2.stop();
}
}
}, _callee2);
}))
);
}
}
}, {
key: "initializeStep",
value: function () {
var _initializeStep = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(step) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!(step === Steps.SyncStep)) {
_context3.next = 5;
break;
}
_context3.next = 3;
return this.initializeSyncingStep();
case 3:
_context3.next = 6;
break;
case 5:
if (step === Steps.FinishStep) {
this.continueTitle = "Finish";
}
case 6:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function initializeStep(_x) {
return _initializeStep.apply(this, arguments);
}
return initializeStep;
}()
}, {
key: "initializeSyncingStep",
value: function () {
var _initializeSyncingStep = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4() {
var passwordSuccess;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
this.lockContinue = true;
this.formData.status = "Processing encryption keys...";
this.formData.processing = true;
_context4.next = 5;
return this.processPasswordChange();
case 5:
passwordSuccess = _context4.sent;
this.formData.statusError = !passwordSuccess;
this.formData.processing = passwordSuccess;
if (passwordSuccess) {
_context4.next = 11;
break;
}
this.formData.status = "Unable to process your password. Please try again.";
return _context4.abrupt("return");
case 11:
this.lockContinue = false;
if (this.changePassword) {
this.formData.status = "Successfully changed password.";
} else if (this.securityUpdate) {
this.formData.status = "Successfully performed account update.";
}
case 13:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function initializeSyncingStep() {
return _initializeSyncingStep.apply(this, arguments);
}
return initializeSyncingStep;
}()
}, {
key: "validateCurrentPassword",
value: function () {
var _validateCurrentPassword = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5() {
var currentPassword, newPass, key;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
currentPassword = this.formData.currentPassword;
newPass = this.securityUpdate ? currentPassword : this.formData.newPassword;
if (!(!currentPassword || currentPassword.length === 0)) {
_context5.next = 5;
break;
}
this.application.alertManager.alert({
text: "Please enter your current password."
});
return _context5.abrupt("return", false);
case 5:
if (!this.changePassword) {
_context5.next = 13;
break;
}
if (!(!newPass || newPass.length === 0)) {
_context5.next = 9;
break;
}
this.application.alertManager.alert({
text: "Please enter a new password."
});
return _context5.abrupt("return", false);
case 9:
if (!(newPass !== this.formData.newPasswordConfirmation)) {
_context5.next = 13;
break;
}
this.application.alertManager.alert({
text: "Your new password does not match its confirmation."
});
this.formData.status = null;
return _context5.abrupt("return", false);
case 13:
if (this.application.getUser().email) {
_context5.next = 17;
break;
}
this.application.alertManager.alert({
text: "We don't have your email stored. Please log out then log back in to fix this issue."
});
this.formData.status = null;
return _context5.abrupt("return", false);
case 17:
_context5.next = 19;
return this.application.validateAccountPassword({
password: this.formData.currentPassword
});
case 19:
key = _context5.sent;
if (key) {
this.currentServerPassword = key.serverPassword;
} else {
this.application.alertManager.alert({
text: "The current password you entered is not correct. Please try again."
});
}
return _context5.abrupt("return", !Object(_utils__WEBPACK_IMPORTED_MODULE_6__["isNullOrUndefined"])(key));
case 22:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function validateCurrentPassword() {
return _validateCurrentPassword.apply(this, arguments);
}
return validateCurrentPassword;
}()
}, {
key: "processPasswordChange",
value: function () {
var _processPasswordChange = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee6() {
var newPassword, response;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
newPassword = this.securityUpdate ? this.formData.currentPassword : this.formData.newPassword;
_context6.next = 3;
return this.application.changePassword({
email: this.application.getUser().email,
currentPassword: this.formData.currentPassword,
newPassword: newPassword
});
case 3:
response = _context6.sent;
if (!response.error) {
_context6.next = 9;
break;
}
this.application.alertManager.alert({
text: response.error.message ? response.error.message : "There was an error changing your password. Please try again."
});
return _context6.abrupt("return", false);
case 9:
return _context6.abrupt("return", true);
case 10:
case "end":
return _context6.stop();
}
}
}, _callee6, this);
}));
function processPasswordChange() {
return _processPasswordChange.apply(this, arguments);
}
return processPasswordChange;
}()
}, {
key: "downloadBackup",
value: function downloadBackup(encrypted) {
this.archiveManager.downloadBackup(encrypted);
}
}, {
key: "dismiss",
value: function dismiss() {
if (this.lockContinue) {
this.application.alertManager.alert({
text: "Cannot close window until pending tasks are complete."
});
} else {
this.$element.remove();
this.$scope.$destroy();
}
}
}]);
return PasswordWizardCtrl;
}();
var PasswordWizard = function PasswordWizard() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, PasswordWizard);
this.restrict = 'E';
this.template = _directives_password_wizard_pug__WEBPACK_IMPORTED_MODULE_4___default.a;
this.controller = PasswordWizardCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
type: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/permissionsModal.js":
/*!*********************************************************************!*\
!*** ./app/assets/javascripts/directives/views/permissionsModal.js ***!
\*********************************************************************/
/*! exports provided: PermissionsModal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PermissionsModal", function() { return PermissionsModal; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _directives_permissions_modal_pug__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! %/directives/permissions-modal.pug */ "./app/assets/templates/directives/permissions-modal.pug");
/* harmony import */ var _directives_permissions_modal_pug__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_directives_permissions_modal_pug__WEBPACK_IMPORTED_MODULE_2__);
var PermissionsModalCtrl =
/*#__PURE__*/
function () {
PermissionsModalCtrl.$inject = ["$element"];
/* @ngInject */
function PermissionsModalCtrl($element) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, PermissionsModalCtrl);
this.$element = $element;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(PermissionsModalCtrl, [{
key: "dismiss",
value: function dismiss() {
this.$element.remove();
}
}, {
key: "accept",
value: function accept() {
this.callback(true);
this.dismiss();
}
}, {
key: "deny",
value: function deny() {
this.callback(false);
this.dismiss();
}
}]);
return PermissionsModalCtrl;
}();
var PermissionsModal = function PermissionsModal() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, PermissionsModal);
this.restrict = 'E';
this.template = _directives_permissions_modal_pug__WEBPACK_IMPORTED_MODULE_2___default.a;
this.controller = PermissionsModalCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
show: '=',
component: '=',
permissionsString: '=',
callback: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/privilegesAuthModal.js":
/*!************************************************************************!*\
!*** ./app/assets/javascripts/directives/views/privilegesAuthModal.js ***!
\************************************************************************/
/*! exports provided: PrivilegesAuthModal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PrivilegesAuthModal", function() { return PrivilegesAuthModal; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _directives_privileges_auth_modal_pug__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! %/directives/privileges-auth-modal.pug */ "./app/assets/templates/directives/privileges-auth-modal.pug");
/* harmony import */ var _directives_privileges_auth_modal_pug__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_directives_privileges_auth_modal_pug__WEBPACK_IMPORTED_MODULE_4__);
var PrivilegesAuthModalCtrl =
/*#__PURE__*/
function () {
PrivilegesAuthModalCtrl.$inject = ["$element", "$timeout", "application"];
/* @ngInject */
function PrivilegesAuthModalCtrl($element, $timeout, application) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, PrivilegesAuthModalCtrl);
this.$element = $element;
this.$timeout = $timeout;
this.application = application;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(PrivilegesAuthModalCtrl, [{
key: "$onInit",
value: function $onInit() {
var _this = this;
this.authParameters = {};
this.sessionLengthOptions = this.application.privilegesManager.getSessionLengthOptions();
this.application.privilegesManager.getSelectedSessionLength().then(function (length) {
_this.$timeout(function () {
_this.selectedSessionLength = length;
});
});
this.application.privilegesManager.netCredentialsForAction(this.action).then(function (credentials) {
_this.$timeout(function () {
_this.requiredCredentials = credentials.sort();
});
});
}
}, {
key: "selectSessionLength",
value: function selectSessionLength(length) {
this.selectedSessionLength = length;
}
}, {
key: "promptForCredential",
value: function promptForCredential(credential) {
return this.application.privilegesManager.displayInfoForCredential(credential).prompt;
}
}, {
key: "cancel",
value: function cancel() {
this.dismiss();
this.onCancel && this.onCancel();
}
}, {
key: "isCredentialInFailureState",
value: function isCredentialInFailureState(credential) {
if (!this.failedCredentials) {
return false;
}
return this.failedCredentials.find(function (candidate) {
return candidate === credential;
}) != null;
}
}, {
key: "validate",
value: function validate() {
var failed = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.requiredCredentials[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var cred = _step.value;
var value = this.authParameters[cred];
if (!value || value.length === 0) {
failed.push(cred);
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
this.failedCredentials = failed;
return failed.length === 0;
}
}, {
key: "submit",
value: function () {
var _submit = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var _this2 = this;
var result;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (this.validate()) {
_context.next = 2;
break;
}
return _context.abrupt("return");
case 2:
_context.next = 4;
return this.application.privilegesManager.authenticateAction(this.action, this.authParameters);
case 4:
result = _context.sent;
this.$timeout(function () {
if (result.success) {
_this2.application.privilegesManager.setSessionLength(_this2.selectedSessionLength);
_this2.onSuccess();
_this2.dismiss();
} else {
_this2.failedCredentials = result.failedCredentials;
}
});
case 6:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function submit() {
return _submit.apply(this, arguments);
}
return submit;
}()
}, {
key: "dismiss",
value: function dismiss() {
this.$element.remove();
}
}]);
return PrivilegesAuthModalCtrl;
}();
var PrivilegesAuthModal = function PrivilegesAuthModal() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, PrivilegesAuthModal);
this.restrict = 'E';
this.template = _directives_privileges_auth_modal_pug__WEBPACK_IMPORTED_MODULE_4___default.a;
this.controller = PrivilegesAuthModalCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
action: '=',
onSuccess: '=',
onCancel: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/privilegesManagementModal.js":
/*!******************************************************************************!*\
!*** ./app/assets/javascripts/directives/views/privilegesManagementModal.js ***!
\******************************************************************************/
/*! exports provided: PrivilegesManagementModal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PrivilegesManagementModal", function() { return PrivilegesManagementModal; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _directives_privileges_management_modal_pug__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! %/directives/privileges-management-modal.pug */ "./app/assets/templates/directives/privileges-management-modal.pug");
/* harmony import */ var _directives_privileges_management_modal_pug__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_directives_privileges_management_modal_pug__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_5__);
var PrivilegesManagementModalCtrl =
/*#__PURE__*/
function () {
PrivilegesManagementModalCtrl.$inject = ["$timeout", "$element", "application"];
/* @ngInject */
function PrivilegesManagementModalCtrl($timeout, $element, application) {
var _this = this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, PrivilegesManagementModalCtrl);
this.$element = $element;
this.$timeout = $timeout;
this.application = application;
application.onUnlock(function () {
_this.hasPasscode = application.hasPasscode();
_this.hasAccount = !application.noAccount();
_this.reloadPrivileges();
});
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(PrivilegesManagementModalCtrl, [{
key: "displayInfoForCredential",
value: function displayInfoForCredential(credential) {
var info = this.application.privilegesManager.displayInfoForCredential(credential);
if (credential === snjs__WEBPACK_IMPORTED_MODULE_5__["PrivilegeCredentials"].LocalPasscode) {
info.availability = this.hasPasscode;
} else if (credential === snjs__WEBPACK_IMPORTED_MODULE_5__["PrivilegeCredentials"].AccountPassword) {
info.availability = this.hasAccount;
} else {
info.availability = true;
}
return info;
}
}, {
key: "displayInfoForAction",
value: function displayInfoForAction(action) {
return this.application.privilegesManager.displayInfoForAction(action).label;
}
}, {
key: "isCredentialRequiredForAction",
value: function isCredentialRequiredForAction(action, credential) {
if (!this.privileges) {
return false;
}
return this.privileges.isCredentialRequiredForAction(action, credential);
}
}, {
key: "clearSession",
value: function () {
var _clearSession = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return this.application.privilegesManager.clearSession();
case 2:
this.reloadPrivileges();
case 3:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function clearSession() {
return _clearSession.apply(this, arguments);
}
return clearSession;
}()
}, {
key: "reloadPrivileges",
value: function () {
var _reloadPrivileges = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var _this2 = this;
var sessionEndDate, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, cred, privs;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
this.availableActions = this.application.privilegesManager.getAvailableActions();
this.availableCredentials = this.application.privilegesManager.getAvailableCredentials();
_context2.next = 4;
return this.application.privilegesManager.getSessionExpirey();
case 4:
sessionEndDate = _context2.sent;
this.sessionExpirey = sessionEndDate.toLocaleString();
this.sessionExpired = new Date() >= sessionEndDate;
this.credentialDisplayInfo = {};
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
_context2.prev = 11;
for (_iterator = this.availableCredentials[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
cred = _step.value;
this.credentialDisplayInfo[cred] = this.displayInfoForCredential(cred);
}
_context2.next = 19;
break;
case 15:
_context2.prev = 15;
_context2.t0 = _context2["catch"](11);
_didIteratorError = true;
_iteratorError = _context2.t0;
case 19:
_context2.prev = 19;
_context2.prev = 20;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 22:
_context2.prev = 22;
if (!_didIteratorError) {
_context2.next = 25;
break;
}
throw _iteratorError;
case 25:
return _context2.finish(22);
case 26:
return _context2.finish(19);
case 27:
_context2.next = 29;
return this.application.privilegesManager.getPrivileges();
case 29:
privs = _context2.sent;
this.$timeout(function () {
_this2.privileges = privs;
});
case 31:
case "end":
return _context2.stop();
}
}
}, _callee2, this, [[11, 15, 19, 27], [20,, 22, 26]]);
}));
function reloadPrivileges() {
return _reloadPrivileges.apply(this, arguments);
}
return reloadPrivileges;
}()
}, {
key: "checkboxValueChanged",
value: function checkboxValueChanged(action, credential) {
this.privileges.toggleCredentialForAction(action, credential);
this.application.privilegesManager.savePrivileges();
}
}, {
key: "cancel",
value: function cancel() {
this.dismiss();
this.onCancel && this.onCancel();
}
}, {
key: "dismiss",
value: function dismiss() {
this.$element.remove();
}
}]);
return PrivilegesManagementModalCtrl;
}();
var PrivilegesManagementModal = function PrivilegesManagementModal() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, PrivilegesManagementModal);
this.restrict = 'E';
this.template = _directives_privileges_management_modal_pug__WEBPACK_IMPORTED_MODULE_4___default.a;
this.controller = PrivilegesManagementModalCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/revisionPreviewModal.js":
/*!*************************************************************************!*\
!*** ./app/assets/javascripts/directives/views/revisionPreviewModal.js ***!
\*************************************************************************/
/*! exports provided: RevisionPreviewModal */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RevisionPreviewModal", function() { return RevisionPreviewModal; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _directives_revision_preview_modal_pug__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! %/directives/revision-preview-modal.pug */ "./app/assets/templates/directives/revision-preview-modal.pug");
/* harmony import */ var _directives_revision_preview_modal_pug__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_directives_revision_preview_modal_pug__WEBPACK_IMPORTED_MODULE_5__);
var RevisionPreviewModalCtrl =
/*#__PURE__*/
function () {
RevisionPreviewModalCtrl.$inject = ["$element", "$scope", "$timeout", "application"];
/* @ngInject */
function RevisionPreviewModalCtrl($element, $scope, $timeout, application) {
var _this = this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, RevisionPreviewModalCtrl);
this.$element = $element;
this.$scope = $scope;
this.$timeout = $timeout;
this.application = application;
this.configure();
$scope.$on('$destroy', function () {
if (_this.identifier) {
_this.application.componentManager.deregisterHandler(_this.identifier);
}
});
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(RevisionPreviewModalCtrl, [{
key: "configure",
value: function () {
var _configure = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var _this2 = this;
var editorForNote, editorCopy;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return this.application.createItem({
contentType: snjs__WEBPACK_IMPORTED_MODULE_4__["ContentTypes"].Note,
content: this.content
});
case 2:
this.note = _context.sent;
/**
* Set UUID so editoForNote can find proper editor, but then generate new uuid
* for note as not to save changes to original, if editor makes changes.
*/
this.note.uuid = this.uuid;
editorForNote = this.application.componentManager.editorForNote(this.note);
_context.next = 7;
return this.application.generateUuid();
case 7:
this.note.uuid = _context.sent;
if (!editorForNote) {
_context.next = 17;
break;
}
_context.next = 11;
return this.application.createItem({
contentType: snjs__WEBPACK_IMPORTED_MODULE_4__["ContentTypes"].Component,
content: editorForNote.content
});
case 11:
editorCopy = _context.sent;
editorCopy.readonly = true;
editorCopy.lockReadonly = true;
this.identifier = editorCopy.uuid;
this.application.componentManager.registerHandler({
identifier: this.identifier,
areas: ['editor-editor'],
contextRequestHandler: function contextRequestHandler(component) {
if (component === _this2.editor) {
return _this2.note;
}
},
componentForSessionKeyHandler: function componentForSessionKeyHandler(key) {
if (key === _this2.editor.sessionKey) {
return _this2.editor;
}
}
});
this.editor = editorCopy;
case 17:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function configure() {
return _configure.apply(this, arguments);
}
return configure;
}()
}, {
key: "restore",
value: function restore(asCopy) {
var _this3 = this;
var run =
/*#__PURE__*/
function () {
var _ref = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var item, contentCopy, uuid;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
if (!asCopy) {
_context2.next = 8;
break;
}
contentCopy = Object.assign({}, _this3.content);
if (contentCopy.title) {
contentCopy.title += " (copy)";
}
_context2.next = 5;
return _this3.application.createItem({
contentType: 'Note',
content: contentCopy,
needsSync: true
});
case 5:
item = _context2.sent;
_context2.next = 13;
break;
case 8:
uuid = _this3.uuid;
item = _this3.application.findItem({
uuid: uuid
});
item.content = Object.assign({}, _this3.content);
_context2.next = 13;
return _this3.application.mergeItem({
item: item,
source: snjs__WEBPACK_IMPORTED_MODULE_4__["PAYLOAD_SOURCE_REMOTE_ACTION_RETRIEVED"]
});
case 13:
_this3.application.saveItem({
item: item
});
_this3.dismiss();
case 15:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function run() {
return _ref.apply(this, arguments);
};
}();
if (!asCopy) {
this.application.alertManager.confirm({
text: "Are you sure you want to replace the current note's contents with what you see in this preview?",
destructive: true,
onConfirm: run
});
} else {
run();
}
}
}, {
key: "dismiss",
value: function dismiss() {
this.$element.remove();
this.$scope.$destroy();
}
}]);
return RevisionPreviewModalCtrl;
}();
var RevisionPreviewModal = function RevisionPreviewModal() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, RevisionPreviewModal);
this.restrict = 'E';
this.template = _directives_revision_preview_modal_pug__WEBPACK_IMPORTED_MODULE_5___default.a;
this.controller = RevisionPreviewModalCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
uuid: '=',
content: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/sessionHistoryMenu.js":
/*!***********************************************************************!*\
!*** ./app/assets/javascripts/directives/views/sessionHistoryMenu.js ***!
\***********************************************************************/
/*! exports provided: SessionHistoryMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SessionHistoryMenu", function() { return SessionHistoryMenu; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _directives_session_history_menu_pug__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! %/directives/session-history-menu.pug */ "./app/assets/templates/directives/session-history-menu.pug");
/* harmony import */ var _directives_session_history_menu_pug__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_directives_session_history_menu_pug__WEBPACK_IMPORTED_MODULE_2__);
var SessionHistoryMenuCtrl =
/*#__PURE__*/
function () {
SessionHistoryMenuCtrl.$inject = ["$timeout", "godService", "application"];
/* @ngInject */
function SessionHistoryMenuCtrl($timeout, godService, application) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, SessionHistoryMenuCtrl);
this.$timeout = $timeout;
this.godService = godService;
this.application = application;
this.diskEnabled = this.application.historyManager.isDiskEnabled();
this.autoOptimize = this.application.historyManager.isAutoOptimizeEnabled();
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(SessionHistoryMenuCtrl, [{
key: "$onInit",
value: function $onInit() {
this.reloadHistory();
}
}, {
key: "reloadHistory",
value: function reloadHistory() {
var history = this.application.historyManager.historyForItem(this.item);
this.entries = history.entries.slice(0).sort(function (a, b) {
return a.item.updated_at < b.item.updated_at ? 1 : -1;
});
this.history = history;
}
}, {
key: "openRevision",
value: function openRevision(revision) {
this.godService.presentRevisionPreviewModal(revision.item.uuid, revision.item.content);
}
}, {
key: "classForRevision",
value: function classForRevision(revision) {
var vector = revision.operationVector();
if (vector === 0) {
return 'default';
} else if (vector === 1) {
return 'success';
} else if (vector === -1) {
return 'danger';
}
}
}, {
key: "clearItemHistory",
value: function clearItemHistory() {
var _this = this;
this.application.alertManager.confirm({
text: "Are you sure you want to delete the local session history for this note?",
destructive: true,
onConfirm: function onConfirm() {
_this.application.historyManager.clearHistoryForItem(_this.item).then(function () {
_this.$timeout(function () {
_this.reloadHistory();
});
});
}
});
}
}, {
key: "clearAllHistory",
value: function clearAllHistory() {
var _this2 = this;
this.application.alertManager.confirm({
text: "Are you sure you want to delete the local session history for all notes?",
destructive: true,
onConfirm: function onConfirm() {
_this2.application.historyManager.clearAllHistory().then(function () {
_this2.$timeout(function () {
_this2.reloadHistory();
});
});
}
});
}
}, {
key: "toggleDiskSaving",
value: function toggleDiskSaving() {
var _this3 = this;
var run = function run() {
_this3.application.historyManager.toggleDiskSaving().then(function () {
_this3.$timeout(function () {
_this3.diskEnabled = _this3.application.historyManager.diskEnabled;
});
});
};
if (!this.application.historyManager.diskEnabled) {
this.application.alertManager.confirm({
text: "Are you sure you want to save history to disk? This will decrease general \n performance, especially as you type. You are advised to disable this feature \n if you experience any lagging.",
destructive: true,
onConfirm: run
});
} else {
run();
}
}
}, {
key: "toggleAutoOptimize",
value: function toggleAutoOptimize() {
var _this4 = this;
this.application.historyManager.toggleAutoOptimize().then(function () {
_this4.$timeout(function () {
_this4.autoOptimize = _this4.application.historyManager.autoOptimize;
});
});
}
}]);
return SessionHistoryMenuCtrl;
}();
var SessionHistoryMenu = function SessionHistoryMenu() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, SessionHistoryMenu);
this.restrict = 'E';
this.template = _directives_session_history_menu_pug__WEBPACK_IMPORTED_MODULE_2___default.a;
this.controller = SessionHistoryMenuCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
item: '='
};
};
/***/ }),
/***/ "./app/assets/javascripts/directives/views/syncResolutionMenu.js":
/*!***********************************************************************!*\
!*** ./app/assets/javascripts/directives/views/syncResolutionMenu.js ***!
\***********************************************************************/
/*! exports provided: SyncResolutionMenu */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SyncResolutionMenu", function() { return SyncResolutionMenu; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _directives_sync_resolution_menu_pug__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! %/directives/sync-resolution-menu.pug */ "./app/assets/templates/directives/sync-resolution-menu.pug");
/* harmony import */ var _directives_sync_resolution_menu_pug__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_directives_sync_resolution_menu_pug__WEBPACK_IMPORTED_MODULE_4__);
var SyncResolutionMenuCtrl =
/*#__PURE__*/
function () {
SyncResolutionMenuCtrl.$inject = ["$timeout", "archiveManager", "application"];
/* @ngInject */
function SyncResolutionMenuCtrl($timeout, archiveManager, application) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, SyncResolutionMenuCtrl);
this.$timeout = $timeout;
this.archiveManager = archiveManager;
this.application = application;
this.status = {};
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(SyncResolutionMenuCtrl, [{
key: "downloadBackup",
value: function downloadBackup(encrypted) {
this.archiveManager.downloadBackup(encrypted);
this.status.backupFinished = true;
}
}, {
key: "skipBackup",
value: function skipBackup() {
this.status.backupFinished = true;
}
}, {
key: "performSyncResolution",
value: function () {
var _performSyncResolution = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var _this = this;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
this.status.resolving = true;
_context.next = 3;
return this.application.resolveOutOfSync();
case 3:
this.$timeout(function () {
_this.status.resolving = false;
_this.status.attemptedResolution = true;
if (_this.application.getSyncStatus().isOutOfSync()) {
_this.status.fail = true;
} else {
_this.status.success = true;
}
});
case 4:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function performSyncResolution() {
return _performSyncResolution.apply(this, arguments);
}
return performSyncResolution;
}()
}, {
key: "close",
value: function close() {
var _this2 = this;
this.$timeout(function () {
_this2.closeFunction()();
});
}
}]);
return SyncResolutionMenuCtrl;
}();
var SyncResolutionMenu = function SyncResolutionMenu() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, SyncResolutionMenu);
this.restrict = 'E';
this.template = _directives_sync_resolution_menu_pug__WEBPACK_IMPORTED_MODULE_4___default.a;
this.controller = SyncResolutionMenuCtrl;
this.controllerAs = 'ctrl';
this.bindToController = true;
this.scope = {
closeFunction: '&'
};
};
/***/ }),
/***/ "./app/assets/javascripts/filters/index.js":
/*!*************************************************!*\
!*** ./app/assets/javascripts/filters/index.js ***!
\*************************************************/
/*! exports provided: trusted */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _trusted__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./trusted */ "./app/assets/javascripts/filters/trusted.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "trusted", function() { return _trusted__WEBPACK_IMPORTED_MODULE_0__["trusted"]; });
/***/ }),
/***/ "./app/assets/javascripts/filters/trusted.js":
/*!***************************************************!*\
!*** ./app/assets/javascripts/filters/trusted.js ***!
\***************************************************/
/*! exports provided: trusted */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "trusted", function() { return trusted; });
trusted.$inject = ["$sce"];
/* @ngInject */
function trusted($sce) {
return function (url) {
return $sce.trustAsResourceUrl(url);
};
}
/***/ }),
/***/ "./app/assets/javascripts/index.js":
/*!*****************************************!*\
!*** ./app/assets/javascripts/index.js ***!
\*****************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var sn_stylekit_dist_stylekit_css__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! sn-stylekit/dist/stylekit.css */ "./node_modules/sn-stylekit/dist/stylekit.css");
/* harmony import */ var sn_stylekit_dist_stylekit_css__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(sn_stylekit_dist_stylekit_css__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _stylesheets_index_css_scss__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../stylesheets/index.css.scss */ "./app/assets/stylesheets/index.css.scss");
/* harmony import */ var _stylesheets_index_css_scss__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_stylesheets_index_css_scss__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _vendor_assets_javascripts_angular_sanitize__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../vendor/assets/javascripts/angular-sanitize */ "./vendor/assets/javascripts/angular-sanitize.js");
/* harmony import */ var _vendor_assets_javascripts_angular_sanitize__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_vendor_assets_javascripts_angular_sanitize__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _vendor_assets_javascripts_zip_deflate__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../vendor/assets/javascripts/zip/deflate */ "./vendor/assets/javascripts/zip/deflate.js");
/* harmony import */ var _vendor_assets_javascripts_zip_deflate__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_vendor_assets_javascripts_zip_deflate__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _vendor_assets_javascripts_zip_inflate__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../vendor/assets/javascripts/zip/inflate */ "./vendor/assets/javascripts/zip/inflate.js");
/* harmony import */ var _vendor_assets_javascripts_zip_inflate__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_vendor_assets_javascripts_zip_inflate__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _vendor_assets_javascripts_zip_zip__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../../vendor/assets/javascripts/zip/zip */ "./vendor/assets/javascripts/zip/zip.js");
/* harmony import */ var _vendor_assets_javascripts_zip_zip__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_vendor_assets_javascripts_zip_zip__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _vendor_assets_javascripts_zip_z_worker__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../../vendor/assets/javascripts/zip/z-worker */ "./vendor/assets/javascripts/zip/z-worker.js");
/* harmony import */ var _vendor_assets_javascripts_zip_z_worker__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_vendor_assets_javascripts_zip_z_worker__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _app__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./app */ "./app/assets/javascripts/app.js");
//= require_tree ./app
// css
// Vendor
// entry point
// eslint-disable-next-line import/first
/***/ }),
/***/ "./app/assets/javascripts/routes.js":
/*!******************************************!*\
!*** ./app/assets/javascripts/routes.js ***!
\******************************************/
/*! exports provided: configRoutes */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "configRoutes", function() { return configRoutes; });
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils */ "./app/assets/javascripts/utils.js");
configRoutes.$inject = ["$locationProvider"];
/* @ngInject */
function configRoutes($locationProvider) {
if (!Object(_utils__WEBPACK_IMPORTED_MODULE_0__["isDesktopApplication"])()) {
if (window.history && window.history.pushState) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}
} else {
$locationProvider.html5Mode(false);
}
}
/***/ }),
/***/ "./app/assets/javascripts/services/alertManager.js":
/*!*********************************************************!*\
!*** ./app/assets/javascripts/services/alertManager.js ***!
\*********************************************************/
/*! exports provided: AlertManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AlertManager", function() { return AlertManager; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var sn_stylekit__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! sn-stylekit */ "./node_modules/sn-stylekit/dist/stylekit.js");
/* harmony import */ var sn_stylekit__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(sn_stylekit__WEBPACK_IMPORTED_MODULE_8__);
/* eslint-disable prefer-promise-reject-errors */
var AlertManager =
/*#__PURE__*/
function (_SNAlertManager) {
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6___default()(AlertManager, _SNAlertManager);
function AlertManager() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, AlertManager);
return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(AlertManager).apply(this, arguments));
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(AlertManager, [{
key: "alert",
value: function () {
var _alert = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var _this = this;
var _ref,
title,
text,
_ref$closeButtonText,
closeButtonText,
onClose,
_args2 = arguments;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_ref = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, title = _ref.title, text = _ref.text, _ref$closeButtonText = _ref.closeButtonText, closeButtonText = _ref$closeButtonText === void 0 ? "OK" : _ref$closeButtonText, onClose = _ref.onClose;
return _context2.abrupt("return", new Promise(function (resolve, reject) {
var buttons = [{
text: closeButtonText,
style: "neutral",
action: function () {
var _action = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (onClose) {
_this.deviceInterface.timeout(onClose);
}
resolve(true);
case 2:
case "end":
return _context.stop();
}
}
}, _callee);
}));
function action() {
return _action.apply(this, arguments);
}
return action;
}()
}];
var alert = new sn_stylekit__WEBPACK_IMPORTED_MODULE_8__["SKAlert"]({
title: title,
text: text,
buttons: buttons
});
alert.present();
}));
case 2:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
function alert() {
return _alert.apply(this, arguments);
}
return alert;
}()
}, {
key: "confirm",
value: function () {
var _confirm = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5() {
var _this2 = this;
var _ref2,
title,
text,
_ref2$confirmButtonTe,
confirmButtonText,
_ref2$cancelButtonTex,
cancelButtonText,
onConfirm,
onCancel,
_ref2$destructive,
destructive,
_args5 = arguments;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_ref2 = _args5.length > 0 && _args5[0] !== undefined ? _args5[0] : {}, title = _ref2.title, text = _ref2.text, _ref2$confirmButtonTe = _ref2.confirmButtonText, confirmButtonText = _ref2$confirmButtonTe === void 0 ? "Confirm" : _ref2$confirmButtonTe, _ref2$cancelButtonTex = _ref2.cancelButtonText, cancelButtonText = _ref2$cancelButtonTex === void 0 ? "Cancel" : _ref2$cancelButtonTex, onConfirm = _ref2.onConfirm, onCancel = _ref2.onCancel, _ref2$destructive = _ref2.destructive, destructive = _ref2$destructive === void 0 ? false : _ref2$destructive;
return _context5.abrupt("return", new Promise(function (resolve, reject) {
var buttons = [{
text: cancelButtonText,
style: "neutral",
action: function () {
var _action2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (onCancel) {
_this2.deviceInterface.timeout(onCancel);
}
reject(false);
case 2:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
function action() {
return _action2.apply(this, arguments);
}
return action;
}()
}, {
text: confirmButtonText,
style: destructive ? "danger" : "info",
action: function () {
var _action3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (onConfirm) {
_this2.deviceInterface.timeout(onConfirm);
}
resolve(true);
case 2:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
function action() {
return _action3.apply(this, arguments);
}
return action;
}()
}];
var alert = new sn_stylekit__WEBPACK_IMPORTED_MODULE_8__["SKAlert"]({
title: title,
text: text,
buttons: buttons
});
alert.present();
}));
case 2:
case "end":
return _context5.stop();
}
}
}, _callee5);
}));
function confirm() {
return _confirm.apply(this, arguments);
}
return confirm;
}()
}]);
return AlertManager;
}(snjs__WEBPACK_IMPORTED_MODULE_7__["SNAlertManager"]);
/***/ }),
/***/ "./app/assets/javascripts/services/archiveManager.js":
/*!***********************************************************!*\
!*** ./app/assets/javascripts/services/archiveManager.js ***!
\***********************************************************/
/*! exports provided: ArchiveManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArchiveManager", function() { return ArchiveManager; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_4__);
var ArchiveManager =
/*#__PURE__*/
function () {
ArchiveManager.$inject = ["lockManager", "application"];
/* @ngInject */
function ArchiveManager(lockManager, application) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, ArchiveManager);
this.lockManager = lockManager;
this.application = application;
}
/*
Public
*/
/** @public */
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(ArchiveManager, [{
key: "downloadBackup",
value: function () {
var _downloadBackup = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(encrypted) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", this.downloadBackupOfItems(this.application.modelManager.allItems, encrypted));
case 1:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function downloadBackup(_x) {
return _downloadBackup.apply(this, arguments);
}
return downloadBackup;
}()
/** @public */
}, {
key: "downloadBackupOfItems",
value: function () {
var _downloadBackupOfItems = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(items, encrypted) {
var _this = this;
var run;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
run =
/*#__PURE__*/
function () {
var _ref = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var intent;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
// download in Standard Notes format
intent = encrypted ? snjs__WEBPACK_IMPORTED_MODULE_4__["EncryptionIntents"].FileEncrypted : snjs__WEBPACK_IMPORTED_MODULE_4__["EncryptionIntents"].FileDecrypted;
_this.itemsData(items, intent).then(function (data) {
var modifier = encrypted ? "Encrypted" : "Decrypted";
_this.downloadData(data, "Standard Notes ".concat(modifier, " Backup - ").concat(_this.formattedDate(), ".txt")); // download as zipped plain text files
if (!encrypted) {
_this.downloadZippedItems(items);
}
});
case 2:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function run() {
return _ref.apply(this, arguments);
};
}();
_context3.next = 3;
return this.application.privilegesManager.actionRequiresPrivilege(snjs__WEBPACK_IMPORTED_MODULE_4__["ProtectedActions"].ManageBackups);
case 3:
if (!_context3.sent) {
_context3.next = 7;
break;
}
this.godService.presentPrivilegesModal(snjs__WEBPACK_IMPORTED_MODULE_4__["ProtectedActions"].ManageBackups, function () {
run();
});
_context3.next = 8;
break;
case 7:
run();
case 8:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function downloadBackupOfItems(_x2, _x3) {
return _downloadBackupOfItems.apply(this, arguments);
}
return downloadBackupOfItems;
}()
/** @private */
}, {
key: "formattedDate",
value: function formattedDate() {
var string = "".concat(new Date()); // Match up to the first parenthesis, i.e do not include '(Central Standard Time)'
var matches = string.match(/^(.*?) \(/);
if (matches.length >= 2) {
return matches[1];
}
return string;
}
/** @private */
}, {
key: "itemsData",
value: function () {
var _itemsData = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(items, intent) {
var data, blobData;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return this.application.protocolService.createBackupFile({
subItems: items,
intent: intent
});
case 2:
data = _context4.sent;
blobData = new Blob([data], {
type: 'text/json'
});
return _context4.abrupt("return", blobData);
case 5:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function itemsData(_x4, _x5) {
return _itemsData.apply(this, arguments);
}
return itemsData;
}()
/** @private */
}, {
key: "loadZip",
value: function () {
var _loadZip = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5() {
var scriptTag, headTag;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
if (!window.zip) {
_context5.next = 2;
break;
}
return _context5.abrupt("return");
case 2:
scriptTag = document.createElement('script');
scriptTag.src = "/assets/zip/zip.js";
scriptTag.async = false;
headTag = document.getElementsByTagName('head')[0];
headTag.appendChild(scriptTag);
return _context5.abrupt("return", new Promise(function (resolve, reject) {
scriptTag.onload = function () {
zip.workerScriptsPath = "assets/zip/";
resolve();
};
}));
case 8:
case "end":
return _context5.stop();
}
}
}, _callee5);
}));
function loadZip() {
return _loadZip.apply(this, arguments);
}
return loadZip;
}()
/** @private */
}, {
key: "downloadZippedItems",
value: function () {
var _downloadZippedItems = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee6(items) {
var _this2 = this;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
_context6.next = 2;
return this.loadZip();
case 2:
zip.createWriter(new zip.BlobWriter("application/zip"), function (zipWriter) {
var index = 0;
var nextFile = function nextFile() {
var item = items[index];
var name, contents;
if (item.content_type === "Note") {
name = item.content.title;
contents = item.content.text;
} else {
name = item.content_type;
contents = JSON.stringify(item.content, null, 2);
}
if (!name) {
name = "";
}
var blob = new Blob([contents], {
type: 'text/plain'
});
var filePrefix = name.replace(/\//g, "").replace(/\\+/g, "");
var fileSuffix = "-".concat(item.uuid.split("-")[0], ".txt"); // Standard max filename length is 255. Slice the note name down to allow filenameEnd
filePrefix = filePrefix.slice(0, 255 - fileSuffix.length);
var fileName = "".concat(item.content_type, "/").concat(filePrefix).concat(fileSuffix);
zipWriter.add(fileName, new zip.BlobReader(blob), function () {
index++;
if (index < items.length) {
nextFile();
} else {
zipWriter.close(function (blob) {
_this2.downloadData(blob, "Standard Notes Backup - ".concat(_this2.formattedDate(), ".zip"));
zipWriter = null;
});
}
});
};
nextFile();
}, onerror);
case 3:
case "end":
return _context6.stop();
}
}
}, _callee6, this);
}));
function downloadZippedItems(_x6) {
return _downloadZippedItems.apply(this, arguments);
}
return downloadZippedItems;
}()
/** @private */
}, {
key: "hrefForData",
value: function hrefForData(data) {
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (this.textFile !== null) {
window.URL.revokeObjectURL(this.textFile);
}
this.textFile = window.URL.createObjectURL(data); // returns a URL you can use as a href
return this.textFile;
}
/** @private */
}, {
key: "downloadData",
value: function downloadData(data, fileName) {
var link = document.createElement('a');
link.setAttribute('download', fileName);
link.href = this.hrefForData(data);
document.body.appendChild(link);
link.click();
link.remove();
}
}]);
return ArchiveManager;
}();
/***/ }),
/***/ "./app/assets/javascripts/services/desktopManager.js":
/*!***********************************************************!*\
!*** ./app/assets/javascripts/services/desktopManager.js ***!
\***********************************************************/
/*! exports provided: DesktopManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DesktopManager", function() { return DesktopManager; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var lodash_pull__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! lodash/pull */ "./node_modules/lodash/pull.js");
/* harmony import */ var lodash_pull__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(lodash_pull__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_6__);
/* eslint-disable camelcase */
// An interface used by the Desktop app to interact with SN
var COMPONENT_DATA_KEY_INSTALL_ERROR = 'installError';
var COMPONENT_CONTENT_KEY_PACKAGE_INFO = 'package_info';
var COMPONENT_CONTENT_KEY_LOCAL_URL = 'local_url';
var DesktopManager =
/*#__PURE__*/
function () {
DesktopManager.$inject = ["$rootScope", "$timeout", "application", "appState"];
/* @ngInject */
function DesktopManager($rootScope, $timeout, application, appState) {
var _this = this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, DesktopManager);
this.$rootScope = $rootScope;
this.$timeout = $timeout;
this.appState = appState;
this.application = application;
this.componentActivationObservers = [];
this.updateObservers = [];
this.isDesktop = Object(_utils__WEBPACK_IMPORTED_MODULE_5__["isDesktopApplication"])();
$rootScope.$on('initial-data-loaded', function () {
_this.dataLoaded = true;
if (_this.dataLoadHandler) {
_this.dataLoadHandler();
}
});
$rootScope.$on('major-data-change', function () {
if (_this.majorDataChangeHandler) {
_this.majorDataChangeHandler();
}
});
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(DesktopManager, [{
key: "saveBackup",
value: function saveBackup() {
this.majorDataChangeHandler && this.majorDataChangeHandler();
}
}, {
key: "getExtServerHost",
value: function getExtServerHost() {
console.assert(this.extServerHost, 'extServerHost is null');
return this.extServerHost;
}
/**
* Sending a component in its raw state is really slow for the desktop app
* Keys are not passed into ItemParams, so the result is not encrypted
*/
}, {
key: "convertComponentForTransmission",
value: function () {
var _convertComponentForTransmission = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(component) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", this.application.protocolService.payloadByEncryptingPayload({
payload: component.payloadRepresentation(),
intent: snjs__WEBPACK_IMPORTED_MODULE_6__["EncryptionIntents"].FileDecrypted
}));
case 1:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function convertComponentForTransmission(_x) {
return _convertComponentForTransmission.apply(this, arguments);
}
return convertComponentForTransmission;
}() // All `components` should be installed
}, {
key: "syncComponentsInstallation",
value: function syncComponentsInstallation(components) {
var _this2 = this;
if (!this.isDesktop) {
return;
}
Promise.all(components.map(function (component) {
return _this2.convertComponentForTransmission(component);
})).then(function (data) {
_this2.installationSyncHandler(data);
});
}
}, {
key: "installComponent",
value: function () {
var _installComponent = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(component) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.t0 = this;
_context2.next = 3;
return this.convertComponentForTransmission(component);
case 3:
_context2.t1 = _context2.sent;
_context2.t0.installComponentHandler.call(_context2.t0, _context2.t1);
case 5:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function installComponent(_x2) {
return _installComponent.apply(this, arguments);
}
return installComponent;
}()
}, {
key: "registerUpdateObserver",
value: function registerUpdateObserver(callback) {
var observer = {
callback: callback
};
this.updateObservers.push(observer);
return observer;
}
}, {
key: "searchText",
value: function searchText(text) {
if (!this.isDesktop) {
return;
}
this.lastSearchedText = text;
this.searchHandler && this.searchHandler(text);
}
}, {
key: "redoSearch",
value: function redoSearch() {
if (this.lastSearchedText) {
this.searchText(this.lastSearchedText);
}
}
}, {
key: "deregisterUpdateObserver",
value: function deregisterUpdateObserver(observer) {
lodash_pull__WEBPACK_IMPORTED_MODULE_4___default()(this.updateObservers, observer);
} // Pass null to cancel search
}, {
key: "desktop_setSearchHandler",
value: function desktop_setSearchHandler(handler) {
this.searchHandler = handler;
}
}, {
key: "desktop_windowGainedFocus",
value: function desktop_windowGainedFocus() {
this.$rootScope.$broadcast('window-gained-focus');
}
}, {
key: "desktop_windowLostFocus",
value: function desktop_windowLostFocus() {
this.$rootScope.$broadcast('window-lost-focus');
}
}, {
key: "desktop_onComponentInstallationComplete",
value: function () {
var _desktop_onComponentInstallationComplete = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(componentData, error) {
var _this3 = this;
var component, permissableKeys, _i, _permissableKeys, key;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return this.application.findItem({
uuid: componentData.uuid
});
case 2:
component = _context3.sent;
if (component) {
_context3.next = 5;
break;
}
return _context3.abrupt("return");
case 5:
if (error) {
component.setAppDataItem(COMPONENT_DATA_KEY_INSTALL_ERROR, error);
} else {
permissableKeys = [COMPONENT_CONTENT_KEY_PACKAGE_INFO, COMPONENT_CONTENT_KEY_LOCAL_URL];
for (_i = 0, _permissableKeys = permissableKeys; _i < _permissableKeys.length; _i++) {
key = _permissableKeys[_i];
component[key] = componentData.content[key];
}
component.setAppDataItem(COMPONENT_DATA_KEY_INSTALL_ERROR, null);
}
this.application.saveItem({
item: component
});
this.$timeout(function () {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = _this3.updateObservers[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var observer = _step.value;
observer.callback(component);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
});
case 8:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function desktop_onComponentInstallationComplete(_x3, _x4) {
return _desktop_onComponentInstallationComplete.apply(this, arguments);
}
return desktop_onComponentInstallationComplete;
}()
}, {
key: "desktop_registerComponentActivationObserver",
value: function desktop_registerComponentActivationObserver(callback) {
var observer = {
id: Math.random,
callback: callback
};
this.componentActivationObservers.push(observer);
return observer;
}
}, {
key: "desktop_deregisterComponentActivationObserver",
value: function desktop_deregisterComponentActivationObserver(observer) {
lodash_pull__WEBPACK_IMPORTED_MODULE_4___default()(this.componentActivationObservers, observer);
}
/* Notify observers that a component has been registered/activated */
}, {
key: "notifyComponentActivation",
value: function () {
var _notifyComponentActivation = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(component) {
var _this4 = this;
var serializedComponent;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return this.convertComponentForTransmission(component);
case 2:
serializedComponent = _context4.sent;
this.$timeout(function () {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = _this4.componentActivationObservers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var observer = _step2.value;
observer.callback(serializedComponent);
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
});
case 4:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function notifyComponentActivation(_x5) {
return _notifyComponentActivation.apply(this, arguments);
}
return notifyComponentActivation;
}()
/* Used to resolve 'sn://' */
}, {
key: "desktop_setExtServerHost",
value: function desktop_setExtServerHost(host) {
this.extServerHost = host;
this.appState.desktopExtensionsReady();
}
}, {
key: "desktop_setComponentInstallationSyncHandler",
value: function desktop_setComponentInstallationSyncHandler(handler) {
this.installationSyncHandler = handler;
}
}, {
key: "desktop_setInstallComponentHandler",
value: function desktop_setInstallComponentHandler(handler) {
this.installComponentHandler = handler;
}
}, {
key: "desktop_setInitialDataLoadHandler",
value: function desktop_setInitialDataLoadHandler(handler) {
this.dataLoadHandler = handler;
if (this.dataLoaded) {
this.dataLoadHandler();
}
}
}, {
key: "desktop_requestBackupFile",
value: function () {
var _desktop_requestBackupFile = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5(callback) {
var data;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
_context5.next = 2;
return this.application.protocolService.createBackupFile({
returnIfEmpty: true
});
case 2:
data = _context5.sent;
callback(data);
case 4:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function desktop_requestBackupFile(_x6) {
return _desktop_requestBackupFile.apply(this, arguments);
}
return desktop_requestBackupFile;
}()
}, {
key: "desktop_setMajorDataChangeHandler",
value: function desktop_setMajorDataChangeHandler(handler) {
this.majorDataChangeHandler = handler;
}
}, {
key: "desktop_didBeginBackup",
value: function desktop_didBeginBackup() {
this.appState.beganBackupDownload();
}
}, {
key: "desktop_didFinishBackup",
value: function desktop_didFinishBackup(success) {
this.appState.endedBackupDownload({
success: success
});
}
}]);
return DesktopManager;
}();
/***/ }),
/***/ "./app/assets/javascripts/services/godService.js":
/*!*******************************************************!*\
!*** ./app/assets/javascripts/services/godService.js ***!
\*******************************************************/
/*! exports provided: GodService */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GodService", function() { return GodService; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! angular */ "./node_modules/angular/index.js");
/* harmony import */ var angular__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(angular__WEBPACK_IMPORTED_MODULE_4__);
var GodService =
/*#__PURE__*/
function () {
GodService.$inject = ["$rootScope", "$compile", "application"];
/* @ngInject */
function GodService($rootScope, $compile, application) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, GodService);
this.$rootScope = $rootScope;
this.$compile = $compile;
this.application = application;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(GodService, [{
key: "checkForSecurityUpdate",
value: function () {
var _checkForSecurityUpdate = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var updateAvailable;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!this.application.noAccount()) {
_context.next = 2;
break;
}
return _context.abrupt("return", false);
case 2:
_context.next = 4;
return this.application.protocolService.upgradeAvailable();
case 4:
updateAvailable = _context.sent;
if (updateAvailable !== this.securityUpdateAvailable) {
this.securityUpdateAvailable = updateAvailable;
this.$rootScope.$broadcast("security-update-status-changed");
}
return _context.abrupt("return", this.securityUpdateAvailable);
case 7:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function checkForSecurityUpdate() {
return _checkForSecurityUpdate.apply(this, arguments);
}
return checkForSecurityUpdate;
}()
}, {
key: "presentPasswordWizard",
value: function presentPasswordWizard(type) {
var scope = this.$rootScope.$new(true);
scope.type = type;
var el = this.$compile("")(scope);
angular__WEBPACK_IMPORTED_MODULE_4___default.a.element(document.body).append(el);
}
}, {
key: "presentPrivilegesModal",
value: function () {
var _presentPrivilegesModal = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(action, onSuccess, onCancel) {
var _this = this;
var customSuccess, customCancel, scope, el;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
if (!this.authenticationInProgress()) {
_context4.next = 3;
break;
}
onCancel && onCancel();
return _context4.abrupt("return");
case 3:
customSuccess =
/*#__PURE__*/
function () {
var _ref = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.t0 = onSuccess;
if (!_context2.t0) {
_context2.next = 4;
break;
}
_context2.next = 4;
return onSuccess();
case 4:
_this.currentAuthenticationElement = null;
case 5:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
return function customSuccess() {
return _ref.apply(this, arguments);
};
}();
customCancel =
/*#__PURE__*/
function () {
var _ref2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.t0 = onCancel;
if (!_context3.t0) {
_context3.next = 4;
break;
}
_context3.next = 4;
return onCancel();
case 4:
_this.currentAuthenticationElement = null;
case 5:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return function customCancel() {
return _ref2.apply(this, arguments);
};
}();
scope = this.$rootScope.$new(true);
scope.action = action;
scope.onSuccess = customSuccess;
scope.onCancel = customCancel;
el = this.$compile("\n \n ")(scope);
angular__WEBPACK_IMPORTED_MODULE_4___default.a.element(document.body).append(el);
this.currentAuthenticationElement = el;
case 12:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function presentPrivilegesModal(_x, _x2, _x3) {
return _presentPrivilegesModal.apply(this, arguments);
}
return presentPrivilegesModal;
}()
}, {
key: "presentPrivilegesManagementModal",
value: function presentPrivilegesManagementModal() {
var scope = this.$rootScope.$new(true);
var el = this.$compile("")(scope);
angular__WEBPACK_IMPORTED_MODULE_4___default.a.element(document.body).append(el);
}
}, {
key: "authenticationInProgress",
value: function authenticationInProgress() {
return this.currentAuthenticationElement != null;
}
}, {
key: "presentPasswordModal",
value: function presentPasswordModal(callback) {
var scope = this.$rootScope.$new(true);
scope.type = "password";
scope.title = "Decryption Assistance";
scope.message = "Unable to decrypt this item with your current keys. \n Please enter your account password at the time of this revision.";
scope.callback = callback;
var el = this.$compile("")(scope);
angular__WEBPACK_IMPORTED_MODULE_4___default.a.element(document.body).append(el);
}
}, {
key: "presentRevisionPreviewModal",
value: function presentRevisionPreviewModal(uuid, content) {
var scope = this.$rootScope.$new(true);
scope.uuid = uuid;
scope.content = content;
var el = this.$compile("")(scope);
angular__WEBPACK_IMPORTED_MODULE_4___default.a.element(document.body).append(el);
}
}]);
return GodService;
}();
/***/ }),
/***/ "./app/assets/javascripts/services/index.js":
/*!**************************************************!*\
!*** ./app/assets/javascripts/services/index.js ***!
\**************************************************/
/*! exports provided: AlertManager, ArchiveManager, DesktopManager, GodService, KeyboardManager, LockManager, NativeExtManager, PreferencesManager, StatusManager, ThemeManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _alertManager__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./alertManager */ "./app/assets/javascripts/services/alertManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AlertManager", function() { return _alertManager__WEBPACK_IMPORTED_MODULE_0__["AlertManager"]; });
/* harmony import */ var _archiveManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./archiveManager */ "./app/assets/javascripts/services/archiveManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArchiveManager", function() { return _archiveManager__WEBPACK_IMPORTED_MODULE_1__["ArchiveManager"]; });
/* harmony import */ var _desktopManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./desktopManager */ "./app/assets/javascripts/services/desktopManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DesktopManager", function() { return _desktopManager__WEBPACK_IMPORTED_MODULE_2__["DesktopManager"]; });
/* harmony import */ var _godService__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./godService */ "./app/assets/javascripts/services/godService.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GodService", function() { return _godService__WEBPACK_IMPORTED_MODULE_3__["GodService"]; });
/* harmony import */ var _keyboardManager__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./keyboardManager */ "./app/assets/javascripts/services/keyboardManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardManager", function() { return _keyboardManager__WEBPACK_IMPORTED_MODULE_4__["KeyboardManager"]; });
/* harmony import */ var _lockManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./lockManager */ "./app/assets/javascripts/services/lockManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LockManager", function() { return _lockManager__WEBPACK_IMPORTED_MODULE_5__["LockManager"]; });
/* harmony import */ var _nativeExtManager__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./nativeExtManager */ "./app/assets/javascripts/services/nativeExtManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NativeExtManager", function() { return _nativeExtManager__WEBPACK_IMPORTED_MODULE_6__["NativeExtManager"]; });
/* harmony import */ var _preferencesManager__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./preferencesManager */ "./app/assets/javascripts/services/preferencesManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PreferencesManager", function() { return _preferencesManager__WEBPACK_IMPORTED_MODULE_7__["PreferencesManager"]; });
/* harmony import */ var _statusManager__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./statusManager */ "./app/assets/javascripts/services/statusManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StatusManager", function() { return _statusManager__WEBPACK_IMPORTED_MODULE_8__["StatusManager"]; });
/* harmony import */ var _themeManager__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./themeManager */ "./app/assets/javascripts/services/themeManager.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ThemeManager", function() { return _themeManager__WEBPACK_IMPORTED_MODULE_9__["ThemeManager"]; });
/***/ }),
/***/ "./app/assets/javascripts/services/keyboardManager.js":
/*!************************************************************!*\
!*** ./app/assets/javascripts/services/keyboardManager.js ***!
\************************************************************/
/*! exports provided: KeyboardKeys, KeyboardModifiers, KeyboardManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardKeys", function() { return KeyboardKeys; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardModifiers", function() { return KeyboardModifiers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardManager", function() { return KeyboardManager; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/** @public */
var KeyboardKeys = {
Tab: "Tab",
Backspace: "Backspace",
Up: "ArrowUp",
Down: "ArrowDown"
};
/** @public */
var KeyboardModifiers = {
Shift: "Shift",
Ctrl: "Control",
/** ⌘ key on Mac, ⊞ key on Windows */
Meta: "Meta",
Alt: "Alt"
};
/** @private */
var KeyboardKeyEvents = {
Down: "KeyEventDown",
Up: "KeyEventUp"
};
var KeyboardManager =
/*#__PURE__*/
function () {
function KeyboardManager() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, KeyboardManager);
this.observers = [];
window.addEventListener('keydown', this.handleKeyDown.bind(this));
window.addEventListener('keyup', this.handleKeyUp.bind(this));
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(KeyboardManager, [{
key: "modifiersForEvent",
value: function modifiersForEvent(event) {
var allModifiers = Object.keys(KeyboardModifiers).map(function (key) {
return KeyboardModifiers[key];
});
var eventModifiers = allModifiers.filter(function (modifier) {
// For a modifier like ctrlKey, must check both event.ctrlKey and event.key.
// That's because on keyup, event.ctrlKey would be false, but event.key == Control would be true.
var matches = (event.ctrlKey || event.key === KeyboardModifiers.Ctrl) && modifier === KeyboardModifiers.Ctrl || (event.metaKey || event.key === KeyboardModifiers.Meta) && modifier === KeyboardModifiers.Meta || (event.altKey || event.key === KeyboardModifiers.Alt) && modifier === KeyboardModifiers.Alt || (event.shiftKey || event.key === KeyboardModifiers.Shift) && modifier === KeyboardModifiers.Shift;
return matches;
});
return eventModifiers;
}
}, {
key: "eventMatchesKeyAndModifiers",
value: function eventMatchesKeyAndModifiers(event, key) {
var modifiers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
var eventModifiers = this.modifiersForEvent(event);
if (eventModifiers.length !== modifiers.length) {
return false;
}
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = modifiers[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var modifier = _step.value;
if (!eventModifiers.includes(modifier)) {
return false;
}
} // Modifers match, check key
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
if (!key) {
return true;
} // In the browser, shift + f results in key 'f', but in Electron, shift + f results in 'F'
// In our case we don't differentiate between the two.
return key.toLowerCase() === event.key.toLowerCase();
}
}, {
key: "notifyObserver",
value: function notifyObserver(event, keyEventType) {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = this.observers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var observer = _step2.value;
if (observer.element && event.target !== observer.element) {
continue;
}
if (observer.elements && !observer.elements.includes(event.target)) {
continue;
}
if (observer.notElement && observer.notElement === event.target) {
continue;
}
if (observer.notElementIds && observer.notElementIds.includes(event.target.id)) {
continue;
}
if (this.eventMatchesKeyAndModifiers(event, observer.key, observer.modifiers)) {
var callback = keyEventType === KeyboardKeyEvents.Down ? observer.onKeyDown : observer.onKeyUp;
if (callback) {
callback(event);
}
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
}
}, {
key: "handleKeyDown",
value: function handleKeyDown(event) {
this.notifyObserver(event, KeyboardKeyEvents.Down);
}
}, {
key: "handleKeyUp",
value: function handleKeyUp(event) {
this.notifyObserver(event, KeyboardKeyEvents.Up);
}
}, {
key: "addKeyObserver",
value: function addKeyObserver(_ref) {
var key = _ref.key,
modifiers = _ref.modifiers,
onKeyDown = _ref.onKeyDown,
onKeyUp = _ref.onKeyUp,
element = _ref.element,
elements = _ref.elements,
notElement = _ref.notElement,
notElementIds = _ref.notElementIds;
var observer = {
key: key,
modifiers: modifiers,
onKeyDown: onKeyDown,
onKeyUp: onKeyUp,
element: element,
elements: elements,
notElement: notElement,
notElementIds: notElementIds
};
this.observers.push(observer);
return observer;
}
}, {
key: "removeKeyObserver",
value: function removeKeyObserver(observer) {
this.observers.splice(this.observers.indexOf(observer), 1);
}
}]);
return KeyboardManager;
}();
/***/ }),
/***/ "./app/assets/javascripts/services/lockManager.js":
/*!********************************************************!*\
!*** ./app/assets/javascripts/services/lockManager.js ***!
\********************************************************/
/*! exports provided: LockManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LockManager", function() { return LockManager; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../state */ "./app/assets/javascripts/state.js");
var MILLISECONDS_PER_SECOND = 1000;
var FOCUS_POLL_INTERVAL = 1 * MILLISECONDS_PER_SECOND;
var LOCK_INTERVAL_NONE = 0;
var LOCK_INTERVAL_IMMEDIATE = 1;
var LOCK_INTERVAL_ONE_MINUTE = 60 * MILLISECONDS_PER_SECOND;
var LOCK_INTERVAL_FIVE_MINUTES = 300 * MILLISECONDS_PER_SECOND;
var LOCK_INTERVAL_ONE_HOUR = 3600 * MILLISECONDS_PER_SECOND;
var STORAGE_KEY_AUTOLOCK_INTERVAL = "AutoLockIntervalKey";
var LockManager =
/*#__PURE__*/
function () {
LockManager.$inject = ["$rootScope", "application", "appState"];
/* @ngInject */
function LockManager($rootScope, application, appState) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, LockManager);
this.$rootScope = $rootScope;
this.application = application;
this.appState = appState;
this.observeVisibility();
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(LockManager, [{
key: "observeVisibility",
value: function observeVisibility() {
var _this = this;
this.appState.addObserver(function (eventName, data) {
if (eventName === _state__WEBPACK_IMPORTED_MODULE_5__["AppStateEvents"].WindowDidBlur) {
_this.documentVisibilityChanged(false);
} else if (eventName === _state__WEBPACK_IMPORTED_MODULE_5__["AppStateEvents"].WindowDidFocus) {
_this.documentVisibilityChanged(true);
}
});
if (!Object(_utils__WEBPACK_IMPORTED_MODULE_4__["isDesktopApplication"])()) {
this.beginWebFocusPolling();
}
}
}, {
key: "setAutoLockInterval",
value: function () {
var _setAutoLockInterval = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(interval) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", this.application.setValue(STORAGE_KEY_AUTOLOCK_INTERVAL, interval));
case 1:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function setAutoLockInterval(_x) {
return _setAutoLockInterval.apply(this, arguments);
}
return setAutoLockInterval;
}()
}, {
key: "getAutoLockInterval",
value: function () {
var _getAutoLockInterval = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var interval;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.application.getValue(STORAGE_KEY_AUTOLOCK_INTERVAL);
case 2:
interval = _context2.sent;
if (!interval) {
_context2.next = 7;
break;
}
return _context2.abrupt("return", interval);
case 7:
return _context2.abrupt("return", LOCK_INTERVAL_NONE);
case 8:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function getAutoLockInterval() {
return _getAutoLockInterval.apply(this, arguments);
}
return getAutoLockInterval;
}()
/**
* Verify document is in focus every so often as visibilitychange event is
* not triggered on a typical window blur event but rather on tab changes.
*/
}, {
key: "beginWebFocusPolling",
value: function beginWebFocusPolling() {
var _this2 = this;
this.pollFocusTimeout = setInterval(function () {
var hasFocus = document.hasFocus();
if (hasFocus && _this2.lastFocusState === 'hidden') {
_this2.documentVisibilityChanged(true);
} else if (!hasFocus && _this2.lastFocusState === 'visible') {
_this2.documentVisibilityChanged(false);
}
/* Save this to compare against next time around */
_this2.lastFocusState = hasFocus ? 'visible' : 'hidden';
}, FOCUS_POLL_INTERVAL);
}
}, {
key: "getAutoLockIntervalOptions",
value: function getAutoLockIntervalOptions() {
return [{
value: LOCK_INTERVAL_NONE,
label: "Off"
}, {
value: LOCK_INTERVAL_IMMEDIATE,
label: "Immediately"
}, {
value: LOCK_INTERVAL_ONE_MINUTE,
label: "1m"
}, {
value: LOCK_INTERVAL_FIVE_MINUTES,
label: "5m"
}, {
value: LOCK_INTERVAL_ONE_HOUR,
label: "1h"
}];
}
}, {
key: "documentVisibilityChanged",
value: function () {
var _documentVisibilityChanged = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(visible) {
var locked;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
if (!visible) {
_context3.next = 8;
break;
}
_context3.next = 3;
return this.application.isPasscodeLocked();
case 3:
locked = _context3.sent;
if (!locked && this.lockAfterDate && new Date() > this.lockAfterDate) {
this.application.passcodeLock();
}
this.cancelAutoLockTimer();
_context3.next = 9;
break;
case 8:
this.beginAutoLockTimer();
case 9:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function documentVisibilityChanged(_x2) {
return _documentVisibilityChanged.apply(this, arguments);
}
return documentVisibilityChanged;
}()
}, {
key: "beginAutoLockTimer",
value: function () {
var _beginAutoLockTimer = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4() {
var _this3 = this;
var interval, addToNow;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return this.getAutoLockInterval();
case 2:
interval = _context4.sent;
if (!(interval === LOCK_INTERVAL_NONE)) {
_context4.next = 5;
break;
}
return _context4.abrupt("return");
case 5:
/**
* Use a timeout if possible, but if the computer is put to sleep, timeouts won't
* work. Need to set a date as backup. this.lockAfterDate does not need to be
* persisted, as living in memory is sufficient. If memory is cleared, then the
* application will lock anyway.
*/
addToNow = function addToNow(seconds) {
var date = new Date();
date.setSeconds(date.getSeconds() + seconds);
return date;
};
this.lockAfterDate = addToNow(interval / MILLISECONDS_PER_SECOND);
this.lockTimeout = setTimeout(function () {
_this3.cancelAutoLockTimer();
_this3.application.passcodeLock();
_this3.lockAfterDate = null;
}, interval);
case 8:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function beginAutoLockTimer() {
return _beginAutoLockTimer.apply(this, arguments);
}
return beginAutoLockTimer;
}()
}, {
key: "cancelAutoLockTimer",
value: function cancelAutoLockTimer() {
clearTimeout(this.lockTimeout);
this.lockAfterDate = null;
}
}]);
return LockManager;
}();
/***/ }),
/***/ "./app/assets/javascripts/services/nativeExtManager.js":
/*!*************************************************************!*\
!*** ./app/assets/javascripts/services/nativeExtManager.js ***!
\*************************************************************/
/*! exports provided: NativeExtManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NativeExtManager", function() { return NativeExtManager; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/state */ "./app/assets/javascripts/state.js");
var STREAM_ITEMS_PERMISSION = 'stream-items';
/** A class for handling installation of system extensions */
var NativeExtManager =
/*#__PURE__*/
function () {
NativeExtManager.$inject = ["application", "appState"];
/* @ngInject */
function NativeExtManager(application, appState) {
var _this = this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, NativeExtManager);
this.application = application;
this.extManagerId = 'org.standardnotes.extensions-manager';
this.batchManagerId = 'org.standardnotes.batch-manager';
this.systemExtensions = [];
this.resolveExtensionsManager();
this.resolveBatchManager();
application.onUnlock(function () {
_this.resolveExtensionsManager();
_this.resolveBatchManager();
});
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(NativeExtManager, [{
key: "isSystemExtension",
value: function isSystemExtension(extension) {
return this.systemExtensions.includes(extension.uuid);
}
}, {
key: "extensionsManagerTemplatePayload",
value: function extensionsManagerTemplatePayload() {
var url = window._extensions_manager_location;
if (!url) {
console.error('window._extensions_manager_location must be set.');
return;
}
var packageInfo = {
name: 'Extensions',
identifier: this.extManagerId
};
var content = {
name: packageInfo.name,
area: 'rooms',
package_info: packageInfo,
permissions: [{
name: STREAM_ITEMS_PERMISSION,
content_types: [snjs__WEBPACK_IMPORTED_MODULE_5__["ContentTypes"].Component, snjs__WEBPACK_IMPORTED_MODULE_5__["ContentTypes"].Theme, snjs__WEBPACK_IMPORTED_MODULE_5__["ContentTypes"].ServerExtension, snjs__WEBPACK_IMPORTED_MODULE_5__["ContentTypes"].ActionsExtension, snjs__WEBPACK_IMPORTED_MODULE_5__["ContentTypes"].Mfa, snjs__WEBPACK_IMPORTED_MODULE_5__["ContentTypes"].Editor, snjs__WEBPACK_IMPORTED_MODULE_5__["ContentTypes"].ExtensionRepo]
}]
};
if (Object(_utils__WEBPACK_IMPORTED_MODULE_4__["isDesktopApplication"])()) {
content.local_url = window._extensions_manager_location;
} else {
content.hosted_url = window._extensions_manager_location;
}
var payload = Object(snjs__WEBPACK_IMPORTED_MODULE_5__["CreateMaxPayloadFromAnyObject"])({
object: {
content_type: snjs__WEBPACK_IMPORTED_MODULE_5__["ContentTypes"].Component,
content: content
}
});
return payload;
}
}, {
key: "resolveExtensionsManager",
value: function () {
var _resolveExtensionsManager = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var contentTypePredicate, packagePredicate, predicate, extensionsManager, needsSync, permission;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
contentTypePredicate = new snjs__WEBPACK_IMPORTED_MODULE_5__["SFPredicate"]('content_type', '=', snjs__WEBPACK_IMPORTED_MODULE_5__["ContentTypes"].Component);
packagePredicate = new snjs__WEBPACK_IMPORTED_MODULE_5__["SFPredicate"]('package_info.identifier', '=', this.extManagerId);
predicate = snjs__WEBPACK_IMPORTED_MODULE_5__["SFPredicate"].CompoundPredicate([contentTypePredicate, packagePredicate]);
_context.next = 5;
return this.application.singletonManager.findOrCreateSingleton({
predicate: predicate,
createPayload: this.extensionsManagerTemplatePayload()
});
case 5:
extensionsManager = _context.sent;
this.systemExtensions.push(extensionsManager.uuid);
needsSync = false;
if (Object(_utils__WEBPACK_IMPORTED_MODULE_4__["isDesktopApplication"])()) {
if (!extensionsManager.local_url) {
extensionsManager.local_url = window._extensions_manager_location;
needsSync = true;
}
} else {
if (!extensionsManager.hosted_url) {
extensionsManager.hosted_url = window._extensions_manager_location;
needsSync = true;
}
} // Handle addition of SN|ExtensionRepo permission
permission = extensionsManager.content.permissions.find(function (p) {
return p.name === STREAM_ITEMS_PERMISSION;
});
if (!permission.content_types.includes(snjs__WEBPACK_IMPORTED_MODULE_5__["ContentTypes"].ExtensionRepo)) {
permission.content_types.push(snjs__WEBPACK_IMPORTED_MODULE_5__["ContentTypes"].ExtensionRepo);
needsSync = true;
}
if (needsSync) {
this.application.saveItem({
item: extensionsManager
});
}
case 12:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function resolveExtensionsManager() {
return _resolveExtensionsManager.apply(this, arguments);
}
return resolveExtensionsManager;
}()
}, {
key: "batchManagerTemplatePayload",
value: function batchManagerTemplatePayload() {
var url = window._batch_manager_location;
if (!url) {
console.error('window._batch_manager_location must be set.');
return;
}
var packageInfo = {
name: 'Batch Manager',
identifier: this.batchManagerId
};
var allContentTypes = Object(_utils__WEBPACK_IMPORTED_MODULE_4__["dictToArray"])(snjs__WEBPACK_IMPORTED_MODULE_5__["ContentTypes"]);
var content = {
name: packageInfo.name,
area: 'modal',
package_info: packageInfo,
permissions: [{
name: STREAM_ITEMS_PERMISSION,
content_types: allContentTypes
}]
};
if (Object(_utils__WEBPACK_IMPORTED_MODULE_4__["isDesktopApplication"])()) {
content.local_url = window._batch_manager_location;
} else {
content.hosted_url = window._batch_manager_location;
}
var payload = Object(snjs__WEBPACK_IMPORTED_MODULE_5__["CreateMaxPayloadFromAnyObject"])({
object: {
content_type: snjs__WEBPACK_IMPORTED_MODULE_5__["ContentTypes"].Component,
content: content
}
});
return payload;
}
}, {
key: "resolveBatchManager",
value: function () {
var _resolveBatchManager = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var contentTypePredicate, packagePredicate, predicate, batchManager, needsSync, permission;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
contentTypePredicate = new snjs__WEBPACK_IMPORTED_MODULE_5__["SFPredicate"]('content_type', '=', snjs__WEBPACK_IMPORTED_MODULE_5__["ContentTypes"].Component);
packagePredicate = new snjs__WEBPACK_IMPORTED_MODULE_5__["SFPredicate"]('package_info.identifier', '=', this.batchManagerId);
predicate = snjs__WEBPACK_IMPORTED_MODULE_5__["SFPredicate"].CompoundPredicate([contentTypePredicate, packagePredicate]);
_context2.next = 5;
return this.application.singletonManager.findOrCreateSingleton({
predicate: predicate,
createPayload: this.batchManagerTemplatePayload()
});
case 5:
batchManager = _context2.sent;
this.systemExtensions.push(batchManager.uuid);
needsSync = false;
if (Object(_utils__WEBPACK_IMPORTED_MODULE_4__["isDesktopApplication"])()) {
if (!batchManager.local_url) {
batchManager.local_url = window._batch_manager_location;
needsSync = true;
}
} else {
if (!batchManager.hosted_url) {
batchManager.hosted_url = window._batch_manager_location;
needsSync = true;
}
} // Handle addition of SN|ExtensionRepo permission
permission = batchManager.content.permissions.find(function (p) {
return p.name === STREAM_ITEMS_PERMISSION;
});
if (!permission.content_types.includes(snjs__WEBPACK_IMPORTED_MODULE_5__["ContentTypes"].ExtensionRepo)) {
permission.content_types.push(snjs__WEBPACK_IMPORTED_MODULE_5__["ContentTypes"].ExtensionRepo);
needsSync = true;
}
if (needsSync) {
this.application.saveItem({
item: batchManager
});
}
case 12:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function resolveBatchManager() {
return _resolveBatchManager.apply(this, arguments);
}
return resolveBatchManager;
}()
}]);
return NativeExtManager;
}();
/***/ }),
/***/ "./app/assets/javascripts/services/preferencesManager.js":
/*!***************************************************************!*\
!*** ./app/assets/javascripts/services/preferencesManager.js ***!
\***************************************************************/
/*! exports provided: PrefKeys, PreferencesManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PrefKeys", function() { return PrefKeys; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PreferencesManager", function() { return PreferencesManager; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_4__);
var PrefKeys = {
TagsPanelWidth: 'tagsPanelWidth',
NotesPanelWidth: 'notesPanelWidth',
EditorWidth: 'editorWidth',
EditorLeft: 'editorLeft',
EditorMonospaceEnabled: 'monospaceFont',
EditorSpellcheck: 'spellcheck',
EditorResizersEnabled: 'marginResizersEnabled',
SortNotesBy: 'sortBy',
SortNotesReverse: 'sortReverse',
NotesShowArchived: 'showArchived',
NotesHidePinned: 'hidePinned',
NotesHideNotePreview: 'hideNotePreview',
NotesHideDate: 'hideDate',
NotesHideTags: 'hideTags'
};
var PreferencesManager =
/*#__PURE__*/
function () {
PreferencesManager.$inject = ["appState", "application"];
/* @ngInject */
function PreferencesManager(appState, application) {
var _this = this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, PreferencesManager);
this.application = application;
this.appState = appState;
application.onUnlock(function () {
_this.streamPreferences();
_this.loadSingleton();
});
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(PreferencesManager, [{
key: "streamPreferences",
value: function streamPreferences() {
var _this2 = this;
this.application.streamItems({
contentType: 'SN|UserPreferences',
stream: function stream() {
_this2.preferencesDidChange();
}
});
}
}, {
key: "loadSingleton",
value: function () {
var _loadSingleton = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var contentType, predicate;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
contentType = 'SN|UserPreferences';
predicate = new snjs__WEBPACK_IMPORTED_MODULE_4__["SFPredicate"]('content_type', '=', contentType);
_context.next = 4;
return this.application.singletonManager.findOrCreateSingleton({
predicate: predicate,
createPayload: Object(snjs__WEBPACK_IMPORTED_MODULE_4__["CreateMaxPayloadFromAnyObject"])({
object: {
content_type: contentType
}
})
});
case 4:
this.userPreferences = _context.sent;
case 5:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function loadSingleton() {
return _loadSingleton.apply(this, arguments);
}
return loadSingleton;
}()
}, {
key: "preferencesDidChange",
value: function preferencesDidChange() {
this.appState.setUserPreferences(this.userPreferences);
}
}, {
key: "syncUserPreferences",
value: function syncUserPreferences() {
if (this.userPreferences) {
this.application.saveItem({
item: this.userPreferences
});
}
}
}, {
key: "getValue",
value: function getValue(key, defaultValue) {
if (!this.userPreferences) {
return defaultValue;
}
var value = this.userPreferences.getAppDataItem(key);
return value !== undefined && value != null ? value : defaultValue;
}
}, {
key: "setUserPrefValue",
value: function setUserPrefValue(key, value, sync) {
this.userPreferences.setAppDataItem(key, value);
if (sync) {
this.syncUserPreferences();
}
}
}]);
return PreferencesManager;
}();
/***/ }),
/***/ "./app/assets/javascripts/services/statusManager.js":
/*!**********************************************************!*\
!*** ./app/assets/javascripts/services/statusManager.js ***!
\**********************************************************/
/*! exports provided: StatusManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StatusManager", function() { return StatusManager; });
/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js");
/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_3__);
var StatusManager =
/*#__PURE__*/
function () {
function StatusManager() {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default()(this, StatusManager);
this.statuses = [];
this.observers = [];
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(StatusManager, [{
key: "statusFromString",
value: function statusFromString(string) {
return {
string: string
};
}
}, {
key: "replaceStatusWithString",
value: function replaceStatusWithString(status, string) {
this.removeStatus(status);
return this.addStatusFromString(string);
}
}, {
key: "addStatusFromString",
value: function addStatusFromString(string) {
return this.addStatus(this.statusFromString(string));
}
}, {
key: "addStatus",
value: function addStatus(status) {
if (_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default()(status) !== "object") {
console.error("Attempting to set non-object status", status);
return;
}
this.statuses.push(status);
this.notifyObservers();
return status;
}
}, {
key: "removeStatus",
value: function removeStatus(status) {
lodash__WEBPACK_IMPORTED_MODULE_3___default.a.pull(this.statuses, status);
this.notifyObservers();
return null;
}
}, {
key: "getStatusString",
value: function getStatusString() {
var result = "";
this.statuses.forEach(function (status, index) {
if (index > 0) {
result += " ";
}
result += status.string;
});
return result;
}
}, {
key: "notifyObservers",
value: function notifyObservers() {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.observers[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var observer = _step.value;
observer(this.getStatusString());
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
}, {
key: "addStatusObserver",
value: function addStatusObserver(callback) {
this.observers.push(callback);
}
}, {
key: "removeStatusObserver",
value: function removeStatusObserver(callback) {
lodash__WEBPACK_IMPORTED_MODULE_3___default.a.pull(this.statuses, callback);
}
}]);
return StatusManager;
}();
/***/ }),
/***/ "./app/assets/javascripts/services/themeManager.js":
/*!*********************************************************!*\
!*** ./app/assets/javascripts/services/themeManager.js ***!
\*********************************************************/
/*! exports provided: ThemeManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ThemeManager", function() { return ThemeManager; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_get__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/get */ "./node_modules/@babel/runtime/helpers/get.js");
/* harmony import */ var _babel_runtime_helpers_get__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_get__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_9__);
/* harmony import */ var _state__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/state */ "./app/assets/javascripts/state.js");
var CACHED_THEMES_KEY = 'cachedThemes';
var ThemeManager =
/*#__PURE__*/
function (_PureService) {
ThemeManager.$inject = ["application", "appState", "desktopManager"];
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_7___default()(ThemeManager, _PureService);
/* @ngInject */
function ThemeManager(application, appState, desktopManager) {
var _this;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, ThemeManager);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(ThemeManager).call(this));
_this.application = application;
_this.appState = appState;
_this.desktopManager = desktopManager;
_this.activeThemes = [];
_this.registerObservers();
application.onStart(function () {
if (!desktopManager.isDesktop) {
_this.activateCachedThemes();
}
});
_this.unsubState = appState.addObserver(function (eventName, data) {
if (eventName === _state__WEBPACK_IMPORTED_MODULE_10__["AppStateEvents"].DesktopExtsReady) {
_this.activateCachedThemes();
}
});
return _this;
}
/** @override */
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(ThemeManager, [{
key: "deinit",
value: function () {
var _deinit = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_babel_runtime_helpers_get__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(ThemeManager.prototype), "deinit", this).call(this);
this.unsubState();
case 2:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function deinit() {
return _deinit.apply(this, arguments);
}
return deinit;
}()
}, {
key: "activateCachedThemes",
value: function () {
var _activateCachedThemes = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var cachedThemes, writeToCache, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, theme;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.getCachedThemes();
case 2:
cachedThemes = _context2.sent;
writeToCache = false;
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
_context2.prev = 7;
for (_iterator = cachedThemes[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
theme = _step.value;
this.activateTheme(theme, writeToCache);
}
_context2.next = 15;
break;
case 11:
_context2.prev = 11;
_context2.t0 = _context2["catch"](7);
_didIteratorError = true;
_iteratorError = _context2.t0;
case 15:
_context2.prev = 15;
_context2.prev = 16;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 18:
_context2.prev = 18;
if (!_didIteratorError) {
_context2.next = 21;
break;
}
throw _iteratorError;
case 21:
return _context2.finish(18);
case 22:
return _context2.finish(15);
case 23:
case "end":
return _context2.stop();
}
}
}, _callee2, this, [[7, 11, 15, 23], [16,, 18, 22]]);
}));
function activateCachedThemes() {
return _activateCachedThemes.apply(this, arguments);
}
return activateCachedThemes;
}()
}, {
key: "registerObservers",
value: function registerObservers() {
var _this2 = this;
this.desktopManager.registerUpdateObserver(function (component) {
// Reload theme if active
if (component.active && component.isTheme()) {
_this2.deactivateTheme(component);
setTimeout(function () {
_this2.activateTheme(component);
}, 10);
}
});
this.application.componentManager.registerHandler({
identifier: 'themeManager',
areas: ['themes'],
activationHandler: function activationHandler(component) {
if (component.active) {
_this2.activateTheme(component);
} else {
_this2.deactivateTheme(component);
}
}
});
}
}, {
key: "hasActiveTheme",
value: function hasActiveTheme() {
return this.application.componentManager.getActiveThemes().length > 0;
}
}, {
key: "deactivateAllThemes",
value: function deactivateAllThemes() {
var activeThemes = this.application.componentManager.getActiveThemes();
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = activeThemes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var theme = _step2.value;
if (theme) {
this.application.componentManager.deactivateComponent(theme);
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
this.decacheThemes();
}
}, {
key: "activateTheme",
value: function activateTheme(theme) {
var writeToCache = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (lodash__WEBPACK_IMPORTED_MODULE_8___default.a.find(this.activeThemes, {
uuid: theme.uuid
})) {
return;
}
this.activeThemes.push(theme);
var url = this.application.componentManager.urlForComponent(theme);
var link = document.createElement('link');
link.href = url;
link.type = 'text/css';
link.rel = 'stylesheet';
link.media = 'screen,print';
link.id = theme.uuid;
document.getElementsByTagName('head')[0].appendChild(link);
if (writeToCache) {
this.cacheThemes();
}
}
}, {
key: "deactivateTheme",
value: function deactivateTheme(theme) {
var element = document.getElementById(theme.uuid);
if (element) {
element.disabled = true;
element.parentNode.removeChild(element);
}
lodash__WEBPACK_IMPORTED_MODULE_8___default.a.remove(this.activeThemes, {
uuid: theme.uuid
});
this.cacheThemes();
}
}, {
key: "cacheThemes",
value: function () {
var _cacheThemes = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4() {
var _this3 = this;
var mapped;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return Promise.all(this.activeThemes.map(
/*#__PURE__*/
function () {
var _ref = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(theme) {
var payload, processedPayload;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
payload = theme.payloadRepresentation();
_context3.next = 3;
return _this3.application.protocolService.payloadByEncryptingPayload({
payload: payload,
intent: snjs__WEBPACK_IMPORTED_MODULE_9__["EncryptionIntents"].LocalStorageDecrypted
});
case 3:
processedPayload = _context3.sent;
return _context3.abrupt("return", processedPayload);
case 5:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return function (_x) {
return _ref.apply(this, arguments);
};
}()));
case 2:
mapped = _context4.sent;
return _context4.abrupt("return", this.application.setValue(CACHED_THEMES_KEY, mapped, snjs__WEBPACK_IMPORTED_MODULE_9__["StorageValueModes"].Nonwrapped));
case 4:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function cacheThemes() {
return _cacheThemes.apply(this, arguments);
}
return cacheThemes;
}()
}, {
key: "decacheThemes",
value: function () {
var _decacheThemes = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
return _context5.abrupt("return", this.application.removeValue(CACHED_THEMES_KEY, snjs__WEBPACK_IMPORTED_MODULE_9__["StorageValueModes"].Nonwrapped));
case 1:
case "end":
return _context5.stop();
}
}
}, _callee5, this);
}));
function decacheThemes() {
return _decacheThemes.apply(this, arguments);
}
return decacheThemes;
}()
}, {
key: "getCachedThemes",
value: function () {
var _getCachedThemes = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee6() {
var cachedThemes, themes, _iteratorNormalCompletion3, _didIteratorError3, _iteratorError3, _iterator3, _step3, cachedTheme, theme;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
_context6.next = 2;
return this.application.getValue(CACHED_THEMES_KEY, snjs__WEBPACK_IMPORTED_MODULE_9__["StorageValueModes"].Nonwrapped);
case 2:
cachedThemes = _context6.sent;
if (!cachedThemes) {
_context6.next = 36;
break;
}
themes = [];
_iteratorNormalCompletion3 = true;
_didIteratorError3 = false;
_iteratorError3 = undefined;
_context6.prev = 8;
_iterator3 = cachedThemes[Symbol.iterator]();
case 10:
if (_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done) {
_context6.next = 19;
break;
}
cachedTheme = _step3.value;
_context6.next = 14;
return this.application.createItem({
contentType: snjs__WEBPACK_IMPORTED_MODULE_9__["ContentTypes"].Theme,
content: cachedTheme.content
});
case 14:
theme = _context6.sent;
themes.push(theme);
case 16:
_iteratorNormalCompletion3 = true;
_context6.next = 10;
break;
case 19:
_context6.next = 25;
break;
case 21:
_context6.prev = 21;
_context6.t0 = _context6["catch"](8);
_didIteratorError3 = true;
_iteratorError3 = _context6.t0;
case 25:
_context6.prev = 25;
_context6.prev = 26;
if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
_iterator3.return();
}
case 28:
_context6.prev = 28;
if (!_didIteratorError3) {
_context6.next = 31;
break;
}
throw _iteratorError3;
case 31:
return _context6.finish(28);
case 32:
return _context6.finish(25);
case 33:
return _context6.abrupt("return", themes);
case 36:
return _context6.abrupt("return", []);
case 37:
case "end":
return _context6.stop();
}
}
}, _callee6, this, [[8, 21, 25, 33], [26,, 28, 32]]);
}));
function getCachedThemes() {
return _getCachedThemes.apply(this, arguments);
}
return getCachedThemes;
}()
}]);
return ThemeManager;
}(snjs__WEBPACK_IMPORTED_MODULE_9__["PureService"]);
/***/ }),
/***/ "./app/assets/javascripts/state.js":
/*!*****************************************!*\
!*** ./app/assets/javascripts/state.js ***!
\*****************************************/
/*! exports provided: AppStateEvents, EventSources, AppState */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppStateEvents", function() { return AppStateEvents; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EventSources", function() { return EventSources; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppState", function() { return AppState; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/utils */ "./app/assets/javascripts/utils.js");
/* harmony import */ var lodash_pull__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! lodash/pull */ "./node_modules/lodash/pull.js");
/* harmony import */ var lodash_pull__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(lodash_pull__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_6__);
var AppStateEvents = {
TagChanged: 1,
NoteChanged: 2,
PreferencesChanged: 3,
PanelResized: 4,
EditorFocused: 5,
BeganBackupDownload: 6,
EndedBackupDownload: 7,
DesktopExtsReady: 8,
WindowDidFocus: 9,
WindowDidBlur: 10
};
var EventSources = {
UserInteraction: 1,
Script: 2
};
var AppState =
/*#__PURE__*/
function () {
AppState.$inject = ["$timeout", "$rootScope", "application"];
/* @ngInject */
function AppState($timeout, $rootScope, application) {
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, AppState);
this.$timeout = $timeout;
this.$rootScope = $rootScope;
this.application = application;
this.observers = [];
this.registerVisibilityObservers();
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(AppState, [{
key: "registerVisibilityObservers",
value: function registerVisibilityObservers() {
var _this = this;
if (Object(_utils__WEBPACK_IMPORTED_MODULE_4__["isDesktopApplication"])()) {
this.$rootScope.$on('window-lost-focus', function () {
_this.notifyEvent(AppStateEvents.WindowDidBlur);
});
this.$rootScope.$on('window-gained-focus', function () {
_this.notifyEvent(AppStateEvents.WindowDidFocus);
});
} else {
/* Tab visibility listener, web only */
document.addEventListener('visibilitychange', function (e) {
var visible = document.visibilityState === "visible";
var event = visible ? AppStateEvents.WindowDidFocus : AppStateEvents.WindowDidBlur;
_this.notifyEvent(event);
});
}
}
/** @returns A function that unregisters this observer */
}, {
key: "addObserver",
value: function addObserver(callback) {
var _this2 = this;
this.observers.push(callback);
return function () {
lodash_pull__WEBPACK_IMPORTED_MODULE_5___default()(_this2.observers, callback);
};
}
}, {
key: "notifyEvent",
value: function () {
var _notifyEvent = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(eventName, data) {
var _this3 = this;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
return _context2.abrupt("return", new Promise(function (resolve) {
_this3.$timeout(
/*#__PURE__*/
_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {
var _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, callback;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_iteratorNormalCompletion = true;
_didIteratorError = false;
_iteratorError = undefined;
_context.prev = 3;
_iterator = _this3.observers[Symbol.iterator]();
case 5:
if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
_context.next = 12;
break;
}
callback = _step.value;
_context.next = 9;
return callback(eventName, data);
case 9:
_iteratorNormalCompletion = true;
_context.next = 5;
break;
case 12:
_context.next = 18;
break;
case 14:
_context.prev = 14;
_context.t0 = _context["catch"](3);
_didIteratorError = true;
_iteratorError = _context.t0;
case 18:
_context.prev = 18;
_context.prev = 19;
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
case 21:
_context.prev = 21;
if (!_didIteratorError) {
_context.next = 24;
break;
}
throw _iteratorError;
case 24:
return _context.finish(21);
case 25:
return _context.finish(18);
case 26:
resolve();
case 27:
case "end":
return _context.stop();
}
}
}, _callee, null, [[3, 14, 18, 26], [19,, 21, 25]]);
})));
}));
case 1:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
function notifyEvent(_x, _x2) {
return _notifyEvent.apply(this, arguments);
}
return notifyEvent;
}()
}, {
key: "setSelectedTag",
value: function setSelectedTag(tag) {
if (this.selectedTag === tag) {
return;
}
var previousTag = this.selectedTag;
this.selectedTag = tag;
this.notifyEvent(AppStateEvents.TagChanged, {
tag: tag,
previousTag: previousTag
});
}
}, {
key: "setSelectedNote",
value: function () {
var _setSelectedNote = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(note) {
var _this4 = this;
var run;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
run =
/*#__PURE__*/
function () {
var _ref2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3() {
var previousNote;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
previousNote = _this4.selectedNote;
_this4.selectedNote = note;
_context3.next = 4;
return _this4.notifyEvent(AppStateEvents.NoteChanged, {
previousNote: previousNote
});
case 4:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
return function run() {
return _ref2.apply(this, arguments);
};
}();
_context4.t0 = note && note.content.protected;
if (!_context4.t0) {
_context4.next = 6;
break;
}
_context4.next = 5;
return this.application.privilegesManager.actionRequiresPrivilege(snjs__WEBPACK_IMPORTED_MODULE_6__["ProtectedActions"].ViewProtectedNotes);
case 5:
_context4.t0 = _context4.sent;
case 6:
if (!_context4.t0) {
_context4.next = 10;
break;
}
this.godService.presentPrivilegesModal(snjs__WEBPACK_IMPORTED_MODULE_6__["ProtectedActions"].ViewProtectedNotes, run);
_context4.next = 11;
break;
case 10:
run();
case 11:
case "end":
return _context4.stop();
}
}
}, _callee4, this);
}));
function setSelectedNote(_x3) {
return _setSelectedNote.apply(this, arguments);
}
return setSelectedNote;
}()
}, {
key: "getSelectedTag",
value: function getSelectedTag() {
return this.selectedTag;
}
}, {
key: "getSelectedNote",
value: function getSelectedNote() {
return this.selectedNote;
}
}, {
key: "setUserPreferences",
value: function setUserPreferences(preferences) {
this.userPreferences = preferences;
this.notifyEvent(AppStateEvents.PreferencesChanged);
}
}, {
key: "panelDidResize",
value: function panelDidResize(_ref3) {
var name = _ref3.name,
collapsed = _ref3.collapsed;
this.notifyEvent(AppStateEvents.PanelResized, {
panel: name,
collapsed: collapsed
});
}
}, {
key: "editorDidFocus",
value: function editorDidFocus(eventSource) {
this.notifyEvent(AppStateEvents.EditorFocused, {
eventSource: eventSource
});
}
}, {
key: "beganBackupDownload",
value: function beganBackupDownload() {
this.notifyEvent(AppStateEvents.BeganBackupDownload);
}
}, {
key: "endedBackupDownload",
value: function endedBackupDownload(_ref4) {
var success = _ref4.success;
this.notifyEvent(AppStateEvents.EndedBackupDownload, {
success: success
});
}
/**
* When the desktop appplication extension server is ready.
*/
}, {
key: "desktopExtensionsReady",
value: function desktopExtensionsReady() {
this.notifyEvent(AppStateEvents.DesktopExtsReady);
}
}]);
return AppState;
}();
/***/ }),
/***/ "./app/assets/javascripts/strings.js":
/*!*******************************************!*\
!*** ./app/assets/javascripts/strings.js ***!
\*******************************************/
/*! exports provided: STRING_SESSION_EXPIRED, STRING_DEFAULT_FILE_ERROR, STRING_GENERIC_SYNC_ERROR, StringSyncException, STRING_NEW_UPDATE_READY, STRING_DELETE_TAG, STRING_DELETED_NOTE, STRING_INVALID_NOTE, STRING_ELLIPSES, STRING_GENERIC_SAVE_ERROR, STRING_DELETE_PLACEHOLDER_ATTEMPT, STRING_DELETE_LOCKED_ATTEMPT, StringDeleteNote, StringEmptyTrash, STRING_ACCOUNT_MENU_UNCHECK_MERGE, STRING_SIGN_OUT_CONFIRMATION, STRING_ERROR_DECRYPTING_IMPORT, STRING_E2E_ENABLED, STRING_LOCAL_ENC_ENABLED, STRING_ENC_NOT_ENABLED, STRING_IMPORT_SUCCESS, STRING_REMOVE_PASSCODE_CONFIRMATION, STRING_REMOVE_PASSCODE_OFFLINE_ADDENDUM, STRING_NON_MATCHING_PASSCODES, STRING_NON_MATCHING_PASSWORDS, STRING_GENERATING_LOGIN_KEYS, STRING_GENERATING_REGISTER_KEYS, STRING_INVALID_IMPORT_FILE, StringImportError, STRING_FAILED_PASSWORD_CHANGE */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_SESSION_EXPIRED", function() { return STRING_SESSION_EXPIRED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_DEFAULT_FILE_ERROR", function() { return STRING_DEFAULT_FILE_ERROR; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_GENERIC_SYNC_ERROR", function() { return STRING_GENERIC_SYNC_ERROR; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StringSyncException", function() { return StringSyncException; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_NEW_UPDATE_READY", function() { return STRING_NEW_UPDATE_READY; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_DELETE_TAG", function() { return STRING_DELETE_TAG; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_DELETED_NOTE", function() { return STRING_DELETED_NOTE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_INVALID_NOTE", function() { return STRING_INVALID_NOTE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_ELLIPSES", function() { return STRING_ELLIPSES; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_GENERIC_SAVE_ERROR", function() { return STRING_GENERIC_SAVE_ERROR; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_DELETE_PLACEHOLDER_ATTEMPT", function() { return STRING_DELETE_PLACEHOLDER_ATTEMPT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_DELETE_LOCKED_ATTEMPT", function() { return STRING_DELETE_LOCKED_ATTEMPT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StringDeleteNote", function() { return StringDeleteNote; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StringEmptyTrash", function() { return StringEmptyTrash; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_ACCOUNT_MENU_UNCHECK_MERGE", function() { return STRING_ACCOUNT_MENU_UNCHECK_MERGE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_SIGN_OUT_CONFIRMATION", function() { return STRING_SIGN_OUT_CONFIRMATION; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_ERROR_DECRYPTING_IMPORT", function() { return STRING_ERROR_DECRYPTING_IMPORT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_E2E_ENABLED", function() { return STRING_E2E_ENABLED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_LOCAL_ENC_ENABLED", function() { return STRING_LOCAL_ENC_ENABLED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_ENC_NOT_ENABLED", function() { return STRING_ENC_NOT_ENABLED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_IMPORT_SUCCESS", function() { return STRING_IMPORT_SUCCESS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_REMOVE_PASSCODE_CONFIRMATION", function() { return STRING_REMOVE_PASSCODE_CONFIRMATION; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_REMOVE_PASSCODE_OFFLINE_ADDENDUM", function() { return STRING_REMOVE_PASSCODE_OFFLINE_ADDENDUM; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_NON_MATCHING_PASSCODES", function() { return STRING_NON_MATCHING_PASSCODES; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_NON_MATCHING_PASSWORDS", function() { return STRING_NON_MATCHING_PASSWORDS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_GENERATING_LOGIN_KEYS", function() { return STRING_GENERATING_LOGIN_KEYS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_GENERATING_REGISTER_KEYS", function() { return STRING_GENERATING_REGISTER_KEYS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_INVALID_IMPORT_FILE", function() { return STRING_INVALID_IMPORT_FILE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StringImportError", function() { return StringImportError; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STRING_FAILED_PASSWORD_CHANGE", function() { return STRING_FAILED_PASSWORD_CHANGE; });
/** @generic */
var STRING_SESSION_EXPIRED = "Your session has expired. New changes will not be pulled in. Please sign out and sign back in to refresh your session.";
var STRING_DEFAULT_FILE_ERROR = "Please use FileSafe or the Bold Editor to attach images and files. Learn more at standardnotes.org/filesafe.";
var STRING_GENERIC_SYNC_ERROR = "There was an error syncing. Please try again. If all else fails, try signing out and signing back in.";
function StringSyncException(data) {
return "There was an error while trying to save your items. Please contact support and share this message: ".concat(data, ".");
}
/** @footer */
var STRING_NEW_UPDATE_READY = "A new update is ready to install. Please use the top-level 'Updates' menu to manage installation.";
/** @tags */
var STRING_DELETE_TAG = "Are you sure you want to delete this tag? Note: deleting a tag will not delete its notes.";
/** @editor */
var STRING_DELETED_NOTE = "The note you are attempting to edit has been deleted, and is awaiting sync. Changes you make will be disregarded.";
var STRING_INVALID_NOTE = "The note you are attempting to save can not be found or has been deleted. Changes you make will not be synced. Please copy this note's text and start a new note.";
var STRING_ELLIPSES = "...";
var STRING_GENERIC_SAVE_ERROR = "There was an error saving your note. Please try again.";
var STRING_DELETE_PLACEHOLDER_ATTEMPT = "This note is a placeholder and cannot be deleted. To remove from your list, simply navigate to a different note.";
var STRING_DELETE_LOCKED_ATTEMPT = "This note is locked. If you'd like to delete it, unlock it, and try again.";
function StringDeleteNote(_ref) {
var title = _ref.title,
permanently = _ref.permanently;
return permanently ? "Are you sure you want to permanently delete ".concat(title, "?") : "Are you sure you want to move ".concat(title, " to the trash?");
}
function StringEmptyTrash(_ref2) {
var count = _ref2.count;
return "Are you sure you want to permanently delete ".concat(count, " note(s)?");
}
/** @account */
var STRING_ACCOUNT_MENU_UNCHECK_MERGE = "Unchecking this option means any of the notes you have written while you were signed out will be deleted. Are you sure you want to discard these notes?";
var STRING_SIGN_OUT_CONFIRMATION = "Are you sure you want to end your session? This will delete all local items and extensions.";
var STRING_ERROR_DECRYPTING_IMPORT = "There was an error decrypting your items. Make sure the password you entered is correct and try again.";
var STRING_E2E_ENABLED = "End-to-end encryption is enabled. Your data is encrypted on your device first, then synced to your private cloud.";
var STRING_LOCAL_ENC_ENABLED = "Encryption is enabled. Your data is encrypted using your passcode before it is saved to your device storage.";
var STRING_ENC_NOT_ENABLED = "Encryption is not enabled. Sign in, register, or add a passcode lock to enable encryption.";
var STRING_IMPORT_SUCCESS = "Your data has been successfully imported.";
var STRING_REMOVE_PASSCODE_CONFIRMATION = "Are you sure you want to remove your local passcode?";
var STRING_REMOVE_PASSCODE_OFFLINE_ADDENDUM = " This will remove encryption from your local data.";
var STRING_NON_MATCHING_PASSCODES = "The two passcodes you entered do not match. Please try again.";
var STRING_NON_MATCHING_PASSWORDS = "The two passwords you entered do not match. Please try again.";
var STRING_GENERATING_LOGIN_KEYS = "Generating Login Keys...";
var STRING_GENERATING_REGISTER_KEYS = "Generating Account Keys...";
var STRING_INVALID_IMPORT_FILE = "Unable to open file. Ensure it is a proper JSON file and try again.";
function StringImportError(_ref3) {
var errorCount = _ref3.errorCount;
return "Import complete. ".concat(errorCount, " items were not imported because there was an error decrypting them. Make sure the password is correct and try again.");
}
/** @password_change */
var STRING_FAILED_PASSWORD_CHANGE = "There was an error re-encrypting your items. Your password was changed, but not all your items were properly re-encrypted and synced. You should try syncing again. If all else fails, you should restore your notes from backup.";
/***/ }),
/***/ "./app/assets/javascripts/utils.js":
/*!*****************************************!*\
!*** ./app/assets/javascripts/utils.js ***!
\*****************************************/
/*! exports provided: getParameterByName, parametersFromURL, isNullOrUndefined, dictToArray, getPlatformString, dateToLocalizedString, debounce, isDesktopApplication */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getParameterByName", function() { return getParameterByName; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parametersFromURL", function() { return parametersFromURL; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNullOrUndefined", function() { return isNullOrUndefined; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dictToArray", function() { return dictToArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPlatformString", function() { return getPlatformString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dateToLocalizedString", function() { return dateToLocalizedString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "debounce", function() { return debounce; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDesktopApplication", function() { return isDesktopApplication; });
function getParameterByName(name, url) {
name = name.replace(/[[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^]*)|&|#|$)');
var results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
function parametersFromURL(url) {
url = url.split('?').slice(-1)[0];
var obj = {};
url.replace(/([^=&]+)=([^&]*)/g, function (m, key, value) {
obj[decodeURIComponent(key)] = decodeURIComponent(value);
});
return obj;
}
function isNullOrUndefined(value) {
return value === null || value === undefined;
}
function dictToArray(dict) {
return Object.keys(dict).map(function (key) {
return dict[key];
});
}
function getPlatformString() {
try {
var platform = navigator.platform.toLowerCase();
var trimmed = '';
if (platform.indexOf('mac') !== -1) {
trimmed = 'mac';
} else if (platform.indexOf('win') !== -1) {
trimmed = 'windows';
}
if (platform.indexOf('linux') !== -1) {
trimmed = 'linux';
}
return trimmed + (isDesktopApplication() ? '-desktop' : '-web');
} catch (e) {
return null;
}
}
var sharedDateFormatter;
function dateToLocalizedString(date) {
if (typeof Intl !== 'undefined' && Intl.DateTimeFormat) {
if (!sharedDateFormatter) {
var locale = navigator.languages && navigator.languages.length ? navigator.languages[0] : navigator.language;
sharedDateFormatter = new Intl.DateTimeFormat(locale, {
year: 'numeric',
month: 'numeric',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
});
}
return sharedDateFormatter.format(date);
} else {
// IE < 11, Safari <= 9.0.
// In English, this generates the string most similar to
// the toLocaleDateString() result above.
return date.toDateString() + ' ' + date.toLocaleTimeString();
}
}
/** Via https://davidwalsh.name/javascript-debounce-function */
function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this;
var args = arguments;
var later = function later() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
;
function isDesktopApplication() {
return window.isElectron;
}
/* Use with numbers and strings, not objects */
// eslint-disable-next-line no-extend-native
Array.prototype.containsPrimitiveSubset = function (array) {
var _this = this;
return !array.some(function (val) {
return _this.indexOf(val) === -1;
});
}; // https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
// eslint-disable-next-line no-extend-native
Object.defineProperty(Array.prototype, 'includes', {
value: function value(searchElement, fromIndex) {
if (this == null) {
throw new TypeError('"this" is null or not defined');
} // 1. Let O be ? ToObject(this value).
var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0; // 3. If len is 0, return false.
if (len === 0) {
return false;
} // 4. Let n be ? ToInteger(fromIndex).
// (If fromIndex is undefined, this step produces the value 0.)
var n = fromIndex | 0; // 5. If n ≥ 0, then
// a. Let k be n.
// 6. Else n < 0,
// a. Let k be len + n.
// b. If k < 0, let k be 0.
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
function sameValueZero(x, y) {
return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);
} // 7. Repeat, while k < len
while (k < len) {
// a. Let elementK be the result of ? Get(O, ! ToString(k)).
// b. If SameValueZero(searchElement, elementK) is true, return true.
if (sameValueZero(o[k], searchElement)) {
return true;
} // c. Increase k by 1.
k++;
} // 8. Return false
return false;
}
});
}
/***/ }),
/***/ "./app/assets/javascripts/web_device_interface.js":
/*!********************************************************!*\
!*** ./app/assets/javascripts/web_device_interface.js ***!
\********************************************************/
/*! exports provided: WebDeviceInterface */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebDeviceInterface", function() { return WebDeviceInterface; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! snjs */ "../snjs/dist/snjs.js");
/* harmony import */ var snjs__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(snjs__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _database__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/database */ "./app/assets/javascripts/database.js");
var KEYCHAIN_STORAGE_KEY = 'keychain';
var WebDeviceInterface =
/*#__PURE__*/
function (_DeviceInterface) {
_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_6___default()(WebDeviceInterface, _DeviceInterface);
function WebDeviceInterface() {
var _this;
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
namespace = _ref.namespace,
timeout = _ref.timeout;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, WebDeviceInterface);
_this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5___default()(WebDeviceInterface).call(this, {
namespace: namespace,
timeout: timeout || setTimeout.bind(Object(snjs__WEBPACK_IMPORTED_MODULE_7__["getGlobalScope"])()),
interval: setInterval.bind(Object(snjs__WEBPACK_IMPORTED_MODULE_7__["getGlobalScope"])())
}));
_this.createDatabase();
return _this;
}
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(WebDeviceInterface, [{
key: "createDatabase",
value: function createDatabase() {
this.database = new _database__WEBPACK_IMPORTED_MODULE_8__["Database"]();
}
}, {
key: "setApplication",
value: function setApplication(application) {
this.database.setApplication(application);
}
/**
* @value storage
*/
}, {
key: "getRawStorageValue",
value: function () {
var _getRawStorageValue = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(key) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt("return", localStorage.getItem(key));
case 1:
case "end":
return _context.stop();
}
}
}, _callee);
}));
function getRawStorageValue(_x) {
return _getRawStorageValue.apply(this, arguments);
}
return getRawStorageValue;
}()
}, {
key: "getAllRawStorageKeyValues",
value: function () {
var _getAllRawStorageKeyValues = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
var results, _i, _Object$keys, key;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
results = [];
for (_i = 0, _Object$keys = Object.keys(localStorage); _i < _Object$keys.length; _i++) {
key = _Object$keys[_i];
results.push({
key: key,
value: localStorage[key]
});
}
return _context2.abrupt("return", results);
case 3:
case "end":
return _context2.stop();
}
}
}, _callee2);
}));
function getAllRawStorageKeyValues() {
return _getAllRawStorageKeyValues.apply(this, arguments);
}
return getAllRawStorageKeyValues;
}()
}, {
key: "setRawStorageValue",
value: function () {
var _setRawStorageValue = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(key, value) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
localStorage.setItem(key, value);
case 1:
case "end":
return _context3.stop();
}
}
}, _callee3);
}));
function setRawStorageValue(_x2, _x3) {
return _setRawStorageValue.apply(this, arguments);
}
return setRawStorageValue;
}()
}, {
key: "removeRawStorageValue",
value: function () {
var _removeRawStorageValue = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(key) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
localStorage.removeItem(key);
case 1:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
function removeRawStorageValue(_x4) {
return _removeRawStorageValue.apply(this, arguments);
}
return removeRawStorageValue;
}()
}, {
key: "removeAllRawStorageValues",
value: function () {
var _removeAllRawStorageValues = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {
while (1) {
switch (_context5.prev = _context5.next) {
case 0:
localStorage.clear();
case 1:
case "end":
return _context5.stop();
}
}
}, _callee5);
}));
function removeAllRawStorageValues() {
return _removeAllRawStorageValues.apply(this, arguments);
}
return removeAllRawStorageValues;
}()
/**
* @database
*/
}, {
key: "openDatabase",
value: function () {
var _openDatabase = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee6() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee6$(_context6) {
while (1) {
switch (_context6.prev = _context6.next) {
case 0:
this.database.setLocked(false);
this.database.openDatabase({
onUpgradeNeeded: function onUpgradeNeeded() {
/**
* New database/database wiped, delete syncToken so that items
* can be refetched entirely from server
*/
/** @todo notify parent */
// this.syncManager.clearSyncPositionTokens();
// this.sync();
}
});
case 2:
case "end":
return _context6.stop();
}
}
}, _callee6, this);
}));
function openDatabase() {
return _openDatabase.apply(this, arguments);
}
return openDatabase;
}()
/** @private */
}, {
key: "getDatabaseKeyPrefix",
value: function getDatabaseKeyPrefix() {
if (this.namespace) {
return "".concat(this.namespace, "-item-");
} else {
return "item-";
}
}
/** @private */
}, {
key: "keyForPayloadId",
value: function keyForPayloadId(id) {
return "".concat(this.getDatabaseKeyPrefix()).concat(id);
}
}, {
key: "getAllRawDatabasePayloads",
value: function () {
var _getAllRawDatabasePayloads = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee7() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee7$(_context7) {
while (1) {
switch (_context7.prev = _context7.next) {
case 0:
return _context7.abrupt("return", this.database.getAllPayloads());
case 1:
case "end":
return _context7.stop();
}
}
}, _callee7, this);
}));
function getAllRawDatabasePayloads() {
return _getAllRawDatabasePayloads.apply(this, arguments);
}
return getAllRawDatabasePayloads;
}()
}, {
key: "saveRawDatabasePayload",
value: function () {
var _saveRawDatabasePayload = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee8(payload) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee8$(_context8) {
while (1) {
switch (_context8.prev = _context8.next) {
case 0:
return _context8.abrupt("return", this.database.savePayload(payload));
case 1:
case "end":
return _context8.stop();
}
}
}, _callee8, this);
}));
function saveRawDatabasePayload(_x5) {
return _saveRawDatabasePayload.apply(this, arguments);
}
return saveRawDatabasePayload;
}()
}, {
key: "saveRawDatabasePayloads",
value: function () {
var _saveRawDatabasePayloads = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee9(payloads) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee9$(_context9) {
while (1) {
switch (_context9.prev = _context9.next) {
case 0:
return _context9.abrupt("return", this.database.savePayloads(payloads));
case 1:
case "end":
return _context9.stop();
}
}
}, _callee9, this);
}));
function saveRawDatabasePayloads(_x6) {
return _saveRawDatabasePayloads.apply(this, arguments);
}
return saveRawDatabasePayloads;
}()
}, {
key: "removeRawDatabasePayloadWithId",
value: function () {
var _removeRawDatabasePayloadWithId = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee10(id) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee10$(_context10) {
while (1) {
switch (_context10.prev = _context10.next) {
case 0:
return _context10.abrupt("return", this.database.deletePayload(id));
case 1:
case "end":
return _context10.stop();
}
}
}, _callee10, this);
}));
function removeRawDatabasePayloadWithId(_x7) {
return _removeRawDatabasePayloadWithId.apply(this, arguments);
}
return removeRawDatabasePayloadWithId;
}()
}, {
key: "removeAllRawDatabasePayloads",
value: function () {
var _removeAllRawDatabasePayloads = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee11() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee11$(_context11) {
while (1) {
switch (_context11.prev = _context11.next) {
case 0:
return _context11.abrupt("return", this.database.clearAllPayloads());
case 1:
case "end":
return _context11.stop();
}
}
}, _callee11, this);
}));
function removeAllRawDatabasePayloads() {
return _removeAllRawDatabasePayloads.apply(this, arguments);
}
return removeAllRawDatabasePayloads;
}()
/** @keychian */
}, {
key: "getRawKeychainValue",
value: function () {
var _getRawKeychainValue = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee12() {
var value;
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee12$(_context12) {
while (1) {
switch (_context12.prev = _context12.next) {
case 0:
value = localStorage.getItem(KEYCHAIN_STORAGE_KEY);
if (!value) {
_context12.next = 3;
break;
}
return _context12.abrupt("return", JSON.parse(value));
case 3:
case "end":
return _context12.stop();
}
}
}, _callee12);
}));
function getRawKeychainValue() {
return _getRawKeychainValue.apply(this, arguments);
}
return getRawKeychainValue;
}()
}, {
key: "setKeychainValue",
value: function () {
var _setKeychainValue = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee13(value) {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee13$(_context13) {
while (1) {
switch (_context13.prev = _context13.next) {
case 0:
localStorage.setItem(KEYCHAIN_STORAGE_KEY, JSON.stringify(value));
case 1:
case "end":
return _context13.stop();
}
}
}, _callee13);
}));
function setKeychainValue(_x8) {
return _setKeychainValue.apply(this, arguments);
}
return setKeychainValue;
}()
}, {
key: "clearKeychainValue",
value: function () {
var _clearKeychainValue = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()(
/*#__PURE__*/
_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee14() {
return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee14$(_context14) {
while (1) {
switch (_context14.prev = _context14.next) {
case 0:
localStorage.removeItem(KEYCHAIN_STORAGE_KEY);
case 1:
case "end":
return _context14.stop();
}
}
}, _callee14);
}));
function clearKeychainValue() {
return _clearKeychainValue.apply(this, arguments);
}
return clearKeychainValue;
}()
/**
* @actions
*/
}, {
key: "openUrl",
value: function openUrl(url) {
var win = window.open(url, '_blank');
if (win) {
win.focus();
}
}
}]);
return WebDeviceInterface;
}(snjs__WEBPACK_IMPORTED_MODULE_7__["DeviceInterface"]);
/***/ }),
/***/ "./app/assets/stylesheets/index.css.scss":
/*!***********************************************!*\
!*** ./app/assets/stylesheets/index.css.scss ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "./app/assets/templates/directives/account-menu.pug":
/*!**********************************************************!*\
!*** ./app/assets/templates/directives/account-menu.pug ***!
\**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/account-menu.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/account-menu.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/actions-menu.pug":
/*!**********************************************************!*\
!*** ./app/assets/templates/directives/actions-menu.pug ***!
\**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/actions-menu.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/actions-menu.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/component-modal.pug":
/*!*************************************************************!*\
!*** ./app/assets/templates/directives/component-modal.pug ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/component-modal.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/component-modal.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/component-view.pug":
/*!************************************************************!*\
!*** ./app/assets/templates/directives/component-view.pug ***!
\************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/component-view.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/component-view.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/conflict-resolution-modal.pug":
/*!***********************************************************************!*\
!*** ./app/assets/templates/directives/conflict-resolution-modal.pug ***!
\***********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/conflict-resolution-modal.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/conflict-resolution-modal.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/editor-menu.pug":
/*!*********************************************************!*\
!*** ./app/assets/templates/directives/editor-menu.pug ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/editor-menu.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/editor-menu.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/input-modal.pug":
/*!*********************************************************!*\
!*** ./app/assets/templates/directives/input-modal.pug ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/input-modal.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/input-modal.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/menu-row.pug":
/*!******************************************************!*\
!*** ./app/assets/templates/directives/menu-row.pug ***!
\******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/menu-row.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/menu-row.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/panel-resizer.pug":
/*!***********************************************************!*\
!*** ./app/assets/templates/directives/panel-resizer.pug ***!
\***********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/panel-resizer.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/panel-resizer.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/password-wizard.pug":
/*!*************************************************************!*\
!*** ./app/assets/templates/directives/password-wizard.pug ***!
\*************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/password-wizard.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/password-wizard.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/permissions-modal.pug":
/*!***************************************************************!*\
!*** ./app/assets/templates/directives/permissions-modal.pug ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/permissions-modal.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/permissions-modal.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/privileges-auth-modal.pug":
/*!*******************************************************************!*\
!*** ./app/assets/templates/directives/privileges-auth-modal.pug ***!
\*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/privileges-auth-modal.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/privileges-auth-modal.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/privileges-management-modal.pug":
/*!*************************************************************************!*\
!*** ./app/assets/templates/directives/privileges-management-modal.pug ***!
\*************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/privileges-management-modal.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/privileges-management-modal.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/revision-preview-modal.pug":
/*!********************************************************************!*\
!*** ./app/assets/templates/directives/revision-preview-modal.pug ***!
\********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/revision-preview-modal.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/revision-preview-modal.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/session-history-menu.pug":
/*!******************************************************************!*\
!*** ./app/assets/templates/directives/session-history-menu.pug ***!
\******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/session-history-menu.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/session-history-menu.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/directives/sync-resolution-menu.pug":
/*!******************************************************************!*\
!*** ./app/assets/templates/directives/sync-resolution-menu.pug ***!
\******************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/directives/sync-resolution-menu.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/directives/sync-resolution-menu.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/editor.pug":
/*!*****************************************!*\
!*** ./app/assets/templates/editor.pug ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/editor.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/editor.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/footer.pug":
/*!*****************************************!*\
!*** ./app/assets/templates/footer.pug ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/footer.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/footer.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/lock-screen.pug":
/*!**********************************************!*\
!*** ./app/assets/templates/lock-screen.pug ***!
\**********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/lock-screen.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/lock-screen.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/notes.pug":
/*!****************************************!*\
!*** ./app/assets/templates/notes.pug ***!
\****************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/notes.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/notes.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/root.pug":
/*!***************************************!*\
!*** ./app/assets/templates/root.pug ***!
\***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/root.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/root.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./app/assets/templates/tags.pug":
/*!***************************************!*\
!*** ./app/assets/templates/tags.pug ***!
\***************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var req = __webpack_require__(/*! !./node_modules/pug-loader!./app/assets/templates/tags.pug */ "./node_modules/pug-loader/index.js!./app/assets/templates/tags.pug");
module.exports = (req['default'] || req).apply(req, [])
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js":
/*!**********************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/assertThisInitialized.js ***!
\**********************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
module.exports = _assertThisInitialized;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js":
/*!*****************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/asyncToGenerator.js ***!
\*****************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
module.exports = _asyncToGenerator;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/classCallCheck.js":
/*!***************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/classCallCheck.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
module.exports = _classCallCheck;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/createClass.js":
/*!************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/createClass.js ***!
\************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
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;
}
module.exports = _createClass;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/defineProperty.js":
/*!***************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/defineProperty.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
module.exports = _defineProperty;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/get.js":
/*!****************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/get.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var superPropBase = __webpack_require__(/*! ./superPropBase */ "./node_modules/@babel/runtime/helpers/superPropBase.js");
function _get(target, property, receiver) {
if (typeof Reflect !== "undefined" && Reflect.get) {
module.exports = _get = Reflect.get;
} else {
module.exports = _get = function _get(target, property, receiver) {
var base = superPropBase(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) {
return desc.get.call(receiver);
}
return desc.value;
};
}
return _get(target, property, receiver || target);
}
module.exports = _get;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js":
/*!***************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/getPrototypeOf.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _getPrototypeOf(o) {
module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
module.exports = _getPrototypeOf;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/inherits.js":
/*!*********************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/inherits.js ***!
\*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf */ "./node_modules/@babel/runtime/helpers/setPrototypeOf.js");
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) setPrototypeOf(subClass, superClass);
}
module.exports = _inherits;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js":
/*!**************************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js ***!
\**************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var _typeof = __webpack_require__(/*! ../helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js");
var assertThisInitialized = __webpack_require__(/*! ./assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js");
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return assertThisInitialized(self);
}
module.exports = _possibleConstructorReturn;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/setPrototypeOf.js":
/*!***************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/setPrototypeOf.js ***!
\***************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _setPrototypeOf(o, p) {
module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
module.exports = _setPrototypeOf;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/superPropBase.js":
/*!**************************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/superPropBase.js ***!
\**************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var getPrototypeOf = __webpack_require__(/*! ./getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js");
function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = getPrototypeOf(object);
if (object === null) break;
}
return object;
}
module.exports = _superPropBase;
/***/ }),
/***/ "./node_modules/@babel/runtime/helpers/typeof.js":
/*!*******************************************************!*\
!*** ./node_modules/@babel/runtime/helpers/typeof.js ***!
\*******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
module.exports = _typeof = function _typeof(obj) {
return typeof obj;
};
} else {
module.exports = _typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
module.exports = _typeof;
/***/ }),
/***/ "./node_modules/@babel/runtime/regenerator/index.js":
/*!**********************************************************!*\
!*** ./node_modules/@babel/runtime/regenerator/index.js ***!
\**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! regenerator-runtime */ "./node_modules/regenerator-runtime/runtime.js");
/***/ }),
/***/ "./node_modules/angular/angular.js":
/*!*****************************************!*\
!*** ./node_modules/angular/angular.js ***!
\*****************************************/
/*! no static exports found */
/***/ (function(module, exports) {
/**
* @license AngularJS v1.7.9
* (c) 2010-2018 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window) {'use strict';
/* exported
minErrConfig,
errorHandlingConfig,
isValidObjectMaxDepth
*/
var minErrConfig = {
objectMaxDepth: 5,
urlErrorParamsEnabled: true
};
/**
* @ngdoc function
* @name angular.errorHandlingConfig
* @module ng
* @kind function
*
* @description
* Configure several aspects of error handling in AngularJS if used as a setter or return the
* current configuration if used as a getter. The following options are supported:
*
* - **objectMaxDepth**: The maximum depth to which objects are traversed when stringified for error messages.
*
* Omitted or undefined options will leave the corresponding configuration values unchanged.
*
* @param {Object=} config - The configuration object. May only contain the options that need to be
* updated. Supported keys:
*
* * `objectMaxDepth` **{Number}** - The max depth for stringifying objects. Setting to a
* non-positive or non-numeric value, removes the max depth limit.
* Default: 5
*
* * `urlErrorParamsEnabled` **{Boolean}** - Specifies wether the generated error url will
* contain the parameters of the thrown error. Disabling the parameters can be useful if the
* generated error url is very long.
*
* Default: true. When used without argument, it returns the current value.
*/
function errorHandlingConfig(config) {
if (isObject(config)) {
if (isDefined(config.objectMaxDepth)) {
minErrConfig.objectMaxDepth = isValidObjectMaxDepth(config.objectMaxDepth) ? config.objectMaxDepth : NaN;
}
if (isDefined(config.urlErrorParamsEnabled) && isBoolean(config.urlErrorParamsEnabled)) {
minErrConfig.urlErrorParamsEnabled = config.urlErrorParamsEnabled;
}
} else {
return minErrConfig;
}
}
/**
* @private
* @param {Number} maxDepth
* @return {boolean}
*/
function isValidObjectMaxDepth(maxDepth) {
return isNumber(maxDepth) && maxDepth > 0;
}
/**
* @description
*
* This object provides a utility for producing rich Error messages within
* AngularJS. It can be called as follows:
*
* var exampleMinErr = minErr('example');
* throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
*
* The above creates an instance of minErr in the example namespace. The
* resulting error will have a namespaced error code of example.one. The
* resulting error will replace {0} with the value of foo, and {1} with the
* value of bar. The object is not restricted in the number of arguments it can
* take.
*
* If fewer arguments are specified than necessary for interpolation, the extra
* interpolation markers will be preserved in the final string.
*
* Since data will be parsed statically during a build step, some restrictions
* are applied with respect to how minErr instances are created and called.
* Instances should have names of the form namespaceMinErr for a minErr created
* using minErr('namespace') . Error codes, namespaces and template strings
* should all be static strings, not variables or general expressions.
*
* @param {string} module The namespace to use for the new minErr instance.
* @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
* error from returned function, for cases when a particular type of error is useful.
* @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
*/
function minErr(module, ErrorConstructor) {
ErrorConstructor = ErrorConstructor || Error;
var url = 'https://errors.angularjs.org/1.7.9/';
var regex = url.replace('.', '\\.') + '[\\s\\S]*';
var errRegExp = new RegExp(regex, 'g');
return function() {
var code = arguments[0],
template = arguments[1],
message = '[' + (module ? module + ':' : '') + code + '] ',
templateArgs = sliceArgs(arguments, 2).map(function(arg) {
return toDebugString(arg, minErrConfig.objectMaxDepth);
}),
paramPrefix, i;
// A minErr message has two parts: the message itself and the url that contains the
// encoded message.
// The message's parameters can contain other error messages which also include error urls.
// To prevent the messages from getting too long, we strip the error urls from the parameters.
message += template.replace(/\{\d+\}/g, function(match) {
var index = +match.slice(1, -1);
if (index < templateArgs.length) {
return templateArgs[index].replace(errRegExp, '');
}
return match;
});
message += '\n' + url + (module ? module + '/' : '') + code;
if (minErrConfig.urlErrorParamsEnabled) {
for (i = 0, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
message += paramPrefix + 'p' + i + '=' + encodeURIComponent(templateArgs[i]);
}
}
return new ErrorConstructor(message);
};
}
/* We need to tell ESLint what variables are being exported */
/* exported
angular,
msie,
jqLite,
jQuery,
slice,
splice,
push,
toString,
minErrConfig,
errorHandlingConfig,
isValidObjectMaxDepth,
ngMinErr,
angularModule,
uid,
REGEX_STRING_REGEXP,
VALIDITY_STATE_PROPERTY,
lowercase,
uppercase,
nodeName_,
isArrayLike,
forEach,
forEachSorted,
reverseParams,
nextUid,
setHashKey,
extend,
toInt,
inherit,
merge,
noop,
identity,
valueFn,
isUndefined,
isDefined,
isObject,
isBlankObject,
isString,
isNumber,
isNumberNaN,
isDate,
isError,
isArray,
isFunction,
isRegExp,
isWindow,
isScope,
isFile,
isFormData,
isBlob,
isBoolean,
isPromiseLike,
trim,
escapeForRegexp,
isElement,
makeMap,
includes,
arrayRemove,
copy,
simpleCompare,
equals,
csp,
jq,
concat,
sliceArgs,
bind,
toJsonReplacer,
toJson,
fromJson,
convertTimezoneToLocal,
timezoneToOffset,
addDateMinutes,
startingTag,
tryDecodeURIComponent,
parseKeyValue,
toKeyValue,
encodeUriSegment,
encodeUriQuery,
angularInit,
bootstrap,
getTestability,
snake_case,
bindJQuery,
assertArg,
assertArgFn,
assertNotHasOwnProperty,
getter,
getBlockNodes,
hasOwnProperty,
createMap,
stringify,
NODE_TYPE_ELEMENT,
NODE_TYPE_ATTRIBUTE,
NODE_TYPE_TEXT,
NODE_TYPE_COMMENT,
NODE_TYPE_DOCUMENT,
NODE_TYPE_DOCUMENT_FRAGMENT
*/
////////////////////////////////////
/**
* @ngdoc module
* @name ng
* @module ng
* @installation
* @description
*
* The ng module is loaded by default when an AngularJS application is started. The module itself
* contains the essential components for an AngularJS application to function. The table below
* lists a high level breakdown of each of the services/factories, filters, directives and testing
* components available within this core module.
*
*/
var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
// The name of a form control's ValidityState property.
// This is used so that it's possible for internal tests to create mock ValidityStates.
var VALIDITY_STATE_PROPERTY = 'validity';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* @private
*
* @description Converts the specified string to lowercase.
* @param {string} string String to be converted to lowercase.
* @returns {string} Lowercased string.
*/
var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
/**
* @private
*
* @description Converts the specified string to uppercase.
* @param {string} string String to be converted to uppercase.
* @returns {string} Uppercased string.
*/
var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
var
msie, // holds major version number for IE, or NaN if UA is not IE.
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
splice = [].splice,
push = [].push,
toString = Object.prototype.toString,
getPrototypeOf = Object.getPrototypeOf,
ngMinErr = minErr('ng'),
/** @name angular */
angular = window.angular || (window.angular = {}),
angularModule,
uid = 0;
// Support: IE 9-11 only
/**
* documentMode is an IE-only property
* http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
*/
msie = window.document.documentMode;
/**
* @private
* @param {*} obj
* @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
* String ...)
*/
function isArrayLike(obj) {
// `null`, `undefined` and `window` are not array-like
if (obj == null || isWindow(obj)) return false;
// arrays, strings and jQuery/jqLite objects are array like
// * jqLite is either the jQuery or jqLite constructor function
// * we have to check the existence of jqLite first as this method is called
// via the forEach method when constructing the jqLite object in the first place
if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
// Support: iOS 8.2 (not reproducible in simulator)
// "length" in obj used to prevent JIT error (gh-11508)
var length = 'length' in Object(obj) && obj.length;
// NodeList objects (with `item` method) and
// other objects with suitable length characteristics are array-like
return isNumber(length) && (length >= 0 && (length - 1) in obj || typeof obj.item === 'function');
}
/**
* @ngdoc function
* @name angular.forEach
* @module ng
* @kind function
*
* @description
* Invokes the `iterator` function once for each item in `obj` collection, which can be either an
* object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
* is the value of an object property or an array element, `key` is the object property key or
* array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
*
* It is worth noting that `.forEach` does not iterate over inherited properties because it filters
* using the `hasOwnProperty` method.
*
* Unlike ES262's
* [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
* providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
* return the value provided.
*
```js
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key) {
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender: male']);
```
*
* @param {Object|Array} obj Object to iterate over.
* @param {Function} iterator Iterator function.
* @param {Object=} context Object to become context (`this`) for the iterator function.
* @returns {Object|Array} Reference to `obj`.
*/
function forEach(obj, iterator, context) {
var key, length;
if (obj) {
if (isFunction(obj)) {
for (key in obj) {
if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key, obj);
}
}
} else if (isArray(obj) || isArrayLike(obj)) {
var isPrimitive = typeof obj !== 'object';
for (key = 0, length = obj.length; key < length; key++) {
if (isPrimitive || key in obj) {
iterator.call(context, obj[key], key, obj);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context, obj);
} else if (isBlankObject(obj)) {
// createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
for (key in obj) {
iterator.call(context, obj[key], key, obj);
}
} else if (typeof obj.hasOwnProperty === 'function') {
// Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key, obj);
}
}
} else {
// Slow path for objects which do not have a method `hasOwnProperty`
for (key in obj) {
if (hasOwnProperty.call(obj, key)) {
iterator.call(context, obj[key], key, obj);
}
}
}
}
return obj;
}
function forEachSorted(obj, iterator, context) {
var keys = Object.keys(obj).sort();
for (var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
/**
* when using forEach the params are value, key, but it is often useful to have key, value.
* @param {function(string, *)} iteratorFn
* @returns {function(*, string)}
*/
function reverseParams(iteratorFn) {
return function(value, key) {iteratorFn(key, value);};
}
/**
* A consistent way of creating unique IDs in angular.
*
* Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
* we hit number precision issues in JavaScript.
*
* Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
*
* @returns {number} an unique alpha-numeric string
*/
function nextUid() {
return ++uid;
}
/**
* Set or clear the hashkey for an object.
* @param obj object
* @param h the hashkey (!truthy to delete the hashkey)
*/
function setHashKey(obj, h) {
if (h) {
obj.$$hashKey = h;
} else {
delete obj.$$hashKey;
}
}
function baseExtend(dst, objs, deep) {
var h = dst.$$hashKey;
for (var i = 0, ii = objs.length; i < ii; ++i) {
var obj = objs[i];
if (!isObject(obj) && !isFunction(obj)) continue;
var keys = Object.keys(obj);
for (var j = 0, jj = keys.length; j < jj; j++) {
var key = keys[j];
var src = obj[key];
if (deep && isObject(src)) {
if (isDate(src)) {
dst[key] = new Date(src.valueOf());
} else if (isRegExp(src)) {
dst[key] = new RegExp(src);
} else if (src.nodeName) {
dst[key] = src.cloneNode(true);
} else if (isElement(src)) {
dst[key] = src.clone();
} else {
if (key !== '__proto__') {
if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
baseExtend(dst[key], [src], true);
}
}
} else {
dst[key] = src;
}
}
}
setHashKey(dst, h);
return dst;
}
/**
* @ngdoc function
* @name angular.extend
* @module ng
* @kind function
*
* @description
* Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
* by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
*
* **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
* {@link angular.merge} for this.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
* @returns {Object} Reference to `dst`.
*/
function extend(dst) {
return baseExtend(dst, slice.call(arguments, 1), false);
}
/**
* @ngdoc function
* @name angular.merge
* @module ng
* @kind function
*
* @description
* Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
* by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
*
* Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
* objects, performing a deep copy.
*
* @deprecated
* sinceVersion="1.6.5"
* This function is deprecated, but will not be removed in the 1.x lifecycle.
* There are edge cases (see {@link angular.merge#known-issues known issues}) that are not
* supported by this function. We suggest using another, similar library for all-purpose merging,
* such as [lodash's merge()](https://lodash.com/docs/4.17.4#merge).
*
* @knownIssue
* This is a list of (known) object types that are not handled correctly by this function:
* - [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob)
* - [`MediaStream`](https://developer.mozilla.org/docs/Web/API/MediaStream)
* - [`CanvasGradient`](https://developer.mozilla.org/docs/Web/API/CanvasGradient)
* - AngularJS {@link $rootScope.Scope scopes};
*
* `angular.merge` also does not support merging objects with circular references.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
* @returns {Object} Reference to `dst`.
*/
function merge(dst) {
return baseExtend(dst, slice.call(arguments, 1), true);
}
function toInt(str) {
return parseInt(str, 10);
}
var isNumberNaN = Number.isNaN || function isNumberNaN(num) {
// eslint-disable-next-line no-self-compare
return num !== num;
};
function inherit(parent, extra) {
return extend(Object.create(parent), extra);
}
/**
* @ngdoc function
* @name angular.noop
* @module ng
* @kind function
*
* @description
* A function that performs no operations. This function can be useful when writing code in the
* functional style.
```js
function foo(callback) {
var result = calculateResult();
(callback || angular.noop)(result);
}
```
*/
function noop() {}
noop.$inject = [];
/**
* @ngdoc function
* @name angular.identity
* @module ng
* @kind function
*
* @description
* A function that returns its first argument. This function is useful when writing code in the
* functional style.
*
```js
function transformer(transformationFn, value) {
return (transformationFn || angular.identity)(value);
};
// E.g.
function getResult(fn, input) {
return (fn || angular.identity)(input);
};
getResult(function(n) { return n * 2; }, 21); // returns 42
getResult(null, 21); // returns 21
getResult(undefined, 21); // returns 21
```
*
* @param {*} value to be returned.
* @returns {*} the value passed in.
*/
function identity($) {return $;}
identity.$inject = [];
function valueFn(value) {return function valueRef() {return value;};}
function hasCustomToString(obj) {
return isFunction(obj.toString) && obj.toString !== toString;
}
/**
* @ngdoc function
* @name angular.isUndefined
* @module ng
* @kind function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value) {return typeof value === 'undefined';}
/**
* @ngdoc function
* @name angular.isDefined
* @module ng
* @kind function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value) {return typeof value !== 'undefined';}
/**
* @ngdoc function
* @name angular.isObject
* @module ng
* @kind function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
* considered to be objects. Note that JavaScript arrays are objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value) {
// http://jsperf.com/isobject4
return value !== null && typeof value === 'object';
}
/**
* Determine if a value is an object with a null prototype
*
* @returns {boolean} True if `value` is an `Object` with a null prototype
*/
function isBlankObject(value) {
return value !== null && typeof value === 'object' && !getPrototypeOf(value);
}
/**
* @ngdoc function
* @name angular.isString
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value) {return typeof value === 'string';}
/**
* @ngdoc function
* @name angular.isNumber
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `Number`.
*
* This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
*
* If you wish to exclude these then you can use the native
* [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
* method.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value) {return typeof value === 'number';}
/**
* @ngdoc function
* @name angular.isDate
* @module ng
* @kind function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value) {
return toString.call(value) === '[object Date]';
}
/**
* @ngdoc function
* @name angular.isArray
* @module ng
* @kind function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/
function isArray(arr) {
return Array.isArray(arr) || arr instanceof Array;
}
/**
* @description
* Determines if a reference is an `Error`.
* Loosely based on https://www.npmjs.com/package/iserror
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Error`.
*/
function isError(value) {
var tag = toString.call(value);
switch (tag) {
case '[object Error]': return true;
case '[object Exception]': return true;
case '[object DOMException]': return true;
default: return value instanceof Error;
}
}
/**
* @ngdoc function
* @name angular.isFunction
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value) {return typeof value === 'function';}
/**
* Determines if a value is a regular expression object.
*
* @private
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `RegExp`.
*/
function isRegExp(value) {
return toString.call(value) === '[object RegExp]';
}
/**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.window === obj;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function isFile(obj) {
return toString.call(obj) === '[object File]';
}
function isFormData(obj) {
return toString.call(obj) === '[object FormData]';
}
function isBlob(obj) {
return toString.call(obj) === '[object Blob]';
}
function isBoolean(value) {
return typeof value === 'boolean';
}
function isPromiseLike(obj) {
return obj && isFunction(obj.then);
}
var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/;
function isTypedArray(value) {
return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
}
function isArrayBuffer(obj) {
return toString.call(obj) === '[object ArrayBuffer]';
}
var trim = function(value) {
return isString(value) ? value.trim() : value;
};
// Copied from:
// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
// Prereq: s is a string.
var escapeForRegexp = function(s) {
return s
.replace(/([-()[\]{}+?*.$^|,:#= 0) {
array.splice(index, 1);
}
return index;
}
/**
* @ngdoc function
* @name angular.copy
* @module ng
* @kind function
*
* @description
* Creates a deep copy of `source`, which should be an object or an array. This functions is used
* internally, mostly in the change-detection code. It is not intended as an all-purpose copy
* function, and has several limitations (see below).
*
* * If no destination is supplied, a copy of the object or array is created.
* * If a destination is provided, all of its elements (for arrays) or properties (for objects)
* are deleted and then all elements/properties from the source are copied to it.
* * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
* * If `source` is identical to `destination` an exception will be thrown.
*
*
*
*
* Only enumerable properties are taken into account. Non-enumerable properties (both on `source`
* and on `destination`) will be ignored.
*
*
*
* `angular.copy` does not check if destination and source are of the same type. It's the
* developer's responsibility to make sure they are compatible.
*
*
* @knownIssue
* This is a non-exhaustive list of object types / features that are not handled correctly by
* `angular.copy`. Note that since this functions is used by the change detection code, this
* means binding or watching objects of these types (or that include these types) might not work
* correctly.
* - [`File`](https://developer.mozilla.org/docs/Web/API/File)
* - [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map)
* - [`ImageData`](https://developer.mozilla.org/docs/Web/API/ImageData)
* - [`MediaStream`](https://developer.mozilla.org/docs/Web/API/MediaStream)
* - [`Set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Set)
* - [`WeakMap`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WeakMap)
* - ['getter'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)/
* [`setter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set)`
*
* @param {*} source The source that will be used to make a copy. Can be any type, including
* primitives, `null`, and `undefined`.
* @param {(Object|Array)=} destination Destination into which the source is copied. If provided,
* must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was specified.
*
* @example
form = {{user | json}}
leader = {{leader | json}}
// Module: copyExample
angular.
module('copyExample', []).
controller('ExampleController', ['$scope', function($scope) {
$scope.leader = {};
$scope.reset = function() {
// Example with 1 argument
$scope.user = angular.copy($scope.leader);
};
$scope.update = function(user) {
// Example with 2 arguments
angular.copy(user, $scope.leader);
};
$scope.reset();
}]);
*/
function copy(source, destination, maxDepth) {
var stackSource = [];
var stackDest = [];
maxDepth = isValidObjectMaxDepth(maxDepth) ? maxDepth : NaN;
if (destination) {
if (isTypedArray(destination) || isArrayBuffer(destination)) {
throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.');
}
if (source === destination) {
throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.');
}
// Empty the destination object
if (isArray(destination)) {
destination.length = 0;
} else {
forEach(destination, function(value, key) {
if (key !== '$$hashKey') {
delete destination[key];
}
});
}
stackSource.push(source);
stackDest.push(destination);
return copyRecurse(source, destination, maxDepth);
}
return copyElement(source, maxDepth);
function copyRecurse(source, destination, maxDepth) {
maxDepth--;
if (maxDepth < 0) {
return '...';
}
var h = destination.$$hashKey;
var key;
if (isArray(source)) {
for (var i = 0, ii = source.length; i < ii; i++) {
destination.push(copyElement(source[i], maxDepth));
}
} else if (isBlankObject(source)) {
// createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
for (key in source) {
destination[key] = copyElement(source[key], maxDepth);
}
} else if (source && typeof source.hasOwnProperty === 'function') {
// Slow path, which must rely on hasOwnProperty
for (key in source) {
if (source.hasOwnProperty(key)) {
destination[key] = copyElement(source[key], maxDepth);
}
}
} else {
// Slowest path --- hasOwnProperty can't be called as a method
for (key in source) {
if (hasOwnProperty.call(source, key)) {
destination[key] = copyElement(source[key], maxDepth);
}
}
}
setHashKey(destination, h);
return destination;
}
function copyElement(source, maxDepth) {
// Simple values
if (!isObject(source)) {
return source;
}
// Already copied values
var index = stackSource.indexOf(source);
if (index !== -1) {
return stackDest[index];
}
if (isWindow(source) || isScope(source)) {
throw ngMinErr('cpws',
'Can\'t copy! Making copies of Window or Scope instances is not supported.');
}
var needsRecurse = false;
var destination = copyType(source);
if (destination === undefined) {
destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
needsRecurse = true;
}
stackSource.push(source);
stackDest.push(destination);
return needsRecurse
? copyRecurse(source, destination, maxDepth)
: destination;
}
function copyType(source) {
switch (toString.call(source)) {
case '[object Int8Array]':
case '[object Int16Array]':
case '[object Int32Array]':
case '[object Float32Array]':
case '[object Float64Array]':
case '[object Uint8Array]':
case '[object Uint8ClampedArray]':
case '[object Uint16Array]':
case '[object Uint32Array]':
return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length);
case '[object ArrayBuffer]':
// Support: IE10
if (!source.slice) {
// If we're in this case we know the environment supports ArrayBuffer
/* eslint-disable no-undef */
var copied = new ArrayBuffer(source.byteLength);
new Uint8Array(copied).set(new Uint8Array(source));
/* eslint-enable */
return copied;
}
return source.slice(0);
case '[object Boolean]':
case '[object Number]':
case '[object String]':
case '[object Date]':
return new source.constructor(source.valueOf());
case '[object RegExp]':
var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]);
re.lastIndex = source.lastIndex;
return re;
case '[object Blob]':
return new source.constructor([source], {type: source.type});
}
if (isFunction(source.cloneNode)) {
return source.cloneNode(true);
}
}
}
// eslint-disable-next-line no-self-compare
function simpleCompare(a, b) { return a === b || (a !== a && b !== b); }
/**
* @ngdoc function
* @name angular.equals
* @module ng
* @kind function
*
* @description
* Determines if two objects or two values are equivalent. Supports value types, regular
* expressions, arrays and objects.
*
* Two objects or values are considered equivalent if at least one of the following is true:
*
* * Both objects or values pass `===` comparison.
* * Both objects or values are of the same type and all of their properties are equal by
* comparing them with `angular.equals`.
* * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
* * Both values represent the same regular expression (In JavaScript,
* /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
* representation matches).
*
* During a property comparison, properties of `function` type and properties with names
* that begin with `$` are ignored.
*
* Scope and DOMWindow objects are being compared only by identify (`===`).
*
* @param {*} o1 Object or value to compare.
* @param {*} o2 Object or value to compare.
* @returns {boolean} True if arguments are equal.
*
* @example
angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {
$scope.user1 = {};
$scope.user2 = {};
$scope.compare = function() {
$scope.result = angular.equals($scope.user1, $scope.user2);
};
}]);
*/
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
// eslint-disable-next-line no-self-compare
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 === t2 && t1 === 'object') {
if (isArray(o1)) {
if (!isArray(o2)) return false;
if ((length = o1.length) === o2.length) {
for (key = 0; key < length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
if (!isDate(o2)) return false;
return simpleCompare(o1.getTime(), o2.getTime());
} else if (isRegExp(o1)) {
if (!isRegExp(o2)) return false;
return o1.toString() === o2.toString();
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
keySet = createMap();
for (key in o1) {
if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
if (!equals(o1[key], o2[key])) return false;
keySet[key] = true;
}
for (key in o2) {
if (!(key in keySet) &&
key.charAt(0) !== '$' &&
isDefined(o2[key]) &&
!isFunction(o2[key])) return false;
}
return true;
}
}
return false;
}
var csp = function() {
if (!isDefined(csp.rules)) {
var ngCspElement = (window.document.querySelector('[ng-csp]') ||
window.document.querySelector('[data-ng-csp]'));
if (ngCspElement) {
var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
ngCspElement.getAttribute('data-ng-csp');
csp.rules = {
noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
};
} else {
csp.rules = {
noUnsafeEval: noUnsafeEval(),
noInlineStyle: false
};
}
}
return csp.rules;
function noUnsafeEval() {
try {
// eslint-disable-next-line no-new, no-new-func
new Function('');
return false;
} catch (e) {
return true;
}
}
};
/**
* @ngdoc directive
* @module ng
* @name ngJq
*
* @element ANY
* @param {string=} ngJq the name of the library available under `window`
* to be used for angular.element
* @description
* Use this directive to force the angular.element library. This should be
* used to force either jqLite by leaving ng-jq blank or setting the name of
* the jquery variable under window (eg. jQuery).
*
* Since AngularJS looks for this directive when it is loaded (doesn't wait for the
* DOMContentLoaded event), it must be placed on an element that comes before the script
* which loads angular. Also, only the first instance of `ng-jq` will be used and all
* others ignored.
*
* @example
* This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
```html
...
...
```
* @example
* This example shows how to use a jQuery based library of a different name.
* The library name must be available at the top most 'window'.
```html
...
...
```
*/
var jq = function() {
if (isDefined(jq.name_)) return jq.name_;
var el;
var i, ii = ngAttrPrefixes.length, prefix, name;
for (i = 0; i < ii; ++i) {
prefix = ngAttrPrefixes[i];
el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]');
if (el) {
name = el.getAttribute(prefix + 'jq');
break;
}
}
return (jq.name_ = name);
};
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
return slice.call(args, startIndex || 0);
}
/**
* @ngdoc function
* @name angular.bind
* @module ng
* @kind function
*
* @description
* Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
* `fn`). You can supply optional `args` that are prebound to the function. This feature is also
* known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
* distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
*
* @param {Object} self Context which `fn` should be evaluated in.
* @param {function()} fn Function to be bound.
* @param {...*} args Optional arguments to be prebound to the `fn` function call.
* @returns {function()} Function that wraps the `fn` with all the specified bindings.
*/
function bind(self, fn) {
var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
if (isFunction(fn) && !(fn instanceof RegExp)) {
return curryArgs.length
? function() {
return arguments.length
? fn.apply(self, concat(curryArgs, arguments, 0))
: fn.apply(self, curryArgs);
}
: function() {
return arguments.length
? fn.apply(self, arguments)
: fn.call(self);
};
} else {
// In IE, native methods are not functions so they cannot be bound (note: they don't need to be).
return fn;
}
}
function toJsonReplacer(key, value) {
var val = value;
if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
} else if (value && window.document === value) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
/**
* @ngdoc function
* @name angular.toJson
* @module ng
* @kind function
*
* @description
* Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
* stripped since AngularJS uses this notation internally.
*
* @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON.
* @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
* If set to an integer, the JSON output will contain that many spaces per indentation.
* @returns {string|undefined} JSON-ified string representing `obj`.
* @knownIssue
*
* The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date`
* object with an invalid date value. The only reliable way to prevent this is to monkeypatch the
* `Date.prototype.toJSON` method as follows:
*
* ```
* var _DatetoJSON = Date.prototype.toJSON;
* Date.prototype.toJSON = function() {
* try {
* return _DatetoJSON.call(this);
* } catch(e) {
* if (e instanceof RangeError) {
* return null;
* }
* throw e;
* }
* };
* ```
*
* See https://github.com/angular/angular.js/pull/14221 for more information.
*/
function toJson(obj, pretty) {
if (isUndefined(obj)) return undefined;
if (!isNumber(pretty)) {
pretty = pretty ? 2 : null;
}
return JSON.stringify(obj, toJsonReplacer, pretty);
}
/**
* @ngdoc function
* @name angular.fromJson
* @module ng
* @kind function
*
* @description
* Deserializes a JSON string.
*
* @param {string} json JSON string to deserialize.
* @returns {Object|Array|string|number} Deserialized JSON string.
*/
function fromJson(json) {
return isString(json)
? JSON.parse(json)
: json;
}
var ALL_COLONS = /:/g;
function timezoneToOffset(timezone, fallback) {
// Support: IE 9-11 only, Edge 13-15+
// IE/Edge do not "understand" colon (`:`) in timezone
timezone = timezone.replace(ALL_COLONS, '');
var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
}
function addDateMinutes(date, minutes) {
date = new Date(date.getTime());
date.setMinutes(date.getMinutes() + minutes);
return date;
}
function convertTimezoneToLocal(date, timezone, reverse) {
reverse = reverse ? -1 : 1;
var dateTimezoneOffset = date.getTimezoneOffset();
var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
}
/**
* @returns {string} Returns the string representation of the element.
*/
function startingTag(element) {
element = jqLite(element).clone().empty();
var elemHtml = jqLite('').append(element).html();
try {
return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
elemHtml.
match(/^(<[^>]+>)/)[1].
replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
} catch (e) {
return lowercase(elemHtml);
}
}
/////////////////////////////////////////////////
/**
* Tries to decode the URI component without throwing an exception.
*
* @private
* @param str value potential URI component to check.
* @returns {boolean} True if `value` can be decoded
* with the decodeURIComponent function.
*/
function tryDecodeURIComponent(value) {
try {
return decodeURIComponent(value);
} catch (e) {
// Ignore any invalid uri component.
}
}
/**
* Parses an escaped url query string into key-value pairs.
* @returns {Object.}
*/
function parseKeyValue(/**string*/keyValue) {
var obj = {};
forEach((keyValue || '').split('&'), function(keyValue) {
var splitPoint, key, val;
if (keyValue) {
key = keyValue = keyValue.replace(/\+/g,'%20');
splitPoint = keyValue.indexOf('=');
if (splitPoint !== -1) {
key = keyValue.substring(0, splitPoint);
val = keyValue.substring(splitPoint + 1);
}
key = tryDecodeURIComponent(key);
if (isDefined(key)) {
val = isDefined(val) ? tryDecodeURIComponent(val) : true;
if (!hasOwnProperty.call(obj, key)) {
obj[key] = val;
} else if (isArray(obj[key])) {
obj[key].push(val);
} else {
obj[key] = [obj[key],val];
}
}
}
});
return obj;
}
function toKeyValue(obj) {
var parts = [];
forEach(obj, function(value, key) {
if (isArray(value)) {
forEach(value, function(arrayValue) {
parts.push(encodeUriQuery(key, true) +
(arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
});
} else {
parts.push(encodeUriQuery(key, true) +
(value === true ? '' : '=' + encodeUriQuery(value, true)));
}
});
return parts.length ? parts.join('&') : '';
}
/**
* We need our custom method because encodeURIComponent is too aggressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%3B/gi, ';').
replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}
var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
function getNgAttribute(element, ngAttr) {
var attr, i, ii = ngAttrPrefixes.length;
for (i = 0; i < ii; ++i) {
attr = ngAttrPrefixes[i] + ngAttr;
if (isString(attr = element.getAttribute(attr))) {
return attr;
}
}
return null;
}
function allowAutoBootstrap(document) {
var script = document.currentScript;
if (!script) {
// Support: IE 9-11 only
// IE does not have `document.currentScript`
return true;
}
// If the `currentScript` property has been clobbered just return false, since this indicates a probable attack
if (!(script instanceof window.HTMLScriptElement || script instanceof window.SVGScriptElement)) {
return false;
}
var attributes = script.attributes;
var srcs = [attributes.getNamedItem('src'), attributes.getNamedItem('href'), attributes.getNamedItem('xlink:href')];
return srcs.every(function(src) {
if (!src) {
return true;
}
if (!src.value) {
return false;
}
var link = document.createElement('a');
link.href = src.value;
if (document.location.origin === link.origin) {
// Same-origin resources are always allowed, even for non-whitelisted schemes.
return true;
}
// Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web.
// This is to prevent angular.js bundled with browser extensions from being used to bypass the
// content security policy in web pages and other browser extensions.
switch (link.protocol) {
case 'http:':
case 'https:':
case 'ftp:':
case 'blob:':
case 'file:':
case 'data:':
return true;
default:
return false;
}
});
}
// Cached as it has to run during loading so that document.currentScript is available.
var isAutoBootstrapAllowed = allowAutoBootstrap(window.document);
/**
* @ngdoc directive
* @name ngApp
* @module ng
*
* @element ANY
* @param {angular.Module} ngApp an optional application
* {@link angular.module module} name to load.
* @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
* created in "strict-di" mode. This means that the application will fail to invoke functions which
* do not use explicit function annotation (and are thus unsuitable for minification), as described
* in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
* tracking down the root of these bugs.
*
* @description
*
* Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
* designates the **root element** of the application and is typically placed near the root element
* of the page - e.g. on the `` or `` tags.
*
* There are a few things to keep in mind when using `ngApp`:
* - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
* found in the document will be used to define the root element to auto-bootstrap as an
* application. To run multiple applications in an HTML document you must manually bootstrap them using
* {@link angular.bootstrap} instead.
* - AngularJS applications cannot be nested within each other.
* - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
* This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
* {@link ngRoute.ngView `ngView`}.
* Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
* causing animations to stop working and making the injector inaccessible from outside the app.
*
* You can specify an **AngularJS module** to be used as the root module for the application. This
* module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
* should contain the application code needed or have dependencies on other modules that will
* contain the code. See {@link angular.module} for more information.
*
* In the example below if the `ngApp` directive were not placed on the `html` element then the
* document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
* would not be resolved to `3`.
*
* @example
*
* ### Simple Usage
*
* `ngApp` is the easiest, and most common way to bootstrap an application.
*
I can add: {{a}} + {{b}} = {{ a+b }}
angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
$scope.a = 1;
$scope.b = 2;
});
*
* @example
*
* ### With `ngStrictDi`
*
* Using `ngStrictDi`, you would see something like this:
*
I can add: {{a}} + {{b}} = {{ a+b }}
This renders because the controller does not fail to
instantiate, by using explicit annotation style (see
script.js for details)
Name:
Hello, {{name}}!
This renders because the controller does not fail to
instantiate, by using explicit annotation style
(see script.js for details)
I can add: {{a}} + {{b}} = {{ a+b }}
The controller could not be instantiated, due to relying
on automatic function annotations (which are disabled in
strict mode). As such, the content of this section is not
interpolated, and there should be an error in your web console.
angular.module('ngAppStrictDemo', [])
// BadController will fail to instantiate, due to relying on automatic function annotation,
// rather than an explicit annotation
.controller('BadController', function($scope) {
$scope.a = 1;
$scope.b = 2;
})
// Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
// due to using explicit annotations using the array style and $inject property, respectively.
.controller('GoodController1', ['$scope', function($scope) {
$scope.a = 1;
$scope.b = 2;
}])
.controller('GoodController2', GoodController2);
function GoodController2($scope) {
$scope.name = 'World';
}
GoodController2.$inject = ['$scope'];
div[ng-controller] {
margin-bottom: 1em;
-webkit-border-radius: 4px;
border-radius: 4px;
border: 1px solid;
padding: .5em;
}
div[ng-controller^=Good] {
border-color: #d6e9c6;
background-color: #dff0d8;
color: #3c763d;
}
div[ng-controller^=Bad] {
border-color: #ebccd1;
background-color: #f2dede;
color: #a94442;
margin-bottom: 0;
}
*/
function angularInit(element, bootstrap) {
var appElement,
module,
config = {};
// The element `element` has priority over any other element.
forEach(ngAttrPrefixes, function(prefix) {
var name = prefix + 'app';
if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
appElement = element;
module = element.getAttribute(name);
}
});
forEach(ngAttrPrefixes, function(prefix) {
var name = prefix + 'app';
var candidate;
if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
appElement = candidate;
module = candidate.getAttribute(name);
}
});
if (appElement) {
if (!isAutoBootstrapAllowed) {
window.console.error('AngularJS: disabling automatic bootstrap.
*
*
*
* ```
*
* @param {DOMElement} element DOM element which is the root of AngularJS application.
* @param {Array=} modules an array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a `config` block.
* See: {@link angular.module modules}
* @param {Object=} config an object for defining configuration options for the application. The
* following keys are supported:
*
* * `strictDi` - disable automatic function annotation for the application. This is meant to
* assist in finding bugs which break minified code. Defaults to `false`.
*
* @returns {auto.$injector} Returns the newly created injector for this app.
*/
function bootstrap(element, modules, config) {
if (!isObject(config)) config = {};
var defaultConfig = {
strictDi: false
};
config = extend(defaultConfig, config);
var doBootstrap = function() {
element = jqLite(element);
if (element.injector()) {
var tag = (element[0] === window.document) ? 'document' : startingTag(element);
// Encode angle brackets to prevent input from being sanitized to empty string #8683.
throw ngMinErr(
'btstrpd',
'App already bootstrapped with this element \'{0}\'',
tag.replace(/,'<').replace(/>/,'>'));
}
modules = modules || [];
modules.unshift(['$provide', function($provide) {
$provide.value('$rootElement', element);
}]);
if (config.debugInfoEnabled) {
// Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
modules.push(['$compileProvider', function($compileProvider) {
$compileProvider.debugInfoEnabled(true);
}]);
}
modules.unshift('ng');
var injector = createInjector(modules, config.strictDi);
injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
function bootstrapApply(scope, element, compile, injector) {
scope.$apply(function() {
element.data('$injector', injector);
compile(element)(scope);
});
}]
);
return injector;
};
var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
config.debugInfoEnabled = true;
window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
}
if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
return doBootstrap();
}
window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
angular.resumeBootstrap = function(extraModules) {
forEach(extraModules, function(module) {
modules.push(module);
});
return doBootstrap();
};
if (isFunction(angular.resumeDeferredBootstrap)) {
angular.resumeDeferredBootstrap();
}
}
/**
* @ngdoc function
* @name angular.reloadWithDebugInfo
* @module ng
* @description
* Use this function to reload the current application with debug information turned on.
* This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
*
* See {@link ng.$compileProvider#debugInfoEnabled} for more.
*/
function reloadWithDebugInfo() {
window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
window.location.reload();
}
/**
* @name angular.getTestability
* @module ng
* @description
* Get the testability service for the instance of AngularJS on the given
* element.
* @param {DOMElement} element DOM element which is the root of AngularJS application.
*/
function getTestability(rootElement) {
var injector = angular.element(rootElement).injector();
if (!injector) {
throw ngMinErr('test',
'no injector found for element argument to getTestability');
}
return injector.get('$$testability');
}
var SNAKE_CASE_REGEXP = /[A-Z]/g;
function snake_case(name, separator) {
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
var bindJQueryFired = false;
function bindJQuery() {
var originalCleanData;
if (bindJQueryFired) {
return;
}
// bind to jQuery if present;
var jqName = jq();
jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
!jqName ? undefined : // use jqLite
window[jqName]; // use jQuery specified by `ngJq`
// Use jQuery if it exists with proper functionality, otherwise default to us.
// AngularJS 1.2+ requires jQuery 1.7+ for on()/off() support.
// AngularJS 1.3+ technically requires at least jQuery 2.1+ but it may work with older
// versions. It will not work for sure with jQuery <1.7, though.
if (jQuery && jQuery.fn.on) {
jqLite = jQuery;
extend(jQuery.fn, {
scope: JQLitePrototype.scope,
isolateScope: JQLitePrototype.isolateScope,
controller: /** @type {?} */ (JQLitePrototype).controller,
injector: JQLitePrototype.injector,
inheritedData: JQLitePrototype.inheritedData
});
} else {
jqLite = JQLite;
}
// All nodes removed from the DOM via various jqLite/jQuery APIs like .remove()
// are passed through jqLite/jQuery.cleanData. Monkey-patch this method to fire
// the $destroy event on all removed nodes.
originalCleanData = jqLite.cleanData;
jqLite.cleanData = function(elems) {
var events;
for (var i = 0, elem; (elem = elems[i]) != null; i++) {
events = (jqLite._data(elem) || {}).events;
if (events && events.$destroy) {
jqLite(elem).triggerHandler('$destroy');
}
}
originalCleanData(elems);
};
angular.element = jqLite;
// Prevent double-proxying.
bindJQueryFired = true;
}
/**
* throw error if the argument is falsy.
*/
function assertArg(arg, name, reason) {
if (!arg) {
throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required'));
}
return arg;
}
function assertArgFn(arg, name, acceptArrayAnnotation) {
if (acceptArrayAnnotation && isArray(arg)) {
arg = arg[arg.length - 1];
}
assertArg(isFunction(arg), name, 'not a function, got ' +
(arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
return arg;
}
/**
* throw error if the name given is hasOwnProperty
* @param {String} name the name to test
* @param {String} context the context in which the name is used, such as module or directive
*/
function assertNotHasOwnProperty(name, context) {
if (name === 'hasOwnProperty') {
throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
}
}
/**
* Return the value accessible from the object by path. Any undefined traversals are ignored
* @param {Object} obj starting object
* @param {String} path path to traverse
* @param {boolean} [bindFnToScope=true]
* @returns {Object} value as accessible by path
*/
//TODO(misko): this function needs to be removed
function getter(obj, path, bindFnToScope) {
if (!path) return obj;
var keys = path.split('.');
var key;
var lastInstance = obj;
var len = keys.length;
for (var i = 0; i < len; i++) {
key = keys[i];
if (obj) {
obj = (lastInstance = obj)[key];
}
}
if (!bindFnToScope && isFunction(obj)) {
return bind(lastInstance, obj);
}
return obj;
}
/**
* Return the DOM siblings between the first and last node in the given array.
* @param {Array} array like object
* @returns {Array} the inputted object or a jqLite collection containing the nodes
*/
function getBlockNodes(nodes) {
// TODO(perf): update `nodes` instead of creating a new object?
var node = nodes[0];
var endNode = nodes[nodes.length - 1];
var blockNodes;
for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
if (blockNodes || nodes[i] !== node) {
if (!blockNodes) {
blockNodes = jqLite(slice.call(nodes, 0, i));
}
blockNodes.push(node);
}
}
return blockNodes || nodes;
}
/**
* Creates a new object without a prototype. This object is useful for lookup without having to
* guard against prototypically inherited properties via hasOwnProperty.
*
* Related micro-benchmarks:
* - http://jsperf.com/object-create2
* - http://jsperf.com/proto-map-lookup/2
* - http://jsperf.com/for-in-vs-object-keys2
*
* @returns {Object}
*/
function createMap() {
return Object.create(null);
}
function stringify(value) {
if (value == null) { // null || undefined
return '';
}
switch (typeof value) {
case 'string':
break;
case 'number':
value = '' + value;
break;
default:
if (hasCustomToString(value) && !isArray(value) && !isDate(value)) {
value = value.toString();
} else {
value = toJson(value);
}
}
return value;
}
var NODE_TYPE_ELEMENT = 1;
var NODE_TYPE_ATTRIBUTE = 2;
var NODE_TYPE_TEXT = 3;
var NODE_TYPE_COMMENT = 8;
var NODE_TYPE_DOCUMENT = 9;
var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
/**
* @ngdoc type
* @name angular.Module
* @module ng
* @description
*
* Interface for configuring AngularJS {@link angular.module modules}.
*/
function setupModuleLoader(window) {
var $injectorMinErr = minErr('$injector');
var ngMinErr = minErr('ng');
function ensure(obj, name, factory) {
return obj[name] || (obj[name] = factory());
}
var angular = ensure(window, 'angular', Object);
// We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
angular.$$minErr = angular.$$minErr || minErr;
return ensure(angular, 'module', function() {
/** @type {Object.} */
var modules = {};
/**
* @ngdoc function
* @name angular.module
* @module ng
* @description
*
* The `angular.module` is a global place for creating, registering and retrieving AngularJS
* modules.
* All modules (AngularJS core or 3rd party) that should be available to an application must be
* registered using this mechanism.
*
* Passing one argument retrieves an existing {@link angular.Module},
* whereas passing more than one argument creates a new {@link angular.Module}
*
*
* # Module
*
* A module is a collection of services, directives, controllers, filters, and configuration information.
* `angular.module` is used to configure the {@link auto.$injector $injector}.
*
* ```js
* // Create a new module
* var myModule = angular.module('myModule', []);
*
* // register a new service
* myModule.value('appName', 'MyCoolApp');
*
* // configure existing services inside initialization blocks.
* myModule.config(['$locationProvider', function($locationProvider) {
* // Configure existing providers
* $locationProvider.hashPrefix('!');
* }]);
* ```
*
* Then you can create an injector and load your modules like this:
*
* ```js
* var injector = angular.injector(['ng', 'myModule'])
* ```
*
* However it's more likely that you'll just use
* {@link ng.directive:ngApp ngApp} or
* {@link angular.bootstrap} to simplify this process for you.
*
* @param {!string} name The name of the module to create or retrieve.
* @param {!Array.=} requires If specified then new module is being created. If
* unspecified then the module is being retrieved for further configuration.
* @param {Function=} configFn Optional configuration function for the module. Same as
* {@link angular.Module#config Module#config()}.
* @returns {angular.Module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
var info = {};
var assertNotHasOwnProperty = function(name, context) {
if (name === 'hasOwnProperty') {
throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
}
};
assertNotHasOwnProperty(name, 'module');
if (requires && modules.hasOwnProperty(name)) {
modules[name] = null;
}
return ensure(modules, name, function() {
if (!requires) {
throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' +
'the module name or forgot to load it. If registering a module ensure that you ' +
'specify the dependencies as the second argument.', name);
}
/** @type {!Array.>} */
var invokeQueue = [];
/** @type {!Array.} */
var configBlocks = [];
/** @type {!Array.} */
var runBlocks = [];
var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
/** @type {angular.Module} */
var moduleInstance = {
// Private state
_invokeQueue: invokeQueue,
_configBlocks: configBlocks,
_runBlocks: runBlocks,
/**
* @ngdoc method
* @name angular.Module#info
* @module ng
*
* @param {Object=} info Information about the module
* @returns {Object|Module} The current info object for this module if called as a getter,
* or `this` if called as a setter.
*
* @description
* Read and write custom information about this module.
* For example you could put the version of the module in here.
*
* ```js
* angular.module('myModule', []).info({ version: '1.0.0' });
* ```
*
* The version could then be read back out by accessing the module elsewhere:
*
* ```
* var version = angular.module('myModule').info().version;
* ```
*
* You can also retrieve this information during runtime via the
* {@link $injector#modules `$injector.modules`} property:
*
* ```js
* var version = $injector.modules['myModule'].info().version;
* ```
*/
info: function(value) {
if (isDefined(value)) {
if (!isObject(value)) throw ngMinErr('aobj', 'Argument \'{0}\' must be an object', 'value');
info = value;
return this;
}
return info;
},
/**
* @ngdoc property
* @name angular.Module#requires
* @module ng
*
* @description
* Holds the list of modules which the injector will load before the current module is
* loaded.
*/
requires: requires,
/**
* @ngdoc property
* @name angular.Module#name
* @module ng
*
* @description
* Name of the module.
*/
name: name,
/**
* @ngdoc method
* @name angular.Module#provider
* @module ng
* @param {string} name service name
* @param {Function} providerType Construction function for creating new instance of the
* service.
* @description
* See {@link auto.$provide#provider $provide.provider()}.
*/
provider: invokeLaterAndSetModuleName('$provide', 'provider'),
/**
* @ngdoc method
* @name angular.Module#factory
* @module ng
* @param {string} name service name
* @param {Function} providerFunction Function for creating new instance of the service.
* @description
* See {@link auto.$provide#factory $provide.factory()}.
*/
factory: invokeLaterAndSetModuleName('$provide', 'factory'),
/**
* @ngdoc method
* @name angular.Module#service
* @module ng
* @param {string} name service name
* @param {Function} constructor A constructor function that will be instantiated.
* @description
* See {@link auto.$provide#service $provide.service()}.
*/
service: invokeLaterAndSetModuleName('$provide', 'service'),
/**
* @ngdoc method
* @name angular.Module#value
* @module ng
* @param {string} name service name
* @param {*} object Service instance object.
* @description
* See {@link auto.$provide#value $provide.value()}.
*/
value: invokeLater('$provide', 'value'),
/**
* @ngdoc method
* @name angular.Module#constant
* @module ng
* @param {string} name constant name
* @param {*} object Constant value.
* @description
* Because the constants are fixed, they get applied before other provide methods.
* See {@link auto.$provide#constant $provide.constant()}.
*/
constant: invokeLater('$provide', 'constant', 'unshift'),
/**
* @ngdoc method
* @name angular.Module#decorator
* @module ng
* @param {string} name The name of the service to decorate.
* @param {Function} decorFn This function will be invoked when the service needs to be
* instantiated and should return the decorated service instance.
* @description
* See {@link auto.$provide#decorator $provide.decorator()}.
*/
decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks),
/**
* @ngdoc method
* @name angular.Module#animation
* @module ng
* @param {string} name animation name
* @param {Function} animationFactory Factory function for creating new instance of an
* animation.
* @description
*
* **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
*
*
* Defines an animation hook that can be later used with
* {@link $animate $animate} service and directives that use this service.
*
* ```js
* module.animation('.animation-name', function($inject1, $inject2) {
* return {
* eventName : function(element, done) {
* //code to run the animation
* //once complete, then run done()
* return function cancellationFunction(element) {
* //code to cancel the animation
* }
* }
* }
* })
* ```
*
* See {@link ng.$animateProvider#register $animateProvider.register()} and
* {@link ngAnimate ngAnimate module} for more information.
*/
animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#filter
* @module ng
* @param {string} name Filter name - this must be a valid AngularJS expression identifier
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*
*
* **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`.
* Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
* your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
* (`myapp_subsection_filterx`).
*
*/
filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @module ng
* @param {string|Object} name Controller name, or an object map of controllers where the
* keys are the names and the values are the constructors.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @module ng
* @param {string|Object} name Directive name, or an object map of directives where the
* keys are the names and the values are the factories.
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider#directive $compileProvider.directive()}.
*/
directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#component
* @module ng
* @param {string|Object} name Name of the component in camelCase (i.e. `myComp` which will match ``),
* or an object map of components where the keys are the names and the values are the component definition objects.
* @param {Object} options Component definition object (a simplified
* {@link ng.$compile#directive-definition-object directive definition object})
*
* @description
* See {@link ng.$compileProvider#component $compileProvider.component()}.
*/
component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
/**
* @ngdoc method
* @name angular.Module#config
* @module ng
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to configure services by injecting their
* {@link angular.Module#provider `providers`}, e.g. for adding routes to the
* {@link ngRoute.$routeProvider $routeProvider}.
*
* Note that you can only inject {@link angular.Module#provider `providers`} and
* {@link angular.Module#constant `constants`} into this function.
*
* For more about how to configure services, see
* {@link providers#provider-recipe Provider Recipe}.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @module ng
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which should be performed when the injector is done
* loading all modules.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod, queue) {
if (!queue) queue = invokeQueue;
return function() {
queue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
};
}
/**
* @param {string} provider
* @param {string} method
* @returns {angular.Module}
*/
function invokeLaterAndSetModuleName(provider, method, queue) {
if (!queue) queue = invokeQueue;
return function(recipeName, factoryFunction) {
if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
queue.push([provider, method, arguments]);
return moduleInstance;
};
}
});
};
});
}
/* global shallowCopy: true */
/**
* Creates a shallow copy of an object, an array or a primitive.
*
* Assumes that there are no proto properties for objects.
*/
function shallowCopy(src, dst) {
if (isArray(src)) {
dst = dst || [];
for (var i = 0, ii = src.length; i < ii; i++) {
dst[i] = src[i];
}
} else if (isObject(src)) {
dst = dst || {};
for (var key in src) {
if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
dst[key] = src[key];
}
}
}
return dst || src;
}
/* exported toDebugString */
function serializeObject(obj, maxDepth) {
var seen = [];
// There is no direct way to stringify object until reaching a specific depth
// and a very deep object can cause a performance issue, so we copy the object
// based on this specific depth and then stringify it.
if (isValidObjectMaxDepth(maxDepth)) {
// This file is also included in `angular-loader`, so `copy()` might not always be available in
// the closure. Therefore, it is lazily retrieved as `angular.copy()` when needed.
obj = angular.copy(obj, null, maxDepth);
}
return JSON.stringify(obj, function(key, val) {
val = toJsonReplacer(key, val);
if (isObject(val)) {
if (seen.indexOf(val) >= 0) return '...';
seen.push(val);
}
return val;
});
}
function toDebugString(obj, maxDepth) {
if (typeof obj === 'function') {
return obj.toString().replace(/ \{[\s\S]*$/, '');
} else if (isUndefined(obj)) {
return 'undefined';
} else if (typeof obj !== 'string') {
return serializeObject(obj, maxDepth);
}
return obj;
}
/* global angularModule: true,
version: true,
$CompileProvider,
htmlAnchorDirective,
inputDirective,
hiddenInputBrowserCacheDirective,
formDirective,
scriptDirective,
selectDirective,
optionDirective,
ngBindDirective,
ngBindHtmlDirective,
ngBindTemplateDirective,
ngClassDirective,
ngClassEvenDirective,
ngClassOddDirective,
ngCloakDirective,
ngControllerDirective,
ngFormDirective,
ngHideDirective,
ngIfDirective,
ngIncludeDirective,
ngIncludeFillContentDirective,
ngInitDirective,
ngNonBindableDirective,
ngPluralizeDirective,
ngRefDirective,
ngRepeatDirective,
ngShowDirective,
ngStyleDirective,
ngSwitchDirective,
ngSwitchWhenDirective,
ngSwitchDefaultDirective,
ngOptionsDirective,
ngTranscludeDirective,
ngModelDirective,
ngListDirective,
ngChangeDirective,
patternDirective,
patternDirective,
requiredDirective,
requiredDirective,
minlengthDirective,
minlengthDirective,
maxlengthDirective,
maxlengthDirective,
ngValueDirective,
ngModelOptionsDirective,
ngAttributeAliasDirectives,
ngEventDirectives,
$AnchorScrollProvider,
$AnimateProvider,
$CoreAnimateCssProvider,
$$CoreAnimateJsProvider,
$$CoreAnimateQueueProvider,
$$AnimateRunnerFactoryProvider,
$$AnimateAsyncRunFactoryProvider,
$BrowserProvider,
$CacheFactoryProvider,
$ControllerProvider,
$DateProvider,
$DocumentProvider,
$$IsDocumentHiddenProvider,
$ExceptionHandlerProvider,
$FilterProvider,
$$ForceReflowProvider,
$InterpolateProvider,
$$IntervalFactoryProvider,
$IntervalProvider,
$HttpProvider,
$HttpParamSerializerProvider,
$HttpParamSerializerJQLikeProvider,
$HttpBackendProvider,
$xhrFactoryProvider,
$jsonpCallbacksProvider,
$LocationProvider,
$LogProvider,
$$MapProvider,
$ParseProvider,
$RootScopeProvider,
$QProvider,
$$QProvider,
$$SanitizeUriProvider,
$SceProvider,
$SceDelegateProvider,
$SnifferProvider,
$$TaskTrackerFactoryProvider,
$TemplateCacheProvider,
$TemplateRequestProvider,
$$TestabilityProvider,
$TimeoutProvider,
$$RAFProvider,
$WindowProvider,
$$jqLiteProvider,
$$CookieReaderProvider
*/
/**
* @ngdoc object
* @name angular.version
* @module ng
* @description
* An object that contains information about the current AngularJS version.
*
* This object has the following properties:
*
* - `full` – `{string}` – Full version string, such as "0.9.18".
* - `major` – `{number}` – Major version number, such as "0".
* - `minor` – `{number}` – Minor version number, such as "9".
* - `dot` – `{number}` – Dot version number, such as "18".
* - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
*/
var version = {
// These placeholder strings will be replaced by grunt's `build` task.
// They need to be double- or single-quoted.
full: '1.7.9',
major: 1,
minor: 7,
dot: 9,
codeName: 'pollution-eradication'
};
function publishExternalAPI(angular) {
extend(angular, {
'errorHandlingConfig': errorHandlingConfig,
'bootstrap': bootstrap,
'copy': copy,
'extend': extend,
'merge': merge,
'equals': equals,
'element': jqLite,
'forEach': forEach,
'injector': createInjector,
'noop': noop,
'bind': bind,
'toJson': toJson,
'fromJson': fromJson,
'identity': identity,
'isUndefined': isUndefined,
'isDefined': isDefined,
'isString': isString,
'isFunction': isFunction,
'isObject': isObject,
'isNumber': isNumber,
'isElement': isElement,
'isArray': isArray,
'version': version,
'isDate': isDate,
'callbacks': {$$counter: 0},
'getTestability': getTestability,
'reloadWithDebugInfo': reloadWithDebugInfo,
'$$minErr': minErr,
'$$csp': csp,
'$$encodeUriSegment': encodeUriSegment,
'$$encodeUriQuery': encodeUriQuery,
'$$lowercase': lowercase,
'$$stringify': stringify,
'$$uppercase': uppercase
});
angularModule = setupModuleLoader(window);
angularModule('ng', ['ngLocale'], ['$provide',
function ngModule($provide) {
// $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
$provide.provider({
$$sanitizeUri: $$SanitizeUriProvider
});
$provide.provider('$compile', $CompileProvider).
directive({
a: htmlAnchorDirective,
input: inputDirective,
textarea: inputDirective,
form: formDirective,
script: scriptDirective,
select: selectDirective,
option: optionDirective,
ngBind: ngBindDirective,
ngBindHtml: ngBindHtmlDirective,
ngBindTemplate: ngBindTemplateDirective,
ngClass: ngClassDirective,
ngClassEven: ngClassEvenDirective,
ngClassOdd: ngClassOddDirective,
ngCloak: ngCloakDirective,
ngController: ngControllerDirective,
ngForm: ngFormDirective,
ngHide: ngHideDirective,
ngIf: ngIfDirective,
ngInclude: ngIncludeDirective,
ngInit: ngInitDirective,
ngNonBindable: ngNonBindableDirective,
ngPluralize: ngPluralizeDirective,
ngRef: ngRefDirective,
ngRepeat: ngRepeatDirective,
ngShow: ngShowDirective,
ngStyle: ngStyleDirective,
ngSwitch: ngSwitchDirective,
ngSwitchWhen: ngSwitchWhenDirective,
ngSwitchDefault: ngSwitchDefaultDirective,
ngOptions: ngOptionsDirective,
ngTransclude: ngTranscludeDirective,
ngModel: ngModelDirective,
ngList: ngListDirective,
ngChange: ngChangeDirective,
pattern: patternDirective,
ngPattern: patternDirective,
required: requiredDirective,
ngRequired: requiredDirective,
minlength: minlengthDirective,
ngMinlength: minlengthDirective,
maxlength: maxlengthDirective,
ngMaxlength: maxlengthDirective,
ngValue: ngValueDirective,
ngModelOptions: ngModelOptionsDirective
}).
directive({
ngInclude: ngIncludeFillContentDirective,
input: hiddenInputBrowserCacheDirective
}).
directive(ngAttributeAliasDirectives).
directive(ngEventDirectives);
$provide.provider({
$anchorScroll: $AnchorScrollProvider,
$animate: $AnimateProvider,
$animateCss: $CoreAnimateCssProvider,
$$animateJs: $$CoreAnimateJsProvider,
$$animateQueue: $$CoreAnimateQueueProvider,
$$AnimateRunner: $$AnimateRunnerFactoryProvider,
$$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
$browser: $BrowserProvider,
$cacheFactory: $CacheFactoryProvider,
$controller: $ControllerProvider,
$document: $DocumentProvider,
$$isDocumentHidden: $$IsDocumentHiddenProvider,
$exceptionHandler: $ExceptionHandlerProvider,
$filter: $FilterProvider,
$$forceReflow: $$ForceReflowProvider,
$interpolate: $InterpolateProvider,
$interval: $IntervalProvider,
$$intervalFactory: $$IntervalFactoryProvider,
$http: $HttpProvider,
$httpParamSerializer: $HttpParamSerializerProvider,
$httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
$httpBackend: $HttpBackendProvider,
$xhrFactory: $xhrFactoryProvider,
$jsonpCallbacks: $jsonpCallbacksProvider,
$location: $LocationProvider,
$log: $LogProvider,
$parse: $ParseProvider,
$rootScope: $RootScopeProvider,
$q: $QProvider,
$$q: $$QProvider,
$sce: $SceProvider,
$sceDelegate: $SceDelegateProvider,
$sniffer: $SnifferProvider,
$$taskTrackerFactory: $$TaskTrackerFactoryProvider,
$templateCache: $TemplateCacheProvider,
$templateRequest: $TemplateRequestProvider,
$$testability: $$TestabilityProvider,
$timeout: $TimeoutProvider,
$window: $WindowProvider,
$$rAF: $$RAFProvider,
$$jqLite: $$jqLiteProvider,
$$Map: $$MapProvider,
$$cookieReader: $$CookieReaderProvider
});
}
])
.info({ angularVersion: '1.7.9' });
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* global
JQLitePrototype: true,
BOOLEAN_ATTR: true,
ALIASED_ATTR: true
*/
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @module ng
* @kind function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
*
* If jQuery is available, `angular.element` is an alias for the
* [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
* delegates to AngularJS's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
*
* jqLite is a tiny, API-compatible subset of jQuery that allows
* AngularJS to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
* commonly needed functionality with the goal of having a very small footprint.
*
* To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
* {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
* specific version of jQuery if multiple versions exist on the page.
*
*
**Note:** All element references in AngularJS are always wrapped with jQuery or
* jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.
*
*
**Note:** Keep in mind that this function will not find elements
* by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
* or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.
*
* ## AngularJS's jqLite
* jqLite provides only the following jQuery methods:
*
* - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument
* - [`after()`](http://api.jquery.com/after/)
* - [`append()`](http://api.jquery.com/append/) - Contrary to jQuery, this doesn't clone elements
* so will not work correctly when invoked on a jqLite object containing more than one DOM node
* - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
* - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData
* - [`children()`](http://api.jquery.com/children/) - Does not support selectors
* - [`clone()`](http://api.jquery.com/clone/)
* - [`contents()`](http://api.jquery.com/contents/)
* - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
* As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
* - [`data()`](http://api.jquery.com/data/)
* - [`detach()`](http://api.jquery.com/detach/)
* - [`empty()`](http://api.jquery.com/empty/)
* - [`eq()`](http://api.jquery.com/eq/)
* - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
* - [`hasClass()`](http://api.jquery.com/hasClass/)
* - [`html()`](http://api.jquery.com/html/)
* - [`next()`](http://api.jquery.com/next/) - Does not support selectors
* - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
* - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
* - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
* - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
* - [`prepend()`](http://api.jquery.com/prepend/)
* - [`prop()`](http://api.jquery.com/prop/)
* - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`)
* - [`remove()`](http://api.jquery.com/remove/)
* - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes
* - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument
* - [`removeData()`](http://api.jquery.com/removeData/)
* - [`replaceWith()`](http://api.jquery.com/replaceWith/)
* - [`text()`](http://api.jquery.com/text/)
* - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument
* - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers
* - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter
* - [`val()`](http://api.jquery.com/val/)
* - [`wrap()`](http://api.jquery.com/wrap/)
*
* ## jQuery/jqLite Extras
* AngularJS also provides the following additional methods and events to both jQuery and jqLite:
*
* ### Events
* - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
* on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
* element before it is removed.
*
* ### Methods
* - `controller(name)` - retrieves the controller of the current element or its parent. By default
* retrieves controller associated with the `ngController` directive. If `name` is provided as
* camelCase directive name, then the controller for this directive will be retrieved (e.g.
* `'ngModel'`).
* - `injector()` - retrieves the injector of the current element or its parent.
* - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
* element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
* be enabled.
* - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
* current element. This getter should be used only on elements that contain a directive which starts a new isolate
* scope. Calling `scope()` on this element always returns the original non-isolate scope.
* Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
* - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
* parent element is reached.
*
* @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See
* https://github.com/angular/angular.js/issues/14251 for more information.
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
* @returns {Object} jQuery object.
*/
JQLite.expando = 'ng339';
var jqCache = JQLite.cache = {},
jqId = 1;
/*
* !!! This is an undocumented "private" function !!!
*/
JQLite._data = function(node) {
//jQuery always returns an object on cache miss
return this.cache[node[this.expando]] || {};
};
function jqNextId() { return ++jqId; }
var DASH_LOWERCASE_REGEXP = /-([a-z])/g;
var MS_HACK_REGEXP = /^-ms-/;
var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' };
var jqLiteMinErr = minErr('jqLite');
/**
* Converts kebab-case to camelCase.
* There is also a special case for the ms prefix starting with a lowercase letter.
* @param name Name to normalize
*/
function cssKebabToCamel(name) {
return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-'));
}
function fnCamelCaseReplace(all, letter) {
return letter.toUpperCase();
}
/**
* Converts kebab-case to camelCase.
* @param name Name to normalize
*/
function kebabToCamel(name) {
return name
.replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace);
}
var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
var HTML_REGEXP = /<|?\w+;/;
var TAG_NAME_REGEXP = /<([\w:-]+)/;
var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
var wrapMap = {
'option': [1, ''],
'thead': [1, '
', '
'],
'col': [2, '
', '
'],
'tr': [2, '
', '
'],
'td': [3, '
', '
'],
'_default': [0, '', '']
};
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function jqLiteIsTextNode(html) {
return !HTML_REGEXP.test(html);
}
function jqLiteAcceptsData(node) {
// The window object can accept data but has no nodeType
// Otherwise we are only interested in elements (1) and documents (9)
var nodeType = node.nodeType;
return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
}
function jqLiteHasData(node) {
for (var key in jqCache[node.ng339]) {
return true;
}
return false;
}
function jqLiteBuildFragment(html, context) {
var tmp, tag, wrap,
fragment = context.createDocumentFragment(),
nodes = [], i;
if (jqLiteIsTextNode(html)) {
// Convert non-html into a text node
nodes.push(context.createTextNode(html));
} else {
// Convert html into DOM nodes
tmp = fragment.appendChild(context.createElement('div'));
tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase();
wrap = wrapMap[tag] || wrapMap._default;
tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1>$2>') + wrap[2];
// Descend through wrappers to the right content
i = wrap[0];
while (i--) {
tmp = tmp.lastChild;
}
nodes = concat(nodes, tmp.childNodes);
tmp = fragment.firstChild;
tmp.textContent = '';
}
// Remove wrapper from fragment
fragment.textContent = '';
fragment.innerHTML = ''; // Clear inner HTML
forEach(nodes, function(node) {
fragment.appendChild(node);
});
return fragment;
}
function jqLiteParseHTML(html, context) {
context = context || window.document;
var parsed;
if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
return [context.createElement(parsed[1])];
}
if ((parsed = jqLiteBuildFragment(html, context))) {
return parsed.childNodes;
}
return [];
}
function jqLiteWrapNode(node, wrapper) {
var parent = node.parentNode;
if (parent) {
parent.replaceChild(wrapper, node);
}
wrapper.appendChild(node);
}
// IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
var jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) {
// eslint-disable-next-line no-bitwise
return !!(this.compareDocumentPosition(arg) & 16);
};
/////////////////////////////////////////////
function JQLite(element) {
if (element instanceof JQLite) {
return element;
}
var argIsString;
if (isString(element)) {
element = trim(element);
argIsString = true;
}
if (!(this instanceof JQLite)) {
if (argIsString && element.charAt(0) !== '<') {
throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
}
return new JQLite(element);
}
if (argIsString) {
jqLiteAddNodes(this, jqLiteParseHTML(element));
} else if (isFunction(element)) {
jqLiteReady(element);
} else {
jqLiteAddNodes(this, element);
}
}
function jqLiteClone(element) {
return element.cloneNode(true);
}
function jqLiteDealoc(element, onlyDescendants) {
if (!onlyDescendants && jqLiteAcceptsData(element)) jqLite.cleanData([element]);
if (element.querySelectorAll) {
jqLite.cleanData(element.querySelectorAll('*'));
}
}
function isEmptyObject(obj) {
var name;
for (name in obj) {
return false;
}
return true;
}
function removeIfEmptyData(element) {
var expandoId = element.ng339;
var expandoStore = expandoId && jqCache[expandoId];
var events = expandoStore && expandoStore.events;
var data = expandoStore && expandoStore.data;
if ((!data || isEmptyObject(data)) && (!events || isEmptyObject(events))) {
delete jqCache[expandoId];
element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
}
}
function jqLiteOff(element, type, fn, unsupported) {
if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
var expandoStore = jqLiteExpandoStore(element);
var events = expandoStore && expandoStore.events;
var handle = expandoStore && expandoStore.handle;
if (!handle) return; //no listeners registered
if (!type) {
for (type in events) {
if (type !== '$destroy') {
element.removeEventListener(type, handle);
}
delete events[type];
}
} else {
var removeHandler = function(type) {
var listenerFns = events[type];
if (isDefined(fn)) {
arrayRemove(listenerFns || [], fn);
}
if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
element.removeEventListener(type, handle);
delete events[type];
}
};
forEach(type.split(' '), function(type) {
removeHandler(type);
if (MOUSE_EVENT_MAP[type]) {
removeHandler(MOUSE_EVENT_MAP[type]);
}
});
}
removeIfEmptyData(element);
}
function jqLiteRemoveData(element, name) {
var expandoId = element.ng339;
var expandoStore = expandoId && jqCache[expandoId];
if (expandoStore) {
if (name) {
delete expandoStore.data[name];
} else {
expandoStore.data = {};
}
removeIfEmptyData(element);
}
}
function jqLiteExpandoStore(element, createIfNecessary) {
var expandoId = element.ng339,
expandoStore = expandoId && jqCache[expandoId];
if (createIfNecessary && !expandoStore) {
element.ng339 = expandoId = jqNextId();
expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
}
return expandoStore;
}
function jqLiteData(element, key, value) {
if (jqLiteAcceptsData(element)) {
var prop;
var isSimpleSetter = isDefined(value);
var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
var massGetter = !key;
var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
var data = expandoStore && expandoStore.data;
if (isSimpleSetter) { // data('key', value)
data[kebabToCamel(key)] = value;
} else {
if (massGetter) { // data()
return data;
} else {
if (isSimpleGetter) { // data('key')
// don't force creation of expandoStore if it doesn't exist yet
return data && data[kebabToCamel(key)];
} else { // mass-setter: data({key1: val1, key2: val2})
for (prop in key) {
data[kebabToCamel(prop)] = key[prop];
}
}
}
}
}
}
function jqLiteHasClass(element, selector) {
if (!element.getAttribute) return false;
return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' ').
indexOf(' ' + selector + ' ') > -1);
}
function jqLiteRemoveClass(element, cssClasses) {
if (cssClasses && element.setAttribute) {
var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
.replace(/[\n\t]/g, ' ');
var newClasses = existingClasses;
forEach(cssClasses.split(' '), function(cssClass) {
cssClass = trim(cssClass);
newClasses = newClasses.replace(' ' + cssClass + ' ', ' ');
});
if (newClasses !== existingClasses) {
element.setAttribute('class', trim(newClasses));
}
}
}
function jqLiteAddClass(element, cssClasses) {
if (cssClasses && element.setAttribute) {
var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
.replace(/[\n\t]/g, ' ');
var newClasses = existingClasses;
forEach(cssClasses.split(' '), function(cssClass) {
cssClass = trim(cssClass);
if (newClasses.indexOf(' ' + cssClass + ' ') === -1) {
newClasses += cssClass + ' ';
}
});
if (newClasses !== existingClasses) {
element.setAttribute('class', trim(newClasses));
}
}
}
function jqLiteAddNodes(root, elements) {
// THIS CODE IS VERY HOT. Don't make changes without benchmarking.
if (elements) {
// if a Node (the most common case)
if (elements.nodeType) {
root[root.length++] = elements;
} else {
var length = elements.length;
// if an Array or NodeList and not a Window
if (typeof length === 'number' && elements.window !== elements) {
if (length) {
for (var i = 0; i < length; i++) {
root[root.length++] = elements[i];
}
}
} else {
root[root.length++] = elements;
}
}
}
}
function jqLiteController(element, name) {
return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
}
function jqLiteInheritedData(element, name, value) {
// if element is the document object work with the html element instead
// this makes $(document).scope() possible
if (element.nodeType === NODE_TYPE_DOCUMENT) {
element = element.documentElement;
}
var names = isArray(name) ? name : [name];
while (element) {
for (var i = 0, ii = names.length; i < ii; i++) {
if (isDefined(value = jqLite.data(element, names[i]))) return value;
}
// If dealing with a document fragment node with a host element, and no parent, use the host
// element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
// to lookup parent controllers.
element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
}
}
function jqLiteEmpty(element) {
jqLiteDealoc(element, true);
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
function jqLiteRemove(element, keepData) {
if (!keepData) jqLiteDealoc(element);
var parent = element.parentNode;
if (parent) parent.removeChild(element);
}
function jqLiteDocumentLoaded(action, win) {
win = win || window;
if (win.document.readyState === 'complete') {
// Force the action to be run async for consistent behavior
// from the action's point of view
// i.e. it will definitely not be in a $apply
win.setTimeout(action);
} else {
// No need to unbind this handler as load is only ever called once
jqLite(win).on('load', action);
}
}
function jqLiteReady(fn) {
function trigger() {
window.document.removeEventListener('DOMContentLoaded', trigger);
window.removeEventListener('load', trigger);
fn();
}
// check if document is already loaded
if (window.document.readyState === 'complete') {
window.setTimeout(fn);
} else {
// We can not use jqLite since we are not done loading and jQuery could be loaded later.
// Works for modern browsers and IE9
window.document.addEventListener('DOMContentLoaded', trigger);
// Fallback to window.onload for others
window.addEventListener('load', trigger);
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
ready: jqLiteReady,
toString: function() {
var value = [];
forEach(this, function(e) { value.push('' + e);});
return '[' + value.join(', ') + ']';
},
eq: function(index) {
return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
},
length: 0,
push: push,
sort: [].sort,
splice: [].splice
};
//////////////////////////////////////////
// Functions iterating getter/setters.
// these functions return self on setter and
// value on get.
//////////////////////////////////////////
var BOOLEAN_ATTR = {};
forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
BOOLEAN_ATTR[lowercase(value)] = value;
});
var BOOLEAN_ELEMENTS = {};
forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
BOOLEAN_ELEMENTS[value] = true;
});
var ALIASED_ATTR = {
'ngMinlength': 'minlength',
'ngMaxlength': 'maxlength',
'ngMin': 'min',
'ngMax': 'max',
'ngPattern': 'pattern',
'ngStep': 'step'
};
function getBooleanAttrName(element, name) {
// check dom last since we will most likely fail on name
var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
// booleanAttr is here twice to minimize DOM access
return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
}
function getAliasedAttrName(name) {
return ALIASED_ATTR[name];
}
forEach({
data: jqLiteData,
removeData: jqLiteRemoveData,
hasData: jqLiteHasData,
cleanData: function jqLiteCleanData(nodes) {
for (var i = 0, ii = nodes.length; i < ii; i++) {
jqLiteRemoveData(nodes[i]);
jqLiteOff(nodes[i]);
}
}
}, function(fn, name) {
JQLite[name] = fn;
});
forEach({
data: jqLiteData,
inheritedData: jqLiteInheritedData,
scope: function(element) {
// Can't use jqLiteData here directly so we stay compatible with jQuery!
return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
},
isolateScope: function(element) {
// Can't use jqLiteData here directly so we stay compatible with jQuery!
return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
},
controller: jqLiteController,
injector: function(element) {
return jqLiteInheritedData(element, '$injector');
},
removeAttr: function(element, name) {
element.removeAttribute(name);
},
hasClass: jqLiteHasClass,
css: function(element, name, value) {
name = cssKebabToCamel(name);
if (isDefined(value)) {
element.style[name] = value;
} else {
return element.style[name];
}
},
attr: function(element, name, value) {
var ret;
var nodeType = element.nodeType;
if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT ||
!element.getAttribute) {
return;
}
var lowercasedName = lowercase(name);
var isBooleanAttr = BOOLEAN_ATTR[lowercasedName];
if (isDefined(value)) {
// setter
if (value === null || (value === false && isBooleanAttr)) {
element.removeAttribute(name);
} else {
element.setAttribute(name, isBooleanAttr ? lowercasedName : value);
}
} else {
// getter
ret = element.getAttribute(name);
if (isBooleanAttr && ret !== null) {
ret = lowercasedName;
}
// Normalize non-existing attributes to undefined (as jQuery).
return ret === null ? undefined : ret;
}
},
prop: function(element, name, value) {
if (isDefined(value)) {
element[name] = value;
} else {
return element[name];
}
},
text: (function() {
getText.$dv = '';
return getText;
function getText(element, value) {
if (isUndefined(value)) {
var nodeType = element.nodeType;
return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
}
element.textContent = value;
}
})(),
val: function(element, value) {
if (isUndefined(value)) {
if (element.multiple && nodeName_(element) === 'select') {
var result = [];
forEach(element.options, function(option) {
if (option.selected) {
result.push(option.value || option.text);
}
});
return result;
}
return element.value;
}
element.value = value;
},
html: function(element, value) {
if (isUndefined(value)) {
return element.innerHTML;
}
jqLiteDealoc(element, true);
element.innerHTML = value;
},
empty: jqLiteEmpty
}, function(fn, name) {
/**
* Properties: writes return selection, reads return first value
*/
JQLite.prototype[name] = function(arg1, arg2) {
var i, key;
var nodeCount = this.length;
// jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
// in a way that survives minification.
// jqLiteEmpty takes no arguments but is a setter.
if (fn !== jqLiteEmpty &&
(isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
if (isObject(arg1)) {
// we are a write, but the object properties are the key/values
for (i = 0; i < nodeCount; i++) {
if (fn === jqLiteData) {
// data() takes the whole object in jQuery
fn(this[i], arg1);
} else {
for (key in arg1) {
fn(this[i], key, arg1[key]);
}
}
}
// return self for chaining
return this;
} else {
// we are a read, so read the first child.
// TODO: do we still need this?
var value = fn.$dv;
// Only if we have $dv do we iterate over all, otherwise it is just the first element.
var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
for (var j = 0; j < jj; j++) {
var nodeValue = fn(this[j], arg1, arg2);
value = value ? value + nodeValue : nodeValue;
}
return value;
}
} else {
// we are a write, so apply to all children
for (i = 0; i < nodeCount; i++) {
fn(this[i], arg1, arg2);
}
// return self for chaining
return this;
}
};
});
function createEventHandler(element, events) {
var eventHandler = function(event, type) {
// jQuery specific api
event.isDefaultPrevented = function() {
return event.defaultPrevented;
};
var eventFns = events[type || event.type];
var eventFnsLength = eventFns ? eventFns.length : 0;
if (!eventFnsLength) return;
if (isUndefined(event.immediatePropagationStopped)) {
var originalStopImmediatePropagation = event.stopImmediatePropagation;
event.stopImmediatePropagation = function() {
event.immediatePropagationStopped = true;
if (event.stopPropagation) {
event.stopPropagation();
}
if (originalStopImmediatePropagation) {
originalStopImmediatePropagation.call(event);
}
};
}
event.isImmediatePropagationStopped = function() {
return event.immediatePropagationStopped === true;
};
// Some events have special handlers that wrap the real handler
var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
// Copy event handlers in case event handlers array is modified during execution.
if ((eventFnsLength > 1)) {
eventFns = shallowCopy(eventFns);
}
for (var i = 0; i < eventFnsLength; i++) {
if (!event.isImmediatePropagationStopped()) {
handlerWrapper(element, event, eventFns[i]);
}
}
};
// TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
// events on `element`
eventHandler.elem = element;
return eventHandler;
}
function defaultHandlerWrapper(element, event, handler) {
handler.call(element, event);
}
function specialMouseHandlerWrapper(target, event, handler) {
// Refer to jQuery's implementation of mouseenter & mouseleave
// Read about mouseenter and mouseleave:
// http://www.quirksmode.org/js/events_mouse.html#link8
var related = event.relatedTarget;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if (!related || (related !== target && !jqLiteContains.call(target, related))) {
handler.call(target, event);
}
}
//////////////////////////////////////////
// Functions iterating traversal.
// These functions chain results into a single
// selector.
//////////////////////////////////////////
forEach({
removeData: jqLiteRemoveData,
on: function jqLiteOn(element, type, fn, unsupported) {
if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
// Do not add event handlers to non-elements because they will not be cleaned up.
if (!jqLiteAcceptsData(element)) {
return;
}
var expandoStore = jqLiteExpandoStore(element, true);
var events = expandoStore.events;
var handle = expandoStore.handle;
if (!handle) {
handle = expandoStore.handle = createEventHandler(element, events);
}
// http://jsperf.com/string-indexof-vs-split
var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
var i = types.length;
var addHandler = function(type, specialHandlerWrapper, noEventListener) {
var eventFns = events[type];
if (!eventFns) {
eventFns = events[type] = [];
eventFns.specialHandlerWrapper = specialHandlerWrapper;
if (type !== '$destroy' && !noEventListener) {
element.addEventListener(type, handle);
}
}
eventFns.push(fn);
};
while (i--) {
type = types[i];
if (MOUSE_EVENT_MAP[type]) {
addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
addHandler(type, undefined, true);
} else {
addHandler(type);
}
}
},
off: jqLiteOff,
one: function(element, type, fn) {
element = jqLite(element);
//add the listener twice so that when it is called
//you can remove the original function and still be
//able to call element.off(ev, fn) normally
element.on(type, function onFn() {
element.off(type, fn);
element.off(type, onFn);
});
element.on(type, fn);
},
replaceWith: function(element, replaceNode) {
var index, parent = element.parentNode;
jqLiteDealoc(element);
forEach(new JQLite(replaceNode), function(node) {
if (index) {
parent.insertBefore(node, index.nextSibling);
} else {
parent.replaceChild(node, element);
}
index = node;
});
},
children: function(element) {
var children = [];
forEach(element.childNodes, function(element) {
if (element.nodeType === NODE_TYPE_ELEMENT) {
children.push(element);
}
});
return children;
},
contents: function(element) {
return element.contentDocument || element.childNodes || [];
},
append: function(element, node) {
var nodeType = element.nodeType;
if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
node = new JQLite(node);
for (var i = 0, ii = node.length; i < ii; i++) {
var child = node[i];
element.appendChild(child);
}
},
prepend: function(element, node) {
if (element.nodeType === NODE_TYPE_ELEMENT) {
var index = element.firstChild;
forEach(new JQLite(node), function(child) {
element.insertBefore(child, index);
});
}
},
wrap: function(element, wrapNode) {
jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
},
remove: jqLiteRemove,
detach: function(element) {
jqLiteRemove(element, true);
},
after: function(element, newElement) {
var index = element, parent = element.parentNode;
if (parent) {
newElement = new JQLite(newElement);
for (var i = 0, ii = newElement.length; i < ii; i++) {
var node = newElement[i];
parent.insertBefore(node, index.nextSibling);
index = node;
}
}
},
addClass: jqLiteAddClass,
removeClass: jqLiteRemoveClass,
toggleClass: function(element, selector, condition) {
if (selector) {
forEach(selector.split(' '), function(className) {
var classCondition = condition;
if (isUndefined(classCondition)) {
classCondition = !jqLiteHasClass(element, className);
}
(classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
});
}
},
parent: function(element) {
var parent = element.parentNode;
return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
},
next: function(element) {
return element.nextElementSibling;
},
find: function(element, selector) {
if (element.getElementsByTagName) {
return element.getElementsByTagName(selector);
} else {
return [];
}
},
clone: jqLiteClone,
triggerHandler: function(element, event, extraParameters) {
var dummyEvent, eventFnsCopy, handlerArgs;
var eventName = event.type || event;
var expandoStore = jqLiteExpandoStore(element);
var events = expandoStore && expandoStore.events;
var eventFns = events && events[eventName];
if (eventFns) {
// Create a dummy event to pass to the handlers
dummyEvent = {
preventDefault: function() { this.defaultPrevented = true; },
isDefaultPrevented: function() { return this.defaultPrevented === true; },
stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
stopPropagation: noop,
type: eventName,
target: element
};
// If a custom event was provided then extend our dummy event with it
if (event.type) {
dummyEvent = extend(dummyEvent, event);
}
// Copy event handlers in case event handlers array is modified during execution.
eventFnsCopy = shallowCopy(eventFns);
handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
forEach(eventFnsCopy, function(fn) {
if (!dummyEvent.isImmediatePropagationStopped()) {
fn.apply(element, handlerArgs);
}
});
}
}
}, function(fn, name) {
/**
* chaining functions
*/
JQLite.prototype[name] = function(arg1, arg2, arg3) {
var value;
for (var i = 0, ii = this.length; i < ii; i++) {
if (isUndefined(value)) {
value = fn(this[i], arg1, arg2, arg3);
if (isDefined(value)) {
// any function which returns a value needs to be wrapped
value = jqLite(value);
}
} else {
jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
}
}
return isDefined(value) ? value : this;
};
});
// bind legacy bind/unbind to on/off
JQLite.prototype.bind = JQLite.prototype.on;
JQLite.prototype.unbind = JQLite.prototype.off;
// Provider for private $$jqLite service
/** @this */
function $$jqLiteProvider() {
this.$get = function $$jqLite() {
return extend(JQLite, {
hasClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteHasClass(node, classes);
},
addClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteAddClass(node, classes);
},
removeClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteRemoveClass(node, classes);
}
});
};
}
/**
* Computes a hash of an 'obj'.
* Hash of a:
* string is string
* number is number as string
* object is either result of calling $$hashKey function on the object or uniquely generated id,
* that is also assigned to the $$hashKey property of the object.
*
* @param obj
* @returns {string} hash string such that the same input will have the same hash string.
* The resulting string key is in 'type:hashKey' format.
*/
function hashKey(obj, nextUidFn) {
var key = obj && obj.$$hashKey;
if (key) {
if (typeof key === 'function') {
key = obj.$$hashKey();
}
return key;
}
var objType = typeof obj;
if (objType === 'function' || (objType === 'object' && obj !== null)) {
key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
} else {
key = objType + ':' + obj;
}
return key;
}
// A minimal ES2015 Map implementation.
// Should be bug/feature equivalent to the native implementations of supported browsers
// (for the features required in Angular).
// See https://kangax.github.io/compat-table/es6/#test-Map
var nanKey = Object.create(null);
function NgMapShim() {
this._keys = [];
this._values = [];
this._lastKey = NaN;
this._lastIndex = -1;
}
NgMapShim.prototype = {
_idx: function(key) {
if (key !== this._lastKey) {
this._lastKey = key;
this._lastIndex = this._keys.indexOf(key);
}
return this._lastIndex;
},
_transformKey: function(key) {
return isNumberNaN(key) ? nanKey : key;
},
get: function(key) {
key = this._transformKey(key);
var idx = this._idx(key);
if (idx !== -1) {
return this._values[idx];
}
},
has: function(key) {
key = this._transformKey(key);
var idx = this._idx(key);
return idx !== -1;
},
set: function(key, value) {
key = this._transformKey(key);
var idx = this._idx(key);
if (idx === -1) {
idx = this._lastIndex = this._keys.length;
}
this._keys[idx] = key;
this._values[idx] = value;
// Support: IE11
// Do not `return this` to simulate the partial IE11 implementation
},
delete: function(key) {
key = this._transformKey(key);
var idx = this._idx(key);
if (idx === -1) {
return false;
}
this._keys.splice(idx, 1);
this._values.splice(idx, 1);
this._lastKey = NaN;
this._lastIndex = -1;
return true;
}
};
// For now, always use `NgMapShim`, even if `window.Map` is available. Some native implementations
// are still buggy (often in subtle ways) and can cause hard-to-debug failures. When native `Map`
// implementations get more stable, we can reconsider switching to `window.Map` (when available).
var NgMap = NgMapShim;
var $$MapProvider = [/** @this */function() {
this.$get = [function() {
return NgMap;
}];
}];
/**
* @ngdoc function
* @module ng
* @name angular.injector
* @kind function
*
* @description
* Creates an injector object that can be used for retrieving services as well as for
* dependency injection (see {@link guide/di dependency injection}).
*
* @param {Array.} modules A list of module functions or their aliases. See
* {@link angular.module}. The `ng` module must be explicitly added.
* @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
* disallows argument name annotation inference.
* @returns {injector} Injector object. See {@link auto.$injector $injector}.
*
* @example
* Typical usage
* ```js
* // create an injector
* var $injector = angular.injector(['ng']);
*
* // use the injector to kick off your application
* // use the type inference to auto inject arguments, or use implicit injection
* $injector.invoke(function($rootScope, $compile, $document) {
* $compile($document)($rootScope);
* $rootScope.$digest();
* });
* ```
*
* Sometimes you want to get access to the injector of a currently running AngularJS app
* from outside AngularJS. Perhaps, you want to inject and compile some markup after the
* application has been bootstrapped. You can do this using the extra `injector()` added
* to JQuery/jqLite elements. See {@link angular.element}.
*
* *This is fairly rare but could be the case if a third party library is injecting the
* markup.*
*
* In the following example a new block of HTML containing a `ng-controller`
* directive is added to the end of the document body by JQuery. We then compile and link
* it into the current AngularJS scope.
*
* ```js
* var $div = $('
{{content.label}}
');
* $(document.body).append($div);
*
* angular.element(document).injector().invoke(function($compile) {
* var scope = angular.element($div).scope();
* $compile($div)(scope);
* });
* ```
*/
/**
* @ngdoc module
* @name auto
* @installation
* @description
*
* Implicit module which gets automatically added to each {@link auto.$injector $injector}.
*/
var ARROW_ARG = /^([^(]+?)=>/;
var FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var $injectorMinErr = minErr('$injector');
function stringifyFn(fn) {
return Function.prototype.toString.call(fn);
}
function extractArgs(fn) {
var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),
args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
return args;
}
function anonFn(fn) {
// For anonymous functions, showing at the very least the function signature can help in
// debugging.
var args = extractArgs(fn);
if (args) {
return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
}
return 'fn';
}
function annotate(fn, strictDi, name) {
var $inject,
argDecl,
last;
if (typeof fn === 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
if (fn.length) {
if (strictDi) {
if (!isString(name) || !name) {
name = fn.name || anonFn(fn);
}
throw $injectorMinErr('strictdi',
'{0} is not using explicit annotation and cannot be invoked in strict mode', name);
}
argDecl = extractArgs(fn);
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
arg.replace(FN_ARG, function(all, underscore, name) {
$inject.push(name);
});
});
}
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last], 'fn');
$inject = fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
}
return $inject;
}
///////////////////////////////////////
/**
* @ngdoc service
* @name $injector
*
* @description
*
* `$injector` is used to retrieve object instances as defined by
* {@link auto.$provide provider}, instantiate types, invoke methods,
* and load modules.
*
* The following always holds true:
*
* ```js
* var $injector = angular.injector();
* expect($injector.get('$injector')).toBe($injector);
* expect($injector.invoke(function($injector) {
* return $injector;
* })).toBe($injector);
* ```
*
* ## Injection Function Annotation
*
* JavaScript does not have annotations, and annotations are needed for dependency injection. The
* following are all valid ways of annotating function with injection arguments and are equivalent.
*
* ```js
* // inferred (only works if code not minified/obfuscated)
* $injector.invoke(function(serviceA){});
*
* // annotated
* function explicit(serviceA) {};
* explicit.$inject = ['serviceA'];
* $injector.invoke(explicit);
*
* // inline
* $injector.invoke(['serviceA', function(serviceA){}]);
* ```
*
* ### Inference
*
* In JavaScript calling `toString()` on a function returns the function definition. The definition
* can then be parsed and the function arguments can be extracted. This method of discovering
* annotations is disallowed when the injector is in strict mode.
* *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
* argument names.
*
* ### `$inject` Annotation
* By adding an `$inject` property onto a function the injection parameters can be specified.
*
* ### Inline
* As an array of injection names, where the last item in the array is the function to call.
*/
/**
* @ngdoc property
* @name $injector#modules
* @type {Object}
* @description
* A hash containing all the modules that have been loaded into the
* $injector.
*
* You can use this property to find out information about a module via the
* {@link angular.Module#info `myModule.info(...)`} method.
*
* For example:
*
* ```
* var info = $injector.modules['ngAnimate'].info();
* ```
*
* **Do not use this property to attempt to modify the modules after the application
* has been bootstrapped.**
*/
/**
* @ngdoc method
* @name $injector#get
*
* @description
* Return an instance of the service.
*
* @param {string} name The name of the instance to retrieve.
* @param {string=} caller An optional string to provide the origin of the function call for error messages.
* @return {*} The instance.
*/
/**
* @ngdoc method
* @name $injector#invoke
*
* @description
* Invoke the method and supply the method arguments from the `$injector`.
*
* @param {Function|Array.} fn The injectable function to invoke. Function parameters are
* injected according to the {@link guide/di $inject Annotation} rules.
* @param {Object=} self The `this` for the invoked method.
* @param {Object=} locals Optional object. If preset then any argument names are read from this
* object first, before the `$injector` is consulted.
* @returns {*} the value returned by the invoked `fn` function.
*/
/**
* @ngdoc method
* @name $injector#has
*
* @description
* Allows the user to query if the particular service exists.
*
* @param {string} name Name of the service to query.
* @returns {boolean} `true` if injector has given service.
*/
/**
* @ngdoc method
* @name $injector#instantiate
* @description
* Create a new instance of JS type. The method takes a constructor function, invokes the new
* operator, and supplies all of the arguments to the constructor function as specified by the
* constructor annotation.
*
* @param {Function} Type Annotated constructor function.
* @param {Object=} locals Optional object. If preset then any argument names are read from this
* object first, before the `$injector` is consulted.
* @returns {Object} new instance of `Type`.
*/
/**
* @ngdoc method
* @name $injector#annotate
*
* @description
* Returns an array of service names which the function is requesting for injection. This API is
* used by the injector to determine which services need to be injected into the function when the
* function is invoked. There are three ways in which the function can be annotated with the needed
* dependencies.
*
* #### Argument names
*
* The simplest form is to extract the dependencies from the arguments of the function. This is done
* by converting the function into a string using `toString()` method and extracting the argument
* names.
* ```js
* // Given
* function MyController($scope, $route) {
* // ...
* }
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* ```
*
* You can disallow this method by using strict injection mode.
*
* This method does not work with code minification / obfuscation. For this reason the following
* annotation strategies are supported.
*
* #### The `$inject` property
*
* If a function has an `$inject` property and its value is an array of strings, then the strings
* represent names of services to be injected into the function.
* ```js
* // Given
* var MyController = function(obfuscatedScope, obfuscatedRoute) {
* // ...
* }
* // Define function dependencies
* MyController['$inject'] = ['$scope', '$route'];
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* ```
*
* #### The array notation
*
* It is often desirable to inline Injected functions and that's when setting the `$inject` property
* is very inconvenient. In these situations using the array notation to specify the dependencies in
* a way that survives minification is a better choice:
*
* ```js
* // We wish to write this (not minification / obfuscation safe)
* injector.invoke(function($compile, $rootScope) {
* // ...
* });
*
* // We are forced to write break inlining
* var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
* // ...
* };
* tmpFn.$inject = ['$compile', '$rootScope'];
* injector.invoke(tmpFn);
*
* // To better support inline function the inline annotation is supported
* injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
* // ...
* }]);
*
* // Therefore
* expect(injector.annotate(
* ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
* ).toEqual(['$compile', '$rootScope']);
* ```
*
* @param {Function|Array.} fn Function for which dependent service names need to
* be retrieved as described above.
*
* @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
*
* @returns {Array.} The names of the services which the function requires.
*/
/**
* @ngdoc method
* @name $injector#loadNewModules
*
* @description
*
* **This is a dangerous API, which you use at your own risk!**
*
* Add the specified modules to the current injector.
*
* This method will add each of the injectables to the injector and execute all of the config and run
* blocks for each module passed to the method.
*
* If a module has already been loaded into the injector then it will not be loaded again.
*
* * The application developer is responsible for loading the code containing the modules; and for
* ensuring that lazy scripts are not downloaded and executed more often that desired.
* * Previously compiled HTML will not be affected by newly loaded directives, filters and components.
* * Modules cannot be unloaded.
*
* You can use {@link $injector#modules `$injector.modules`} to check whether a module has been loaded
* into the injector, which may indicate whether the script has been executed already.
*
* @example
* Here is an example of loading a bundle of modules, with a utility method called `getScript`:
*
* ```javascript
* app.factory('loadModule', function($injector) {
* return function loadModule(moduleName, bundleUrl) {
* return getScript(bundleUrl).then(function() { $injector.loadNewModules([moduleName]); });
* };
* })
* ```
*
* @param {Array=} mods an array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a `config` block.
* See: {@link angular.module modules}
*/
/**
* @ngdoc service
* @name $provide
*
* @description
*
* The {@link auto.$provide $provide} service has a number of methods for registering components
* with the {@link auto.$injector $injector}. Many of these functions are also exposed on
* {@link angular.Module}.
*
* An AngularJS **service** is a singleton object created by a **service factory**. These **service
* factories** are functions which, in turn, are created by a **service provider**.
* The **service providers** are constructor functions. When instantiated they must contain a
* property called `$get`, which holds the **service factory** function.
*
* When you request a service, the {@link auto.$injector $injector} is responsible for finding the
* correct **service provider**, instantiating it and then calling its `$get` **service factory**
* function to get the instance of the **service**.
*
* Often services have no configuration options and there is no need to add methods to the service
* provider. The provider will be no more than a constructor function with a `$get` property. For
* these cases the {@link auto.$provide $provide} service has additional helper methods to register
* services without specifying a provider.
*
* * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the
* {@link auto.$injector $injector}
* * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by
* providers and services.
* * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by
* services, not providers.
* * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**
* that will be wrapped in a **service provider** object, whose `$get` property will contain the
* given factory function.
* * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**
* that will be wrapped in a **service provider** object, whose `$get` property will instantiate
* a new object using the given constructor function.
* * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that
* will be able to modify or replace the implementation of another service.
*
* See the individual methods for more information and examples.
*/
/**
* @ngdoc method
* @name $provide#provider
* @description
*
* Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
* are constructor functions, whose instances are responsible for "providing" a factory for a
* service.
*
* Service provider names start with the name of the service they provide followed by `Provider`.
* For example, the {@link ng.$log $log} service has a provider called
* {@link ng.$logProvider $logProvider}.
*
* Service provider objects can have additional methods which allow configuration of the provider
* and its service. Importantly, you can configure what kind of service is created by the `$get`
* method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
* method {@link ng.$logProvider#debugEnabled debugEnabled}
* which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
* console or not.
*
* It is possible to inject other providers into the provider function,
* but the injected provider must have been defined before the one that requires it.
*
* @param {string} name The name of the instance. NOTE: the provider will be available under `name +
'Provider'` key.
* @param {(Object|function())} provider If the provider is:
*
* - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
* {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
* - `Constructor`: a new instance of the provider will be created using
* {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
*
* @returns {Object} registered provider instance
* @example
*
* The following example shows how to create a simple event tracking service and register it using
* {@link auto.$provide#provider $provide.provider()}.
*
* ```js
* // Define the eventTracker provider
* function EventTrackerProvider() {
* var trackingUrl = '/track';
*
* // A provider method for configuring where the tracked events should been saved
* this.setTrackingUrl = function(url) {
* trackingUrl = url;
* };
*
* // The service factory function
* this.$get = ['$http', function($http) {
* var trackedEvents = {};
* return {
* // Call this to track an event
* event: function(event) {
* var count = trackedEvents[event] || 0;
* count += 1;
* trackedEvents[event] = count;
* return count;
* },
* // Call this to save the tracked events to the trackingUrl
* save: function() {
* $http.post(trackingUrl, trackedEvents);
* }
* };
* }];
* }
*
* describe('eventTracker', function() {
* var postSpy;
*
* beforeEach(module(function($provide) {
* // Register the eventTracker provider
* $provide.provider('eventTracker', EventTrackerProvider);
* }));
*
* beforeEach(module(function(eventTrackerProvider) {
* // Configure eventTracker provider
* eventTrackerProvider.setTrackingUrl('/custom-track');
* }));
*
* it('tracks events', inject(function(eventTracker) {
* expect(eventTracker.event('login')).toEqual(1);
* expect(eventTracker.event('login')).toEqual(2);
* }));
*
* it('saves to the tracking url', inject(function(eventTracker, $http) {
* postSpy = spyOn($http, 'post');
* eventTracker.event('login');
* eventTracker.save();
* expect(postSpy).toHaveBeenCalled();
* expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
* expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
* expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
* }));
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#factory
* @description
*
* Register a **service factory**, which will be called to return the service instance.
* This is short for registering a service where its provider consists of only a `$get` property,
* which is the given service factory function.
* You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
* configure your service in a provider.
*
* @param {string} name The name of the instance.
* @param {Function|Array.} $getFn The injectable $getFn for the instance creation.
* Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
* @returns {Object} registered provider instance
*
* @example
* Here is an example of registering a service
* ```js
* $provide.factory('ping', ['$http', function($http) {
* return function ping() {
* return $http.send('/ping');
* };
* }]);
* ```
* You would then inject and use this service like this:
* ```js
* someModule.controller('Ctrl', ['ping', function(ping) {
* ping();
* }]);
* ```
*/
/**
* @ngdoc method
* @name $provide#service
* @description
*
* Register a **service constructor**, which will be invoked with `new` to create the service
* instance.
* This is short for registering a service where its provider's `$get` property is a factory
* function that returns an instance instantiated by the injector from the service constructor
* function.
*
* Internally it looks a bit like this:
*
* ```
* {
* $get: function() {
* return $injector.instantiate(constructor);
* }
* }
* ```
*
*
* You should use {@link auto.$provide#service $provide.service(class)} if you define your service
* as a type/class.
*
* @param {string} name The name of the instance.
* @param {Function|Array.} constructor An injectable class (constructor function)
* that will be instantiated.
* @returns {Object} registered provider instance
*
* @example
* Here is an example of registering a service using
* {@link auto.$provide#service $provide.service(class)}.
* ```js
* var Ping = function($http) {
* this.$http = $http;
* };
*
* Ping.$inject = ['$http'];
*
* Ping.prototype.send = function() {
* return this.$http.get('/ping');
* };
* $provide.service('ping', Ping);
* ```
* You would then inject and use this service like this:
* ```js
* someModule.controller('Ctrl', ['ping', function(ping) {
* ping.send();
* }]);
* ```
*/
/**
* @ngdoc method
* @name $provide#value
* @description
*
* Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
* number, an array, an object or a function. This is short for registering a service where its
* provider's `$get` property is a factory function that takes no arguments and returns the **value
* service**. That also means it is not possible to inject other services into a value service.
*
* Value services are similar to constant services, except that they cannot be injected into a
* module configuration function (see {@link angular.Module#config}) but they can be overridden by
* an AngularJS {@link auto.$provide#decorator decorator}.
*
* @param {string} name The name of the instance.
* @param {*} value The value.
* @returns {Object} registered provider instance
*
* @example
* Here are some examples of creating value services.
* ```js
* $provide.value('ADMIN_USER', 'admin');
*
* $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
*
* $provide.value('halfOf', function(value) {
* return value / 2;
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#constant
* @description
*
* Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
* a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
* possible to inject other services into a constant.
*
* But unlike {@link auto.$provide#value value}, a constant can be
* injected into a module configuration function (see {@link angular.Module#config}) and it cannot
* be overridden by an AngularJS {@link auto.$provide#decorator decorator}.
*
* @param {string} name The name of the constant.
* @param {*} value The constant value.
* @returns {Object} registered instance
*
* @example
* Here a some examples of creating constants:
* ```js
* $provide.constant('SHARD_HEIGHT', 306);
*
* $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
*
* $provide.constant('double', function(value) {
* return value * 2;
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#decorator
* @description
*
* Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function
* intercepts the creation of a service, allowing it to override or modify the behavior of the
* service. The return value of the decorator function may be the original service, or a new service
* that replaces (or wraps and delegates to) the original service.
*
* You can find out more about using decorators in the {@link guide/decorators} guide.
*
* @param {string} name The name of the service to decorate.
* @param {Function|Array.} decorator This function will be invoked when the service needs to be
* provided and should return the decorated service instance. The function is called using
* the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
* Local injection arguments:
*
* * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,
* decorated or delegated to.
*
* @example
* Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
* calls to {@link ng.$log#error $log.warn()}.
* ```js
* $provide.decorator('$log', ['$delegate', function($delegate) {
* $delegate.warn = $delegate.error;
* return $delegate;
* }]);
* ```
*/
function createInjector(modulesToLoad, strictDi) {
strictDi = (strictDi === true);
var INSTANTIATING = {},
providerSuffix = 'Provider',
path = [],
loadedModules = new NgMap(),
providerCache = {
$provide: {
provider: supportObject(provider),
factory: supportObject(factory),
service: supportObject(service),
value: supportObject(value),
constant: supportObject(constant),
decorator: decorator
}
},
providerInjector = (providerCache.$injector =
createInternalInjector(providerCache, function(serviceName, caller) {
if (angular.isString(caller)) {
path.push(caller);
}
throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- '));
})),
instanceCache = {},
protoInstanceInjector =
createInternalInjector(instanceCache, function(serviceName, caller) {
var provider = providerInjector.get(serviceName + providerSuffix, caller);
return instanceInjector.invoke(
provider.$get, provider, undefined, serviceName);
}),
instanceInjector = protoInstanceInjector;
providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
instanceInjector.modules = providerInjector.modules = createMap();
var runBlocks = loadModules(modulesToLoad);
instanceInjector = protoInstanceInjector.get('$injector');
instanceInjector.strictDi = strictDi;
forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
instanceInjector.loadNewModules = function(mods) {
forEach(loadModules(mods), function(fn) { if (fn) instanceInjector.invoke(fn); });
};
return instanceInjector;
////////////////////////////////////
// $provider
////////////////////////////////////
function supportObject(delegate) {
return function(key, value) {
if (isObject(key)) {
forEach(key, reverseParams(delegate));
} else {
return delegate(key, value);
}
};
}
function provider(name, provider_) {
assertNotHasOwnProperty(name, 'service');
if (isFunction(provider_) || isArray(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name);
}
return (providerCache[name + providerSuffix] = provider_);
}
function enforceReturnValue(name, factory) {
return /** @this */ function enforcedReturnValue() {
var result = instanceInjector.invoke(factory, this);
if (isUndefined(result)) {
throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name);
}
return result;
};
}
function factory(name, factoryFn, enforce) {
return provider(name, {
$get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
});
}
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
function value(name, val) { return factory(name, valueFn(val), false); }
function constant(name, value) {
assertNotHasOwnProperty(name, 'constant');
providerCache[name] = value;
instanceCache[name] = value;
}
function decorator(serviceName, decorFn) {
var origProvider = providerInjector.get(serviceName + providerSuffix),
orig$get = origProvider.$get;
origProvider.$get = function() {
var origInstance = instanceInjector.invoke(orig$get, origProvider);
return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
};
}
////////////////////////////////////
// Module Loading
////////////////////////////////////
function loadModules(modulesToLoad) {
assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
var runBlocks = [], moduleFn;
forEach(modulesToLoad, function(module) {
if (loadedModules.get(module)) return;
loadedModules.set(module, true);
function runInvokeQueue(queue) {
var i, ii;
for (i = 0, ii = queue.length; i < ii; i++) {
var invokeArgs = queue[i],
provider = providerInjector.get(invokeArgs[0]);
provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
}
}
try {
if (isString(module)) {
moduleFn = angularModule(module);
instanceInjector.modules[module] = moduleFn;
runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
runInvokeQueue(moduleFn._invokeQueue);
runInvokeQueue(moduleFn._configBlocks);
} else if (isFunction(module)) {
runBlocks.push(providerInjector.invoke(module));
} else if (isArray(module)) {
runBlocks.push(providerInjector.invoke(module));
} else {
assertArgFn(module, 'module');
}
} catch (e) {
if (isArray(module)) {
module = module[module.length - 1];
}
if (e.message && e.stack && e.stack.indexOf(e.message) === -1) {
// Safari & FF's stack traces don't contain error.message content
// unlike those of Chrome and IE
// So if stack doesn't contain message, we create a new string that contains both.
// Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
// eslint-disable-next-line no-ex-assign
e = e.message + '\n' + e.stack;
}
throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}',
module, e.stack || e.message || e);
}
});
return runBlocks;
}
////////////////////////////////////
// internal Injector
////////////////////////////////////
function createInternalInjector(cache, factory) {
function getService(serviceName, caller) {
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
serviceName + ' <- ' + path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
cache[serviceName] = factory(serviceName, caller);
return cache[serviceName];
} catch (err) {
if (cache[serviceName] === INSTANTIATING) {
delete cache[serviceName];
}
throw err;
} finally {
path.shift();
}
}
}
function injectionArgs(fn, locals, serviceName) {
var args = [],
$inject = createInjector.$$annotate(fn, strictDi, serviceName);
for (var i = 0, length = $inject.length; i < length; i++) {
var key = $inject[i];
if (typeof key !== 'string') {
throw $injectorMinErr('itkn',
'Incorrect injection token! Expected service name as string, got {0}', key);
}
args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
getService(key, serviceName));
}
return args;
}
function isClass(func) {
// Support: IE 9-11 only
// IE 9-11 do not support classes and IE9 leaks with the code below.
if (msie || typeof func !== 'function') {
return false;
}
var result = func.$$ngIsClass;
if (!isBoolean(result)) {
result = func.$$ngIsClass = /^class\b/.test(stringifyFn(func));
}
return result;
}
function invoke(fn, self, locals, serviceName) {
if (typeof locals === 'string') {
serviceName = locals;
locals = null;
}
var args = injectionArgs(fn, locals, serviceName);
if (isArray(fn)) {
fn = fn[fn.length - 1];
}
if (!isClass(fn)) {
// http://jsperf.com/angularjs-invoke-apply-vs-switch
// #5388
return fn.apply(self, args);
} else {
args.unshift(null);
return new (Function.prototype.bind.apply(fn, args))();
}
}
function instantiate(Type, locals, serviceName) {
// Check if Type is annotated and use just the given function at n-1 as parameter
// e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
var args = injectionArgs(Type, locals, serviceName);
// Empty object at position 0 is ignored for invocation with `new`, but required.
args.unshift(null);
return new (Function.prototype.bind.apply(ctor, args))();
}
return {
invoke: invoke,
instantiate: instantiate,
get: getService,
annotate: createInjector.$$annotate,
has: function(name) {
return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
}
};
}
}
createInjector.$$annotate = annotate;
/**
* @ngdoc provider
* @name $anchorScrollProvider
* @this
*
* @description
* Use `$anchorScrollProvider` to disable automatic scrolling whenever
* {@link ng.$location#hash $location.hash()} changes.
*/
function $AnchorScrollProvider() {
var autoScrollingEnabled = true;
/**
* @ngdoc method
* @name $anchorScrollProvider#disableAutoScrolling
*
* @description
* By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
* {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.
* Use this method to disable automatic scrolling.
*
* If automatic scrolling is disabled, one must explicitly call
* {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
* current hash.
*/
this.disableAutoScrolling = function() {
autoScrollingEnabled = false;
};
/**
* @ngdoc service
* @name $anchorScroll
* @kind function
* @requires $window
* @requires $location
* @requires $rootScope
*
* @description
* When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
* current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
* in the
* [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).
*
* It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
* match any anchor whenever it changes. This can be disabled by calling
* {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
*
* Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
* vertical scroll-offset (either fixed or dynamic).
*
* @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
* {@link ng.$location#hash $location.hash()} will be used.
*
* @property {(number|function|jqLite)} yOffset
* If set, specifies a vertical scroll-offset. This is often useful when there are fixed
* positioned elements at the top of the page, such as navbars, headers etc.
*
* `yOffset` can be specified in various ways:
* - **number**: A fixed number of pixels to be used as offset.
* - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
* a number representing the offset (in pixels).
* - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
* the top of the page to the element's bottom will be used as offset.
* **Note**: The element will be taken into account only as long as its `position` is set to
* `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
* their height and/or positioning according to the viewport's size.
*
*
*
* In order for `yOffset` to work properly, scrolling should take place on the document's root and
* not some child element.
*
angular.module('anchorScrollExample', [])
.controller('ScrollController', ['$scope', '$location', '$anchorScroll',
function($scope, $location, $anchorScroll) {
$scope.gotoBottom = function() {
// set the location.hash to the id of
// the element you wish to scroll to.
$location.hash('bottom');
// call $anchorScroll()
$anchorScroll();
};
}]);
#scrollArea {
height: 280px;
overflow: auto;
}
#bottom {
display: block;
margin-top: 2000px;
}
*
*
* The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
* See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
*
* @example
angular.module('anchorScrollOffsetExample', [])
.run(['$anchorScroll', function($anchorScroll) {
$anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
}])
.controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
function($anchorScroll, $location, $scope) {
$scope.gotoAnchor = function(x) {
var newHash = 'anchor' + x;
if ($location.hash() !== newHash) {
// set the $location.hash to `newHash` and
// $anchorScroll will automatically scroll to it
$location.hash('anchor' + x);
} else {
// call $anchorScroll() explicitly,
// since $location.hash hasn't changed
$anchorScroll();
}
};
}
]);
body {
padding-top: 50px;
}
.anchor {
border: 2px dashed DarkOrchid;
padding: 10px 10px 200px 10px;
}
.fixed-header {
background-color: rgba(0, 0, 0, 0.2);
height: 50px;
position: fixed;
top: 0; left: 0; right: 0;
}
.fixed-header > a {
display: inline-block;
margin: 5px 15px;
}
*/
this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
var document = $window.document;
// Helper function to get first anchor from a NodeList
// (using `Array#some()` instead of `angular#forEach()` since it's more performant
// and working in all supported browsers.)
function getFirstAnchor(list) {
var result = null;
Array.prototype.some.call(list, function(element) {
if (nodeName_(element) === 'a') {
result = element;
return true;
}
});
return result;
}
function getYOffset() {
var offset = scroll.yOffset;
if (isFunction(offset)) {
offset = offset();
} else if (isElement(offset)) {
var elem = offset[0];
var style = $window.getComputedStyle(elem);
if (style.position !== 'fixed') {
offset = 0;
} else {
offset = elem.getBoundingClientRect().bottom;
}
} else if (!isNumber(offset)) {
offset = 0;
}
return offset;
}
function scrollTo(elem) {
if (elem) {
elem.scrollIntoView();
var offset = getYOffset();
if (offset) {
// `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
// This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
// top of the viewport.
//
// IF the number of pixels from the top of `elem` to the end of the page's content is less
// than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
// way down the page.
//
// This is often the case for elements near the bottom of the page.
//
// In such cases we do not need to scroll the whole `offset` up, just the difference between
// the top of the element and the offset, which is enough to align the top of `elem` at the
// desired position.
var elemTop = elem.getBoundingClientRect().top;
$window.scrollBy(0, elemTop - offset);
}
} else {
$window.scrollTo(0, 0);
}
}
function scroll(hash) {
// Allow numeric hashes
hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash();
var elm;
// empty hash, scroll to the top of the page
if (!hash) scrollTo(null);
// element with given id
else if ((elm = document.getElementById(hash))) scrollTo(elm);
// first anchor with given name :-D
else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
// no element and hash === 'top', scroll to the top of the page
else if (hash === 'top') scrollTo(null);
}
// does not scroll when user clicks on anchor link that is currently on
// (no url change, no $location.hash() change), browser native does scroll
if (autoScrollingEnabled) {
$rootScope.$watch(function autoScrollWatch() {return $location.hash();},
function autoScrollWatchAction(newVal, oldVal) {
// skip the initial scroll if $location.hash is empty
if (newVal === oldVal && newVal === '') return;
jqLiteDocumentLoaded(function() {
$rootScope.$evalAsync(scroll);
});
});
}
return scroll;
}];
}
var $animateMinErr = minErr('$animate');
var ELEMENT_NODE = 1;
var NG_ANIMATE_CLASSNAME = 'ng-animate';
function mergeClasses(a,b) {
if (!a && !b) return '';
if (!a) return b;
if (!b) return a;
if (isArray(a)) a = a.join(' ');
if (isArray(b)) b = b.join(' ');
return a + ' ' + b;
}
function extractElementNode(element) {
for (var i = 0; i < element.length; i++) {
var elm = element[i];
if (elm.nodeType === ELEMENT_NODE) {
return elm;
}
}
}
function splitClasses(classes) {
if (isString(classes)) {
classes = classes.split(' ');
}
// Use createMap() to prevent class assumptions involving property names in
// Object.prototype
var obj = createMap();
forEach(classes, function(klass) {
// sometimes the split leaves empty string values
// incase extra spaces were applied to the options
if (klass.length) {
obj[klass] = true;
}
});
return obj;
}
// if any other type of options value besides an Object value is
// passed into the $animate.method() animation then this helper code
// will be run which will ignore it. While this patch is not the
// greatest solution to this, a lot of existing plugins depend on
// $animate to either call the callback (< 1.2) or return a promise
// that can be changed. This helper function ensures that the options
// are wiped clean incase a callback function is provided.
function prepareAnimateOptions(options) {
return isObject(options)
? options
: {};
}
var $$CoreAnimateJsProvider = /** @this */ function() {
this.$get = noop;
};
// this is prefixed with Core since it conflicts with
// the animateQueueProvider defined in ngAnimate/animateQueue.js
var $$CoreAnimateQueueProvider = /** @this */ function() {
var postDigestQueue = new NgMap();
var postDigestElements = [];
this.$get = ['$$AnimateRunner', '$rootScope',
function($$AnimateRunner, $rootScope) {
return {
enabled: noop,
on: noop,
off: noop,
pin: noop,
push: function(element, event, options, domOperation) {
if (domOperation) {
domOperation();
}
options = options || {};
if (options.from) {
element.css(options.from);
}
if (options.to) {
element.css(options.to);
}
if (options.addClass || options.removeClass) {
addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
}
var runner = new $$AnimateRunner();
// since there are no animations to run the runner needs to be
// notified that the animation call is complete.
runner.complete();
return runner;
}
};
function updateData(data, classes, value) {
var changed = false;
if (classes) {
classes = isString(classes) ? classes.split(' ') :
isArray(classes) ? classes : [];
forEach(classes, function(className) {
if (className) {
changed = true;
data[className] = value;
}
});
}
return changed;
}
function handleCSSClassChanges() {
forEach(postDigestElements, function(element) {
var data = postDigestQueue.get(element);
if (data) {
var existing = splitClasses(element.attr('class'));
var toAdd = '';
var toRemove = '';
forEach(data, function(status, className) {
var hasClass = !!existing[className];
if (status !== hasClass) {
if (status) {
toAdd += (toAdd.length ? ' ' : '') + className;
} else {
toRemove += (toRemove.length ? ' ' : '') + className;
}
}
});
forEach(element, function(elm) {
if (toAdd) {
jqLiteAddClass(elm, toAdd);
}
if (toRemove) {
jqLiteRemoveClass(elm, toRemove);
}
});
postDigestQueue.delete(element);
}
});
postDigestElements.length = 0;
}
function addRemoveClassesPostDigest(element, add, remove) {
var data = postDigestQueue.get(element) || {};
var classesAdded = updateData(data, add, true);
var classesRemoved = updateData(data, remove, false);
if (classesAdded || classesRemoved) {
postDigestQueue.set(element, data);
postDigestElements.push(element);
if (postDigestElements.length === 1) {
$rootScope.$$postDigest(handleCSSClassChanges);
}
}
}
}];
};
/**
* @ngdoc provider
* @name $animateProvider
*
* @description
* Default implementation of $animate that doesn't perform any animations, instead just
* synchronously performs DOM updates and resolves the returned runner promise.
*
* In order to enable animations the `ngAnimate` module has to be loaded.
*
* To see the functional implementation check out `src/ngAnimate/animate.js`.
*/
var $AnimateProvider = ['$provide', /** @this */ function($provide) {
var provider = this;
var classNameFilter = null;
var customFilter = null;
this.$$registeredAnimations = Object.create(null);
/**
* @ngdoc method
* @name $animateProvider#register
*
* @description
* Registers a new injectable animation factory function. The factory function produces the
* animation object which contains callback functions for each event that is expected to be
* animated.
*
* * `eventFn`: `function(element, ... , doneFunction, options)`
* The element to animate, the `doneFunction` and the options fed into the animation. Depending
* on the type of animation additional arguments will be injected into the animation function. The
* list below explains the function signatures for the different animation methods:
*
* - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
* - addClass: function(element, addedClasses, doneFunction, options)
* - removeClass: function(element, removedClasses, doneFunction, options)
* - enter, leave, move: function(element, doneFunction, options)
* - animate: function(element, fromStyles, toStyles, doneFunction, options)
*
* Make sure to trigger the `doneFunction` once the animation is fully complete.
*
* ```js
* return {
* //enter, leave, move signature
* eventFn : function(element, done, options) {
* //code to run the animation
* //once complete, then run done()
* return function endFunction(wasCancelled) {
* //code to cancel the animation
* }
* }
* }
* ```
*
* @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
* @param {Function} factory The factory function that will be executed to return the animation
* object.
*/
this.register = function(name, factory) {
if (name && name.charAt(0) !== '.') {
throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name);
}
var key = name + '-animation';
provider.$$registeredAnimations[name.substr(1)] = key;
$provide.factory(key, factory);
};
/**
* @ngdoc method
* @name $animateProvider#customFilter
*
* @description
* Sets and/or returns the custom filter function that is used to "filter" animations, i.e.
* determine if an animation is allowed or not. When no filter is specified (the default), no
* animation will be blocked. Setting the `customFilter` value will only allow animations for
* which the filter function's return value is truthy.
*
* This allows to easily create arbitrarily complex rules for filtering animations, such as
* allowing specific events only, or enabling animations on specific subtrees of the DOM, etc.
* Filtering animations can also boost performance for low-powered devices, as well as
* applications containing a lot of structural operations.
*
*
* **Best Practice:**
* Keep the filtering function as lean as possible, because it will be called for each DOM
* action (e.g. insertion, removal, class change) performed by "animation-aware" directives.
* See {@link guide/animations#which-directives-support-animations- here} for a list of built-in
* directives that support animations.
* Performing computationally expensive or time-consuming operations on each call of the
* filtering function can make your animations sluggish.
*
*
* **Note:** If present, `customFilter` will be checked before
* {@link $animateProvider#classNameFilter classNameFilter}.
*
* @param {Function=} filterFn - The filter function which will be used to filter all animations.
* If a falsy value is returned, no animation will be performed. The function will be called
* with the following arguments:
* - **node** `{DOMElement}` - The DOM element to be animated.
* - **event** `{String}` - The name of the animation event (e.g. `enter`, `leave`, `addClass`
* etc).
* - **options** `{Object}` - A collection of options/styles used for the animation.
* @return {Function} The current filter function or `null` if there is none set.
*/
this.customFilter = function(filterFn) {
if (arguments.length === 1) {
customFilter = isFunction(filterFn) ? filterFn : null;
}
return customFilter;
};
/**
* @ngdoc method
* @name $animateProvider#classNameFilter
*
* @description
* Sets and/or returns the CSS class regular expression that is checked when performing
* an animation. Upon bootstrap the classNameFilter value is not set at all and will
* therefore enable $animate to attempt to perform an animation on any element that is triggered.
* When setting the `classNameFilter` value, animations will only be performed on elements
* that successfully match the filter expression. This in turn can boost performance
* for low-powered devices as well as applications containing a lot of structural operations.
*
* **Note:** If present, `classNameFilter` will be checked after
* {@link $animateProvider#customFilter customFilter}. If `customFilter` is present and returns
* false, `classNameFilter` will not be checked.
*
* @param {RegExp=} expression The className expression which will be checked against all animations
* @return {RegExp} The current CSS className expression value. If null then there is no expression value
*/
this.classNameFilter = function(expression) {
if (arguments.length === 1) {
classNameFilter = (expression instanceof RegExp) ? expression : null;
if (classNameFilter) {
var reservedRegex = new RegExp('[(\\s|\\/)]' + NG_ANIMATE_CLASSNAME + '[(\\s|\\/)]');
if (reservedRegex.test(classNameFilter.toString())) {
classNameFilter = null;
throw $animateMinErr('nongcls', '$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
}
}
}
return classNameFilter;
};
this.$get = ['$$animateQueue', function($$animateQueue) {
function domInsert(element, parentElement, afterElement) {
// if for some reason the previous element was removed
// from the dom sometime before this code runs then let's
// just stick to using the parent element as the anchor
if (afterElement) {
var afterNode = extractElementNode(afterElement);
if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
afterElement = null;
}
}
if (afterElement) {
afterElement.after(element);
} else {
parentElement.prepend(element);
}
}
/**
* @ngdoc service
* @name $animate
* @description The $animate service exposes a series of DOM utility methods that provide support
* for animation hooks. The default behavior is the application of DOM operations, however,
* when an animation is detected (and animations are enabled), $animate will do the heavy lifting
* to ensure that animation runs with the triggered DOM operation.
*
* By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
* included and only when it is active then the animation hooks that `$animate` triggers will be
* functional. Once active then all structural `ng-` directives will trigger animations as they perform
* their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
* `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
*
* It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
*
* To learn more about enabling animation support, click here to visit the
* {@link ngAnimate ngAnimate module page}.
*/
return {
// we don't call it directly since non-existant arguments may
// be interpreted as null within the sub enabled function
/**
*
* @ngdoc method
* @name $animate#on
* @kind function
* @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
* has fired on the given element or among any of its children. Once the listener is fired, the provided callback
* is fired with the following params:
*
* ```js
* $animate.on('enter', container,
* function callback(element, phase) {
* // cool we detected an enter animation within the container
* }
* );
* ```
*
*
* **Note**: Generally, the events that are fired correspond 1:1 to `$animate` method names,
* e.g. {@link ng.$animate#addClass addClass()} will fire `addClass`, and {@link ng.ngClass}
* will fire `addClass` if classes are added, and `removeClass` if classes are removed.
* However, there are two exceptions:
*
*
*
if both an {@link ng.$animate#addClass addClass()} and a
* {@link ng.$animate#removeClass removeClass()} action are performed during the same
* animation, the event fired will be `setClass`. This is true even for `ngClass`.
*
an {@link ng.$animate#animate animate()} call that adds and removes classes will fire
* the `setClass` event, but if it either removes or adds classes,
* it will fire `animate` instead.
*
*
*
*
* @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
* @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
* as well as among its children
* @param {Function} callback the callback function that will be fired when the listener is triggered.
*
* The arguments present in the callback function are:
* * `element` - The captured DOM element that the animation was fired on.
* * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
* * `data` - an object with these properties:
* * addClass - `{string|null}` - space-separated CSS classes to add to the element
* * removeClass - `{string|null}` - space-separated CSS classes to remove from the element
* * from - `{Object|null}` - CSS properties & values at the beginning of the animation
* * to - `{Object|null}` - CSS properties & values at the end of the animation
*
* Note that the callback does not trigger a scope digest. Wrap your call into a
* {@link $rootScope.Scope#$apply scope.$apply} to propagate changes to the scope.
*/
on: $$animateQueue.on,
/**
*
* @ngdoc method
* @name $animate#off
* @kind function
* @description Deregisters an event listener based on the event which has been associated with the provided element. This method
* can be used in three different ways depending on the arguments:
*
* ```js
* // remove all the animation event listeners listening for `enter`
* $animate.off('enter');
*
* // remove listeners for all animation events from the container element
* $animate.off(container);
*
* // remove all the animation event listeners listening for `enter` on the given element and its children
* $animate.off('enter', container);
*
* // remove the event listener function provided by `callback` that is set
* // to listen for `enter` on the given `container` as well as its children
* $animate.off('enter', container, callback);
* ```
*
* @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,
* addClass, removeClass, etc...), or the container element. If it is the element, all other
* arguments are ignored.
* @param {DOMElement=} container the container element the event listener was placed on
* @param {Function=} callback the callback function that was registered as the listener
*/
off: $$animateQueue.off,
/**
* @ngdoc method
* @name $animate#pin
* @kind function
* @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
* outside of the DOM structure of the AngularJS application. By doing so, any animation triggered via `$animate` can be issued on the
* element despite being outside the realm of the application or within another application. Say for example if the application
* was bootstrapped on an element that is somewhere inside of the `` tag, but we wanted to allow for an element to be situated
* as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
* that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
*
* Note that this feature is only active when the `ngAnimate` module is used.
*
* @param {DOMElement} element the external element that will be pinned
* @param {DOMElement} parentElement the host parent element that will be associated with the external element
*/
pin: $$animateQueue.pin,
/**
*
* @ngdoc method
* @name $animate#enabled
* @kind function
* @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
* function can be called in four ways:
*
* ```js
* // returns true or false
* $animate.enabled();
*
* // changes the enabled state for all animations
* $animate.enabled(false);
* $animate.enabled(true);
*
* // returns true or false if animations are enabled for an element
* $animate.enabled(element);
*
* // changes the enabled state for an element and its children
* $animate.enabled(element, true);
* $animate.enabled(element, false);
* ```
*
* @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
* @param {boolean=} enabled whether or not the animations will be enabled for the element
*
* @return {boolean} whether or not animations are enabled
*/
enabled: $$animateQueue.enabled,
/**
* @ngdoc method
* @name $animate#cancel
* @kind function
* @description Cancels the provided animation and applies the end state of the animation.
* Note that this does not cancel the underlying operation, e.g. the setting of classes or
* adding the element to the DOM.
*
* @param {animationRunner} animationRunner An animation runner returned by an $animate function.
*
* @example
angular.module('animationExample', ['ngAnimate']).component('cancelExample', {
templateUrl: 'template.html',
controller: function($element, $animate) {
this.runner = null;
this.addClass = function() {
this.runner = $animate.addClass($element.find('div'), 'red');
var ctrl = this;
this.runner.finally(function() {
ctrl.runner = null;
});
};
this.removeClass = function() {
this.runner = $animate.removeClass($element.find('div'), 'red');
var ctrl = this;
this.runner.finally(function() {
ctrl.runner = null;
});
};
this.cancel = function() {
$animate.cancel(this.runner);
};
}
});
CSS-Animated Text
.red-add, .red-remove {
transition: all 4s cubic-bezier(0.250, 0.460, 0.450, 0.940);
}
.red,
.red-add.red-add-active {
color: #FF0000;
font-size: 40px;
}
.red-remove.red-remove-active {
font-size: 10px;
color: black;
}
*/
cancel: function(runner) {
if (runner.cancel) {
runner.cancel();
}
},
/**
*
* @ngdoc method
* @name $animate#enter
* @kind function
* @description Inserts the element into the DOM either after the `after` element (if provided) or
* as the first child within the `parent` element and then triggers an animation.
* A promise is returned that will be resolved during the next digest once the animation
* has completed.
*
* @param {DOMElement} element the element which will be inserted into the DOM
* @param {DOMElement} parent the parent element which will append the element as
* a child (so long as the after element is not present)
* @param {DOMElement=} after the sibling element after which the element will be appended
* @param {object=} options an optional collection of options/styles that will be applied to the element.
* The object can have the following properties:
*
* - **addClass** - `{string}` - space-separated CSS classes to add to element
* - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
* - **removeClass** - `{string}` - space-separated CSS classes to remove from element
* - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
*
* @return {Runner} the animation runner
*/
enter: function(element, parent, after, options) {
parent = parent && jqLite(parent);
after = after && jqLite(after);
parent = parent || after.parent();
domInsert(element, parent, after);
return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
},
/**
*
* @ngdoc method
* @name $animate#move
* @kind function
* @description Inserts (moves) the element into its new position in the DOM either after
* the `after` element (if provided) or as the first child within the `parent` element
* and then triggers an animation. A promise is returned that will be resolved
* during the next digest once the animation has completed.
*
* @param {DOMElement} element the element which will be moved into the new DOM position
* @param {DOMElement} parent the parent element which will append the element as
* a child (so long as the after element is not present)
* @param {DOMElement=} after the sibling element after which the element will be appended
* @param {object=} options an optional collection of options/styles that will be applied to the element.
* The object can have the following properties:
*
* - **addClass** - `{string}` - space-separated CSS classes to add to element
* - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
* - **removeClass** - `{string}` - space-separated CSS classes to remove from element
* - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
*
* @return {Runner} the animation runner
*/
move: function(element, parent, after, options) {
parent = parent && jqLite(parent);
after = after && jqLite(after);
parent = parent || after.parent();
domInsert(element, parent, after);
return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
},
/**
* @ngdoc method
* @name $animate#leave
* @kind function
* @description Triggers an animation and then removes the element from the DOM.
* When the function is called a promise is returned that will be resolved during the next
* digest once the animation has completed.
*
* @param {DOMElement} element the element which will be removed from the DOM
* @param {object=} options an optional collection of options/styles that will be applied to the element.
* The object can have the following properties:
*
* - **addClass** - `{string}` - space-separated CSS classes to add to element
* - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
* - **removeClass** - `{string}` - space-separated CSS classes to remove from element
* - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
*
* @return {Runner} the animation runner
*/
leave: function(element, options) {
return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
element.remove();
});
},
/**
* @ngdoc method
* @name $animate#addClass
* @kind function
*
* @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
* execution, the addClass operation will only be handled after the next digest and it will not trigger an
* animation if element already contains the CSS class or if the class is removed at a later step.
* Note that class-based animations are treated differently compared to structural animations
* (like enter, move and leave) since the CSS classes may be added/removed at different points
* depending if CSS or JavaScript animations are used.
*
* @param {DOMElement} element the element which the CSS classes will be applied to
* @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
* @param {object=} options an optional collection of options/styles that will be applied to the element.
* The object can have the following properties:
*
* - **removeClass** - `{string}` - space-separated CSS classes to remove from element
* - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
* - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
*
* @return {Runner} animationRunner the animation runner
*/
addClass: function(element, className, options) {
options = prepareAnimateOptions(options);
options.addClass = mergeClasses(options.addclass, className);
return $$animateQueue.push(element, 'addClass', options);
},
/**
* @ngdoc method
* @name $animate#removeClass
* @kind function
*
* @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
* execution, the removeClass operation will only be handled after the next digest and it will not trigger an
* animation if element does not contain the CSS class or if the class is added at a later step.
* Note that class-based animations are treated differently compared to structural animations
* (like enter, move and leave) since the CSS classes may be added/removed at different points
* depending if CSS or JavaScript animations are used.
*
* @param {DOMElement} element the element which the CSS classes will be applied to
* @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
* @param {object=} options an optional collection of options/styles that will be applied to the element.
* The object can have the following properties:
*
* - **addClass** - `{string}` - space-separated CSS classes to add to element
* - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
* - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
*
* @return {Runner} the animation runner
*/
removeClass: function(element, className, options) {
options = prepareAnimateOptions(options);
options.removeClass = mergeClasses(options.removeClass, className);
return $$animateQueue.push(element, 'removeClass', options);
},
/**
* @ngdoc method
* @name $animate#setClass
* @kind function
*
* @description Performs both the addition and removal of a CSS classes on an element and (during the process)
* triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
* `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
* passed. Note that class-based animations are treated differently compared to structural animations
* (like enter, move and leave) since the CSS classes may be added/removed at different points
* depending if CSS or JavaScript animations are used.
*
* @param {DOMElement} element the element which the CSS classes will be applied to
* @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
* @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
* @param {object=} options an optional collection of options/styles that will be applied to the element.
* The object can have the following properties:
*
* - **addClass** - `{string}` - space-separated CSS classes to add to element
* - **removeClass** - `{string}` - space-separated CSS classes to remove from element
* - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
* - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
*
* @return {Runner} the animation runner
*/
setClass: function(element, add, remove, options) {
options = prepareAnimateOptions(options);
options.addClass = mergeClasses(options.addClass, add);
options.removeClass = mergeClasses(options.removeClass, remove);
return $$animateQueue.push(element, 'setClass', options);
},
/**
* @ngdoc method
* @name $animate#animate
* @kind function
*
* @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
* If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
* on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and
* `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
* style in `to`, the style in `from` is applied immediately, and no animation is run.
* If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
* method (or as part of the `options` parameter):
*
* ```js
* ngModule.animation('.my-inline-animation', function() {
* return {
* animate : function(element, from, to, done, options) {
* //animation
* done();
* }
* }
* });
* ```
*
* @param {DOMElement} element the element which the CSS styles will be applied to
* @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
* @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
* @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
* this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
* (Note that if no animation is detected then this value will not be applied to the element.)
* @param {object=} options an optional collection of options/styles that will be applied to the element.
* The object can have the following properties:
*
* - **addClass** - `{string}` - space-separated CSS classes to add to element
* - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
* - **removeClass** - `{string}` - space-separated CSS classes to remove from element
* - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
*
* @return {Runner} the animation runner
*/
animate: function(element, from, to, className, options) {
options = prepareAnimateOptions(options);
options.from = options.from ? extend(options.from, from) : from;
options.to = options.to ? extend(options.to, to) : to;
className = className || 'ng-inline-animate';
options.tempClasses = mergeClasses(options.tempClasses, className);
return $$animateQueue.push(element, 'animate', options);
}
};
}];
}];
var $$AnimateAsyncRunFactoryProvider = /** @this */ function() {
this.$get = ['$$rAF', function($$rAF) {
var waitQueue = [];
function waitForTick(fn) {
waitQueue.push(fn);
if (waitQueue.length > 1) return;
$$rAF(function() {
for (var i = 0; i < waitQueue.length; i++) {
waitQueue[i]();
}
waitQueue = [];
});
}
return function() {
var passed = false;
waitForTick(function() {
passed = true;
});
return function(callback) {
if (passed) {
callback();
} else {
waitForTick(callback);
}
};
};
}];
};
var $$AnimateRunnerFactoryProvider = /** @this */ function() {
this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout',
function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) {
var INITIAL_STATE = 0;
var DONE_PENDING_STATE = 1;
var DONE_COMPLETE_STATE = 2;
AnimateRunner.chain = function(chain, callback) {
var index = 0;
next();
function next() {
if (index === chain.length) {
callback(true);
return;
}
chain[index](function(response) {
if (response === false) {
callback(false);
return;
}
index++;
next();
});
}
};
AnimateRunner.all = function(runners, callback) {
var count = 0;
var status = true;
forEach(runners, function(runner) {
runner.done(onProgress);
});
function onProgress(response) {
status = status && response;
if (++count === runners.length) {
callback(status);
}
}
};
function AnimateRunner(host) {
this.setHost(host);
var rafTick = $$animateAsyncRun();
var timeoutTick = function(fn) {
$timeout(fn, 0, false);
};
this._doneCallbacks = [];
this._tick = function(fn) {
if ($$isDocumentHidden()) {
timeoutTick(fn);
} else {
rafTick(fn);
}
};
this._state = 0;
}
AnimateRunner.prototype = {
setHost: function(host) {
this.host = host || {};
},
done: function(fn) {
if (this._state === DONE_COMPLETE_STATE) {
fn();
} else {
this._doneCallbacks.push(fn);
}
},
progress: noop,
getPromise: function() {
if (!this.promise) {
var self = this;
this.promise = $q(function(resolve, reject) {
self.done(function(status) {
if (status === false) {
reject();
} else {
resolve();
}
});
});
}
return this.promise;
},
then: function(resolveHandler, rejectHandler) {
return this.getPromise().then(resolveHandler, rejectHandler);
},
'catch': function(handler) {
return this.getPromise()['catch'](handler);
},
'finally': function(handler) {
return this.getPromise()['finally'](handler);
},
pause: function() {
if (this.host.pause) {
this.host.pause();
}
},
resume: function() {
if (this.host.resume) {
this.host.resume();
}
},
end: function() {
if (this.host.end) {
this.host.end();
}
this._resolve(true);
},
cancel: function() {
if (this.host.cancel) {
this.host.cancel();
}
this._resolve(false);
},
complete: function(response) {
var self = this;
if (self._state === INITIAL_STATE) {
self._state = DONE_PENDING_STATE;
self._tick(function() {
self._resolve(response);
});
}
},
_resolve: function(response) {
if (this._state !== DONE_COMPLETE_STATE) {
forEach(this._doneCallbacks, function(fn) {
fn(response);
});
this._doneCallbacks.length = 0;
this._state = DONE_COMPLETE_STATE;
}
}
};
return AnimateRunner;
}];
};
/* exported $CoreAnimateCssProvider */
/**
* @ngdoc service
* @name $animateCss
* @kind object
* @this
*
* @description
* This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
* then the `$animateCss` service will actually perform animations.
*
* Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
*/
var $CoreAnimateCssProvider = function() {
this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
return function(element, initialOptions) {
// all of the animation functions should create
// a copy of the options data, however, if a
// parent service has already created a copy then
// we should stick to using that
var options = initialOptions || {};
if (!options.$$prepared) {
options = copy(options);
}
// there is no point in applying the styles since
// there is no animation that goes on at all in
// this version of $animateCss.
if (options.cleanupStyles) {
options.from = options.to = null;
}
if (options.from) {
element.css(options.from);
options.from = null;
}
var closed, runner = new $$AnimateRunner();
return {
start: run,
end: run
};
function run() {
$$rAF(function() {
applyAnimationContents();
if (!closed) {
runner.complete();
}
closed = true;
});
return runner;
}
function applyAnimationContents() {
if (options.addClass) {
element.addClass(options.addClass);
options.addClass = null;
}
if (options.removeClass) {
element.removeClass(options.removeClass);
options.removeClass = null;
}
if (options.to) {
element.css(options.to);
options.to = null;
}
}
};
}];
};
/* global getHash: true, stripHash: false */
function getHash(url) {
var index = url.indexOf('#');
return index === -1 ? '' : url.substr(index);
}
function trimEmptyHash(url) {
return url.replace(/#$/, '');
}
/**
* ! This is a private undocumented service !
*
* @name $browser
* @requires $log
* @description
* This object has two goals:
*
* - hide all the global state in the browser caused by the window object
* - abstract away all the browser specific features and inconsistencies
*
* For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
* service, which can be used for convenient testing of the application without the interaction with
* the real browser apis.
*/
/**
* @param {object} window The global window object.
* @param {object} document jQuery wrapped document.
* @param {object} $log window.console or an object with the same interface.
* @param {object} $sniffer $sniffer service
*/
function Browser(window, document, $log, $sniffer, $$taskTrackerFactory) {
var self = this,
location = window.location,
history = window.history,
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
pendingDeferIds = {},
taskTracker = $$taskTrackerFactory($log);
self.isMock = false;
//////////////////////////////////////////////////////////////
// Task-tracking API
//////////////////////////////////////////////////////////////
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = taskTracker.completeTask;
self.$$incOutstandingRequestCount = taskTracker.incTaskCount;
// TODO(vojta): prefix this method with $$ ?
self.notifyWhenNoOutstandingRequests = taskTracker.notifyWhenNoPendingTasks;
//////////////////////////////////////////////////////////////
// URL API
//////////////////////////////////////////////////////////////
var cachedState, lastHistoryState,
lastBrowserUrl = location.href,
baseElement = document.find('base'),
pendingLocation = null,
getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
try {
return history.state;
} catch (e) {
// MSIE can reportedly throw when there is no state (UNCONFIRMED).
}
};
cacheState();
/**
* @name $browser#url
*
* @description
* GETTER:
* Without any argument, this method just returns current value of `location.href` (with a
* trailing `#` stripped of if the hash is empty).
*
* SETTER:
* With at least one argument, this method sets url to new value.
* If html5 history api supported, `pushState`/`replaceState` is used, otherwise
* `location.href`/`location.replace` is used.
* Returns its own instance to allow chaining.
*
* NOTE: this api is intended for use only by the `$location` service. Please use the
* {@link ng.$location $location service} to change url.
*
* @param {string} url New url (when used as setter)
* @param {boolean=} replace Should new url replace current history record?
* @param {object=} state State object to use with `pushState`/`replaceState`
*/
self.url = function(url, replace, state) {
// In modern browsers `history.state` is `null` by default; treating it separately
// from `undefined` would cause `$browser.url('/foo')` to change `history.state`
// to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
if (isUndefined(state)) {
state = null;
}
// Android Browser BFCache causes location, history reference to become stale.
if (location !== window.location) location = window.location;
if (history !== window.history) history = window.history;
// setter
if (url) {
var sameState = lastHistoryState === state;
// Normalize the inputted URL
url = urlResolve(url).href;
// Don't change anything if previous and current URLs and states match. This also prevents
// IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
// See https://github.com/angular/angular.js/commit/ffb2701
if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
return self;
}
var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
lastBrowserUrl = url;
lastHistoryState = state;
// Don't use history API if only the hash changed
// due to a bug in IE10/IE11 which leads
// to not firing a `hashchange` nor `popstate` event
// in some cases (see #9143).
if ($sniffer.history && (!sameBase || !sameState)) {
history[replace ? 'replaceState' : 'pushState'](state, '', url);
cacheState();
} else {
if (!sameBase) {
pendingLocation = url;
}
if (replace) {
location.replace(url);
} else if (!sameBase) {
location.href = url;
} else {
location.hash = getHash(url);
}
if (location.href !== url) {
pendingLocation = url;
}
}
if (pendingLocation) {
pendingLocation = url;
}
return self;
// getter
} else {
// - pendingLocation is needed as browsers don't allow to read out
// the new location.href if a reload happened or if there is a bug like in iOS 9 (see
// https://openradar.appspot.com/22186109).
return trimEmptyHash(pendingLocation || location.href);
}
};
/**
* @name $browser#state
*
* @description
* This method is a getter.
*
* Return history.state or null if history.state is undefined.
*
* @returns {object} state
*/
self.state = function() {
return cachedState;
};
var urlChangeListeners = [],
urlChangeInit = false;
function cacheStateAndFireUrlChange() {
pendingLocation = null;
fireStateOrUrlChange();
}
// This variable should be used *only* inside the cacheState function.
var lastCachedState = null;
function cacheState() {
// This should be the only place in $browser where `history.state` is read.
cachedState = getCurrentState();
cachedState = isUndefined(cachedState) ? null : cachedState;
// Prevent callbacks fo fire twice if both hashchange & popstate were fired.
if (equals(cachedState, lastCachedState)) {
cachedState = lastCachedState;
}
lastCachedState = cachedState;
lastHistoryState = cachedState;
}
function fireStateOrUrlChange() {
var prevLastHistoryState = lastHistoryState;
cacheState();
if (lastBrowserUrl === self.url() && prevLastHistoryState === cachedState) {
return;
}
lastBrowserUrl = self.url();
lastHistoryState = cachedState;
forEach(urlChangeListeners, function(listener) {
listener(self.url(), cachedState);
});
}
/**
* @name $browser#onUrlChange
*
* @description
* Register callback function that will be called, when url changes.
*
* It's only called when the url is changed from outside of AngularJS:
* - user types different url into address bar
* - user clicks on history (forward/back) button
* - user clicks on a link
*
* It's not called when url is changed by $browser.url() method
*
* The listener gets called with new url as parameter.
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to monitor url changes in AngularJS apps.
*
* @param {function(string)} listener Listener function to be called when url changes.
* @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
*/
self.onUrlChange = function(callback) {
// TODO(vojta): refactor to use node's syntax for events
if (!urlChangeInit) {
// We listen on both (hashchange/popstate) when available, as some browsers don't
// fire popstate when user changes the address bar and don't fire hashchange when url
// changed by push/replaceState
// html5 history api - popstate event
if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
// hashchange event
jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
urlChangeInit = true;
}
urlChangeListeners.push(callback);
return callback;
};
/**
* @private
* Remove popstate and hashchange handler from window.
*
* NOTE: this api is intended for use only by $rootScope.
*/
self.$$applicationDestroyed = function() {
jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
};
/**
* Checks whether the url has changed outside of AngularJS.
* Needs to be exported to be able to check for changes that have been done in sync,
* as hashchange/popstate events fire in async.
*/
self.$$checkUrlChange = fireStateOrUrlChange;
//////////////////////////////////////////////////////////////
// Misc API
//////////////////////////////////////////////////////////////
/**
* @name $browser#baseHref
*
* @description
* Returns current
* (always relative - without domain)
*
* @returns {string} The current base href
*/
self.baseHref = function() {
var href = baseElement.attr('href');
return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : '';
};
/**
* @name $browser#defer
* @param {function()} fn A function, who's execution should be deferred.
* @param {number=} [delay=0] Number of milliseconds to defer the function execution.
* @param {string=} [taskType=DEFAULT_TASK_TYPE] The type of task that is deferred.
* @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
*
* @description
* Executes a fn asynchronously via `setTimeout(fn, delay)`.
*
* Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
* `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
* via `$browser.defer.flush()`.
*
*/
self.defer = function(fn, delay, taskType) {
var timeoutId;
delay = delay || 0;
taskType = taskType || taskTracker.DEFAULT_TASK_TYPE;
taskTracker.incTaskCount(taskType);
timeoutId = setTimeout(function() {
delete pendingDeferIds[timeoutId];
taskTracker.completeTask(fn, taskType);
}, delay);
pendingDeferIds[timeoutId] = taskType;
return timeoutId;
};
/**
* @name $browser#defer.cancel
*
* @description
* Cancels a deferred task identified with `deferId`.
*
* @param {*} deferId Token returned by the `$browser.defer` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
* canceled.
*/
self.defer.cancel = function(deferId) {
if (pendingDeferIds.hasOwnProperty(deferId)) {
var taskType = pendingDeferIds[deferId];
delete pendingDeferIds[deferId];
clearTimeout(deferId);
taskTracker.completeTask(noop, taskType);
return true;
}
return false;
};
}
/** @this */
function $BrowserProvider() {
this.$get = ['$window', '$log', '$sniffer', '$document', '$$taskTrackerFactory',
function($window, $log, $sniffer, $document, $$taskTrackerFactory) {
return new Browser($window, $document, $log, $sniffer, $$taskTrackerFactory);
}];
}
/**
* @ngdoc service
* @name $cacheFactory
* @this
*
* @description
* Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
* them.
*
* ```js
*
* var cache = $cacheFactory('cacheId');
* expect($cacheFactory.get('cacheId')).toBe(cache);
* expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
*
* cache.put("key", "value");
* cache.put("another key", "another value");
*
* // We've specified no options on creation
* expect(cache.info()).toEqual({id: 'cacheId', size: 2});
*
* ```
*
*
* @param {string} cacheId Name or id of the newly created cache.
* @param {object=} options Options object that specifies the cache behavior. Properties:
*
* - `{number=}` `capacity` — turns the cache into LRU cache.
*
* @returns {object} Newly created cache object with the following set of methods:
*
* - `{object}` `info()` — Returns id, size, and options of cache.
* - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
* it.
* - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
* - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
* - `{void}` `removeAll()` — Removes all cached values.
* - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
*
* @example
Cached Values
:
Cache Info
:
angular.module('cacheExampleApp', []).
controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
$scope.keys = [];
$scope.cache = $cacheFactory('cacheId');
$scope.put = function(key, value) {
if (angular.isUndefined($scope.cache.get(key))) {
$scope.keys.push(key);
}
$scope.cache.put(key, angular.isUndefined(value) ? null : value);
};
}]);
p {
margin: 10px 0 3px;
}
*/
function $CacheFactoryProvider() {
this.$get = function() {
var caches = {};
function cacheFactory(cacheId, options) {
if (cacheId in caches) {
throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId);
}
var size = 0,
stats = extend({}, options, {id: cacheId}),
data = createMap(),
capacity = (options && options.capacity) || Number.MAX_VALUE,
lruHash = createMap(),
freshEnd = null,
staleEnd = null;
/**
* @ngdoc type
* @name $cacheFactory.Cache
*
* @description
* A cache object used to store and retrieve data, primarily used by
* {@link $templateRequest $templateRequest} and the {@link ng.directive:script script}
* directive to cache templates and other data.
*
* ```js
* angular.module('superCache')
* .factory('superCache', ['$cacheFactory', function($cacheFactory) {
* return $cacheFactory('super-cache');
* }]);
* ```
*
* Example test:
*
* ```js
* it('should behave like a cache', inject(function(superCache) {
* superCache.put('key', 'value');
* superCache.put('another key', 'another value');
*
* expect(superCache.info()).toEqual({
* id: 'super-cache',
* size: 2
* });
*
* superCache.remove('another key');
* expect(superCache.get('another key')).toBeUndefined();
*
* superCache.removeAll();
* expect(superCache.info()).toEqual({
* id: 'super-cache',
* size: 0
* });
* }));
* ```
*/
return (caches[cacheId] = {
/**
* @ngdoc method
* @name $cacheFactory.Cache#put
* @kind function
*
* @description
* Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
* retrieved later, and incrementing the size of the cache if the key was not already
* present in the cache. If behaving like an LRU cache, it will also remove stale
* entries from the set.
*
* It will not insert undefined values into the cache.
*
* @param {string} key the key under which the cached data is stored.
* @param {*} value the value to store alongside the key. If it is undefined, the key
* will not be stored.
* @returns {*} the value stored.
*/
put: function(key, value) {
if (isUndefined(value)) return;
if (capacity < Number.MAX_VALUE) {
var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
refresh(lruEntry);
}
if (!(key in data)) size++;
data[key] = value;
if (size > capacity) {
this.remove(staleEnd.key);
}
return value;
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#get
* @kind function
*
* @description
* Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
*
* @param {string} key the key of the data to be retrieved
* @returns {*} the value stored.
*/
get: function(key) {
if (capacity < Number.MAX_VALUE) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
refresh(lruEntry);
}
return data[key];
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#remove
* @kind function
*
* @description
* Removes an entry from the {@link $cacheFactory.Cache Cache} object.
*
* @param {string} key the key of the entry to be removed
*/
remove: function(key) {
if (capacity < Number.MAX_VALUE) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
if (lruEntry === freshEnd) freshEnd = lruEntry.p;
if (lruEntry === staleEnd) staleEnd = lruEntry.n;
link(lruEntry.n,lruEntry.p);
delete lruHash[key];
}
if (!(key in data)) return;
delete data[key];
size--;
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#removeAll
* @kind function
*
* @description
* Clears the cache object of any entries.
*/
removeAll: function() {
data = createMap();
size = 0;
lruHash = createMap();
freshEnd = staleEnd = null;
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#destroy
* @kind function
*
* @description
* Destroys the {@link $cacheFactory.Cache Cache} object entirely,
* removing it from the {@link $cacheFactory $cacheFactory} set.
*/
destroy: function() {
data = null;
stats = null;
lruHash = null;
delete caches[cacheId];
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#info
* @kind function
*
* @description
* Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
*
* @returns {object} an object with the following properties:
*
*
**id**: the id of the cache instance
*
**size**: the number of entries kept in the cache instance
*
**...**: any additional properties from the options object when creating the
* cache.
*
*/
info: function() {
return extend({}, stats, {size: size});
}
});
/**
* makes the `entry` the freshEnd of the LRU linked list
*/
function refresh(entry) {
if (entry !== freshEnd) {
if (!staleEnd) {
staleEnd = entry;
} else if (staleEnd === entry) {
staleEnd = entry.n;
}
link(entry.n, entry.p);
link(entry, freshEnd);
freshEnd = entry;
freshEnd.n = null;
}
}
/**
* bidirectionally links two entries of the LRU linked list
*/
function link(nextEntry, prevEntry) {
if (nextEntry !== prevEntry) {
if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
}
}
}
/**
* @ngdoc method
* @name $cacheFactory#info
*
* @description
* Get information about all the caches that have been created
*
* @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
*/
cacheFactory.info = function() {
var info = {};
forEach(caches, function(cache, cacheId) {
info[cacheId] = cache.info();
});
return info;
};
/**
* @ngdoc method
* @name $cacheFactory#get
*
* @description
* Get access to a cache object by the `cacheId` used when it was created.
*
* @param {string} cacheId Name or id of a cache to access.
* @returns {object} Cache object identified by the cacheId or undefined if no such cache.
*/
cacheFactory.get = function(cacheId) {
return caches[cacheId];
};
return cacheFactory;
};
}
/**
* @ngdoc service
* @name $templateCache
* @this
*
* @description
* `$templateCache` is a {@link $cacheFactory.Cache Cache object} created by the
* {@link ng.$cacheFactory $cacheFactory}.
*
* The first time a template is used, it is loaded in the template cache for quick retrieval. You
* can load templates directly into the cache in a `script` tag, by using {@link $templateRequest},
* or by consuming the `$templateCache` service directly.
*
* Adding via the `script` tag:
*
* ```html
*
* ```
*
* **Note:** the `script` tag containing the template does not need to be included in the `head` of
* the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (e.g.
* element with {@link ngApp} attribute), otherwise the template will be ignored.
*
* Adding via the `$templateCache` service:
*
* ```js
* var myApp = angular.module('myApp', []);
* myApp.run(function($templateCache) {
* $templateCache.put('templateId.html', 'This is the content of the template');
* });
* ```
*
* To retrieve the template later, simply use it in your component:
* ```js
* myApp.component('myComponent', {
* templateUrl: 'templateId.html'
* });
* ```
*
* or get it via the `$templateCache` service:
* ```js
* $templateCache.get('templateId.html')
* ```
*
*/
function $TemplateCacheProvider() {
this.$get = ['$cacheFactory', function($cacheFactory) {
return $cacheFactory('templates');
}];
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables like document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
*
* DOM-related variables:
*
* - "node" - DOM Node
* - "element" - DOM Element or Node
* - "$node" or "$element" - jqLite-wrapped node or element
*
*
* Compiler related stuff:
*
* - "linkFn" - linking fn of a single directive
* - "nodeLinkFn" - function that aggregates all linking fns for a particular node
* - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
* - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
*/
/**
* @ngdoc service
* @name $compile
* @kind function
*
* @description
* Compiles an HTML string or DOM into a template and produces a template function, which
* can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
*
* The compilation is a process of walking the DOM tree and matching DOM elements to
* {@link ng.$compileProvider#directive directives}.
*
*
* **Note:** This document is an in-depth reference of all directive options.
* For a gentle introduction to directives with examples of common use cases,
* see the {@link guide/directive directive guide}.
*
*
* ## Comprehensive Directive API
*
* There are many different options for a directive.
*
* The difference resides in the return value of the factory function.
* You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)}
* that defines the directive properties, or just the `postLink` function (all other properties will have
* the default values).
*
*
* **Best Practice:** It's recommended to use the "directive definition object" form.
*
* **Note:** Any unspecified options will use the default value. You can see the default values below.
*
*
* Therefore the above can be simplified as:
*
* ```js
* var myModule = angular.module(...);
*
* myModule.directive('directiveName', function factory(injectables) {
* var directiveDefinitionObject = {
* link: function postLink(scope, iElement, iAttrs) { ... }
* };
* return directiveDefinitionObject;
* // or
* // return function postLink(scope, iElement, iAttrs) { ... }
* });
* ```
*
* ### Life-cycle hooks
* Directive controllers can provide the following methods that are called by AngularJS at points in the life-cycle of the
* directive:
* * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
* had their bindings initialized (and before the pre & post linking functions for the directives on
* this element). This is a good place to put initialization code for your controller.
* * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
* `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
* object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a
* component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will
* also be called when your bindings are initialized.
* * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on
* changes. Any actions that you wish to take in response to the changes that you detect must be
* invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook
* could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not
* be detected by AngularJS's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments;
* if detecting changes, you must store the previous value(s) for comparison to the current values.
* * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
* external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
* the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
* components will have their `$onDestroy()` hook called before child components.
* * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
* function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
* Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
* they are waiting for their template to load asynchronously and their own compilation and linking has been
* suspended until that occurs.
*
* #### Comparison with life-cycle hooks in the new Angular
* The new Angular also uses life-cycle hooks for its components. While the AngularJS life-cycle hooks are similar there are
* some differences that you should be aware of, especially when it comes to moving your code from AngularJS to Angular:
*
* * AngularJS hooks are prefixed with `$`, such as `$onInit`. Angular hooks are prefixed with `ng`, such as `ngOnInit`.
* * AngularJS hooks can be defined on the controller prototype or added to the controller inside its constructor.
* In Angular you can only define hooks on the prototype of the Component class.
* * Due to the differences in change-detection, you may get many more calls to `$doCheck` in AngularJS than you would to
* `ngDoCheck` in Angular.
* * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be
* propagated throughout the application.
* Angular does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an
* error or do nothing depending upon the state of `enableProdMode()`.
*
* #### Life-cycle hook examples
*
* This example shows how you can check for mutations to a Date object even though the identity of the object
* has not changed.
*
*
*
* angular.module('do-check-module', [])
* .component('app', {
* template:
* 'Month: ' +
* 'Date: {{ $ctrl.date }}' +
* '',
* controller: function() {
* this.date = new Date();
* this.month = this.date.getMonth();
* this.updateDate = function() {
* this.date.setMonth(this.month);
* };
* }
* })
* .component('test', {
* bindings: { date: '<' },
* template:
* '
{{ $ctrl.log | json }}
',
* controller: function() {
* var previousValue;
* this.log = [];
* this.$doCheck = function() {
* var currentValue = this.date && this.date.valueOf();
* if (previousValue !== currentValue) {
* this.log.push('doCheck: date mutated: ' + this.date);
* previousValue = currentValue;
* }
* };
* }
* });
*
*
*
*
*
*
* This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the
* actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large
* arrays or objects can have a negative impact on your application performance.)
*
*
*
*
',
* controller: function() {
* this.log = [];
*
* this.$doCheck = function() {
* if (this.items_ref !== this.items) {
* this.log.push('doCheck: items changed');
* this.items_ref = this.items;
* }
* if (!angular.equals(this.items_clone, this.items)) {
* this.log.push('doCheck: items mutated');
* this.items_clone = angular.copy(this.items);
* }
* };
* }
* });
*
*
*
*
* ### Directive Definition Object
*
* The directive definition object provides instructions to the {@link ng.$compile
* compiler}. The attributes are:
*
* #### `multiElement`
* When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between
* nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
* together as the directive elements. It is recommended that this feature be used on directives
* which are not strictly behavioral (such as {@link ngClick}), and which
* do not manipulate or replace child nodes (such as {@link ngInclude}).
*
* #### `priority`
* When there are multiple directives defined on a single DOM element, sometimes it
* is necessary to specify the order in which the directives are applied. The `priority` is used
* to sort the directives before their `compile` functions get called. Priority is defined as a
* number. Directives with greater numerical `priority` are compiled first. Pre-link functions
* are also run in priority order, but post-link functions are run in reverse order. The order
* of directives with the same priority is undefined. The default priority is `0`.
*
* #### `terminal`
* If set to true then the current `priority` will be the last set of directives
* which will execute (any directives at the current priority will still execute
* as the order of execution on same `priority` is undefined). Note that expressions
* and other directives used in the directive's template will also be excluded from execution.
*
* #### `scope`
* The scope property can be `false`, `true`, or an object:
*
* * **`false` (default):** No scope will be created for the directive. The directive will use its
* parent's scope.
*
* * **`true`:** A new child scope that prototypically inherits from its parent will be created for
* the directive's element. If multiple directives on the same element request a new scope,
* only one new scope is created.
*
* * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's template.
* The 'isolate' scope differs from normal scope in that it does not prototypically
* inherit from its parent scope. This is useful when creating reusable components, which should not
* accidentally read or modify data in the parent scope. Note that an isolate scope
* directive without a `template` or `templateUrl` will not apply the isolate scope
* to its children elements.
*
* The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
* directive's element. These local properties are useful for aliasing values for templates. The keys in
* the object hash map to the name of the property on the isolate scope; the values define how the property
* is bound to the parent scope, via matching attributes on the directive's element:
*
* * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
* always a string since DOM attributes are strings. If no `attr` name is specified then the
* attribute name is assumed to be the same as the local name. Given `` and the isolate scope definition `scope: { localName:'@myAttr' }`,
* the directive's scope property `localName` will reflect the interpolated value of `hello
* {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
* scope. The `name` is read from the parent scope (not the directive's scope).
*
* * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
* passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
* If no `attr` name is specified then the attribute name is assumed to be the same as the local
* name. Given `` and the isolate scope definition `scope: {
* localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
* value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
* `localModel` and vice versa. If the binding expression is non-assignable, or if the attribute
* isn't optional and doesn't exist, an exception
* ({@link error/$compile/nonassign `$compile:nonassign`}) will be thrown upon discovering changes
* to the local value, since it will be impossible to sync them back to the parent scope.
*
* By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
* method is used for tracking changes, and the equality check is based on object identity.
* However, if an object literal or an array literal is passed as the binding expression, the
* equality check is done by value (using the {@link angular.equals} function). It's also possible
* to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
* `$watchCollection`}: use `=*` or `=*attr`
*
* * `<` or `` and directive definition of
* `scope: { localModel:'` and the isolate scope definition `scope: {
* localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
* the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
* via an expression to the parent scope. This can be done by passing a map of local variable names
* and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
* then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
*
* All 4 kinds of bindings (`@`, `=`, `<`, and `&`) can be made optional by adding `?` to the expression.
* The marker must come after the mode and before the attribute name.
* See the {@link error/$compile/iscp Invalid Isolate Scope Definition error} for definition examples.
* This is useful to refine the interface directives provide.
* One subtle difference between optional and non-optional happens **when the binding attribute is not
* set**:
* - the binding is optional: the property will not be defined
* - the binding is not optional: the property is defined
*
* ```js
*app.directive('testDir', function() {
return {
scope: {
notoptional: '=',
optional: '=?',
},
bindToController: true,
controller: function() {
this.$onInit = function() {
console.log(this.hasOwnProperty('notoptional')) // true
console.log(this.hasOwnProperty('optional')) // false
}
}
}
})
*```
*
*
* ##### Combining directives with different scope defintions
*
* In general it's possible to apply more than one directive to one element, but there might be limitations
* depending on the type of scope required by the directives. The following points will help explain these limitations.
* For simplicity only two directives are taken into account, but it is also applicable for several directives:
*
* * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
* * **child scope** + **no scope** => Both directives will share one single child scope
* * **child scope** + **child scope** => Both directives will share one single child scope
* * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
* its parent's scope
* * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
* be applied to the same element.
* * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
* cannot be applied to the same element.
*
*
* #### `bindToController`
* This property is used to bind scope properties directly to the controller. It can be either
* `true` or an object hash with the same format as the `scope` property.
*
* When an isolate scope is used for a directive (see above), `bindToController: true` will
* allow a component to have its properties bound to the controller, rather than to scope.
*
* After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
* properties. You can access these bindings once they have been initialized by providing a controller method called
* `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
* initialized.
*
* It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
* This will set up the scope bindings to the controller directly. Note that `scope` can still be used
* to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
* scope (useful for component directives).
*
* If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
*
*
* #### `controller`
* Controller constructor function. The controller is instantiated before the
* pre-linking phase and can be accessed by other directives (see
* `require` attribute). This allows the directives to communicate with each other and augment
* each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
*
* * `$scope` - Current scope associated with the element
* * `$element` - Current element
* * `$attrs` - Current attributes object for the element
* * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
* `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
* * `scope`: (optional) override the scope.
* * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
* * `futureParentElement` (optional):
* * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
* * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
* * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
* and when the `cloneLinkingFn` is passed,
* as those elements need to created and cloned in a special way when they are defined outside their
* usual containers (e.g. like `