@shopgate/pwa-core 7.30.0-alpha.7 → 7.30.0-alpha.9

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.
Files changed (85) hide show
  1. package/classes/AppCommand/index.js +115 -11
  2. package/classes/AppCommand/spec.js +260 -6
  3. package/classes/AppCommandRequest/index.js +129 -20
  4. package/classes/AppPermissionsRequest/AppPermissionsRequest.js +45 -7
  5. package/classes/AppPermissionsRequest/GetAppPermissionsRequest.js +48 -9
  6. package/classes/AppPermissionsRequest/RequestAppPermissionsRequest.js +54 -9
  7. package/classes/Bridge/index.js +34 -4
  8. package/classes/Bridge/spec.js +24 -1
  9. package/classes/BrightnessRequest/index.js +59 -10
  10. package/classes/BrightnessRequest/spec.js +111 -6
  11. package/classes/BrowserConnector/index.js +180 -26
  12. package/classes/Conditioner/index.js +74 -8
  13. package/classes/Conditioner/spec.js +75 -1
  14. package/classes/DataRequest/index.js +116 -13
  15. package/classes/DevServerBridge/index.js +85 -9
  16. package/classes/DevServerBridge/spec.js +230 -14
  17. package/classes/ErrorManager/index.js +144 -20
  18. package/classes/ErrorManager/spec.js +244 -2
  19. package/classes/Event/index.js +101 -15
  20. package/classes/HttpRequest/index.js +182 -21
  21. package/classes/PipelineDependencies/index.js +42 -6
  22. package/classes/PipelineDependencies/spec.js +46 -3
  23. package/classes/PipelineManager/index.js +517 -71
  24. package/classes/PipelineManager/spec.js +733 -15
  25. package/classes/PipelineRequest/index.js +167 -19
  26. package/classes/PipelineRequest/mock.js +118 -21
  27. package/classes/PipelineRequest/spec.js +333 -2
  28. package/classes/PipelineSequence/index.js +34 -6
  29. package/classes/Request/index.js +61 -13
  30. package/classes/RequestBuffer/index.js +43 -6
  31. package/classes/RequestManager/index.js +216 -33
  32. package/classes/RequestManager/spec.js +188 -1
  33. package/classes/Scanner/index.js +246 -67
  34. package/classes/ScannerEvent/index.js +23 -9
  35. package/classes/ScannerEventHandler/index.js +39 -16
  36. package/classes/ScannerEventListener/index.js +84 -24
  37. package/classes/ScannerManager/ScanProcessingError.js +11 -3
  38. package/classes/ScannerManager/index.js +133 -21
  39. package/classes/WebStorageRequest/index.js +76 -9
  40. package/commands/analyticsSetCustomValues.js +8 -2
  41. package/commands/appPermissions.js +10 -3
  42. package/commands/brightness.js +33 -5
  43. package/commands/broadcastEvent.js +8 -2
  44. package/commands/cleanTab.js +11 -3
  45. package/commands/closeInAppBrowser.js +22 -2
  46. package/commands/flushTab.js +8 -2
  47. package/commands/getWebStorageEntry.js +11 -2
  48. package/commands/hideMenuBar.js +8 -2
  49. package/commands/hideNavigationBar.js +8 -2
  50. package/commands/hideSplashScreen.js +8 -2
  51. package/commands/onload.js +13 -3
  52. package/commands/openAppSettings.js +8 -2
  53. package/commands/openPage.js +8 -2
  54. package/commands/openPageExtern.js +8 -2
  55. package/commands/performCommandsAfterDelay.js +11 -3
  56. package/commands/plotProjects.js +65 -7
  57. package/commands/popTabToRoot.js +11 -3
  58. package/commands/registerEvents.js +10 -2
  59. package/commands/scanner.js +76 -7
  60. package/commands/setCookie.js +8 -2
  61. package/commands/setDebugLoggingEnabled.js +8 -2
  62. package/commands/setScrollingEnabled.js +7 -2
  63. package/commands/setWebStorageEntry.js +8 -2
  64. package/commands/shareItem.js +18 -2
  65. package/commands/showNavigationBar.js +8 -2
  66. package/commands/showTab.js +13 -2
  67. package/commands/unifiedTracking.js +128 -30
  68. package/constants/AppCommands.js +6 -1
  69. package/constants/AppEvents.js +9 -1
  70. package/constants/AppPermissions.js +57 -13
  71. package/constants/Command.js +1 -1
  72. package/constants/ErrorHandleTypes.js +2 -1
  73. package/constants/ErrorManager.js +15 -1
  74. package/constants/Pipeline.js +52 -17
  75. package/constants/ProcessTypes.js +3 -1
  76. package/constants/RequestManagerModes.js +19 -7
  77. package/constants/RequestTypes.js +2 -1
  78. package/constants/Scanner.js +39 -10
  79. package/constants/Trilean.js +6 -1
  80. package/emitters/ui.js +2 -1
  81. package/helpers/index.js +66 -8
  82. package/helpers/logGroup.js +56 -8
  83. package/helpers/version.js +216 -22
  84. package/index.js +60 -5
  85. package/package.json +1 -2
@@ -1,69 +1,248 @@
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);});};}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 _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}import{logger}from"../../helpers";import{isLibVersionAtLeast}from"../../helpers/version";import ScannerEvent from"../ScannerEvent";import ScannerEventHandler from"../ScannerEventHandler";import appEvent from"../Event";import registerEvents from"../../commands/registerEvents";import{APP_EVENT_SCANNER_DID_SCAN}from"../../constants/AppEvents";import{SCANNER_MODE_ON,SCANNER_TYPE_BARCODE,SCANNER_TYPE_IMAGE,SCANNER_ANIMATION_NONE,SCANNER_MIN_APP_LIB_VERSION}from"../../constants/Scanner";import{openScanner as openAppScanner,startScanner as startAppScanner,stopScanner as stopAppScanner,closeScanner as closeAppScanner,setFlashlightMode as setAppScannerFlashlightMode}from"../../commands/scanner";/**
1
+ import { logger } from "../../helpers";
2
+ import { isLibVersionAtLeast } from "../../helpers/version";
3
+ import ScannerEvent from "../ScannerEvent";
4
+ import ScannerEventHandler from "../ScannerEventHandler";
5
+ import appEvent from "../Event";
6
+ import registerEvents from "../../commands/registerEvents";
7
+ import { APP_EVENT_SCANNER_DID_SCAN } from "../../constants/AppEvents";
8
+ import { SCANNER_MODE_ON, SCANNER_TYPE_BARCODE, SCANNER_TYPE_IMAGE, SCANNER_ANIMATION_NONE, SCANNER_MIN_APP_LIB_VERSION } from "../../constants/Scanner";
9
+ import { openScanner as openAppScanner, startScanner as startAppScanner, stopScanner as stopAppScanner, closeScanner as closeAppScanner, setFlashlightMode as setAppScannerFlashlightMode } from "../../commands/scanner";
10
+
11
+ /**
2
12
  * Represents the app scanner.
3
- */export var Scanner=/*#__PURE__*/_createClass(/**
13
+ */
14
+ export class Scanner {
15
+ /**
4
16
  * Initializes the scanner
5
- */function Scanner(){var _this=this;_classCallCheck(this,Scanner);/**
6
- * Reset Scanner state
7
- */_defineProperty(this,"reset",function(){_this.scope=null;_this.type=null;_this.opened=false;_this.running=false;_this.handling=false;_this.flashlightEnabled=false;_this.closeHandler=null;});/**
8
- * Adds an event listener to the scanner.
9
- * @param {ScannerEventListener} eventListener The eventListener to add.
10
- */_defineProperty(this,"addListener",function(eventListener){_this.eventHandler.attach(eventListener);});/**
11
- * @param {ScannerEventListener} eventListener The event listener to remove.
12
- * @returns {boolean} Returns false if the listener was not found by id. Returns true otherwise.
13
- */_defineProperty(this,"removeListener",function(eventListener){return _this.eventHandler.detach(eventListener);});/**
14
- * Callback for the close handler for the scanner. The scanner stops scanning and notifies
15
- * the close handler when it's done. The close handler can either shut down the Scanner instance
16
- * by calling its close() method or restart it to continue scanning.
17
- *
18
- * @callback Scanner~CloseHandler
19
- * @param {Scanner} scannerInstance The instance of the scanner which requested closing.
20
- * @returns {undefined|null} The return value is ignored.
21
- */ /**
22
- * Starts the app scanner. It will instantly start the scanning process for type
23
- * "barcodeRecognition". The image scanner requires user interaction to scan.
24
- * @param {string} scope The initially activated scanner scope.
25
- * @param {ScannerType|string} type The initially activated scanner type.
26
- * @param {CloseHandler|null} [closeHandler] This handler is called when the Scanner is closed.
27
- * @param {string|null} [source] Tells the app which overlay to use, null for "current".
28
- * @param {string|null} [animation] Tells the app what type of animation to apply when opening.
29
- */_defineProperty(this,"open",/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(scope){var type,closeHandler,source,animation,errMsgPrefix,libVersionResult,err,_err,_err2,_err3,_err4,_args=arguments;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:type=_args.length>1&&_args[1]!==undefined?_args[1]:SCANNER_TYPE_BARCODE;closeHandler=_args.length>2&&_args[2]!==undefined?_args[2]:null;source=_args.length>3&&_args[3]!==undefined?_args[3]:null;animation=_args.length>4&&_args[4]!==undefined?_args[4]:null;errMsgPrefix='Failed to open scanner:';// A minimum app lib version is required, which is defined above.
30
- _context.prev=5;_context.next=8;return isLibVersionAtLeast(SCANNER_MIN_APP_LIB_VERSION);case 8:libVersionResult=_context.sent;_context.next=15;break;case 11:_context.prev=11;_context.t0=_context["catch"](5);logger.error("".concat(errMsgPrefix," Could not fetch app lib version. Instead received error:"),_context.t0);return _context.abrupt("return");case 15:if(libVersionResult){_context.next=19;break;}err=new Error("".concat(errMsgPrefix," App lib version must be at least equal to or higher than ").concat(SCANNER_MIN_APP_LIB_VERSION,"."));logger.error(err);return _context.abrupt("return");case 19:if(!(!scope||scope==='')){_context.next=23;break;}_err=new Error("".concat(errMsgPrefix," Scope can not be empty."));logger.error(_err);return _context.abrupt("return");case 23:if(_this.supportedTypes.includes(type)){_context.next=27;break;}_err2=new Error("".concat(errMsgPrefix," ").concat(type," is a not supported scanner type."));logger.error(_err2);return _context.abrupt("return");case 27:if(!_this.opened){_context.next=31;break;}_err3=new Error("".concat(errMsgPrefix," An instance with scope \"").concat(_this.scope,"\" is already running."));logger.error(_err3);return _context.abrupt("return");case 31:if(!(closeHandler!==null&&typeof closeHandler!=='function')){_context.next=35;break;}_err4=new Error("".concat(errMsgPrefix," Close handler must be a function."));logger.error(_err4);return _context.abrupt("return");case 35:// Add a listener to the scannerDidScan app event to process scanned data.
31
- appEvent.addCallback(APP_EVENT_SCANNER_DID_SCAN,_this.handleScan);// Open the app scanner.
32
- openAppScanner({src:source||'',modes:_defineProperty({},type,SCANNER_MODE_ON),animation:animation||SCANNER_ANIMATION_NONE});// Initialize internal states
33
- _this.scope=scope;_this.type=type;_this.opened=true;// Image scanner does not automatically scan
34
- _this.running=_this.type!==SCANNER_TYPE_IMAGE;_this.closeHandler=closeHandler||null;case 42:case"end":return _context.stop();}},_callee,null,[[5,11]]);}));return function(_x){return _ref.apply(this,arguments);};}());/**
35
- * Starts the Scanner if it is opened and not already running.
36
- */_defineProperty(this,"start",function(){if(!_this.opened){logger.error(new Error("Can't start Scanner: Scanner is not opened."));return;}_this.handling=false;// Start only if not already running.
37
- if(!_this.running){_this.running=true;startAppScanner();}});/**
38
- * Stops the scanner if it is opened and running.
39
- */_defineProperty(this,"stop",function(){if(!_this.opened){logger.error(new Error("Can't start Scanner: Scanner is not opened."));return;}// Stop only if is running at the moment.
40
- if(_this.isRunning){_this.running=false;stopAppScanner();}});/**
41
- * Close the app scanner.
42
- */_defineProperty(this,"close",function(){if(!_this.opened){logger.warn("Can't close Scanner: Scanner is not opened.");return;}// Remove the listener to avoid further scan results.
43
- appEvent.removeCallback(APP_EVENT_SCANNER_DID_SCAN,_this.handleScan);// Switch off flashlight to make sure it does not stay enabled.
44
- _this.toggleFlashlight(false);closeAppScanner();_this.reset();});/**
45
- * Switches between the flashlight being on or off. The return result might not always
46
- * be reliable when the app is brought into the background or if other apps interfere.
47
- * Can only be toggled when the scanner is opened.
48
- * @param {boolean|undefined} [enable] True/false to switch on/off or leave out for toggle.
49
- * @returns {boolean} Returns the new flashlight on/off state.
50
- */_defineProperty(this,"toggleFlashlight",function(){var enable=arguments.length>0&&arguments[0]!==undefined?arguments[0]:undefined;if(!_this.opened){logger.error(new Error("Can't toggle the flashlight: Scanner not opened!"));return false;}if(enable!==undefined){_this.flashlightEnabled=!!enable;}else{_this.flashlightEnabled=!_this.flashlightEnabled;}setAppScannerFlashlightMode(_this.flashlightEnabled);return _this.flashlightEnabled;});/**
51
- * Because opening the scanner can fail silently, this is a way to check if it was
52
- * opened properly.
53
- * @returns {boolean}
54
- */_defineProperty(this,"isOpened",function(){return _this.opened;});/**
55
- * Some scanner types don't start and all of them stop running after a successful scan.
56
- * This method allows checking if a scan is currently in progress.
57
- * @returns {boolean}
58
- */_defineProperty(this,"isRunning",function(){return _this.running;});/**
59
- * Helps checking the current state of the flashlight. This might not be reliable as the
60
- * flashlight is turned off without notice, when the app is pushed into the background.
61
- * @returns {boolean}
62
- */_defineProperty(this,"isFlashlightEnabled",function(){return _this.flashlightEnabled;});/**
63
- * The internal handler for the "scannerDidScan" app event.
64
- * @private
65
- * @param {ScannerEventPayload} payload The payload of the scanner event for the scanned result.
66
- */_defineProperty(this,"handleScan",/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(payload){var event;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:event=new ScannerEvent(_this.scope,_this.type,payload);if(_this.eventHandler.hasListenersForEvent(event)){_context2.next=4;break;}logger.warn('No scanner listeners',payload);return _context2.abrupt("return");case 4:if(!_this.handling){_context2.next=7;break;}logger.warn('Scan result ignored in handling stage',payload);return _context2.abrupt("return");case 7:_this.handling=true;_this.stop();_context2.prev=9;_context2.next=12;return _this.eventHandler.notifyAllListeners(event);case 12:// Notify the close handler that the Scanner is done doing his work.
67
- if(_this.closeHandler){_this.closeHandler(_this);}_context2.next=19;break;case 15:_context2.prev=15;_context2.t0=_context2["catch"](9);logger.warn('Scan handler threw error:',_context2.t0);// Force restart when a handler throws an error.
68
- _this.start();case 19:case"end":return _context2.stop();}},_callee2,null,[[9,15]]);}));return function(_x2){return _ref2.apply(this,arguments);};}());this.supportedTypes=[SCANNER_TYPE_BARCODE,SCANNER_TYPE_IMAGE];this.eventHandler=new ScannerEventHandler();// Register app scan event to listen for.
69
- registerEvents([APP_EVENT_SCANNER_DID_SCAN]);this.reset();});export default new Scanner();
17
+ */
18
+ constructor() {
19
+ /**
20
+ * Reset Scanner state
21
+ */
22
+ this.reset = () => {
23
+ this.scope = null;
24
+ this.type = null;
25
+ this.opened = false;
26
+ this.running = false;
27
+ this.handling = false;
28
+ this.flashlightEnabled = false;
29
+ this.closeHandler = null;
30
+ };
31
+ /**
32
+ * Adds an event listener to the scanner.
33
+ * @param {ScannerEventListener} eventListener The eventListener to add.
34
+ */
35
+ this.addListener = eventListener => {
36
+ this.eventHandler.attach(eventListener);
37
+ };
38
+ /**
39
+ * @param {ScannerEventListener} eventListener The event listener to remove.
40
+ * @returns {boolean} Returns false if the listener was not found by id. Returns true otherwise.
41
+ */
42
+ this.removeListener = eventListener => this.eventHandler.detach(eventListener);
43
+ /**
44
+ * Callback for the close handler for the scanner. The scanner stops scanning and notifies
45
+ * the close handler when it's done. The close handler can either shut down the Scanner instance
46
+ * by calling its close() method or restart it to continue scanning.
47
+ *
48
+ * @callback Scanner~CloseHandler
49
+ * @param {Scanner} scannerInstance The instance of the scanner which requested closing.
50
+ * @returns {undefined|null} The return value is ignored.
51
+ */
52
+ /**
53
+ * Starts the app scanner. It will instantly start the scanning process for type
54
+ * "barcodeRecognition". The image scanner requires user interaction to scan.
55
+ * @param {string} scope The initially activated scanner scope.
56
+ * @param {ScannerType|string} type The initially activated scanner type.
57
+ * @param {CloseHandler|null} [closeHandler] This handler is called when the Scanner is closed.
58
+ * @param {string|null} [source] Tells the app which overlay to use, null for "current".
59
+ * @param {string|null} [animation] Tells the app what type of animation to apply when opening.
60
+ */
61
+ this.open = async (scope, type = SCANNER_TYPE_BARCODE, closeHandler = null, source = null, animation = null) => {
62
+ const errMsgPrefix = 'Failed to open scanner:';
63
+
64
+ // A minimum app lib version is required, which is defined above.
65
+ let libVersionResult;
66
+ try {
67
+ libVersionResult = await isLibVersionAtLeast(SCANNER_MIN_APP_LIB_VERSION);
68
+ } catch (err) {
69
+ logger.error(`${errMsgPrefix} Could not fetch app lib version. Instead received error:`, err);
70
+ return;
71
+ }
72
+ if (!libVersionResult) {
73
+ const err = new Error(`${errMsgPrefix} App lib version must be at least equal to or higher than ${SCANNER_MIN_APP_LIB_VERSION}.`);
74
+ logger.error(err);
75
+ return;
76
+ }
77
+
78
+ // Make sure the scope was properly set
79
+ if (!scope || scope === '') {
80
+ const err = new Error(`${errMsgPrefix} Scope can not be empty.`);
81
+ logger.error(err);
82
+ return;
83
+ }
84
+ if (!this.supportedTypes.includes(type)) {
85
+ const err = new Error(`${errMsgPrefix} ${type} is a not supported scanner type.`);
86
+ logger.error(err);
87
+ return;
88
+ }
89
+
90
+ // Only one instance can be running at the same time.
91
+ if (this.opened) {
92
+ const err = new Error(`${errMsgPrefix} An instance with scope "${this.scope}" is already running.`);
93
+ logger.error(err);
94
+ return;
95
+ }
96
+ if (closeHandler !== null && typeof closeHandler !== 'function') {
97
+ const err = new Error(`${errMsgPrefix} Close handler must be a function.`);
98
+ logger.error(err);
99
+ return;
100
+ }
101
+
102
+ // Add a listener to the scannerDidScan app event to process scanned data.
103
+ appEvent.addCallback(APP_EVENT_SCANNER_DID_SCAN, this.handleScan);
104
+
105
+ // Open the app scanner.
106
+ openAppScanner({
107
+ src: source || '',
108
+ modes: {
109
+ [type]: SCANNER_MODE_ON
110
+ },
111
+ animation: animation || SCANNER_ANIMATION_NONE
112
+ });
113
+
114
+ // Initialize internal states
115
+ this.scope = scope;
116
+ this.type = type;
117
+ this.opened = true;
118
+
119
+ // Image scanner does not automatically scan
120
+ this.running = this.type !== SCANNER_TYPE_IMAGE;
121
+ this.closeHandler = closeHandler || null;
122
+ };
123
+ /**
124
+ * Starts the Scanner if it is opened and not already running.
125
+ */
126
+ this.start = () => {
127
+ if (!this.opened) {
128
+ logger.error(new Error("Can't start Scanner: Scanner is not opened."));
129
+ return;
130
+ }
131
+ this.handling = false;
132
+
133
+ // Start only if not already running.
134
+ if (!this.running) {
135
+ this.running = true;
136
+ startAppScanner();
137
+ }
138
+ };
139
+ /**
140
+ * Stops the scanner if it is opened and running.
141
+ */
142
+ this.stop = () => {
143
+ if (!this.opened) {
144
+ logger.error(new Error("Can't start Scanner: Scanner is not opened."));
145
+ return;
146
+ }
147
+
148
+ // Stop only if is running at the moment.
149
+ if (this.isRunning) {
150
+ this.running = false;
151
+ stopAppScanner();
152
+ }
153
+ };
154
+ /**
155
+ * Close the app scanner.
156
+ */
157
+ this.close = () => {
158
+ if (!this.opened) {
159
+ logger.warn("Can't close Scanner: Scanner is not opened.");
160
+ return;
161
+ }
162
+
163
+ // Remove the listener to avoid further scan results.
164
+ appEvent.removeCallback(APP_EVENT_SCANNER_DID_SCAN, this.handleScan);
165
+
166
+ // Switch off flashlight to make sure it does not stay enabled.
167
+ this.toggleFlashlight(false);
168
+ closeAppScanner();
169
+ this.reset();
170
+ };
171
+ /**
172
+ * Switches between the flashlight being on or off. The return result might not always
173
+ * be reliable when the app is brought into the background or if other apps interfere.
174
+ * Can only be toggled when the scanner is opened.
175
+ * @param {boolean|undefined} [enable] True/false to switch on/off or leave out for toggle.
176
+ * @returns {boolean} Returns the new flashlight on/off state.
177
+ */
178
+ this.toggleFlashlight = (enable = undefined) => {
179
+ if (!this.opened) {
180
+ logger.error(new Error("Can't toggle the flashlight: Scanner not opened!"));
181
+ return false;
182
+ }
183
+ if (enable !== undefined) {
184
+ this.flashlightEnabled = !!enable;
185
+ } else {
186
+ this.flashlightEnabled = !this.flashlightEnabled;
187
+ }
188
+ setAppScannerFlashlightMode(this.flashlightEnabled);
189
+ return this.flashlightEnabled;
190
+ };
191
+ /**
192
+ * Because opening the scanner can fail silently, this is a way to check if it was
193
+ * opened properly.
194
+ * @returns {boolean}
195
+ */
196
+ this.isOpened = () => this.opened;
197
+ /**
198
+ * Some scanner types don't start and all of them stop running after a successful scan.
199
+ * This method allows checking if a scan is currently in progress.
200
+ * @returns {boolean}
201
+ */
202
+ this.isRunning = () => this.running;
203
+ /**
204
+ * Helps checking the current state of the flashlight. This might not be reliable as the
205
+ * flashlight is turned off without notice, when the app is pushed into the background.
206
+ * @returns {boolean}
207
+ */
208
+ this.isFlashlightEnabled = () => this.flashlightEnabled;
209
+ /**
210
+ * The internal handler for the "scannerDidScan" app event.
211
+ * @private
212
+ * @param {ScannerEventPayload} payload The payload of the scanner event for the scanned result.
213
+ */
214
+ this.handleScan = async payload => {
215
+ const event = new ScannerEvent(this.scope, this.type, payload);
216
+ if (!this.eventHandler.hasListenersForEvent(event)) {
217
+ logger.warn('No scanner listeners', payload);
218
+ return;
219
+ }
220
+ if (this.handling) {
221
+ logger.warn('Scan result ignored in handling stage', payload);
222
+ return;
223
+ }
224
+ this.handling = true;
225
+ this.stop();
226
+ try {
227
+ // Ignore return values from handlers.
228
+ await this.eventHandler.notifyAllListeners(event);
229
+
230
+ // Notify the close handler that the Scanner is done doing his work.
231
+ if (this.closeHandler) {
232
+ this.closeHandler(this);
233
+ }
234
+ } catch (error) {
235
+ logger.warn('Scan handler threw error:', error);
236
+ // Force restart when a handler throws an error.
237
+ this.start();
238
+ }
239
+ };
240
+ this.supportedTypes = [SCANNER_TYPE_BARCODE, SCANNER_TYPE_IMAGE];
241
+ this.eventHandler = new ScannerEventHandler();
242
+
243
+ // Register app scan event to listen for.
244
+ registerEvents([APP_EVENT_SCANNER_DID_SCAN]);
245
+ this.reset();
246
+ }
247
+ }
248
+ export default new Scanner();
@@ -1,17 +1,31 @@
1
- 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 _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}/**
1
+ /**
2
2
  * @typedef {Object} ScannerEventPayload
3
3
  * @property {string} format
4
4
  * @property {string} code
5
5
  *
6
6
  * Defines an event which is emitted when the scanner scans something.
7
- */var ScannerEvent=/*#__PURE__*/_createClass(/**
7
+ */
8
+ export default class ScannerEvent {
9
+ /**
8
10
  * @param {string} scope The scanner instance, that was running when this event was emitted.
9
11
  * @param {string} type The type of scanner that produced this result.
10
12
  * @param {ScannerEventPayload} payload The payload of the scan result.
11
- */function ScannerEvent(scope,type,payload){var _this=this;_classCallCheck(this,ScannerEvent);/**
12
- * @returns {string}
13
- */_defineProperty(this,"getScope",function(){return _this.scope;});/**
14
- * @returns {string}
15
- */_defineProperty(this,"getType",function(){return _this.type;});/**
16
- * @returns {ScannerEventPayload}
17
- */_defineProperty(this,"getPayload",function(){return _this.payload;});this.scope=scope;this.type=type;this.payload=payload;});export{ScannerEvent as default};
13
+ */
14
+ constructor(scope, type, payload) {
15
+ /**
16
+ * @returns {string}
17
+ */
18
+ this.getScope = () => this.scope;
19
+ /**
20
+ * @returns {string}
21
+ */
22
+ this.getType = () => this.type;
23
+ /**
24
+ * @returns {ScannerEventPayload}
25
+ */
26
+ this.getPayload = () => this.payload;
27
+ this.scope = scope;
28
+ this.type = type;
29
+ this.payload = payload;
30
+ }
31
+ }
@@ -1,18 +1,41 @@
1
- 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 _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}/**
1
+ /**
2
2
  * Manages scanner event listeners.
3
- */var ScannerEventHandler=/*#__PURE__*/_createClass(/**
3
+ */
4
+ export default class ScannerEventHandler {
5
+ /**
4
6
  * Initializes the event handler.
5
- */function ScannerEventHandler(){var _this=this;_classCallCheck(this,ScannerEventHandler);/**
6
- * @param {ScannerEventListener} eventListener The event listener to attach to the handler.
7
- */_defineProperty(this,"attach",function(eventListener){_this.eventListeners.add(eventListener);});/**
8
- * @param {ScannerEventListener} eventListener The event listener to detach from the handler.
9
- * @returns {boolean} Returns true if the event listener was detached successfully.
10
- */_defineProperty(this,"detach",function(eventListener){return _this.eventListeners["delete"](eventListener);});/**
11
- * @param {ScannerEvent} event The event which has been emitted by the scanner.
12
- * @returns {boolean}
13
- */_defineProperty(this,"hasListenersForEvent",function(event){return Array.from(_this.eventListeners).some(function(listener){return listener.canHandleEvent(event);});});/**
14
- * @param {ScannerEvent} event The event which has been emitted by the scanner.
15
- * @returns {Promise<undefined>}
16
- * @throws {Error}
17
- */_defineProperty(this,"notifyAllListeners",function(event){var notifyResults=[];_this.eventListeners.forEach(function(listener){notifyResults.push(listener.notify(event));});// Forward occurring errors only, because there should be no return value from "notify"
18
- return Promise.all(notifyResults).then(function(){});});this.eventListeners=new Set();});export{ScannerEventHandler as default};
7
+ */
8
+ constructor() {
9
+ /**
10
+ * @param {ScannerEventListener} eventListener The event listener to attach to the handler.
11
+ */
12
+ this.attach = eventListener => {
13
+ this.eventListeners.add(eventListener);
14
+ };
15
+ /**
16
+ * @param {ScannerEventListener} eventListener The event listener to detach from the handler.
17
+ * @returns {boolean} Returns true if the event listener was detached successfully.
18
+ */
19
+ this.detach = eventListener => this.eventListeners.delete(eventListener);
20
+ /**
21
+ * @param {ScannerEvent} event The event which has been emitted by the scanner.
22
+ * @returns {boolean}
23
+ */
24
+ this.hasListenersForEvent = event => Array.from(this.eventListeners).some(listener => listener.canHandleEvent(event));
25
+ /**
26
+ * @param {ScannerEvent} event The event which has been emitted by the scanner.
27
+ * @returns {Promise<undefined>}
28
+ * @throws {Error}
29
+ */
30
+ this.notifyAllListeners = event => {
31
+ const notifyResults = [];
32
+ this.eventListeners.forEach(listener => {
33
+ notifyResults.push(listener.notify(event));
34
+ });
35
+
36
+ // Forward occurring errors only, because there should be no return value from "notify"
37
+ return Promise.all(notifyResults).then(() => {});
38
+ };
39
+ this.eventListeners = new Set();
40
+ }
41
+ }
@@ -1,29 +1,89 @@
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);});};}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 _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}import{logger}from"../../helpers";import AppScanner from"../Scanner";/**
1
+ import { logger } from "../../helpers";
2
+ import AppScanner from "../Scanner";
3
+
4
+ /**
2
5
  * Allows anyone to listen for scan results based on scope, type or both.
3
- */var ScannerEventListener=/*#__PURE__*/_createClass(/**
6
+ */
7
+ class ScannerEventListener {
8
+ /**
4
9
  * @param {string|null} name A name for the listener object to refer to.
5
10
  * @param {string|null} scope The scanner scope to listen for.
6
11
  * @param {string|null} type THe type of scanner events to listen for.
7
12
  * @param {Array} formats The formats which can be processed by the listener.
8
- */function ScannerEventListener(){var _this=this;var name=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;var scope=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var type=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;var formats=arguments.length>3&&arguments[3]!==undefined?arguments[3]:[];_classCallCheck(this,ScannerEventListener);/**
9
- * Callback for an instance of an event listener. It is expected to return no value on success.
10
- * Throw an Error() to force the scanner to restart.
11
- *
12
- * @callback ScannerEventListener~Handler
13
- * @param {ScannerEvent} event The event which is emitted, when something was scanned.
14
- * @returns {undefined|null} The return value is ignored. Returning a value will cause a warning.
15
- * @throws {Error} Throwing an error will cause the Scanner to restart and scan again.
16
- */ /**
17
- * @param {Handler} handler The function which is called when a scan is done.
18
- * @returns {ScannerEventListener}
19
- */_defineProperty(this,"setHandler",function(handler){if(typeof handler!=='function'){logger.error(new Error('The ScannerEventListener handler must be a function!'));}_this.handler=handler;return _this;});/**
20
- * Checks if the event fits to the handler.
21
- * @param {ScannerEvent} event The scanner event which was emitted.
22
- * @returns {boolean}
23
- */_defineProperty(this,"canHandleEvent",function(event){if(!_this.handler){logger.warn("No event handler defined for eventListener \"".concat(_this.name,"\""));return false;}if(_this.type&&_this.type!==event.getType()){return false;}if(_this.scope&&_this.scope!==event.getScope()){return false;}var _ref=event.getPayload()||{},format=_ref.format;if(_this.formats.length&&!_this.formats.includes(format)){return false;}return true;});/**
24
- * Attach the current event listener to the app scanner.
25
- */_defineProperty(this,"attach",function(){AppScanner.addListener(_this);});/**
26
- * Checks the event to see, if the listener is interested in it and call it's handler.
27
- * @param {ScannerEvent} event The scanner event which was emitted.
28
- */_defineProperty(this,"notify",/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(event){var handlerResult;return _regeneratorRuntime.wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:if(_this.canHandleEvent(event)){_context.next=2;break;}return _context.abrupt("return");case 2:_context.next=4;return _this.handler(event);case 4:handlerResult=_context.sent;// Don't expect anything else than undefined or null
29
- if(handlerResult!==undefined&&handlerResult!==null){logger.warn("Expected the ScannerEventListener::Handler \"".concat(_this.name,"\" to return no value,"),"but it returned \"".concat(handlerResult,"\""));}case 6:case"end":return _context.stop();}},_callee);}));return function(_x){return _ref2.apply(this,arguments);};}());this.name=name||'unnamed';this.scope=scope||null;this.type=type||null;this.formats=formats||[];this.handler=null;});export default ScannerEventListener;
13
+ */
14
+ constructor(name = null, scope = null, type = null, formats = []) {
15
+ /**
16
+ * Callback for an instance of an event listener. It is expected to return no value on success.
17
+ * Throw an Error() to force the scanner to restart.
18
+ *
19
+ * @callback ScannerEventListener~Handler
20
+ * @param {ScannerEvent} event The event which is emitted, when something was scanned.
21
+ * @returns {undefined|null} The return value is ignored. Returning a value will cause a warning.
22
+ * @throws {Error} Throwing an error will cause the Scanner to restart and scan again.
23
+ */
24
+ /**
25
+ * @param {Handler} handler The function which is called when a scan is done.
26
+ * @returns {ScannerEventListener}
27
+ */
28
+ this.setHandler = handler => {
29
+ if (typeof handler !== 'function') {
30
+ logger.error(new Error('The ScannerEventListener handler must be a function!'));
31
+ }
32
+ this.handler = handler;
33
+ return this;
34
+ };
35
+ /**
36
+ * Checks if the event fits to the handler.
37
+ * @param {ScannerEvent} event The scanner event which was emitted.
38
+ * @returns {boolean}
39
+ */
40
+ this.canHandleEvent = event => {
41
+ if (!this.handler) {
42
+ logger.warn(`No event handler defined for eventListener "${this.name}"`);
43
+ return false;
44
+ }
45
+ if (this.type && this.type !== event.getType()) {
46
+ return false;
47
+ }
48
+ if (this.scope && this.scope !== event.getScope()) {
49
+ return false;
50
+ }
51
+ const {
52
+ format
53
+ } = event.getPayload() || {};
54
+ if (this.formats.length && !this.formats.includes(format)) {
55
+ return false;
56
+ }
57
+ return true;
58
+ };
59
+ /**
60
+ * Attach the current event listener to the app scanner.
61
+ */
62
+ this.attach = () => {
63
+ AppScanner.addListener(this);
64
+ };
65
+ /**
66
+ * Checks the event to see, if the listener is interested in it and call it's handler.
67
+ * @param {ScannerEvent} event The scanner event which was emitted.
68
+ */
69
+ this.notify = async event => {
70
+ if (!this.canHandleEvent(event)) {
71
+ return;
72
+ }
73
+
74
+ // Call the listener which was previously registered
75
+ const handlerResult = await this.handler(event);
76
+
77
+ // Don't expect anything else than undefined or null
78
+ if (handlerResult !== undefined && handlerResult !== null) {
79
+ logger.warn(`Expected the ScannerEventListener::Handler "${this.name}" to return no value,`, `but it returned "${handlerResult}"`);
80
+ }
81
+ };
82
+ this.name = name || 'unnamed';
83
+ this.scope = scope || null;
84
+ this.type = type || null;
85
+ this.formats = formats || [];
86
+ this.handler = null;
87
+ }
88
+ }
89
+ export default ScannerEventListener;
@@ -1,9 +1,17 @@
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 _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 _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}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 _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 _wrapNativeSuper(Class){var _cache=typeof Map==="function"?new Map():undefined;_wrapNativeSuper=function _wrapNativeSuper(Class){if(Class===null||!_isNativeFunction(Class))return Class;if(typeof Class!=="function"){throw new TypeError("Super expression must either be null or a function");}if(typeof _cache!=="undefined"){if(_cache.has(Class))return _cache.get(Class);_cache.set(Class,Wrapper);}function Wrapper(){return _construct(Class,arguments,_getPrototypeOf(this).constructor);}Wrapper.prototype=Object.create(Class.prototype,{constructor:{value:Wrapper,enumerable:false,writable:true,configurable:true}});return _setPrototypeOf(Wrapper,Class);};return _wrapNativeSuper(Class);}function isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Date.prototype.toString.call(Reflect.construct(Date,[],function(){}));return true;}catch(e){return false;}}function _construct(Parent,args,Class){if(isNativeReflectConstruct()){_construct=Reflect.construct;}else{_construct=function _construct(Parent,args,Class){var a=[null];a.push.apply(a,args);var Constructor=Function.bind.apply(Parent,a);var instance=new Constructor();if(Class)_setPrototypeOf(instance,Class.prototype);return instance;};}return _construct.apply(null,arguments);}function _isNativeFunction(fn){return Function.toString.call(fn).indexOf("[native code]")!==-1;}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf||function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}/**
1
+ /**
2
2
  * The ScanProcessingError is supposed to be thrown in case of a processing error of the scanned
3
3
  * content. It's properties will be used to display an error message to the user.
4
4
  * @extends Error
5
- */var ScanProcessingError=/*#__PURE__*/function(_Error){/**
5
+ */
6
+ class ScanProcessingError extends Error {
7
+ /**
6
8
  * Constructor for the ScanProcessingError
7
9
  * @param {string} message The message of the error.
8
10
  * @param {string} [title=null] The title of the error.
9
- */function ScanProcessingError(message){var _this2;var title=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;_classCallCheck(this,ScanProcessingError);_this2=_callSuper(this,ScanProcessingError,[message]);_this2.title=title;return _this2;}_inherits(ScanProcessingError,_Error);return _createClass(ScanProcessingError);}(/*#__PURE__*/_wrapNativeSuper(Error));export default ScanProcessingError;
11
+ */
12
+ constructor(message, title = null) {
13
+ super(message);
14
+ this.title = title;
15
+ }
16
+ }
17
+ export default ScanProcessingError;