@shopgate/pwa-core 7.12.3-beta.1 → 7.20.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/classes/AppCommand/index.js +3 -3
- package/classes/AppCommand/spec.js +1 -1
- package/classes/AppCommandRequest/index.js +78 -0
- package/classes/AppPermissionsRequest/AppPermissionsRequest.js +12 -39
- package/classes/AppPermissionsRequest/GetAppPermissionsRequest.js +5 -5
- package/classes/AppPermissionsRequest/RequestAppPermissionsRequest.js +5 -5
- package/classes/Bridge/index.js +1 -1
- package/classes/BrightnessRequest/index.js +4 -4
- package/classes/BrightnessRequest/spec.js +3 -3
- package/classes/BrowserConnector/index.js +19 -19
- package/classes/Conditioner/index.js +4 -4
- package/classes/Conditioner/spec.js +1 -1
- package/classes/DataRequest/index.js +7 -7
- package/classes/DevServerBridge/index.js +2 -2
- package/classes/ErrorManager/index.js +14 -5
- package/classes/ErrorManager/spec.js +1 -1
- package/classes/Event/index.js +12 -9
- package/classes/HttpRequest/index.js +9 -9
- package/classes/PipelineDependencies/index.js +2 -2
- package/classes/PipelineManager/index.js +9 -9
- package/classes/PipelineRequest/index.js +5 -5
- package/classes/PipelineRequest/mock.js +11 -11
- package/classes/PipelineSequence/index.js +2 -2
- package/classes/Request/index.js +8 -8
- package/classes/RequestBuffer/index.js +4 -3
- package/classes/RequestManager/index.js +2 -2
- package/classes/RequestManager/spec.js +1 -1
- package/classes/Scanner/index.js +61 -11
- package/classes/ScannerEvent/index.js +8 -4
- package/classes/ScannerEventHandler/index.js +15 -5
- package/classes/ScannerEventListener/index.js +14 -5
- package/classes/ScannerManager/ScanProcessingError.js +3 -3
- package/classes/ScannerManager/index.js +6 -6
- package/classes/WebStorageRequest/index.js +7 -7
- package/commands/brightness.js +1 -1
- package/commands/scanner.js +2 -2
- package/constants/AppEvents.js +1 -1
- package/constants/AppPermissions.js +18 -4
- package/constants/Trilean.js +3 -0
- package/helpers/index.js +1 -1
- package/helpers/version.js +7 -7
- package/index.js +1 -1
- package/package.json +1 -1
|
@@ -7,7 +7,7 @@ import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGenera
|
|
|
7
7
|
* Sets the command name.
|
|
8
8
|
* @param {string} name The command name.
|
|
9
9
|
* @return {AppCommand}
|
|
10
|
-
*/_createClass(AppCommand,[{key:"setCommandName",value:function setCommandName(name){if(typeof name==='string'){this.name=name;}else{logger.error('Invalid command name',name);}return this;}/**
|
|
10
|
+
*/return _createClass(AppCommand,[{key:"setCommandName",value:function setCommandName(name){if(typeof name==='string'){this.name=name;}else{logger.error('Invalid command name',name);}return this;}/**
|
|
11
11
|
* Sets the command params.
|
|
12
12
|
* @param {Object} [params=null] The command params.
|
|
13
13
|
* @return {AppCommand}
|
|
@@ -28,6 +28,6 @@ import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGenera
|
|
|
28
28
|
* of refactoring within existing code. But it resolves with FALSE in those cases.
|
|
29
29
|
* @param {Object} [params] The command params.
|
|
30
30
|
* @return {Promise<boolean>}
|
|
31
|
-
*/},{key:"dispatch",value:function(){var _dispatch=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(params){var command,appLibVersion,appHasSupport,bridge;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)
|
|
31
|
+
*/},{key:"dispatch",value:function(){var _dispatch=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(params){var command,appLibVersion,appHasSupport,bridge;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:if(params){this.setCommandParams(params);}command=this.buildCommand();// Only proceed if the command is valid.
|
|
32
32
|
if(!(command===null)){_context.next=5;break;}logger.error("Dispatch aborted for invalid command. name: \"".concat(this.name,"\" | params:"),this.params);return _context.abrupt("return",false);case 5:appLibVersion=this.libVersion;appHasSupport=true;// Perform a libVersion check if the flag is active.
|
|
33
|
-
if(!this.checkLibVersion){_context.next=12;break;}_context.next=10;return getLibVersion();case 10:appLibVersion=_context.sent;appHasSupport=isVersionAtLeast(this.libVersion,appLibVersion);case 12:if(appHasSupport){_context.next=15;break;}logger.warn("The command \"".concat(this.name,"\" is not supported by LibVersion (required ").concat(this.libVersion," | current ").concat(appLibVersion,")"));return _context.abrupt("return",false);case 15:bridge=new Bridge();_context.prev=16;bridge.dispatchCommand(command,appLibVersion);this.logCommand();_context.next=25;break;case 21:_context.prev=21;_context.t0=_context["catch"](16);logger.error(_context.t0);return _context.abrupt("return",false);case 25:return _context.abrupt("return",true);case 26:case"end":return _context.stop();}}
|
|
33
|
+
if(!this.checkLibVersion){_context.next=12;break;}_context.next=10;return getLibVersion();case 10:appLibVersion=_context.sent;appHasSupport=isVersionAtLeast(this.libVersion,appLibVersion);case 12:if(appHasSupport){_context.next=15;break;}logger.warn("The command \"".concat(this.name,"\" is not supported by LibVersion (required ").concat(this.libVersion," | current ").concat(appLibVersion,")"));return _context.abrupt("return",false);case 15:bridge=new Bridge();_context.prev=16;bridge.dispatchCommand(command,appLibVersion);this.logCommand();_context.next=25;break;case 21:_context.prev=21;_context.t0=_context["catch"](16);logger.error(_context.t0);return _context.abrupt("return",false);case 25:return _context.abrupt("return",true);case 26:case"end":return _context.stop();}},_callee,this,[[16,21]]);}));function dispatch(_x){return _dispatch.apply(this,arguments);}return dispatch;}()}]);}();export default AppCommand;
|
|
@@ -5,4 +5,4 @@ var mockedBridgeDispatch=jest.fn();jest.mock("../DevServerBridge",function(){ret
|
|
|
5
5
|
var mockedClientInformation=null;jest.mock("../../commands/getWebStorageEntry",function(){return jest.fn().mockImplementation(function(){return{then:function then(cb){cb({value:mockedClientInformation});}};});});var defaultLibVersion=defaultClientInformation.libVersion;/**
|
|
6
6
|
* Updates the mocked client information.
|
|
7
7
|
* @param {string} libVersion The libVersion.
|
|
8
|
-
*/var setClientInformation=function setClientInformation(){var libVersion=arguments.length>0&&arguments[0]!==undefined?arguments[0]:defaultLibVersion;mockedClientInformation={libVersion:libVersion};};describe('AppCommand',function(){var instance;beforeEach(function(){setClientInformation();mockedLoggerError.mockClear();mockedLoggerWarn.mockClear();mockedLogGroup.mockClear();mockedBridgeDispatch.mockClear();instance=new AppCommand(true,true);});describe('.constructor()',function(){it('should construct as expected without parameters',function(){instance=new AppCommand();expect(instance.log).toBe(true);expect(instance.checkLibVersion).toBe(false);});it('should construct as expected when the SGJavaScriptBridge was detected',function(){hasSGJavaScriptBridge.mockReturnValueOnce(true);instance=new AppCommand();expect(instance.log).toBe(true);expect(instance.checkLibVersion).toBe(true);});it('should construct as expected when log parameter is false',function(){instance=new AppCommand(false,true);expect(instance.log).toBe(false);expect(instance.checkLibVersion).toBe(true);});});describe('.setCommandName()',function(){it('should set a valid value',function(){var value='sendPipelineRequest';var command=instance.setCommandName(value);expect(command).toEqual(instance);expect(command.name).toEqual(value);});it('should not set an invalid value',function(){var initial=instance.name;var command=instance.setCommandName(17.3);expect(command).toEqual(instance);expect(command.name).toEqual(initial);expect(mockedLoggerError).toHaveBeenCalledTimes(1);});});describe('.setCommandParams()',function(){it('should set a valid value',function(){var value={paramOne:'foo',paramTwo:1337};var command=instance.setCommandParams(value);expect(command).toEqual(instance);expect(command.params).toEqual(value);});it('should not set an invalid value',function(){var initial=instance.params;var command=instance.setCommandParams('sendPipelineRequest');expect(command).toEqual(instance);expect(command.params).toEqual(initial);expect(mockedLoggerError).toHaveBeenCalledTimes(1);});});describe('.setLibVersion()',function(){it('should set a valid value',function(){var value='17.2';var command=instance.setLibVersion(value);expect(command).toEqual(instance);expect(command.libVersion).toEqual(value);});it('should not set an invalid value',function(){var initial=instance.libVersion;var command=instance.setLibVersion('sendPipelineRequest');expect(command).toEqual(instance);expect(command.libVersion).toEqual(initial);expect(mockedLoggerError).toHaveBeenCalledTimes(1);});});describe('.logCommand',function(){it('should log a command',function(){instance.setCommandName('openPage');var command=instance.logCommand();expect(command).toEqual(instance);expect(mockedLogGroup).toHaveBeenCalledTimes(1);});it('should not log a command when logging is turned off',function(){instance=new AppCommand(false);instance.setCommandName('openPage');var command=instance.logCommand();expect(command).toEqual(instance);expect(mockedLogGroup).toHaveBeenCalledTimes(0);});it('should not log a command when it is blacklisted',function(){instance.setCommandName('sendPipelineRequest');var command=instance.logCommand();expect(command).toEqual(instance);expect(mockedLogGroup).toHaveBeenCalledTimes(0);});});describe('.buildCommand()',function(){it('should build a command when name and params are set',function(){var name='sendPipelineRequest';var params={paramOne:'foo',paramTwo:1337};var expected={c:name,p:params};instance.setCommandName(name);instance.setCommandParams(params);var result=instance.buildCommand();expect(result).toEqual(expected);});it('should build a command when only the name is set',function(){var name='sendPipelineRequest';var expected={c:name};instance.setCommandName(name);var result=instance.buildCommand();expect(result).toEqual(expected);});it('should not build a command when no name is set',function(){var params={paramOne:'foo',paramTwo:1337};instance.setCommandParams(params);var result=instance.buildCommand();expect(result).toEqual(null);});});describe('.dispatch()',function(){it('should dispatch as expected',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var name,result;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)
|
|
8
|
+
*/var setClientInformation=function setClientInformation(){var libVersion=arguments.length>0&&arguments[0]!==undefined?arguments[0]:defaultLibVersion;mockedClientInformation={libVersion:libVersion};};describe('AppCommand',function(){var instance;beforeEach(function(){setClientInformation();mockedLoggerError.mockClear();mockedLoggerWarn.mockClear();mockedLogGroup.mockClear();mockedBridgeDispatch.mockClear();instance=new AppCommand(true,true);});describe('.constructor()',function(){it('should construct as expected without parameters',function(){instance=new AppCommand();expect(instance.log).toBe(true);expect(instance.checkLibVersion).toBe(false);});it('should construct as expected when the SGJavaScriptBridge was detected',function(){hasSGJavaScriptBridge.mockReturnValueOnce(true);instance=new AppCommand();expect(instance.log).toBe(true);expect(instance.checkLibVersion).toBe(true);});it('should construct as expected when log parameter is false',function(){instance=new AppCommand(false,true);expect(instance.log).toBe(false);expect(instance.checkLibVersion).toBe(true);});});describe('.setCommandName()',function(){it('should set a valid value',function(){var value='sendPipelineRequest';var command=instance.setCommandName(value);expect(command).toEqual(instance);expect(command.name).toEqual(value);});it('should not set an invalid value',function(){var initial=instance.name;var command=instance.setCommandName(17.3);expect(command).toEqual(instance);expect(command.name).toEqual(initial);expect(mockedLoggerError).toHaveBeenCalledTimes(1);});});describe('.setCommandParams()',function(){it('should set a valid value',function(){var value={paramOne:'foo',paramTwo:1337};var command=instance.setCommandParams(value);expect(command).toEqual(instance);expect(command.params).toEqual(value);});it('should not set an invalid value',function(){var initial=instance.params;var command=instance.setCommandParams('sendPipelineRequest');expect(command).toEqual(instance);expect(command.params).toEqual(initial);expect(mockedLoggerError).toHaveBeenCalledTimes(1);});});describe('.setLibVersion()',function(){it('should set a valid value',function(){var value='17.2';var command=instance.setLibVersion(value);expect(command).toEqual(instance);expect(command.libVersion).toEqual(value);});it('should not set an invalid value',function(){var initial=instance.libVersion;var command=instance.setLibVersion('sendPipelineRequest');expect(command).toEqual(instance);expect(command.libVersion).toEqual(initial);expect(mockedLoggerError).toHaveBeenCalledTimes(1);});});describe('.logCommand',function(){it('should log a command',function(){instance.setCommandName('openPage');var command=instance.logCommand();expect(command).toEqual(instance);expect(mockedLogGroup).toHaveBeenCalledTimes(1);});it('should not log a command when logging is turned off',function(){instance=new AppCommand(false);instance.setCommandName('openPage');var command=instance.logCommand();expect(command).toEqual(instance);expect(mockedLogGroup).toHaveBeenCalledTimes(0);});it('should not log a command when it is blacklisted',function(){instance.setCommandName('sendPipelineRequest');var command=instance.logCommand();expect(command).toEqual(instance);expect(mockedLogGroup).toHaveBeenCalledTimes(0);});});describe('.buildCommand()',function(){it('should build a command when name and params are set',function(){var name='sendPipelineRequest';var params={paramOne:'foo',paramTwo:1337};var expected={c:name,p:params};instance.setCommandName(name);instance.setCommandParams(params);var result=instance.buildCommand();expect(result).toEqual(expected);});it('should build a command when only the name is set',function(){var name='sendPipelineRequest';var expected={c:name};instance.setCommandName(name);var result=instance.buildCommand();expect(result).toEqual(expected);});it('should not build a command when no name is set',function(){var params={paramOne:'foo',paramTwo:1337};instance.setCommandParams(params);var result=instance.buildCommand();expect(result).toEqual(null);});});describe('.dispatch()',function(){it('should dispatch as expected',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var name,result;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:name='sendPipelineRequest';instance.setCommandName(name);_context.next=4;return instance.dispatch();case 4:result=_context.sent;expect(result).toBe(true);expect(mockedBridgeDispatch).toHaveBeenCalledTimes(1);expect(mockedBridgeDispatch.mock.calls[0][0][0].c).toBe(name);expect(mockedBridgeDispatch.mock.calls[0][1]).toBe(defaultLibVersion);expect(mockedLoggerError).toHaveBeenCalledTimes(0);expect(mockedLoggerWarn).toHaveBeenCalledTimes(0);case 11:case"end":return _context.stop();}},_callee);})));it('should set the params if passed to dispatch',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var params,result;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:params={paramOne:'foo',paramTwo:1337};instance.setCommandName('sendPipelineRequest');_context2.next=4;return instance.dispatch(params);case 4:result=_context2.sent;expect(result).toBe(true);expect(mockedBridgeDispatch).toHaveBeenCalledTimes(1);expect(mockedBridgeDispatch.mock.calls[0][0][0].p).toEqual(params);expect(mockedLoggerError).toHaveBeenCalledTimes(0);expect(mockedLoggerWarn).toHaveBeenCalledTimes(0);case 10:case"end":return _context2.stop();}},_callee2);})));it('should not dispatch when no command was set up',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){var result;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:_context3.next=2;return instance.dispatch();case 2:result=_context3.sent;expect(result).toBe(false);expect(mockedBridgeDispatch).toHaveBeenCalledTimes(0);expect(mockedLoggerError).toHaveBeenCalledTimes(1);expect(mockedLoggerWarn).toHaveBeenCalledTimes(0);case 7:case"end":return _context3.stop();}},_callee3);})));it('should not dispatch when the command is not supported by the app',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){var libVersion,result;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1)switch(_context4.prev=_context4.next){case 0:libVersion=(Number.parseFloat(defaultLibVersion)+1).toFixed(1);instance.setCommandName('sendPipelineRequest');instance.setLibVersion(libVersion);_context4.next=5;return instance.dispatch();case 5:result=_context4.sent;expect(result).toBe(false);expect(mockedBridgeDispatch).toHaveBeenCalledTimes(0);expect(mockedLoggerError).toHaveBeenCalledTimes(0);expect(mockedLoggerWarn).toHaveBeenCalledTimes(1);case 10:case"end":return _context4.stop();}},_callee4);})));it('should dispatch when the command is not supported by the app but the check is off',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(){var libVersion,result;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1)switch(_context5.prev=_context5.next){case 0:libVersion=(Number.parseFloat(defaultLibVersion)+1).toFixed(1);instance=new AppCommand(true,false);instance.setCommandName('sendPipelineRequest');instance.setLibVersion(libVersion);_context5.next=6;return instance.dispatch();case 6:result=_context5.sent;expect(result).toBe(true);expect(mockedBridgeDispatch.mock.calls[0][1]).toBe(libVersion);expect(mockedBridgeDispatch).toHaveBeenCalledTimes(1);expect(mockedLoggerError).toHaveBeenCalledTimes(0);expect(mockedLoggerWarn).toHaveBeenCalledTimes(0);case 12:case"end":return _context5.stop();}},_callee5);})));it('should handle errors during bridge dispatch',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(){var name,result;return _regeneratorRuntime.wrap(function _callee6$(_context6){while(1)switch(_context6.prev=_context6.next){case 0:mockedBridgeDispatch=jest.fn().mockImplementation(function(){throw new Error();});name='sendPipelineRequest';instance.setCommandName(name);_context6.next=5;return instance.dispatch();case 5:result=_context6.sent;expect(result).toBe(false);expect(mockedBridgeDispatch).toHaveBeenCalledTimes(1);expect(mockedLoggerError).toHaveBeenCalledTimes(1);expect(mockedLoggerWarn).toHaveBeenCalledTimes(0);case 10:case"end":return _context6.stop();}},_callee6);})));});});
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import _regeneratorRuntime from"@babel/runtime/regenerator";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 _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}function 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);});};}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<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}function _callSuper(_this,derived,args){function isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{return!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch(e){return false;}}derived=_getPrototypeOf(derived);return _possibleConstructorReturn(_this,isNativeReflectConstruct()?Reflect.construct(derived,args||[],_getPrototypeOf(_this).constructor):derived.apply(_this,args));}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call;}return _assertThisInitialized(self);}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return self;}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}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);}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}/* eslint-disable class-methods-use-this */import Request from"../Request";import AppCommand from"../AppCommand";import event from"../Event";import requestBuffer from"../RequestBuffer";import{logger}from"../../helpers";import logGroup from"../../helpers/logGroup";var DEFAULT_LIB_VERSION='25.0';/**
|
|
2
|
+
* The AppCommandRequest class is the base class to implement request like app commands that have a
|
|
3
|
+
* corresponding app event that delivers response data.
|
|
4
|
+
* It contains the logic which in necessary to establish the process of sending an
|
|
5
|
+
* app command and receiving an associated event.
|
|
6
|
+
*/var AppCommandRequest=/*#__PURE__*/function(_Request){/**
|
|
7
|
+
* The constructor.
|
|
8
|
+
* @param {string} commandName The name of the command which is dispatched to the app.
|
|
9
|
+
* @param {string} eventName The event name which is called by the app to deliver the data.
|
|
10
|
+
*/function AppCommandRequest(commandName,eventName){var _this2;_classCallCheck(this,AppCommandRequest);_this2=_callSuper(this,AppCommandRequest);_this2.commandName=commandName;_this2.eventName=eventName||"".concat(commandName,"Response");_this2.commandParams=null;_this2.libVersion=DEFAULT_LIB_VERSION;_this2.logColor='#9a9800';event.registerEvent(_this2.eventName);_this2.createSerial(_this2.commandName);_this2.createEventCallbackName(_this2.eventName);return _this2;}/**
|
|
11
|
+
* Sets the parameters for the app command.
|
|
12
|
+
* @param {Object} [commandParams=null] The parameters.
|
|
13
|
+
* @return {AppCommandRequest}
|
|
14
|
+
*/_inherits(AppCommandRequest,_Request);return _createClass(AppCommandRequest,[{key:"setCommandParams",value:function setCommandParams(){var commandParams=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;this.commandParams=commandParams;return this;}/**
|
|
15
|
+
* Sets the minimum lib version for the app command.
|
|
16
|
+
* @param {string} [libVersion="25.0"] The lib version.
|
|
17
|
+
* @return {AppCommandRequest}
|
|
18
|
+
*/},{key:"setLibVersion",value:function setLibVersion(){var libVersion=arguments.length>0&&arguments[0]!==undefined?arguments[0]:DEFAULT_LIB_VERSION;this.libVersion=libVersion;return this;}/**
|
|
19
|
+
* Cleans up the instance after a successful or failed request.
|
|
20
|
+
* @private
|
|
21
|
+
* @param {Function} requestCallback The event callback that processes the response.
|
|
22
|
+
* @return {AppCommandRequest}
|
|
23
|
+
*/},{key:"cleanUpRequest",value:function cleanUpRequest(requestCallback){// Remove the event listener entry.
|
|
24
|
+
event.removeCallback(this.getEventCallbackName(),requestCallback);// Remove the request from the buffer.
|
|
25
|
+
requestBuffer.remove(this.serial);return this;}/**
|
|
26
|
+
* Validates the command params before dispatch.
|
|
27
|
+
*
|
|
28
|
+
* This method is supposed to be overwritten by an inheriting class. It's invoked with the
|
|
29
|
+
* currently configured command params object.
|
|
30
|
+
* @param {Object} commandParams The params of the command to be dispatched
|
|
31
|
+
* @return {boolean}
|
|
32
|
+
*/},{key:"validateCommandParams",value:function validateCommandParams(){return true;}/**
|
|
33
|
+
* Creates a title for the app command request log.
|
|
34
|
+
*
|
|
35
|
+
* This method is supposed to be overwritten by an inheriting class to enable customization of
|
|
36
|
+
* log output.
|
|
37
|
+
* @returns {string}
|
|
38
|
+
*/},{key:"getRequestLogTitle",value:function getRequestLogTitle(){return"AppCommandRequest %c".concat(this.commandName);}/**
|
|
39
|
+
* Creates a title for the app command response log.
|
|
40
|
+
*
|
|
41
|
+
* This method is supposed to be overwritten by an inheriting class to enable customization of
|
|
42
|
+
* log output.
|
|
43
|
+
* @returns {string}
|
|
44
|
+
*/},{key:"getResponseLogTitle",value:function getResponseLogTitle(){return"AppCommandResponse %c".concat(this.commandName);}/**
|
|
45
|
+
* Creates payload for the app command response log.
|
|
46
|
+
*
|
|
47
|
+
* This default handler expects the command serial as first and the request response as
|
|
48
|
+
* second command response event parameter. If the class is used for request commands with a
|
|
49
|
+
* different response even payload, this method needs to be overwritten.
|
|
50
|
+
* @param {string} serial The serial that was used to identify the response callback.
|
|
51
|
+
* @param {Object} response The response object for the request
|
|
52
|
+
* @returns {Object}
|
|
53
|
+
*/},{key:"getResponseLogPayload",value:function getResponseLogPayload(serial,response){return response;}/**
|
|
54
|
+
* App command response handler. Can be used to implement custom logic for handling the incoming
|
|
55
|
+
* data.
|
|
56
|
+
*
|
|
57
|
+
* This default handler expects the command serial as first and the request response as
|
|
58
|
+
* second command response event parameter. If the class is used for request commands with a
|
|
59
|
+
* different response event payload, this method needs to be overwritten.
|
|
60
|
+
* @param {Function} resolve Resolve callback of the promise returned by the dispatch method
|
|
61
|
+
* of the AppCommandRequest instance.
|
|
62
|
+
* @param {Function} reject Reject callback of the promise returned by the dispatch method
|
|
63
|
+
* of the AppCommandRequest instance.
|
|
64
|
+
* @param {string} serial The serial that was used to identify the response callback.
|
|
65
|
+
* @param {Object} response The response object for the request
|
|
66
|
+
*/},{key:"onResponse",value:function onResponse(resolve,reject,serial,response){resolve(response);}/**
|
|
67
|
+
* Dispatches the app request command.
|
|
68
|
+
* @private
|
|
69
|
+
* @param {Function} resolve The resolve() callback of the dispatch promise.
|
|
70
|
+
* @param {Function} reject The reject() callback of the dispatch promise.
|
|
71
|
+
*/},{key:"onDispatch",value:function(){var _onDispatch=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(resolve,reject){var _this3=this;var message,requestCallback,command,success;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:if(!(this.validateCommandParams(this.commandParams)===false)){_context.next=5;break;}// In case of an error log a message and reject the request promise.
|
|
72
|
+
message="".concat(this.commandName," - invalid command parameters passed");logger.error(message,this.commandParams);reject(new Error(message));return _context.abrupt("return");case 5:/**
|
|
73
|
+
* The event callback for the command response.
|
|
74
|
+
*/requestCallback=function requestCallback(){for(var _len=arguments.length,params=new Array(_len),_key=0;_key<_len;_key++){params[_key]=arguments[_key];}logGroup(_this3.getResponseLogTitle(),_this3.getResponseLogPayload.apply(_this3,params)||{},_this3.logColor);_this3.cleanUpRequest(requestCallback);_this3.onResponse.apply(_this3,[resolve,reject].concat(params));};// Add the request to the buffer.
|
|
75
|
+
requestBuffer.add(this,this.serial);// Add the event callback for the response.
|
|
76
|
+
event.addCallback(this.getEventCallbackName(),requestCallback);// Prepare the command.
|
|
77
|
+
command=new AppCommand().setCommandName(this.commandName).setLibVersion(this.libVersion).setCommandParams(_extends({serial:this.serial},this.commandParams&&_extends({},this.commandParams)));// Try to dispatch the command.
|
|
78
|
+
_context.next=11;return command.dispatch();case 11:success=_context.sent;if(!(success===false)){_context.next=16;break;}this.cleanUpRequest(requestCallback);reject(new Error("".concat(this.commandName," command dispatch failed")));return _context.abrupt("return");case 16:logGroup(this.getRequestLogTitle(),this.commandParams||{},this.logColor);case 17:case"end":return _context.stop();}},_callee,this);}));function onDispatch(_x,_x2){return _onDispatch.apply(this,arguments);}return onDispatch;}()}]);}(Request);/* eslint-enable class-methods-use-this */export default AppCommandRequest;
|
|
@@ -1,50 +1,23 @@
|
|
|
1
|
-
|
|
2
|
-
* The AppPermissionsRequest class is
|
|
1
|
+
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<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}function _callSuper(_this,derived,args){function isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{return!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch(e){return false;}}derived=_getPrototypeOf(derived);return _possibleConstructorReturn(_this,isNativeReflectConstruct()?Reflect.construct(derived,args||[],_getPrototypeOf(_this).constructor):derived.apply(_this,args));}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call;}return _assertThisInitialized(self);}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return self;}function _get(target,property,receiver){if(typeof Reflect!=="undefined"&&Reflect.get){_get=Reflect.get;}else{_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);}function _superPropBase(object,property){while(!Object.prototype.hasOwnProperty.call(object,property)){object=_getPrototypeOf(object);if(object===null)break;}return object;}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}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);}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}import AppCommandRequest from"../AppCommandRequest";/**
|
|
2
|
+
* The AppPermissionsRequest class is the base class for app permission related requests.
|
|
3
3
|
* It contains the logic which in necessary to establish the process of sending an
|
|
4
4
|
* app command and receiving an associated event.
|
|
5
|
-
*/var AppPermissionsRequest=/*#__PURE__*/function(
|
|
5
|
+
*/var AppPermissionsRequest=/*#__PURE__*/function(_AppCommandRequest){/**
|
|
6
6
|
* The constructor.
|
|
7
7
|
* @param {string} commandName The name of the command which is dispatched to the app.
|
|
8
8
|
* @param {string} eventName The event name which is called by the app to deliver the data.
|
|
9
|
-
*/function AppPermissionsRequest(commandName,eventName){var
|
|
10
|
-
* Sets the parameters for the app command.
|
|
11
|
-
* @private
|
|
12
|
-
* @param {Object} commandParams The parameters.
|
|
13
|
-
* @return {AppPermissionsRequest}
|
|
14
|
-
*/_createClass(AppPermissionsRequest,[{key:"setCommandParams",value:function setCommandParams(commandParams){this.commandParams=commandParams;return this;}/**
|
|
9
|
+
*/function AppPermissionsRequest(commandName,eventName){var _this2;_classCallCheck(this,AppPermissionsRequest);_this2=_callSuper(this,AppPermissionsRequest,[commandName,eventName]);_this2.dispatchMock=null;_this2.setLibVersion('18.0');return _this2;}/**
|
|
15
10
|
* Sets a mock for the dispatch method
|
|
16
11
|
* @private
|
|
17
12
|
* @param {Function} dispatchMock The dispatch mock
|
|
18
13
|
* @returns {AppPermissionsRequest}
|
|
19
|
-
*/
|
|
20
|
-
*
|
|
21
|
-
* @
|
|
22
|
-
|
|
23
|
-
*
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
requestBuffer.remove(this.serial);return this;}/* eslint-disable class-methods-use-this */ /**
|
|
27
|
-
* Validates the command params before dispatch.
|
|
28
|
-
* @private
|
|
29
|
-
* @abstract
|
|
30
|
-
* @throws {Error}
|
|
31
|
-
*/},{key:"validateCommandParams",value:function validateCommandParams(){throw new Error('validateCommandParams needs to be overwritten by inherited class.');}/* eslint-enable class-methods-use-this */ /**
|
|
32
|
-
* Dispatches the app permissions command.
|
|
33
|
-
* @private
|
|
34
|
-
* @param {Function} resolve The resolve() callback of the dispatch promise.
|
|
35
|
-
* @param {Function} reject The reject() callback of the dispatch promise.
|
|
36
|
-
*/},{key:"onDispatch",value:function(){var _onDispatch=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(resolve,reject){var _this2=this;var requestType,message,requestCallback,command,success;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:// Prepare the request type for logging.
|
|
37
|
-
requestType=this.commandName.replace('AppPermissions','');// Validate the command parameters.
|
|
38
|
-
if(!(this.validateCommandParams(this.commandParams)===false)){_context.next=6;break;}// In case of an error log a message and reject the request promise.
|
|
39
|
-
message="".concat(this.commandName," - invalid command parameters passed");logger.error(message,this.commandParams);reject(new Error(message));return _context.abrupt("return");case 6:/**
|
|
40
|
-
* The event callback for the permissions response.
|
|
41
|
-
* @param {string} serial The serial that was used to identify the callback.
|
|
42
|
-
* @param {Array} permissions An array with the current app permissions.
|
|
43
|
-
*/requestCallback=function requestCallback(serial,permissions){logGroup("AppPermissionsResponse %c".concat(requestType),permissions,'#9a9800');_this2.cleanUpRequest(requestCallback);resolve(permissions);};// Add the request to the buffer.
|
|
44
|
-
requestBuffer.add(this,this.serial);// Add the event callback for the response.
|
|
45
|
-
event.addCallback(this.getEventCallbackName(),requestCallback);// Prepare the permissions command.
|
|
46
|
-
command=new AppCommand().setCommandName(this.commandName).setLibVersion(this.libVersion).setCommandParams(_extends({serial:this.serial},this.commandParams&&_extends({},this.commandParams)));// Try to dispatch the command.
|
|
47
|
-
_context.next=12;return command.dispatch();case 12:success=_context.sent;if(!(success===false)){_context.next=17;break;}this.cleanUpRequest(requestCallback);reject(new Error("".concat(this.commandName," command dispatch failed")));return _context.abrupt("return");case 17:logGroup("AppPermissionsRequest %c".concat(requestType),this.commandParams,'#adab00');case 18:case"end":return _context.stop();}}},_callee,this);}));function onDispatch(_x,_x2){return _onDispatch.apply(this,arguments);}return onDispatch;}()/**
|
|
14
|
+
*/_inherits(AppPermissionsRequest,_AppCommandRequest);return _createClass(AppPermissionsRequest,[{key:"setDispatchMock",value:function setDispatchMock(){var dispatchMock=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;this.dispatchMock=dispatchMock;return this;}/**
|
|
15
|
+
* Creates title for the app command request log
|
|
16
|
+
* @returns {string}
|
|
17
|
+
*/},{key:"getRequestLogTitle",value:function getRequestLogTitle(){var requestType=this.commandName.replace('AppPermissions','');return"AppPermissionsRequest %c".concat(requestType);}/**
|
|
18
|
+
* Creates title for the app command response log
|
|
19
|
+
* @returns {string}
|
|
20
|
+
*/},{key:"getResponseLogTitle",value:function getResponseLogTitle(){var requestType=this.commandName.replace('AppPermissions','');return"AppPermissionsResponse %c".concat(requestType);}/**
|
|
48
21
|
* Dispatches the request.
|
|
49
22
|
* @return {Promise} A promise that is fulfilled when a response is received for this request.
|
|
50
|
-
*/},{key:"dispatch",value:function dispatch(){if(typeof this.dispatchMock==='function'){return this.dispatchMock(this.commandName,this.commandParams);}return _get(_getPrototypeOf(AppPermissionsRequest.prototype),"dispatch",this).call(this);}}]);
|
|
23
|
+
*/},{key:"dispatch",value:function dispatch(){if(typeof this.dispatchMock==='function'){return this.dispatchMock(this.commandName,this.commandParams);}return _get(_getPrototypeOf(AppPermissionsRequest.prototype),"dispatch",this).call(this);}}]);}(AppCommandRequest);export default AppPermissionsRequest;
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
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<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call;}return _assertThisInitialized(self);}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return self;}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}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);}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}import
|
|
1
|
+
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<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}function _callSuper(_this,derived,args){function isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{return!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch(e){return false;}}derived=_getPrototypeOf(derived);return _possibleConstructorReturn(_this,isNativeReflectConstruct()?Reflect.construct(derived,args||[],_getPrototypeOf(_this).constructor):derived.apply(_this,args));}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call;}return _assertThisInitialized(self);}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return self;}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}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);}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}import AppPermissionsRequest from"./AppPermissionsRequest";import{availablePermissionsIds}from"../../constants/AppPermissions";import{COMMAND_GET_APP_PERMISSIONS}from"../../constants/AppCommands";/**
|
|
2
2
|
* The GetAppPermissionsRequest class is about to get an overview about the already granted
|
|
3
3
|
* permissions by the operation system e.g. location or camera access.
|
|
4
|
-
*/var GetAppPermissionsRequest=/*#__PURE__*/function(_AppPermissionsReques){
|
|
4
|
+
*/var GetAppPermissionsRequest=/*#__PURE__*/function(_AppPermissionsReques){/**
|
|
5
5
|
* The constructor.
|
|
6
|
-
*/function GetAppPermissionsRequest(){_classCallCheck(this,GetAppPermissionsRequest);return
|
|
6
|
+
*/function GetAppPermissionsRequest(){_classCallCheck(this,GetAppPermissionsRequest);return _callSuper(this,GetAppPermissionsRequest,[COMMAND_GET_APP_PERMISSIONS]);}/**
|
|
7
7
|
* Sets the desired permission ids for the request.
|
|
8
8
|
* @param {Array} [permissionIds=[]] The permission ids.
|
|
9
9
|
* @return {GetAppPermissionsRequest}
|
|
10
|
-
*/_createClass(GetAppPermissionsRequest,[{key:"setPermissionIds",value:function setPermissionIds(){var permissionIds=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];this.setCommandParams({permissionIds:permissionIds});return this;}/**
|
|
10
|
+
*/_inherits(GetAppPermissionsRequest,_AppPermissionsReques);return _createClass(GetAppPermissionsRequest,[{key:"setPermissionIds",value:function setPermissionIds(){var permissionIds=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];this.setCommandParams({permissionIds:permissionIds});return this;}/**
|
|
11
11
|
* Validates the request command parameters.
|
|
12
12
|
* @override
|
|
13
13
|
* @private
|
|
@@ -16,4 +16,4 @@ function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="s
|
|
|
16
16
|
if(this.commandParams===null){return true;}var permissionIds=this.commandParams.permissionIds;// If permission ids are present they have to be an array.
|
|
17
17
|
if(!Array.isArray(permissionIds)){return false;}// An empty permissionsIds array is ok for the command.
|
|
18
18
|
if(permissionIds.length===0){return true;}// Check if all permission ids are valid.
|
|
19
|
-
return permissionIds.every(function(permissionId){return availablePermissionsIds.includes(permissionId);});}}]);
|
|
19
|
+
return permissionIds.every(function(permissionId){return availablePermissionsIds.includes(permissionId);});}}]);}(AppPermissionsRequest);export default GetAppPermissionsRequest;
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
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<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call;}return _assertThisInitialized(self);}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return self;}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}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);}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}import
|
|
1
|
+
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<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}function _callSuper(_this,derived,args){function isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{return!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch(e){return false;}}derived=_getPrototypeOf(derived);return _possibleConstructorReturn(_this,isNativeReflectConstruct()?Reflect.construct(derived,args||[],_getPrototypeOf(_this).constructor):derived.apply(_this,args));}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call;}return _assertThisInitialized(self);}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return self;}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}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);}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}import AppPermissionsRequest from"./AppPermissionsRequest";import{availablePermissionsIds}from"../../constants/AppPermissions";import{COMMAND_REQUEST_APP_PERMISSIONS}from"../../constants/AppCommands";/**
|
|
2
2
|
* The RequestAppPermissionsRequest class is about to initiate the process to request
|
|
3
3
|
* additional permissions from the operating system e.g. location or camera access.
|
|
4
|
-
*/var RequestAppPermissionsRequest=/*#__PURE__*/function(_AppPermissionsReques){
|
|
4
|
+
*/var RequestAppPermissionsRequest=/*#__PURE__*/function(_AppPermissionsReques){/**
|
|
5
5
|
* The constructor.
|
|
6
|
-
*/function RequestAppPermissionsRequest(){_classCallCheck(this,RequestAppPermissionsRequest);return
|
|
6
|
+
*/function RequestAppPermissionsRequest(){_classCallCheck(this,RequestAppPermissionsRequest);return _callSuper(this,RequestAppPermissionsRequest,[COMMAND_REQUEST_APP_PERMISSIONS]);}/**
|
|
7
7
|
* Sets the desired permissions for the request.
|
|
8
8
|
* @param {Array} permissions The permissions.
|
|
9
9
|
* @return {RequestAppPermissionsRequest}
|
|
10
|
-
*/_createClass(RequestAppPermissionsRequest,[{key:"setPermissions",value:function setPermissions(permissions){this.setCommandParams({permissions:permissions});return this;}/**
|
|
10
|
+
*/_inherits(RequestAppPermissionsRequest,_AppPermissionsReques);return _createClass(RequestAppPermissionsRequest,[{key:"setPermissions",value:function setPermissions(permissions){this.setCommandParams({permissions:permissions});return this;}/**
|
|
11
11
|
* Validates the request command parameters.
|
|
12
12
|
* @override
|
|
13
13
|
* @private
|
|
@@ -16,4 +16,4 @@ function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="s
|
|
|
16
16
|
if(this.commandParams===null){return false;}var permissions=this.commandParams.permissions;// If permissions are present they have to be an array.
|
|
17
17
|
if(!Array.isArray(permissions)||permissions.length===0){return false;}return permissions.every(function(permission){// Check if the permission is a plain object.
|
|
18
18
|
if(permission===null||_typeof(permission)!=='object'){return false;}var permissionId=permission.permissionId;// Check if the permission id is valid.
|
|
19
|
-
if(!availablePermissionsIds.includes(permissionId)){return false;}return true;});}}]);
|
|
19
|
+
if(!availablePermissionsIds.includes(permissionId)){return false;}return true;});}}]);}(AppPermissionsRequest);export default RequestAppPermissionsRequest;
|
package/classes/Bridge/index.js
CHANGED
|
@@ -7,4 +7,4 @@ function _classCallCheck(instance,Constructor){if(!(instance instanceof Construc
|
|
|
7
7
|
* Dispatches an app command to the native app wrapper.
|
|
8
8
|
* @param {Object} command The app command to dispatch.
|
|
9
9
|
* @param {string} libVersion The command's lib version.
|
|
10
|
-
*/_createClass(Bridge,[{key:"dispatchCommand",value:function dispatchCommand(command,libVersion){if('dispatchCommandForVersion'in this.bridge){this.bridge.dispatchCommandForVersion(command,libVersion);/* istanbul ignore else */}else if('dispatchCommandsForVersion'in this.bridge){this.bridge.dispatchCommandsForVersion([command],libVersion);}else{this.bridge.dispatchCommandsStringForVersion(JSON.stringify([command]),libVersion);}}}]);
|
|
10
|
+
*/return _createClass(Bridge,[{key:"dispatchCommand",value:function dispatchCommand(command,libVersion){if('dispatchCommandForVersion'in this.bridge){this.bridge.dispatchCommandForVersion(command,libVersion);/* istanbul ignore else */}else if('dispatchCommandsForVersion'in this.bridge){this.bridge.dispatchCommandsForVersion([command],libVersion);}else{this.bridge.dispatchCommandsStringForVersion(JSON.stringify([command]),libVersion);}}}]);}();export default Bridge;
|
|
@@ -5,13 +5,13 @@ import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGenera
|
|
|
5
5
|
* `.dispatch`.
|
|
6
6
|
*/export var BrightnessRequest=/*#__PURE__*/function(){/**
|
|
7
7
|
* Constructor.
|
|
8
|
-
*/function BrightnessRequest(){var _this=this;_classCallCheck(this,BrightnessRequest)
|
|
8
|
+
*/function BrightnessRequest(){var _this=this;_classCallCheck(this,BrightnessRequest);/**
|
|
9
9
|
* Handles responses
|
|
10
10
|
* @param {Object} response Response.
|
|
11
|
-
*/_createClass(BrightnessRequest,[{key:"dispatch"
|
|
11
|
+
*/_defineProperty(this,"handleResponse",function(response){var queueEntry=_this.responseQueue.shift();if(typeof queueEntry==='undefined'){logger.error('currentBrightnessResponse received but the response handler queue is empty.');return;}var resolve=queueEntry.resolve,reject=queueEntry.reject;if(!response.hasOwnProperty('brightness')){reject(new Error('Invalid response for currentBrightnessResponse. Missing brightness property.'));return;}resolve(response.brightness);});this.responseQueue=[];event.addCallback(RESPONSE_EVENT_NAME,this.handleResponse);}return _createClass(BrightnessRequest,[{key:"dispatch",value:/**
|
|
12
12
|
* Dispatches the request.
|
|
13
13
|
* @returns {Promise}
|
|
14
|
-
*/
|
|
14
|
+
*/function dispatch(){var _this2=this;return new Promise(/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(resolve,reject){var command,result;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:_this2.responseQueue.push({resolve:resolve,reject:reject});// Prepare the AppComand.
|
|
15
15
|
command=new AppCommand().setCommandName(GET_COMMAND_NAME).setLibVersion(LIB_VERSION);// Dispatch the command. The method will resolve with FALSE in case of an error.
|
|
16
16
|
_context.next=4;return command.dispatch();case 4:result=_context.sent;if(result===false){// Remove the queue entry when the dispatch failed.
|
|
17
|
-
_this2.responseQueue.pop();reject(new Error('getCurrentBrightness command dispatch failed'));}case 6:case"end":return _context.stop();}}
|
|
17
|
+
_this2.responseQueue.pop();reject(new Error('getCurrentBrightness command dispatch failed'));}case 6:case"end":return _context.stop();}},_callee);}));return function(_x,_x2){return _ref.apply(this,arguments);};}());}}]);}();export default new BrightnessRequest();
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import _regeneratorRuntime from"@babel/runtime/regenerator";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);});};}/* eslint-disable import/named */import{mockedSetCommandName,mockedSetLibVersion,mockedDispatch,triggerDispatchError}from"../AppCommand";/* eslint-enable import/named */var mockedAddCallback=jest.fn();jest.mock("../Event",function(){return{addCallback:function addCallback(){mockedAddCallback.apply(void 0,arguments);}};});jest.mock("../AppCommand");var mockedLoggerError=jest.fn();jest.mock("../../helpers",function(){return{logger:{error:function error(){mockedLoggerError.apply(void 0,arguments);}}};});describe('BrightnessRequest',function(){/* eslint-disable global-require */var brightnessRequest=require("./index")["default"];var _require=require("./index"),BrightnessRequest=_require.BrightnessRequest;/* eslint-enable global-require */beforeEach(function(){mockedLoggerError.mockClear();mockedAddCallback.mockClear();mockedSetCommandName.mockClear();mockedSetLibVersion.mockClear();mockedDispatch.mockClear();// Reset the queue for each test
|
|
2
|
-
brightnessRequest.responseQueue=[];});it('should export an already instantiated class',function(){expect(brightnessRequest).toBeInstanceOf(BrightnessRequest);expect(brightnessRequest.responseQueue).toEqual([]);});it('should dispatch a command and prepare a handler for response',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){return _regeneratorRuntime.wrap(function _callee$(_context){while(1)
|
|
2
|
+
brightnessRequest.responseQueue=[];});it('should export an already instantiated class',function(){expect(brightnessRequest).toBeInstanceOf(BrightnessRequest);expect(brightnessRequest.responseQueue).toEqual([]);});it('should dispatch a command and prepare a handler for response',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:brightnessRequest.dispatch().then(function(result){expect(mockedSetCommandName).toHaveBeenCalled();expect(mockedSetCommandName).toHaveBeenLastCalledWith('getCurrentBrightness');expect(mockedSetLibVersion).toHaveBeenCalledTimes(1);expect(mockedSetLibVersion).toHaveBeenLastCalledWith('17.0');expect(mockedDispatch).toHaveBeenCalledTimes(1);expect(brightnessRequest.responseQueue).toHaveLength(0);expect(result).toBe(100);});_context.next=3;return brightnessRequest.handleResponse({brightness:100});case 3:case"end":return _context.stop();}},_callee);})));it('should handle two parallel requests as expected',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var requestOne,requestTwo;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:// Prepare two requests
|
|
3
3
|
requestOne=brightnessRequest.dispatch();requestTwo=brightnessRequest.dispatch();// Check if the queue looks like expected
|
|
4
4
|
expect(brightnessRequest.responseQueue).toHaveLength(2);requestOne.then(function(result){expect(brightnessRequest.responseQueue).toHaveLength(1);expect(result).toBe(100);});requestTwo.then(function(result){expect(brightnessRequest.responseQueue).toHaveLength(0);expect(result).toBe(80);});// Simulate incoming of the first event
|
|
5
|
-
_context2.next=7;return brightnessRequest.handleResponse({brightness:100});case 7:_context2.next=9;return brightnessRequest.handleResponse({brightness:80});case 9:case"end":return _context2.stop();}}
|
|
6
|
-
triggerDispatchError();_context3.prev=1;_context3.next=4;return brightnessRequest.dispatch();case 4:_context3.next=12;break;case 6:_context3.prev=6;_context3.t0=_context3["catch"](1);expect(_context3.t0).toBeInstanceOf(Error);expect(_context3.t0.message).toContain('getCurrentBrightness');expect(brightnessRequest.responseQueue).toHaveLength(0);expect(mockedDispatch).toHaveBeenCalledTimes(1);case 12:case"end":return _context3.stop();}}
|
|
5
|
+
_context2.next=7;return brightnessRequest.handleResponse({brightness:100});case 7:_context2.next=9;return brightnessRequest.handleResponse({brightness:80});case 9:case"end":return _context2.stop();}},_callee2);})));it('should reject a promise when response is not valid',function(done){var assertError=new Error('Did not reject');brightnessRequest.dispatch().then(function(){throw assertError;})["catch"](function(e){expect(e).not.toBe(assertError);done();});brightnessRequest.handleResponse({brightnessFFOFOF:100});});it('should reject a promise when the command dispatch failed',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:// Configure the AppCommand mock to respolve with an error.
|
|
6
|
+
triggerDispatchError();_context3.prev=1;_context3.next=4;return brightnessRequest.dispatch();case 4:_context3.next=12;break;case 6:_context3.prev=6;_context3.t0=_context3["catch"](1);expect(_context3.t0).toBeInstanceOf(Error);expect(_context3.t0.message).toContain('getCurrentBrightness');expect(brightnessRequest.responseQueue).toHaveLength(0);expect(mockedDispatch).toHaveBeenCalledTimes(1);case 12:case"end":return _context3.stop();}},_callee3,null,[[1,6]]);})));it('should handle incoming events which did not have a dispatch',function(){var result=brightnessRequest.handleResponse({brightness:100});expect(result).toBe(undefined);expect(mockedLoggerError).toHaveBeenCalledTimes(1);});});
|
|
@@ -5,31 +5,23 @@ function _extends(){_extends=Object.assign||function(target){for(var i=1;i<argum
|
|
|
5
5
|
* The constructor.
|
|
6
6
|
* @param {string} [ip=process.env.IP] The IP of the dev server.
|
|
7
7
|
* @param {number} [port=process.env.PORT] The port of the dev server.
|
|
8
|
-
*/function BrowserConnector(){var _this=this;var ip=arguments.length>0&&arguments[0]!==undefined?arguments[0]:process.env.IP;var port=arguments.length>1&&arguments[1]!==undefined?arguments[1]:process.env.PORT;_classCallCheck(this,BrowserConnector)
|
|
9
|
-
cmds.forEach(function(command){var name=command.c;var params=command.p;var args=[];/**
|
|
10
|
-
* The server returns a response command for a request command.
|
|
11
|
-
* If the native app receives such a command, it calls a related event within the
|
|
12
|
-
* webviews. Here the response parameters are sorted in the specified order for
|
|
13
|
-
* the different response events.
|
|
14
|
-
*/if(name==='pipelineResponse'){args=[params.error,params.serial,params.output];}else if(name==='httpResponse'){args=[params.error,params.serial,params.response];}else if(name==='dataResponse'){args=[params.serial,params.status,params.body,params.bodyContentType];}else if(name==='webStorageResponse'){args=[params.serial,params.age,params.value];}event.call(name,args);});return _this;});this.ip=ip;this.port=port;this.supportedCommands=[appCommands.COMMAND_SEND_PIPELINE_REQUEST,appCommands.COMMAND_SEND_HTTP_REQUEST,appCommands.COMMAND_SEND_DATA_REQUEST,appCommands.COMMAND_GET_WEBSTORAGE_ENTRY];this.appConfig=appConfig;}/**
|
|
8
|
+
*/function BrowserConnector(){var _this=this;var ip=arguments.length>0&&arguments[0]!==undefined?arguments[0]:process.env.IP;var port=arguments.length>1&&arguments[1]!==undefined?arguments[1]:process.env.PORT;_classCallCheck(this,BrowserConnector);/**
|
|
15
9
|
* Builds the GET query.
|
|
16
10
|
* @param {Object} input The input parameters.
|
|
17
11
|
* @return {string}
|
|
18
|
-
*/
|
|
19
|
-
* @param {string} libVersion The library version.
|
|
20
|
-
* @returns {string}
|
|
21
|
-
*/value:function getRequestBody(libVersion){if(this.isPipelineRequest){var p=this.command.p;var input=p.input;return JSON.stringify(input);}return JSON.stringify({cmds:[this.command],ver:libVersion});}/**
|
|
22
|
-
* Dispatches a single command to the dev server.
|
|
23
|
-
* @param {Object} command The command to dispatch.
|
|
24
|
-
* @param {string} libVersion The lib version for the command.
|
|
25
|
-
* @return {BrowserConnector}
|
|
26
|
-
*/},{key:"dispatchCommandForVersion",value:function dispatchCommandForVersion(command,libVersion){this.command=command;var _ref2=this.command||{},name=_ref2.c;if(this.supportedCommands.includes(name)){var URL=this.isPipelineRequest?this.connectUrl:this.localURL;var options=_extends({method:this.requestType,credentials:'include',headers:new Headers({'Content-Type':'application/json'})},this.isPOST&&{body:this.getRequestBody(libVersion)});fetch(URL,options).then(function(response){return response.json();}).then(this.processResponse)["catch"](function(err){return err&&logger.error(err);});}return this;}/**
|
|
12
|
+
*/_defineProperty(this,"buildQueryString",function(input){if(Object.keys(input).length===0||_this.isPOST){return'';}var query=Object.keys(input).map(function(key){return"".concat(key,"=").concat(input[key]);}).join('&');return"?".concat(query);});/**
|
|
27
13
|
* Handles a response of the server.
|
|
28
14
|
* @param {Object} response The server response.
|
|
29
15
|
* @return {BrowserConnector}
|
|
30
|
-
*/},{
|
|
16
|
+
*/_defineProperty(this,"processResponse",function(response){var _ref=response||{},_ref$cmds=_ref.cmds,cmds=_ref$cmds===void 0?[]:_ref$cmds;if(cmds.length===0){if(_this.command.c===appCommands.COMMAND_SEND_PIPELINE_REQUEST){event.call("pipelineResponse:".concat(_this.command.p.serial),[response.error||null,_this.command.p.serial,!response.error?response:undefined]);}}// Process the response commands.
|
|
17
|
+
cmds.forEach(function(command){var name=command.c;var params=command.p;var args=[];/**
|
|
18
|
+
* The server returns a response command for a request command.
|
|
19
|
+
* If the native app receives such a command, it calls a related event within the
|
|
20
|
+
* webviews. Here the response parameters are sorted in the specified order for
|
|
21
|
+
* the different response events.
|
|
22
|
+
*/if(name==='pipelineResponse'){args=[params.error,params.serial,params.output];}else if(name==='httpResponse'){args=[params.error,params.serial,params.response];}else if(name==='dataResponse'){args=[params.serial,params.status,params.body,params.bodyContentType];}else if(name==='webStorageResponse'){args=[params.serial,params.age,params.value];}event.call(name,args);});return _this;});this.ip=ip;this.port=port;this.supportedCommands=[appCommands.COMMAND_SEND_PIPELINE_REQUEST,appCommands.COMMAND_SEND_HTTP_REQUEST,appCommands.COMMAND_SEND_DATA_REQUEST,appCommands.COMMAND_GET_WEBSTORAGE_ENTRY];this.appConfig=appConfig;}return _createClass(BrowserConnector,[{key:"requestType",get:/**
|
|
31
23
|
* @return {string}
|
|
32
|
-
*/
|
|
24
|
+
*/function get(){if(!this.isPipelineRequest){return requestTypes.REQUEST_TYPE_POST;}var segments=this.command.p.name.split('.');if(segments[2].startsWith('get')){return requestTypes.REQUEST_TYPE_GET;}return requestTypes.REQUEST_TYPE_POST;}/**
|
|
33
25
|
* @return {boolean}
|
|
34
26
|
*/},{key:"isGET",get:function get(){return this.requestType===requestTypes.REQUEST_TYPE_GET;}/**
|
|
35
27
|
* @return {boolean}
|
|
@@ -41,4 +33,12 @@ cmds.forEach(function(command){var name=command.c;var params=command.p;var args=
|
|
|
41
33
|
* @return {string}
|
|
42
34
|
*/},{key:"suffix",get:function get(){if(this.command.c===appCommands.COMMAND_GET_WEBSTORAGE_ENTRY){return'web_storage';}if(this.command.c===appCommands.COMMAND_SEND_HTTP_REQUEST){return'http_request';}return'';}/**
|
|
43
35
|
* @return {string}
|
|
44
|
-
*/},{key:"localURL",get:function get(){return"http://".concat(this.ip,":").concat(this.port,"/").concat(this.suffix);}
|
|
36
|
+
*/},{key:"localURL",get:function get(){return"http://".concat(this.ip,":").concat(this.port,"/").concat(this.suffix);}/**
|
|
37
|
+
* @param {string} libVersion The library version.
|
|
38
|
+
* @returns {string}
|
|
39
|
+
*/},{key:"getRequestBody",value:function getRequestBody(libVersion){if(this.isPipelineRequest){var p=this.command.p;var input=p.input;return JSON.stringify(input);}return JSON.stringify({cmds:[this.command],ver:libVersion});}/**
|
|
40
|
+
* Dispatches a single command to the dev server.
|
|
41
|
+
* @param {Object} command The command to dispatch.
|
|
42
|
+
* @param {string} libVersion The lib version for the command.
|
|
43
|
+
* @return {BrowserConnector}
|
|
44
|
+
*/},{key:"dispatchCommandForVersion",value:function dispatchCommandForVersion(command,libVersion){this.command=command;var _ref2=this.command||{},name=_ref2.c;if(this.supportedCommands.includes(name)){var URL=this.isPipelineRequest?this.connectUrl:this.localURL;var options=_extends({method:this.requestType,credentials:'include',headers:new Headers({'Content-Type':'application/json'})},this.isPOST&&{body:this.getRequestBody(libVersion)});fetch(URL,options).then(function(response){return response.json();}).then(this.processResponse)["catch"](function(err){return err&&logger.error(err);});}return this;}}]);}();export default BrowserConnector;
|
|
@@ -7,14 +7,14 @@ import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGenera
|
|
|
7
7
|
* @param {Function} conditioner The registered conditioner.
|
|
8
8
|
* @param {number} priority conditioner priority
|
|
9
9
|
* @return {Conditioner}
|
|
10
|
-
*/_createClass(Conditioner,[{key:"addConditioner",value:function addConditioner(name,conditioner){var priority=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;if(typeof conditioner!=='function'){throw new Error("Conditioners need to be of type function. Received: '".concat(_typeof(conditioner),"'"));}this.conditions.set(name,{priority:priority,conditioner:conditioner});return this;}/**
|
|
10
|
+
*/return _createClass(Conditioner,[{key:"addConditioner",value:function addConditioner(name,conditioner){var priority=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;if(typeof conditioner!=='function'){throw new Error("Conditioners need to be of type function. Received: '".concat(_typeof(conditioner),"'"));}this.conditions.set(name,{priority:priority,conditioner:conditioner});return this;}/**
|
|
11
11
|
* @param {string} name The name of the registered conditioner.
|
|
12
12
|
* @return {Conditioner}
|
|
13
|
-
*/},{key:"removeConditioner",value:function removeConditioner(name){if(!this.conditions.has(name)){return this;}this.conditions["delete"](name);return this;}/**
|
|
13
|
+
*/},{key:"removeConditioner",value:function removeConditioner(name){if(!this.conditions.has(name)){logger.warn("Couldn't remove conditioner. '".concat(name,"' no found."));return this;}this.conditions["delete"](name);return this;}/**
|
|
14
14
|
* @param {string} name The name of the conditioner to eliminate.
|
|
15
15
|
* @return {Conditioner} new instance with cloned conditions
|
|
16
16
|
*/},{key:"without",value:function without(name){var clonedConditions=new Map(this.conditions);if(clonedConditions.has(name)){clonedConditions["delete"](name);}return new Conditioner(clonedConditions);}/**
|
|
17
17
|
* Resolves if all conditions are fulfilled.
|
|
18
18
|
* @return {Promise}
|
|
19
|
-
*/},{key:"check",value:function check(){var _this=this;return new Promise(/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(resolve,reject){var sorted,i,condition,conditionResult;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)
|
|
20
|
-
_context.next=7;return condition.conditioner();case 7:conditionResult=_context.sent;if(!(conditionResult===false)){_context.next=11;break;}logger.warn('conditioner failed',i,condition,_this.conditions);return _context.abrupt("return",resolve(false));case 11:i+=1;_context.next=3;break;case 14:return _context.abrupt("return",resolve(true));case 17:_context.prev=17;_context.t0=_context["catch"](1);return _context.abrupt("return",reject(_context.t0));case 20:case"end":return _context.stop();}}
|
|
19
|
+
*/},{key:"check",value:function check(){var _this=this;return new Promise(/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(resolve,reject){var sorted,i,condition,conditionResult;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:sorted=Array.from(_this.conditions.values()).sort(function(a,b){if(a.priority===b.priority){return 0;}return a.priority<b.priority?-1:1;});_context.prev=1;i=0;case 3:if(!(i<sorted.length)){_context.next=14;break;}condition=sorted[i];// eslint-disable-next-line no-await-in-loop
|
|
20
|
+
_context.next=7;return condition.conditioner();case 7:conditionResult=_context.sent;if(!(conditionResult===false)){_context.next=11;break;}logger.warn('conditioner failed',i,condition,_this.conditions);return _context.abrupt("return",resolve(false));case 11:i+=1;_context.next=3;break;case 14:return _context.abrupt("return",resolve(true));case 17:_context.prev=17;_context.t0=_context["catch"](1);return _context.abrupt("return",reject(_context.t0));case 20:case"end":return _context.stop();}},_callee,null,[[1,17]]);}));return function(_x,_x2){return _ref.apply(this,arguments);};}());}}]);}();export default Conditioner;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import _regeneratorRuntime from"@babel/runtime/regenerator";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);});};}import Conditioner from"./index";import{logger}from"../../helpers";jest.mock("../../helpers",function(){return{logger:{warn:jest.fn()}};});describe('Conditioner',function(){var conditioner;var cond1;var cond2;var cond3;beforeEach(function(){jest.clearAllMocks();conditioner=new Conditioner();cond1=jest.fn().mockReturnValue(true);cond2=jest.fn().mockReturnValue(true);cond3=jest.fn().mockReturnValue(true);});it('should fail on first sorted condition',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){return _regeneratorRuntime.wrap(function _callee$(_context){while(1)
|
|
1
|
+
import _regeneratorRuntime from"@babel/runtime/regenerator";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);});};}import Conditioner from"./index";import{logger}from"../../helpers";jest.mock("../../helpers",function(){return{logger:{warn:jest.fn()}};});describe('Conditioner',function(){var conditioner;var cond1;var cond2;var cond3;beforeEach(function(){jest.clearAllMocks();conditioner=new Conditioner();cond1=jest.fn().mockReturnValue(true);cond2=jest.fn().mockReturnValue(true);cond3=jest.fn().mockReturnValue(true);});it('should fail on first sorted condition',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:cond3.mockReturnValue(false);conditioner.addConditioner(1,cond1);conditioner.addConditioner(2,cond2,-1);conditioner.addConditioner(3,cond3,-2);_context.t0=expect;_context.next=7;return conditioner.check();case 7:_context.t1=_context.sent;(0,_context.t0)(_context.t1).toBeFalsy();expect(cond3).toBeCalledTimes(1);expect(cond1).toBeCalledTimes(0);expect(cond2).toBeCalledTimes(0);expect(logger.warn).toBeCalledTimes(1);case 13:case"end":return _context.stop();}},_callee);})));it('should fail on first promisified sorted condition',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:expect.assertions(5);cond3.mockResolvedValue(false);conditioner.addConditioner(1,cond1);conditioner.addConditioner(2,cond2,-1);conditioner.addConditioner(2,cond3,-2);_context2.t0=expect;_context2.next=8;return conditioner.check();case 8:_context2.t1=_context2.sent;(0,_context2.t0)(_context2.t1).toBeFalsy();expect(cond3).toBeCalledTimes(1);expect(cond1).toBeCalledTimes(0);expect(cond2).toBeCalledTimes(0);expect(logger.warn).toBeCalledTimes(1);case 14:case"end":return _context2.stop();}},_callee2);})));it('should fail on second promisified sorted condition',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:expect.assertions(5);cond3.mockResolvedValue(false);conditioner.addConditioner(1,cond1);conditioner.addConditioner(2,cond2,-10);conditioner.addConditioner(2,cond3,-2);_context3.t0=expect;_context3.next=8;return conditioner.check();case 8:_context3.t1=_context3.sent;(0,_context3.t0)(_context3.t1).toBeFalsy();expect(cond3).toBeCalledTimes(1);expect(cond1).toBeCalledTimes(0);expect(cond2).toBeCalledTimes(0);expect(logger.warn).toBeCalledTimes(1);case 14:case"end":return _context3.stop();}},_callee3);})));it('should resolve true',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1)switch(_context4.prev=_context4.next){case 0:conditioner.addConditioner(1,cond1);conditioner.addConditioner(2,cond2);conditioner.addConditioner(3,cond3);_context4.t0=expect;_context4.next=6;return conditioner.check();case 6:_context4.t1=_context4.sent;(0,_context4.t0)(_context4.t1).toBeTruthy();expect(cond1).toBeCalledTimes(1);expect(cond2).toBeCalledTimes(1);expect(cond3).toBeCalledTimes(1);expect(logger.warn).toBeCalledTimes(0);case 12:case"end":return _context4.stop();}},_callee4);})));it('should return cloned conditioner',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(){var newConditioner;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1)switch(_context5.prev=_context5.next){case 0:conditioner.addConditioner('one',cond1);conditioner.addConditioner('two',cond2);newConditioner=conditioner.without('one');expect(newConditioner).not.toBe(conditioner);expect(newConditioner.conditions).not.toBe(conditioner.conditions);expect(newConditioner.conditions.has('one')).toBeFalsy();expect(newConditioner.conditions.has('two')).toBeTruthy();expect(logger.warn).toBeCalledTimes(0);case 8:case"end":return _context5.stop();}},_callee5);})));});
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
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<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call;}return _assertThisInitialized(self);}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return self;}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}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);}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}import event from"../Event";import AppCommand from"../AppCommand";import Request from"../Request";import requestBuffer from"../RequestBuffer";import{logger,ajaxUrl}from"../../helpers";/**
|
|
1
|
+
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<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);return Constructor;}function _callSuper(_this,derived,args){function isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{return!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch(e){return false;}}derived=_getPrototypeOf(derived);return _possibleConstructorReturn(_this,isNativeReflectConstruct()?Reflect.construct(derived,args||[],_getPrototypeOf(_this).constructor):derived.apply(_this,args));}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call;}return _assertThisInitialized(self);}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return self;}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}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);}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}import event from"../Event";import AppCommand from"../AppCommand";import Request from"../Request";import requestBuffer from"../RequestBuffer";import{logger,ajaxUrl}from"../../helpers";/**
|
|
2
2
|
* The DataRequest class. It is the interface to the legacy system.
|
|
3
|
-
*/var DataRequest=/*#__PURE__*/function(_Request){
|
|
3
|
+
*/var DataRequest=/*#__PURE__*/function(_Request){/**
|
|
4
4
|
* Initializes the DataRequest object
|
|
5
5
|
* @param {string} src The source url
|
|
6
|
-
*/function DataRequest(src){var
|
|
6
|
+
*/function DataRequest(src){var _this2;_classCallCheck(this,DataRequest);_this2=_callSuper(this,DataRequest);_this2.src=src;_this2.payload={};_this2.noCache=true;_this2.createSerial(_this2.src);_this2.createEventCallbackName('dataResponse');return _this2;}/**
|
|
7
7
|
* Sets the payload for the DataRequest
|
|
8
8
|
* @param {Object|string} [payload={}] The payload to send with the request
|
|
9
9
|
* @returns {DataRequest}
|
|
10
|
-
*/_createClass(DataRequest,[{key:"setPayload",value:function setPayload(){var payload=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};this.payload=payload;return this;}/**
|
|
10
|
+
*/_inherits(DataRequest,_Request);return _createClass(DataRequest,[{key:"setPayload",value:function setPayload(){var payload=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};this.payload=payload;return this;}/**
|
|
11
11
|
* Decides if the response of the DataRequest will be cached
|
|
12
12
|
* @param {boolean} [noCache=true] If set to `true`, then the DataResponse will not be cached
|
|
13
13
|
* @returns {DataRequest} The DataRequest
|
|
@@ -26,7 +26,7 @@ function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="s
|
|
|
26
26
|
* Dispatches the data request.
|
|
27
27
|
* @param {Function} resolve The resolve() callback of the request promise.
|
|
28
28
|
* @param {Function} reject The reject() callback of the request promise.
|
|
29
|
-
*/},{key:"onDispatch",value:function onDispatch(resolve,reject){var
|
|
29
|
+
*/},{key:"onDispatch",value:function onDispatch(resolve,reject){var _this3=this;// Add the request to the buffer.
|
|
30
30
|
requestBuffer.add(this,this.serial);var requestCallbackName=this.getEventCallbackName();/**
|
|
31
31
|
* The request event callback for the response call.
|
|
32
32
|
* @param {string} serial The serial that was used to identify the DataRequest callback..
|
|
@@ -34,6 +34,6 @@ requestBuffer.add(this,this.serial);var requestCallbackName=this.getEventCallbac
|
|
|
34
34
|
* @param {string} body The response body.
|
|
35
35
|
* @param {string} bodyContentType The type of data within the response body.
|
|
36
36
|
* @return {Object}
|
|
37
|
-
*/var requestCallback=function requestCallback(serial,status,body,bodyContentType){event.removeCallback(requestCallbackName,requestCallback);requestBuffer.remove(serial);if(status!==200){return reject(status);}var responsePayload=body;if(bodyContentType==='application/json; charset=UTF-8'){responsePayload=JSON.parse(responsePayload);}logger.log("dataResponse: ".concat(
|
|
37
|
+
*/var requestCallback=function requestCallback(serial,status,body,bodyContentType){event.removeCallback(requestCallbackName,requestCallback);requestBuffer.remove(serial);if(status!==200){return reject(status);}var responsePayload=body;if(bodyContentType==='application/json; charset=UTF-8'){responsePayload=JSON.parse(responsePayload);}logger.log("dataResponse: ".concat(_this3.src),{status:status,responsePayload:responsePayload});return resolve(responsePayload);};// Apply the event callback.
|
|
38
38
|
event.addCallback(requestCallbackName,requestCallback);// Send the DataRequest.
|
|
39
|
-
var command=new AppCommand();command.setCommandName('sendDataRequest').dispatch({src:ajaxUrl(this.src),serial:this.serial,body:this.getRequestBody(),bodyContentType:this.getContentType(),noCache:this.noCache});}}]);
|
|
39
|
+
var command=new AppCommand();command.setCommandName('sendDataRequest').dispatch({src:ajaxUrl(this.src),serial:this.serial,body:this.getRequestBody(),bodyContentType:this.getContentType(),noCache:this.noCache});}}]);}(Request);export default DataRequest;
|
|
@@ -10,7 +10,7 @@ function _classCallCheck(instance,Constructor){if(!(instance instanceof Construc
|
|
|
10
10
|
* @param {Array} commands The commands to dispatch.
|
|
11
11
|
* @param {string} libVersion The lib version for the command.
|
|
12
12
|
* @return {DevServerBridge}
|
|
13
|
-
*/_createClass(DevServerBridge,[{key:"dispatchCommandsForVersion",value:function dispatchCommandsForVersion(commands,libVersion){var _this=this;if(Array.isArray(commands)){commands.forEach(function(command){_this.dispatchCommandForVersion(command,libVersion);});}return this;}/**
|
|
13
|
+
*/return _createClass(DevServerBridge,[{key:"dispatchCommandsForVersion",value:function dispatchCommandsForVersion(commands,libVersion){var _this=this;if(Array.isArray(commands)){commands.forEach(function(command){_this.dispatchCommandForVersion(command,libVersion);});}return this;}/**
|
|
14
14
|
* Dispatches a single command to the dev server.
|
|
15
15
|
* @param {Object} command The command to dispatch.
|
|
16
16
|
* @param {string} libVersion The lib version for the command.
|
|
@@ -26,4 +26,4 @@ cmds.forEach(function(command){var name=command.c;var params=command.p;var args=
|
|
|
26
26
|
* If the native app receives such a command, it calls a related event within the
|
|
27
27
|
* webviews. Here the response parameters are sorted in the specified order for
|
|
28
28
|
* the different response events.
|
|
29
|
-
*/if(name==='pipelineResponse'){args=[params.error,params.serial,params.output];}else if(name==='httpResponse'){args=[params.error,params.serial,params.response];}else if(name==='dataResponse'){args=[params.serial,params.status,params.body,params.bodyContentType];}else if(name==='webStorageResponse'){args=[params.serial,params.age,params.value];}event.call(name,args);});return this;}}]);
|
|
29
|
+
*/if(name==='pipelineResponse'){args=[params.error,params.serial,params.output];}else if(name==='httpResponse'){args=[params.error,params.serial,params.response];}else if(name==='dataResponse'){args=[params.serial,params.status,params.body,params.bodyContentType];}else if(name==='webStorageResponse'){args=[params.serial,params.age,params.value];}event.call(name,args);});return this;}}]);}();export default DevServerBridge;
|