dynamsoft-barcode-reader-bundle 10.4.3100 → 10.5.1000-iv-singlewasm

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 (66) hide show
  1. package/dynamsoft-barcode-reader@10.4.31/dist/DBR-PresetTemplates.json +628 -0
  2. package/dynamsoft-barcode-reader@10.4.31/dist/dbr.d.ts +383 -0
  3. package/dynamsoft-barcode-reader@10.4.31/dist/dbr.esm.js +11 -0
  4. package/dynamsoft-barcode-reader@10.4.31/dist/dbr.js +11 -0
  5. package/dynamsoft-barcode-reader@10.4.31/dist/dbr.mjs +11 -0
  6. package/dynamsoft-camera-enhancer@4.1.1/dist/dce.d.ts +1877 -0
  7. package/dynamsoft-camera-enhancer@4.1.1/dist/dce.esm.js +11 -0
  8. package/dynamsoft-camera-enhancer@4.1.1/dist/dce.js +11 -0
  9. package/dynamsoft-camera-enhancer@4.1.1/dist/dce.mjs +11 -0
  10. package/dynamsoft-camera-enhancer@4.1.1/dist/dce.mobile-native.ui.html +222 -0
  11. package/dynamsoft-camera-enhancer@4.1.1/dist/dce.ui.html +115 -0
  12. package/dynamsoft-capture-vision-router@2.4.33/dist/cvr.d.ts +663 -0
  13. package/dynamsoft-capture-vision-router@2.4.33/dist/cvr.esm.js +2121 -0
  14. package/dynamsoft-capture-vision-router@2.4.33/dist/cvr.js +11 -0
  15. package/dynamsoft-capture-vision-router@2.4.33/dist/cvr.mjs +2121 -0
  16. package/dynamsoft-capture-vision-router@2.4.33/dist/cvr.worker.js +21 -0
  17. package/dynamsoft-capture-vision-std@1.4.21/dist/std.js +1 -0
  18. package/dynamsoft-capture-vision-std@1.4.21/dist/std.wasm +0 -0
  19. package/dynamsoft-code-parser@2.4.32/dist/dcp.d.ts +90 -0
  20. package/dynamsoft-code-parser@2.4.32/dist/dcp.esm.js +11 -0
  21. package/dynamsoft-code-parser@2.4.32/dist/dcp.js +11 -0
  22. package/dynamsoft-code-parser@2.4.32/dist/dcp.worker.js +21 -0
  23. package/dynamsoft-code-parser@2.4.32/dist/specification/AADHAAR.data +0 -0
  24. package/dynamsoft-code-parser@2.4.32/dist/specification/AADHAAR_Map.txt +3 -0
  25. package/dynamsoft-code-parser@2.4.32/dist/specification/AAMVA_DL_ID.data +0 -0
  26. package/dynamsoft-code-parser@2.4.32/dist/specification/AAMVA_DL_ID_WITH_MAG_STRIPE.data +0 -0
  27. package/dynamsoft-code-parser@2.4.32/dist/specification/AAMVA_Map.txt +70 -0
  28. package/dynamsoft-code-parser@2.4.32/dist/specification/MRTD_Map.txt +255 -0
  29. package/dynamsoft-code-parser@2.4.32/dist/specification/MRTD_TD1_ID.data +0 -0
  30. package/dynamsoft-code-parser@2.4.32/dist/specification/MRTD_TD2_FRENCH_ID.data +0 -0
  31. package/dynamsoft-code-parser@2.4.32/dist/specification/MRTD_TD2_ID.data +0 -0
  32. package/dynamsoft-code-parser@2.4.32/dist/specification/MRTD_TD2_VISA.data +0 -0
  33. package/dynamsoft-code-parser@2.4.32/dist/specification/MRTD_TD3_PASSPORT.data +0 -0
  34. package/dynamsoft-code-parser@2.4.32/dist/specification/MRTD_TD3_VISA.data +0 -0
  35. package/dynamsoft-code-parser@2.4.32/dist/specification/SOUTH_AFRICA_DL.data +0 -0
  36. package/dynamsoft-code-parser@2.4.32/dist/specification/SouthAfricaDL_Map.txt +3 -0
  37. package/dynamsoft-code-parser@2.4.32/dist/specification/VIN.data +0 -0
  38. package/dynamsoft-code-parser@2.4.32/dist/specification/VIN_Map.txt +150 -0
  39. package/dynamsoft-core@3.4.31/dist/core.d.ts +1019 -0
  40. package/dynamsoft-core@3.4.31/dist/core.esm.js +11 -0
  41. package/dynamsoft-core@3.4.31/dist/core.js +11 -0
  42. package/dynamsoft-core@3.4.31/dist/core.mjs +11 -0
  43. package/dynamsoft-core@3.4.31/dist/core.worker.js +11 -0
  44. package/dynamsoft-license@3.4.31/dist/dls.license.dialog.html +20 -0
  45. package/dynamsoft-license@3.4.31/dist/license.d.ts +40 -0
  46. package/dynamsoft-license@3.4.31/dist/license.esm.js +11 -0
  47. package/dynamsoft-license@3.4.31/dist/license.js +11 -0
  48. package/dynamsoft-license@3.4.31/dist/license.mjs +11 -0
  49. package/dynamsoft-license@3.4.31/dist/license.worker.js +11 -0
  50. package/dynamsoft-utility@1.4.32/dist/utility.d.ts +118 -0
  51. package/dynamsoft-utility@1.4.32/dist/utility.esm.js +11 -0
  52. package/dynamsoft-utility@1.4.32/dist/utility.js +11 -0
  53. package/dynamsoft-utility@1.4.32/dist/utility.mjs +11 -0
  54. package/dynamsoft-utility@1.4.32/dist/utility.worker.js +11 -0
  55. package/package.json +9 -82
  56. package/API Reference.url +0 -2
  57. package/LEGAL.txt +0 -353
  58. package/LICENSE +0 -4
  59. package/README.html +0 -836
  60. package/README.md +0 -735
  61. package/samples.url +0 -2
  62. /package/{dist → dynamsoft-barcode-reader-bundle@10.4.3100/dist}/dbr.bundle.d.ts +0 -0
  63. /package/{dist → dynamsoft-barcode-reader-bundle@10.4.3100/dist}/dbr.bundle.esm.d.ts +0 -0
  64. /package/{dist → dynamsoft-barcode-reader-bundle@10.4.3100/dist}/dbr.bundle.js +0 -0
  65. /package/{dist → dynamsoft-barcode-reader-bundle@10.4.3100/dist}/dbr.bundle.mjs +0 -0
  66. /package/{dist → dynamsoft-barcode-reader-bundle@10.4.3100/dist}/dbr.no-content-bundle.esm.js +0 -0
@@ -0,0 +1,2121 @@
1
+ /*!
2
+ * Dynamsoft JavaScript Library
3
+ * @product Dynamsoft Capture Vision Router JS Edition
4
+ * @website http://www.dynamsoft.com
5
+ * @copyright Copyright 2024, Dynamsoft Corporation
6
+ * @author Dynamsoft
7
+ * @version "2.4.33"
8
+ * @fileoverview Dynamsoft JavaScript Library for Capture Vision
9
+ * More info on cvr JS: https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/capture-vision-router-module.html
10
+ */
11
+ import { getNextTaskID, mapTaskCallBack, worker, CoreModule, workerAutoResources, mapPackageRegister, compareVersion, innerVersions, EnumCapturedResultItemType, loadWasm, handleEngineResourcePaths, EnumImagePixelFormat, EnumColourChannelUsageType, isDSImageData, requestResource, EnumIntermediateResultUnitType } from 'dynamsoft-core';
12
+
13
+ /******************************************************************************
14
+ Copyright (c) Microsoft Corporation.
15
+
16
+ Permission to use, copy, modify, and/or distribute this software for any
17
+ purpose with or without fee is hereby granted.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
20
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
21
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
22
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
23
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
24
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
25
+ PERFORMANCE OF THIS SOFTWARE.
26
+ ***************************************************************************** */
27
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
28
+
29
+
30
+ function __classPrivateFieldGet(receiver, state, kind, f) {
31
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
32
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
33
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
34
+ }
35
+
36
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
37
+ if (kind === "m") throw new TypeError("Private method is not writable");
38
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
39
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
40
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
41
+ }
42
+
43
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
44
+ var e = new Error(message);
45
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
46
+ };
47
+
48
+ const isPromiseLike = (value) => (value && "object" === typeof value && "function" === typeof value.then);
49
+ // get original `Promise`, avoid other js change the `Promise`
50
+ const Promise$1 = (async () => { })().constructor;
51
+ class MutablePromise extends Promise$1 {
52
+ get status() { return this._s; }
53
+ get isPending() { return "pending" === this._s; }
54
+ get isFulfilled() { return "fulfilled" === this._s; }
55
+ get isRejected() { return "rejected" === this._s; }
56
+ get task() { return this._task; }
57
+ set task(value) {
58
+ //if(!this.isPending){ return; }
59
+ this._task = value;
60
+ let p;
61
+ if (isPromiseLike(value)) {
62
+ p = value;
63
+ }
64
+ else if ("function" === typeof value) {
65
+ p = new Promise$1(value);
66
+ }
67
+ if (p) {
68
+ (async () => {
69
+ try {
70
+ const ret = await p;
71
+ // make sure task not change
72
+ if (value === this._task) {
73
+ this.resolve(ret);
74
+ }
75
+ }
76
+ catch (reason) {
77
+ // make sure task not change
78
+ if (value === this._task) {
79
+ this.reject(reason);
80
+ }
81
+ }
82
+ })();
83
+ }
84
+ }
85
+ get isEmpty() { return null == this._task; }
86
+ constructor(executor) {
87
+ let rs;
88
+ let rj;
89
+ const fn = (_rs, _rj) => { rs = _rs; rj = _rj; };
90
+ super(fn);
91
+ // walkaround babel which can not extend builtin class
92
+ // let _this = this;
93
+ // let then = new Promise(fn).then;
94
+ // this.then = function(){ then.apply(_this, arguments) } as any;
95
+ this._s = "pending";
96
+ this.resolve = (value) => {
97
+ if (this.isPending) {
98
+ if (isPromiseLike(value)) {
99
+ this.task = value;
100
+ }
101
+ else {
102
+ this._s = "fulfilled";
103
+ rs(value);
104
+ }
105
+ }
106
+ };
107
+ this.reject = (reason) => {
108
+ if (this.isPending) {
109
+ this._s = "rejected";
110
+ rj(reason);
111
+ }
112
+ };
113
+ this.task = executor;
114
+ }
115
+ }
116
+
117
+ class BufferedItemsManager {
118
+ constructor(cvr) {
119
+ this._cvr = cvr;
120
+ }
121
+ /**
122
+ * Gets the maximum number of buffered items.
123
+ * @returns Returns the maximum number of buffered items.
124
+ */
125
+ async getMaxBufferedItems() {
126
+ return await new Promise((rs, rj) => {
127
+ let taskID = getNextTaskID();
128
+ mapTaskCallBack[taskID] = async (body) => {
129
+ if (body.success) {
130
+ return rs(body.count);
131
+ }
132
+ else {
133
+ let ex = new Error(body.message);
134
+ ex.stack = body.stack + '\n' + ex.stack;
135
+ return rj(ex);
136
+ }
137
+ };
138
+ worker.postMessage({
139
+ type: "cvr_getMaxBufferedItems",
140
+ id: taskID,
141
+ instanceID: this._cvr._instanceID
142
+ });
143
+ });
144
+ }
145
+ ;
146
+ /**
147
+ * Sets the maximum number of buffered items.
148
+ * @param count the maximum number of buffered items
149
+ */
150
+ async setMaxBufferedItems(count) {
151
+ return await new Promise((rs, rj) => {
152
+ let taskID = getNextTaskID();
153
+ mapTaskCallBack[taskID] = async (body) => {
154
+ if (body.success) {
155
+ return rs();
156
+ }
157
+ else {
158
+ let ex = new Error(body.message);
159
+ ex.stack = body.stack + '\n' + ex.stack;
160
+ return rj(ex);
161
+ }
162
+ };
163
+ worker.postMessage({
164
+ type: "cvr_setMaxBufferedItems",
165
+ id: taskID,
166
+ instanceID: this._cvr._instanceID,
167
+ body: {
168
+ count
169
+ }
170
+ });
171
+ });
172
+ }
173
+ ;
174
+ /**
175
+ * Gets the buffered character items.
176
+ * @return the buffered character items
177
+ */
178
+ async getBufferedCharacterItemSet() {
179
+ return await new Promise((rs, rj) => {
180
+ let taskID = getNextTaskID();
181
+ mapTaskCallBack[taskID] = async (body) => {
182
+ if (body.success) {
183
+ return rs(body.itemSet);
184
+ }
185
+ else {
186
+ let ex = new Error(body.message);
187
+ ex.stack = body.stack + '\n' + ex.stack;
188
+ return rj(ex);
189
+ }
190
+ };
191
+ worker.postMessage({
192
+ type: "cvr_getBufferedCharacterItemSet",
193
+ id: taskID,
194
+ instanceID: this._cvr._instanceID
195
+ });
196
+ });
197
+ }
198
+ ;
199
+ }
200
+
201
+ var irrRegistryState = {
202
+ onTaskResultsReceived: false,
203
+ onTaskResultsReceivedForDce: false,
204
+ // section
205
+ onPredetectedRegionsReceived: false,
206
+ onLocalizedBarcodesReceived: false,
207
+ onDecodedBarcodesReceived: false,
208
+ onLocalizedTextLinesReceived: false,
209
+ onRecognizedTextLinesReceived: false,
210
+ onDetectedQuadsReceived: false,
211
+ onNormalizedImagesReceived: false,
212
+ // stage
213
+ onColourImageUnitReceived: false,
214
+ onScaledDownColourImageUnitReceived: false,
215
+ onGrayscaleImageUnitReceived: false,
216
+ onTransformedGrayscaleImageUnitReceived: false,
217
+ onEnhancedGrayscaleImageUnitReceived: false,
218
+ onBinaryImageUnitReceived: false,
219
+ onTextureDetectionResultUnitReceived: false,
220
+ onTextureRemovedGrayscaleImageUnitReceived: false,
221
+ onTextureRemovedBinaryImageUnitReceived: false,
222
+ onContoursUnitReceived: false,
223
+ onLineSegmentsUnitReceived: false,
224
+ onTextZonesUnitReceived: false,
225
+ onTextRemovedBinaryImageUnitReceived: false,
226
+ onRawTextLinesReceived: false,
227
+ onLongLinesUnitReceived: false,
228
+ onCornersUnitReceived: false,
229
+ onCandidateQuadEdgesUnitReceived: false,
230
+ onCandidateBarcodeZonesUnitReceived: false,
231
+ onScaledUpBarcodeImageUnitReceived: false,
232
+ onDeformationResistedBarcodeImageUnitReceived: false,
233
+ onComplementedBarcodeImageUnitReceived: false,
234
+ onShortLinesUnitReceived: false,
235
+ onLogicLinesReceived: false
236
+ };
237
+
238
+ const _handleIntermediateResultReceiver = (irr) => {
239
+ for (let irs in irr._irrRegistryState) {
240
+ irr._irrRegistryState[irs] = false;
241
+ }
242
+ for (let receiver of irr._intermediateResultReceiverSet) {
243
+ if (receiver.isDce || receiver.isFilter) {
244
+ irr._irrRegistryState.onTaskResultsReceivedForDce = true;
245
+ continue;
246
+ }
247
+ for (let r in receiver) {
248
+ if (!irr._irrRegistryState[r]) {
249
+ irr._irrRegistryState[r] = !!receiver[r];
250
+ }
251
+ }
252
+ }
253
+ };
254
+ class IntermediateResultManager {
255
+ constructor(cvr) {
256
+ this._irrRegistryState = irrRegistryState;
257
+ this._intermediateResultReceiverSet = new Set();
258
+ this._cvr = cvr;
259
+ }
260
+ /**
261
+ * Adds a `IntermediateResultReceiver` object as the receiver of intermediate results.
262
+ * @param receiver The receiver object, of type `IntermediateResultReceiver`.
263
+ */
264
+ async addResultReceiver(receiver) {
265
+ if (typeof receiver !== "object")
266
+ throw new Error(`Invalid receiver.`);
267
+ this._intermediateResultReceiverSet.add(receiver);
268
+ _handleIntermediateResultReceiver(this);
269
+ let observedResultUnitTypes = -1;
270
+ let observedTaskMap = {};
271
+ if (!receiver.isDce && !receiver.isFilter) {
272
+ if (!receiver._observedResultUnitTypes || !receiver._observedTaskMap) {
273
+ throw new Error("Invalid Intermediate Result Receiver.");
274
+ }
275
+ observedResultUnitTypes = receiver._observedResultUnitTypes;
276
+ receiver._observedTaskMap.forEach((value, key) => {
277
+ observedTaskMap[key] = value;
278
+ });
279
+ receiver._observedTaskMap.clear();
280
+ }
281
+ return await new Promise((rs, rj) => {
282
+ let taskID = getNextTaskID();
283
+ mapTaskCallBack[taskID] = async (body) => {
284
+ if (body.success) {
285
+ return rs();
286
+ }
287
+ else {
288
+ let ex = new Error(body.message);
289
+ ex.stack = body.stack + '\n' + ex.stack;
290
+ return rj(ex);
291
+ }
292
+ };
293
+ worker.postMessage({
294
+ type: "cvr_setIrrRegistry",
295
+ id: taskID,
296
+ instanceID: this._cvr._instanceID,
297
+ body: {
298
+ receiverObj: this._irrRegistryState,
299
+ observedResultUnitTypes: observedResultUnitTypes.toString(),
300
+ observedTaskMap
301
+ }
302
+ });
303
+ });
304
+ }
305
+ ;
306
+ /**
307
+ * Removes the specified `IntermediateResultReceiver` object.
308
+ * @param receiver The receiver object, of type `IntermediateResultReceiver`.
309
+ */
310
+ async removeResultReceiver(receiver) {
311
+ this._intermediateResultReceiverSet.delete(receiver);
312
+ _handleIntermediateResultReceiver(this);
313
+ return await new Promise((rs, rj) => {
314
+ let taskID = getNextTaskID();
315
+ mapTaskCallBack[taskID] = async (body) => {
316
+ if (body.success) {
317
+ return rs();
318
+ }
319
+ else {
320
+ let ex = new Error(body.message);
321
+ ex.stack = body.stack + '\n' + ex.stack;
322
+ return rj(ex);
323
+ }
324
+ };
325
+ worker.postMessage({
326
+ type: "cvr_setIrrRegistry",
327
+ id: taskID,
328
+ instanceID: this._cvr._instanceID,
329
+ body: {
330
+ receiverObj: this._irrRegistryState
331
+ }
332
+ });
333
+ });
334
+ }
335
+ ;
336
+ /**
337
+ * Retrieves the original image data.
338
+ *
339
+ * @returns A promise that resolves when the operation has successfully completed. It provides the original image upon resolution.
340
+ */
341
+ getOriginalImage() {
342
+ return this._cvr._dsImage;
343
+ }
344
+ ;
345
+ }
346
+
347
+ const bSSR = "undefined" == typeof self;
348
+
349
+ const isWebWorker = "function" == typeof importScripts, curScriptDir = (() => {
350
+ if (!isWebWorker) {
351
+ if (!bSSR && document.currentScript) {
352
+ let src = document.currentScript.src, idxSearch = src.indexOf("?");
353
+ if (-1 != idxSearch) src = src.substring(0, idxSearch); else {
354
+ let idxHash = src.indexOf("#");
355
+ -1 != idxHash && (src = src.substring(0, idxHash));
356
+ }
357
+ return src.substring(0, src.lastIndexOf("/") + 1);
358
+ }
359
+ return "./";
360
+ }
361
+ })(), getAbsoluteDir = value => {
362
+ if (null == value && (value = "./"), bSSR || isWebWorker) ; else {
363
+ let a = document.createElement("a");
364
+ a.href = value, value = a.href;
365
+ }
366
+ return value.endsWith("/") || (value += "/"), value;
367
+ };
368
+
369
+ var _a;
370
+ CoreModule.engineResourcePaths.cvr = { version: "2.4.33", path: curScriptDir, isInternal: true };
371
+ workerAutoResources.cvr = { js: true, wasm: true, deps: ["license", "dip"] };
372
+ mapPackageRegister.cvr = {};
373
+ const stdVersion = "1.4.21";
374
+ if ('string' != typeof CoreModule.engineResourcePaths.std && compareVersion(CoreModule.engineResourcePaths.std.version, stdVersion) < 0) {
375
+ CoreModule.engineResourcePaths.std = { version: stdVersion, path: getAbsoluteDir(curScriptDir + `../../dynamsoft-capture-vision-std@${stdVersion}/dist/`), isInternal: true };
376
+ }
377
+ const dipVersion = "2.4.31";
378
+ if (!CoreModule.engineResourcePaths.dip || 'string' != typeof CoreModule.engineResourcePaths.dip && compareVersion(CoreModule.engineResourcePaths.dip.version, dipVersion) < 0) {
379
+ CoreModule.engineResourcePaths.dip = { version: dipVersion, path: getAbsoluteDir(curScriptDir + `../../dynamsoft-image-processing@${dipVersion}/dist/`), isInternal: true };
380
+ }
381
+ class CaptureVisionRouterModule {
382
+ static getVersion() {
383
+ return this._version;
384
+ }
385
+ }
386
+ CaptureVisionRouterModule._version = `${"2.4.33"}(Worker: ${(_a = innerVersions.cvr) === null || _a === void 0 ? void 0 : _a.worker}, Wasm: loading...`;
387
+
388
+ const resultItemMapConfig = {
389
+ "barcodeResultItems": {
390
+ type: EnumCapturedResultItemType.CRIT_BARCODE,
391
+ reveiver: "onDecodedBarcodesReceived",
392
+ isNeedFilter: true
393
+ },
394
+ "textLineResultItems": {
395
+ type: EnumCapturedResultItemType.CRIT_TEXT_LINE,
396
+ reveiver: "onRecognizedTextLinesReceived",
397
+ isNeedFilter: true
398
+ },
399
+ "detectedQuadResultItems": {
400
+ type: EnumCapturedResultItemType.CRIT_DETECTED_QUAD,
401
+ reveiver: "onDetectedQuadsReceived",
402
+ isNeedFilter: false
403
+ },
404
+ "normalizedImageResultItems": {
405
+ type: EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE,
406
+ reveiver: "onNormalizedImagesReceived",
407
+ isNeedFilter: false
408
+ },
409
+ "parsedResultItems": {
410
+ type: EnumCapturedResultItemType.CRIT_PARSED_RESULT,
411
+ reveiver: "onParsedResultsReceived",
412
+ isNeedFilter: false
413
+ }
414
+ };
415
+
416
+ var EnumImageSourceState;
417
+ (function (EnumImageSourceState) {
418
+ EnumImageSourceState[EnumImageSourceState["ISS_BUFFER_EMPTY"] = 0] = "ISS_BUFFER_EMPTY";
419
+ EnumImageSourceState[EnumImageSourceState["ISS_EXHAUSTED"] = 1] = "ISS_EXHAUSTED";
420
+ })(EnumImageSourceState || (EnumImageSourceState = {}));
421
+
422
+ function convertCoordinates(item, compressRate) {
423
+ if (item && item.location) {
424
+ const points = item.location.points;
425
+ for (let point of points) {
426
+ point.x = point.x / compressRate;
427
+ point.y = point.y / compressRate;
428
+ }
429
+ convertCoordinates(item.referencedItem, compressRate);
430
+ }
431
+ }
432
+ function checkIsDisposed(cvr) {
433
+ if (cvr.disposed) {
434
+ throw new Error(`"CaptureVisionRouter" instance has been disposed`);
435
+ }
436
+ }
437
+
438
+ var _CaptureVisionRouter_isa, _CaptureVisionRouter_canvas, _CaptureVisionRouter_promiseStartScan, _CaptureVisionRouter_intermediateResultManager, _CaptureVisionRouter_bufferdItemsManager, _CaptureVisionRouter_resultReceiverSet, _CaptureVisionRouter_isaStateListenerSet, _CaptureVisionRouter_resultFilterSet, _CaptureVisionRouter_compressRate, _CaptureVisionRouter_isScanner, _CaptureVisionRouter_innerUseTag, _CaptureVisionRouter_isDestroyed;
439
+ const _intermediateResultReceiverOfFilter = {
440
+ onTaskResultsReceived: () => { },
441
+ isFilter: true
442
+ };
443
+ class CaptureVisionRouter {
444
+ constructor() {
445
+ this.maxImageSideLength = ["iPhone", "Android", "HarmonyOS"].includes(CoreModule.browserInfo.OS) ? 2048 : 4096;
446
+ this._instanceID = undefined;
447
+ this._dsImage = null;
448
+ this._isPauseScan = true;
449
+ this._isOutputOriginalImage = false;
450
+ this._isOpenDetectVerify = false;
451
+ this._isOpenNormalizeVerify = false;
452
+ this._isOpenBarcodeVerify = false;
453
+ this._isOpenLabelVerify = false;
454
+ this._minImageCaptureInterval = 0;
455
+ this._averageProcessintTimeArray = [];
456
+ this._averageFetchImageTimeArray = [];
457
+ this._currentSettings = null;
458
+ this._averageTime = 999;
459
+ _CaptureVisionRouter_isa.set(this, null);
460
+ _CaptureVisionRouter_canvas.set(this, null);
461
+ _CaptureVisionRouter_promiseStartScan.set(this, null);
462
+ _CaptureVisionRouter_intermediateResultManager.set(this, null);
463
+ _CaptureVisionRouter_bufferdItemsManager.set(this, null);
464
+ _CaptureVisionRouter_resultReceiverSet.set(this, new Set());
465
+ _CaptureVisionRouter_isaStateListenerSet.set(this, new Set());
466
+ _CaptureVisionRouter_resultFilterSet.set(this, new Set());
467
+ _CaptureVisionRouter_compressRate.set(this, 0);
468
+ _CaptureVisionRouter_isScanner.set(this, false);
469
+ _CaptureVisionRouter_innerUseTag.set(this, false);
470
+ _CaptureVisionRouter_isDestroyed.set(this, false);
471
+ this._singleFrameModeCallbackBind = this._singleFrameModeCallback.bind(this);
472
+ }
473
+ /**
474
+ * Returns whether the `CaptureVisionRouter` instance has been disposed of.
475
+ *
476
+ * @returns Boolean indicating whether the `CaptureVisionRouter` instance has been disposed of.
477
+ */
478
+ get disposed() {
479
+ return __classPrivateFieldGet(this, _CaptureVisionRouter_isDestroyed, "f");
480
+ }
481
+ /**
482
+ * Initializes a new instance of the `CaptureVisionRouter` class.
483
+ *
484
+ * @returns A promise that resolves with the initialized `CaptureVisionRouter` instance.
485
+ */
486
+ static async createInstance() {
487
+ if (!mapPackageRegister.license) {
488
+ throw Error('Module `license` is not existed.');
489
+ }
490
+ await mapPackageRegister.license.dynamsoft();
491
+ await loadWasm(["cvr"]);
492
+ const captureVisionRouter = new CaptureVisionRouter();
493
+ const p = new MutablePromise();
494
+ let taskID = getNextTaskID();
495
+ mapTaskCallBack[taskID] = async (body) => {
496
+ var _a;
497
+ if (body.success) {
498
+ captureVisionRouter._instanceID = body.instanceID;
499
+ captureVisionRouter._currentSettings = JSON.parse(JSON.parse(body.outputSettings).data);
500
+ CaptureVisionRouterModule._version = `${"2.4.33"}(Worker: ${(_a = innerVersions.cvr) === null || _a === void 0 ? void 0 : _a.worker}, Wasm: ${body.version})`;
501
+ __classPrivateFieldSet(captureVisionRouter, _CaptureVisionRouter_innerUseTag, true, "f");
502
+ __classPrivateFieldSet(captureVisionRouter, _CaptureVisionRouter_intermediateResultManager, captureVisionRouter.getIntermediateResultManager(), "f");
503
+ __classPrivateFieldSet(captureVisionRouter, _CaptureVisionRouter_innerUseTag, false, "f");
504
+ p.resolve(captureVisionRouter);
505
+ }
506
+ else {
507
+ const err = Error(body.message);
508
+ if (body.stack) {
509
+ err.stack = body.stack;
510
+ }
511
+ p.reject(err);
512
+ }
513
+ };
514
+ worker.postMessage({
515
+ type: 'cvr_createInstance',
516
+ id: taskID,
517
+ });
518
+ return p;
519
+ }
520
+ ;
521
+ async _singleFrameModeCallback(dsImage) {
522
+ for (let receiver of __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f")) {
523
+ this._isOutputOriginalImage && receiver.onOriginalImageResultReceived && receiver.onOriginalImageResultReceived({ imageData: dsImage });
524
+ }
525
+ const copyDsImageData = {
526
+ bytes: new Uint8Array(dsImage.bytes),
527
+ width: dsImage.width,
528
+ height: dsImage.height,
529
+ stride: dsImage.stride,
530
+ format: dsImage.format,
531
+ tag: dsImage.tag
532
+ };
533
+ if (!this._templateName)
534
+ this._templateName = this._currentSettings.CaptureVisionTemplates[0].Name;
535
+ const result = await this.capture(copyDsImageData, this._templateName);
536
+ result.originalImageTag = dsImage.tag;
537
+ const resultCommonPart = {
538
+ originalImageHashId: result.originalImageHashId,
539
+ originalImageTag: result.originalImageTag,
540
+ errorCode: result.errorCode,
541
+ errorString: result.errorString
542
+ };
543
+ for (let receiver of __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f")) {
544
+ if (receiver.isDce) {
545
+ receiver.onCapturedResultReceived(result, {
546
+ isDetectVerifyOpen: false,
547
+ isNormalizeVerifyOpen: false,
548
+ isBarcodeVerifyOpen: false,
549
+ isLabelVerifyOpen: false,
550
+ });
551
+ continue;
552
+ }
553
+ for (let resultItem in resultItemMapConfig) {
554
+ const _itemType = resultItem;
555
+ const _itemConfig = resultItemMapConfig[_itemType];
556
+ receiver[_itemConfig.reveiver] && result[_itemType] && receiver[_itemConfig.reveiver](Object.assign(Object.assign({}, resultCommonPart), { [_itemType]: result[_itemType] }));
557
+ }
558
+ receiver.onCapturedResultReceived && receiver.onCapturedResultReceived(result);
559
+ }
560
+ }
561
+ /**
562
+ * Sets up an image source to provide images for continuous processing.
563
+ * @param imageSource The image source which is compliant with the `ImageSourceAdapter` interface.
564
+ */
565
+ setInput(imageSource) {
566
+ checkIsDisposed(this);
567
+ if (!imageSource) {
568
+ __classPrivateFieldSet(this, _CaptureVisionRouter_isa, null, "f");
569
+ return;
570
+ }
571
+ __classPrivateFieldSet(this, _CaptureVisionRouter_isa, imageSource, "f");
572
+ if (imageSource.isCameraEnhancer) {
573
+ if (__classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f")) {
574
+ __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f")._intermediateResultReceiver.isDce = true;
575
+ __classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f").addResultReceiver(__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f")._intermediateResultReceiver);
576
+ }
577
+ const cameraView = __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").getCameraView();
578
+ if (cameraView) {
579
+ const dceCrr = cameraView._capturedResultReceiver;
580
+ dceCrr.isDce = true;
581
+ __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f").add(dceCrr);
582
+ }
583
+ // TODO: think about off.
584
+ //(imageSource as any).on("singleFrameAcquired", this._singleFrameModeCallback);
585
+ }
586
+ }
587
+ ;
588
+ /**
589
+ * Returns the image source object.
590
+ */
591
+ getInput() {
592
+ return __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f");
593
+ }
594
+ ;
595
+ /**
596
+ * Adds or removes listeners for image source state change.
597
+ */
598
+ addImageSourceStateListener(listener) {
599
+ checkIsDisposed(this);
600
+ if (typeof listener !== "object")
601
+ return console.warn(`Invalid ISA state listener.`);
602
+ if (!listener || !Object.keys(listener))
603
+ return;
604
+ __classPrivateFieldGet(this, _CaptureVisionRouter_isaStateListenerSet, "f").add(listener);
605
+ }
606
+ ;
607
+ removeImageSourceStateListener(listener) {
608
+ checkIsDisposed(this);
609
+ return __classPrivateFieldGet(this, _CaptureVisionRouter_isaStateListenerSet, "f").delete(listener);
610
+ }
611
+ /**
612
+ * Adds a `CapturedResultReceiver` object as the receiver of captured results.
613
+ * @param receiver The receiver object, of type `CapturedResultReceiver`.
614
+ */
615
+ addResultReceiver(receiver) {
616
+ checkIsDisposed(this);
617
+ if (typeof receiver !== "object")
618
+ throw new Error(`Invalid receiver.`);
619
+ if (!receiver || !Object.keys(receiver).length)
620
+ return;
621
+ __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f").add(receiver);
622
+ this._setCrrRegistry();
623
+ }
624
+ ;
625
+ /**
626
+ * Removes the specified `CapturedResultReceiver` object.
627
+ * @param receiver The receiver object, of type `CapturedResultReceiver`.
628
+ */
629
+ removeResultReceiver(receiver) {
630
+ checkIsDisposed(this);
631
+ __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f").delete(receiver);
632
+ this._setCrrRegistry();
633
+ }
634
+ async _setCrrRegistry() {
635
+ const receiver = {
636
+ onCapturedResultReceived: false,
637
+ onDecodedBarcodesReceived: false,
638
+ onRecognizedTextLinesReceived: false,
639
+ onDetectedQuadsReceived: false,
640
+ onNormalizedImagesReceived: false,
641
+ onParsedResultsReceived: false
642
+ };
643
+ for (let r of __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f")) {
644
+ if (r.isDce)
645
+ continue;
646
+ receiver.onCapturedResultReceived = !!r["onCapturedResultReceived"];
647
+ receiver.onDecodedBarcodesReceived = !!r["onDecodedBarcodesReceived"];
648
+ receiver.onRecognizedTextLinesReceived = !!r["onRecognizedTextLinesReceived"];
649
+ receiver.onDetectedQuadsReceived = !!r["onDetectedQuadsReceived"];
650
+ receiver.onNormalizedImagesReceived = !!r["onNormalizedImagesReceived"];
651
+ receiver.onParsedResultsReceived = !!r["onParsedResultsReceived"];
652
+ }
653
+ const p = new MutablePromise();
654
+ let taskID = getNextTaskID();
655
+ mapTaskCallBack[taskID] = async (body) => {
656
+ if (body.success) {
657
+ p.resolve();
658
+ }
659
+ else {
660
+ let ex = new Error(body.message);
661
+ ex.stack = body.stack + '\n' + ex.stack;
662
+ p.reject();
663
+ }
664
+ };
665
+ worker.postMessage({
666
+ type: "cvr_setCrrRegistry",
667
+ id: taskID,
668
+ instanceID: this._instanceID,
669
+ body: {
670
+ receiver: JSON.stringify(receiver)
671
+ }
672
+ });
673
+ return p;
674
+ }
675
+ /**
676
+ * Adds a `MultiFrameResultCrossFilter` object to filter non-essential results.
677
+ * @param filter The filter object, of type `MultiFrameResultCrossFilter`.
678
+ *
679
+ * @returns A promise that resolves when the operation has successfully completed. It does not provide any value upon resolution.
680
+ */
681
+ async addResultFilter(filter) {
682
+ checkIsDisposed(this);
683
+ if (!filter || typeof filter !== "object" || !Object.keys(filter).length) {
684
+ return console.warn(`Invalid filter.`);
685
+ }
686
+ __classPrivateFieldGet(this, _CaptureVisionRouter_resultFilterSet, "f").add(filter);
687
+ // When cvr.addResultFilter is called, this method will automatically be invoked to batch update the filter statuses that were set before calling addResultFilter.
688
+ filter._dynamsoft();
689
+ await this._handleFilterUpdate();
690
+ }
691
+ ;
692
+ /**
693
+ * Removes the specified `MultiFrameResultCrossFilter` object.
694
+ * @param filter The filter object, of type `MultiFrameResultCrossFilter`.
695
+ *
696
+ * @returns A promise that resolves when the operation has successfully completed. It does not provide any value upon resolution.
697
+ */
698
+ async removeResultFilter(filter) {
699
+ checkIsDisposed(this);
700
+ __classPrivateFieldGet(this, _CaptureVisionRouter_resultFilterSet, "f").delete(filter);
701
+ await this._handleFilterUpdate();
702
+ }
703
+ async _handleFilterUpdate() {
704
+ /**
705
+ * Each time a "filter" is added or removed, the "filter set" will be re-traversed,
706
+ * and _intermediateResultReceiverOfFilter will be added when necessary.
707
+ * This ensures that _intermediateResultReceiverOfFilter is not left in the "filter set" when the "filter set" is empty or when no filter in the "filter set" has isLatestOverlappingEnabled set to true.
708
+ */
709
+ __classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f").removeResultReceiver(_intermediateResultReceiverOfFilter);
710
+ if (__classPrivateFieldGet(this, _CaptureVisionRouter_resultFilterSet, "f").size === 0) {
711
+ this._isOpenBarcodeVerify = false;
712
+ this._isOpenLabelVerify = false;
713
+ this._isOpenDetectVerify = false;
714
+ this._isOpenNormalizeVerify = false;
715
+ const _verificationEnabled = {
716
+ [EnumCapturedResultItemType.CRIT_BARCODE]: false,
717
+ [EnumCapturedResultItemType.CRIT_TEXT_LINE]: false,
718
+ [EnumCapturedResultItemType.CRIT_DETECTED_QUAD]: false,
719
+ [EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE]: false
720
+ };
721
+ const _duplicateFilterEnabled = {
722
+ [EnumCapturedResultItemType.CRIT_BARCODE]: false,
723
+ [EnumCapturedResultItemType.CRIT_TEXT_LINE]: false,
724
+ [EnumCapturedResultItemType.CRIT_DETECTED_QUAD]: false,
725
+ [EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE]: false
726
+ };
727
+ await _enableResultCrossVerification(this, _verificationEnabled);
728
+ await _enableResultDeduplication(this, _duplicateFilterEnabled);
729
+ return;
730
+ }
731
+ for (let filter of __classPrivateFieldGet(this, _CaptureVisionRouter_resultFilterSet, "f")) {
732
+ this._isOpenBarcodeVerify = filter.isResultCrossVerificationEnabled(EnumCapturedResultItemType.CRIT_BARCODE);
733
+ this._isOpenLabelVerify = filter.isResultCrossVerificationEnabled(EnumCapturedResultItemType.CRIT_TEXT_LINE);
734
+ this._isOpenDetectVerify = filter.isResultCrossVerificationEnabled(EnumCapturedResultItemType.CRIT_DETECTED_QUAD);
735
+ this._isOpenNormalizeVerify = filter.isResultCrossVerificationEnabled(EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE);
736
+ if (filter.isLatestOverlappingEnabled(EnumCapturedResultItemType.CRIT_BARCODE)) {
737
+ const _isExist = [...__classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f")._intermediateResultReceiverSet.values()].find((receiver) => { return receiver.isFilter; });
738
+ if (!_isExist) {
739
+ __classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f").addResultReceiver(_intermediateResultReceiverOfFilter);
740
+ }
741
+ }
742
+ await _enableResultCrossVerification(this, filter.verificationEnabled);
743
+ await _enableResultDeduplication(this, filter.duplicateFilterEnabled);
744
+ await _setDuplicateForgetTime(this, filter.duplicateForgetTime);
745
+ }
746
+ }
747
+ /**
748
+ * Initiates a capturing process based on a specified template. This process is repeated for each image fetched from the source.
749
+ * @param templateName [Optional] Specifies a "CaptureVisionTemplate" to use.
750
+ *
751
+ * @returns A promise that resolves when the capturing process has successfully started. It does not provide any value upon resolution.
752
+ */
753
+ async startCapturing(templateName) {
754
+ var _a, _b;
755
+ checkIsDisposed(this);
756
+ if (!this._isPauseScan)
757
+ return;
758
+ if (!__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f"))
759
+ throw new Error(`'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'`);
760
+ if (!templateName)
761
+ templateName = CaptureVisionRouter._defaultTemplate;
762
+ const tasks = await this.containsTask(templateName);
763
+ await loadWasm(tasks);
764
+ /*
765
+ * Why do we need to re-add an existing "filter" when calling "startCapturing"?
766
+ * Because there may be a situation where the corresponding wasm module has not been loaded when adding "filter",
767
+ * so after checking the required wasm module in "startCapturing", we will add "filter" again to ensure that "filter" takes effect in wasm.
768
+ *
769
+ * Why not check for the required wasm when adding the "filter"?
770
+ * Because each result type has a default value, we cannot know which wasm modules are actually needed through the passed "filter"
771
+ *
772
+ * This part of the logic has room for optimization. will do.
773
+ **/
774
+ for (let filter of __classPrivateFieldGet(this, _CaptureVisionRouter_resultFilterSet, "f")) {
775
+ await this.addResultFilter(filter);
776
+ }
777
+ if (tasks.includes("dlr") && !((_a = mapPackageRegister.dlr) === null || _a === void 0 ? void 0 : _a.bLoadConfusableCharsData)) {
778
+ const _engineResourcePaths = handleEngineResourcePaths(CoreModule.engineResourcePaths);
779
+ await ((_b = mapPackageRegister.dlr) === null || _b === void 0 ? void 0 : _b.loadRecognitionData("ConfusableChars", _engineResourcePaths.dlr));
780
+ }
781
+ if (__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").isCameraEnhancer) {
782
+ if (tasks.includes("ddn")) {
783
+ __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").setPixelFormat(EnumImagePixelFormat.IPF_ABGR_8888);
784
+ }
785
+ else {
786
+ __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").setPixelFormat(EnumImagePixelFormat.IPF_GRAYSCALED);
787
+ }
788
+ }
789
+ if (__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").singleFrameMode !== undefined && __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").singleFrameMode !== "disabled") {
790
+ this._templateName = templateName;
791
+ __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").on("singleFrameAcquired", this._singleFrameModeCallbackBind);
792
+ return;
793
+ }
794
+ const colourChannelUsageType = __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").getColourChannelUsageType();
795
+ if (colourChannelUsageType === EnumColourChannelUsageType.CCUT_AUTO) {
796
+ __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").setColourChannelUsageType(tasks.includes("ddn") ?
797
+ EnumColourChannelUsageType.CCUT_FULL_CHANNEL
798
+ :
799
+ EnumColourChannelUsageType.CCUT_Y_CHANNEL_ONLY);
800
+ }
801
+ if (__classPrivateFieldGet(this, _CaptureVisionRouter_promiseStartScan, "f") && __classPrivateFieldGet(this, _CaptureVisionRouter_promiseStartScan, "f").isPending)
802
+ return __classPrivateFieldGet(this, _CaptureVisionRouter_promiseStartScan, "f");
803
+ __classPrivateFieldSet(this, _CaptureVisionRouter_promiseStartScan, new MutablePromise((rs, rj) => {
804
+ if (this.disposed)
805
+ return;
806
+ let taskID = getNextTaskID();
807
+ mapTaskCallBack[taskID] = async (body) => {
808
+ if (!__classPrivateFieldGet(this, _CaptureVisionRouter_promiseStartScan, "f") || __classPrivateFieldGet(this, _CaptureVisionRouter_promiseStartScan, "f").isFulfilled)
809
+ return;
810
+ if (body.success) {
811
+ this._isPauseScan = false;
812
+ this._isOutputOriginalImage = body.isOutputOriginalImage;
813
+ this._loopReadVideoTimeoutId && clearTimeout(this._loopReadVideoTimeoutId);
814
+ this._loopReadVideoTimeoutId = setTimeout(async () => {
815
+ if (this._minImageCaptureInterval !== -1) {
816
+ __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").startFetching();
817
+ }
818
+ this._loopReadVideo(templateName);
819
+ // try {
820
+ // await this._loopReadVideo(templateName);
821
+ // } catch (ex) {
822
+ // rj(ex);
823
+ // }
824
+ rs();
825
+ }, 0);
826
+ }
827
+ else {
828
+ let ex = new Error(body.message);
829
+ ex.stack = body.stack + '\n' + ex.stack;
830
+ return rj(ex);
831
+ }
832
+ };
833
+ worker.postMessage({
834
+ type: "cvr_startCapturing",
835
+ id: taskID,
836
+ instanceID: this._instanceID,
837
+ body: { templateName }
838
+ });
839
+ }), "f");
840
+ return await __classPrivateFieldGet(this, _CaptureVisionRouter_promiseStartScan, "f");
841
+ }
842
+ /**
843
+ * Stops the capturing process.
844
+ */
845
+ stopCapturing() {
846
+ checkIsDisposed(this);
847
+ if (!__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f"))
848
+ return;
849
+ if (__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").isCameraEnhancer) {
850
+ if (__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").singleFrameMode !== undefined && __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").singleFrameMode !== "disabled") {
851
+ __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").off("singleFrameAcquired", this._singleFrameModeCallbackBind);
852
+ return;
853
+ }
854
+ }
855
+ _clearVerifyList(this);
856
+ __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").stopFetching();
857
+ this._averageProcessintTimeArray = [];
858
+ this._averageTime = 999;
859
+ this._isPauseScan = true;
860
+ __classPrivateFieldSet(this, _CaptureVisionRouter_promiseStartScan, null, "f");
861
+ __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").setColourChannelUsageType(EnumColourChannelUsageType.CCUT_AUTO);
862
+ }
863
+ async containsTask(templateName) {
864
+ checkIsDisposed(this);
865
+ return await new Promise((rs, rj) => {
866
+ let taskID = getNextTaskID();
867
+ mapTaskCallBack[taskID] = async (body) => {
868
+ if (body.success) {
869
+ return rs(JSON.parse(body.tasks));
870
+ }
871
+ else {
872
+ let ex = new Error(body.message);
873
+ ex.stack = body.stack + '\n' + ex.stack;
874
+ return rj(ex);
875
+ }
876
+ };
877
+ worker.postMessage({
878
+ type: "cvr_containsTask",
879
+ id: taskID,
880
+ instanceID: this._instanceID,
881
+ body: {
882
+ templateName
883
+ }
884
+ });
885
+ });
886
+ }
887
+ /**
888
+ * Video stream capture, recursive call, loop frame capture
889
+ */
890
+ async _loopReadVideo(templateName) {
891
+ if ((this.disposed || this._isPauseScan)) {
892
+ return;
893
+ }
894
+ __classPrivateFieldSet(this, _CaptureVisionRouter_isScanner, true, "f");
895
+ if (__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").isBufferEmpty()) {
896
+ if (__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").hasNextImageToFetch()) {
897
+ for (let listener of __classPrivateFieldGet(this, _CaptureVisionRouter_isaStateListenerSet, "f")) {
898
+ listener.onImageSourceStateReceived && listener.onImageSourceStateReceived(EnumImageSourceState.ISS_BUFFER_EMPTY);
899
+ }
900
+ }
901
+ else if (!(__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").hasNextImageToFetch())) {
902
+ for (let listener of __classPrivateFieldGet(this, _CaptureVisionRouter_isaStateListenerSet, "f")) {
903
+ listener.onImageSourceStateReceived && listener.onImageSourceStateReceived(EnumImageSourceState.ISS_EXHAUSTED);
904
+ }
905
+ }
906
+ }
907
+ if (this._minImageCaptureInterval === -1 || __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").isBufferEmpty()) {
908
+ try {
909
+ if (__classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").isBufferEmpty() && CaptureVisionRouter._onLog)
910
+ CaptureVisionRouter._onLog(`buffer is empty so fetch image`);
911
+ if (CaptureVisionRouter._onLog) {
912
+ CaptureVisionRouter._onLog(`DCE: start fetching a frame: ${Date.now()}`);
913
+ }
914
+ this._dsImage = __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").fetchImage();
915
+ if (CaptureVisionRouter._onLog) {
916
+ CaptureVisionRouter._onLog(`DCE: finish fetching a frame: ${Date.now()}`);
917
+ }
918
+ __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").setImageFetchInterval(this._averageTime);
919
+ }
920
+ catch (e) {
921
+ this._reRunCurrnetFunc(templateName);
922
+ return;
923
+ }
924
+ }
925
+ else {
926
+ __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").setImageFetchInterval(this._averageTime - (this._dsImage && this._dsImage.tag ? this._dsImage.tag.timeSpent : 0));
927
+ this._dsImage = __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").getImage();
928
+ if (this._dsImage.tag) {
929
+ if (Date.now() - this._dsImage.tag.timeStamp > 200) {
930
+ this._reRunCurrnetFunc(templateName);
931
+ return;
932
+ }
933
+ }
934
+ }
935
+ if (!this._dsImage) {
936
+ this._reRunCurrnetFunc(templateName);
937
+ return;
938
+ }
939
+ for (let receiver of __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f")) {
940
+ this._isOutputOriginalImage && receiver.onOriginalImageResultReceived && receiver.onOriginalImageResultReceived({ imageData: this._dsImage });
941
+ }
942
+ // capture
943
+ // try {
944
+ // const captureStartTime = Date.now();
945
+ // const result = await this._captureDsimage(this._dsImage, templateName);
946
+ // if (CaptureVisionRouter._onLog) CaptureVisionRouter._onLog(`no js handle time: ${Date.now() - captureStartTime}`);
947
+ // if (this._isPauseScan) {
948
+ // this._reRunCurrnetFunc(templateName);
949
+ // return;
950
+ // }
951
+ // (result as any).originalImageTag = this._dsImage.tag ? this._dsImage.tag : null;
952
+ // const resultCommonPart = {
953
+ // originalImageHashId: result.originalImageHashId,
954
+ // originalImageTag: result.originalImageTag,
955
+ // errorCode: result.errorCode,
956
+ // errorString: result.errorString
957
+ // }
958
+ // for (let receiver of this.#resultReceiverSet) {
959
+ // if ((receiver as any).isDce) {
960
+ // const drawTime = Date.now();
961
+ // (receiver as any).onCapturedResultReceived(result, {
962
+ // isDetectVerifyOpen: this._isOpenDetectVerify,
963
+ // isNormalizeVerifyOpen: this._isOpenNormalizeVerify,
964
+ // isBarcodeVerifyOpen: this._isOpenBarcodeVerify,
965
+ // isLabelVerifyOpen: this._isOpenLabelVerify,
966
+ // });
967
+ // if (CaptureVisionRouter._onLog) {
968
+ // const time = Date.now() - drawTime;
969
+ // if (time > 10) CaptureVisionRouter._onLog(`draw result time: ${time}`)
970
+ // };
971
+ // }
972
+ // receiver.onDecodedBarcodesReceived && result.barcodeResultItems && receiver.onDecodedBarcodesReceived({
973
+ // ...resultCommonPart,
974
+ // barcodeResultItems: result.barcodeResultItems.filter((item: any) => { return !item.isFilter })
975
+ // } as DecodedBarcodesResult);
976
+ // receiver.onRecognizedTextLinesReceived && result.textLineResultItems && receiver.onRecognizedTextLinesReceived({
977
+ // ...resultCommonPart,
978
+ // textLineResultItems: result.textLineResultItems.filter((item: any) => { return !item.isFilter })
979
+ // } as RecognizedTextLinesResult);
980
+ // receiver.onDetectedQuadsReceived && result.detectedQuadResultItems && receiver.onDetectedQuadsReceived({
981
+ // ...resultCommonPart,
982
+ // detectedQuadResultItems: result.detectedQuadResultItems.filter((item: any) => { return !item.isFilter })
983
+ // } as DetectedQuadsResult);
984
+ // receiver.onNormalizedImagesReceived && result.normalizedImageResultItems && receiver.onNormalizedImagesReceived({
985
+ // ...resultCommonPart,
986
+ // normalizedImageResultItems: result.normalizedImageResultItems.filter((item: any) => { return !item.isFilter })
987
+ // } as NormalizedImagesResult);
988
+ // receiver.onParsedResultsReceived && result.parsedResultItems && receiver.onParsedResultsReceived({
989
+ // ...resultCommonPart,
990
+ // parsedResultItems: result.parsedResultItems.filter((item: any) => { return !item.isFilter })
991
+ // } as ParsedResult);
992
+ // if (receiver.onCapturedResultReceived && !(receiver as any).isDce) {
993
+ // (result as any).items = result.items.filter((item: any) => { return !item.isFilter });
994
+ // if ((result as any).barcodeResultItems) (result as any).barcodeResultItems = result.barcodeResultItems.filter((item: any) => { return !item.isFilter });
995
+ // if ((result as any).textLineResultItems) (result as any).textLineResultItems = result.textLineResultItems.filter((item: any) => { return !item.isFilter });
996
+ // if ((result as any).detectedQuadResultItems) (result as any).detectedQuadResultItems = result.detectedQuadResultItems.filter((item: any) => { return !item.isFilter });
997
+ // if ((result as any).normalizedImageResultItems) (result as any).normalizedImageResultItems = result.normalizedImageResultItems.filter((item: any) => { return !item.isFilter });
998
+ // if ((result as any).parsedResultItems) (result as any).parsedResultItems = result.parsedResultItems.filter((item: any) => { return !item.isFilter });
999
+ // receiver.onCapturedResultReceived(result);
1000
+ // }
1001
+ // }
1002
+ // const fetchImageCalculateStartTime = Date.now();
1003
+ // if (this._minImageCaptureInterval > -1) {
1004
+ // if (this._averageProcessintTimeArray.length === 5) this._averageProcessintTimeArray.shift();
1005
+ // if (this._averageFetchImageTimeArray.length === 5) this._averageFetchImageTimeArray.shift();
1006
+ // this._averageProcessintTimeArray.push(Date.now() - captureStartTime);
1007
+ // //this._averageTime = this._averageProcessintTimeArray.reduce((time, value) => time + value, 0) / this._averageProcessintTimeArray.length;
1008
+ // this._averageFetchImageTimeArray.push((this._dsImage && this._dsImage.tag ? (this._dsImage.tag as any).timeSpent : 0));
1009
+ // this._averageTime = Math.min(...this._averageProcessintTimeArray) - Math.max(...this._averageFetchImageTimeArray);
1010
+ // this._averageTime = this._averageTime > 0 ? this._averageTime : 0;
1011
+ // if (CaptureVisionRouter._onLog) {
1012
+ // CaptureVisionRouter._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`);
1013
+ // CaptureVisionRouter._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`);
1014
+ // CaptureVisionRouter._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`);
1015
+ // CaptureVisionRouter._onLog(`averageTime: ${this._averageTime}`);
1016
+ // };
1017
+ // }
1018
+ // if (CaptureVisionRouter._onLog) {
1019
+ // const time = Date.now() - fetchImageCalculateStartTime;
1020
+ // if (time > 10) CaptureVisionRouter._onLog(`fetch image calculate time: ${time}`)
1021
+ // };
1022
+ // if (CaptureVisionRouter._onLog) CaptureVisionRouter._onLog(`time finish decode: ${Date.now()}`)
1023
+ // if (CaptureVisionRouter._onLog) CaptureVisionRouter._onLog(`main time: ${Date.now() - captureStartTime}`);
1024
+ // if (CaptureVisionRouter._onLog) CaptureVisionRouter._onLog("====================================================");
1025
+ // this._loopReadVideoTimeoutId && clearTimeout(this._loopReadVideoTimeoutId);
1026
+ // if (this._minImageCaptureInterval > 0 && this._minImageCaptureInterval >= this._averageTime) {
1027
+ // this._loopReadVideoTimeoutId = setTimeout(() => {
1028
+ // this._loopReadVideo(templateName);
1029
+ // }, this._minImageCaptureInterval - this._averageTime);
1030
+ // } else {
1031
+ // this._loopReadVideoTimeoutId = setTimeout(() => {
1032
+ // this._loopReadVideo(templateName);
1033
+ // }, Math.max(this._minImageCaptureInterval, 0));
1034
+ // }
1035
+ // } catch (ex) {
1036
+ // this.#isa.stopFetching();
1037
+ // this._loopReadVideoTimeoutId && clearTimeout(this._loopReadVideoTimeoutId);
1038
+ // this._loopReadVideoTimeoutId = setTimeout(() => {
1039
+ // this.#isa.startFetching();
1040
+ // this._loopReadVideo(templateName);
1041
+ // }, Math.max(this._minImageCaptureInterval, 1000));
1042
+ // if (!(ex.message === 'platform error')) {
1043
+ // throw ex;
1044
+ // }
1045
+ // }
1046
+ const captureStartTime = Date.now();
1047
+ this._captureDsimage(this._dsImage, templateName).then(async (result) => {
1048
+ if (CaptureVisionRouter._onLog)
1049
+ CaptureVisionRouter._onLog(`no js handle time: ${Date.now() - captureStartTime}`);
1050
+ if (this._isPauseScan) {
1051
+ this._reRunCurrnetFunc(templateName);
1052
+ return;
1053
+ }
1054
+ result.originalImageTag = this._dsImage.tag ? this._dsImage.tag : null;
1055
+ const resultCommonPart = {
1056
+ originalImageHashId: result.originalImageHashId,
1057
+ originalImageTag: result.originalImageTag,
1058
+ errorCode: result.errorCode,
1059
+ errorString: result.errorString
1060
+ };
1061
+ for (let receiver of __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f")) {
1062
+ if (receiver.isDce) {
1063
+ const drawTime = Date.now();
1064
+ receiver.onCapturedResultReceived(result, {
1065
+ isDetectVerifyOpen: this._isOpenDetectVerify,
1066
+ isNormalizeVerifyOpen: this._isOpenNormalizeVerify,
1067
+ isBarcodeVerifyOpen: this._isOpenBarcodeVerify,
1068
+ isLabelVerifyOpen: this._isOpenLabelVerify,
1069
+ });
1070
+ if (CaptureVisionRouter._onLog) {
1071
+ const time = Date.now() - drawTime;
1072
+ if (time > 10)
1073
+ CaptureVisionRouter._onLog(`draw result time: ${time}`);
1074
+ }
1075
+ continue;
1076
+ }
1077
+ for (let resultItem in resultItemMapConfig) {
1078
+ const _itemType = resultItem;
1079
+ const _itemConfig = resultItemMapConfig[_itemType];
1080
+ receiver[_itemConfig.reveiver];
1081
+ receiver[_itemConfig.reveiver] && result[_itemType] && receiver[_itemConfig.reveiver](Object.assign(Object.assign({}, resultCommonPart), { [_itemType]: result[_itemType].filter((item) => {
1082
+ return !_itemConfig.isNeedFilter || !item.isFilter;
1083
+ }) }));
1084
+ if (result[_itemType])
1085
+ result[_itemType] = result[_itemType].filter((item) => {
1086
+ return !_itemConfig.isNeedFilter || !item.isFilter;
1087
+ });
1088
+ }
1089
+ if (receiver.onCapturedResultReceived) {
1090
+ result.items = result.items.filter((item) => {
1091
+ return [EnumCapturedResultItemType.CRIT_DETECTED_QUAD, EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE].includes(item.type) || !item.isFilter;
1092
+ });
1093
+ receiver.onCapturedResultReceived(result);
1094
+ }
1095
+ }
1096
+ const fetchImageCalculateStartTime = Date.now();
1097
+ if (this._minImageCaptureInterval > -1) {
1098
+ if (this._averageProcessintTimeArray.length === 5)
1099
+ this._averageProcessintTimeArray.shift();
1100
+ if (this._averageFetchImageTimeArray.length === 5)
1101
+ this._averageFetchImageTimeArray.shift();
1102
+ this._averageProcessintTimeArray.push(Date.now() - captureStartTime);
1103
+ //this._averageTime = this._averageProcessintTimeArray.reduce((time, value) => time + value, 0) / this._averageProcessintTimeArray.length;
1104
+ this._averageFetchImageTimeArray.push((this._dsImage && this._dsImage.tag ? this._dsImage.tag.timeSpent : 0));
1105
+ this._averageTime = Math.min(...this._averageProcessintTimeArray) - Math.max(...this._averageFetchImageTimeArray);
1106
+ this._averageTime = this._averageTime > 0 ? this._averageTime : 0;
1107
+ if (CaptureVisionRouter._onLog) {
1108
+ CaptureVisionRouter._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`);
1109
+ CaptureVisionRouter._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`);
1110
+ CaptureVisionRouter._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`);
1111
+ CaptureVisionRouter._onLog(`averageTime: ${this._averageTime}`);
1112
+ }
1113
+ }
1114
+ if (CaptureVisionRouter._onLog) {
1115
+ const time = Date.now() - fetchImageCalculateStartTime;
1116
+ if (time > 10)
1117
+ CaptureVisionRouter._onLog(`fetch image calculate time: ${time}`);
1118
+ }
1119
+ if (CaptureVisionRouter._onLog)
1120
+ CaptureVisionRouter._onLog(`time finish decode: ${Date.now()}`);
1121
+ if (CaptureVisionRouter._onLog)
1122
+ CaptureVisionRouter._onLog(`main time: ${Date.now() - captureStartTime}`);
1123
+ if (CaptureVisionRouter._onLog)
1124
+ CaptureVisionRouter._onLog("====================================================");
1125
+ this._loopReadVideoTimeoutId && clearTimeout(this._loopReadVideoTimeoutId);
1126
+ if (this._minImageCaptureInterval > 0 && this._minImageCaptureInterval >= this._averageTime) {
1127
+ this._loopReadVideoTimeoutId = setTimeout(() => {
1128
+ this._loopReadVideo(templateName);
1129
+ }, this._minImageCaptureInterval - this._averageTime);
1130
+ }
1131
+ else {
1132
+ this._loopReadVideoTimeoutId = setTimeout(() => {
1133
+ this._loopReadVideo(templateName);
1134
+ }, Math.max(this._minImageCaptureInterval, 0));
1135
+ }
1136
+ }).catch((ex) => {
1137
+ __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").stopFetching();
1138
+ if (ex.errorCode && ex.errorCode === 0) {
1139
+ this._loopReadVideoTimeoutId && clearTimeout(this._loopReadVideoTimeoutId);
1140
+ this._loopReadVideoTimeoutId = setTimeout(() => {
1141
+ __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f").startFetching();
1142
+ this._loopReadVideo(templateName);
1143
+ }, Math.max(this._minImageCaptureInterval, 1000));
1144
+ }
1145
+ if (!(ex.message === 'platform error')) {
1146
+ setTimeout(() => { throw ex; }, 0);
1147
+ }
1148
+ });
1149
+ }
1150
+ _reRunCurrnetFunc(templateName) {
1151
+ this._loopReadVideoTimeoutId && clearTimeout(this._loopReadVideoTimeoutId);
1152
+ this._loopReadVideoTimeoutId = setTimeout(() => {
1153
+ this._loopReadVideo(templateName);
1154
+ }, 0);
1155
+ }
1156
+ /**
1157
+ * Processes a single image or a file containing a single image to derive important information.
1158
+ * @param imageOrFile Specifies the image or file to be processed. The following data types are accepted: `Blob`, `HTMLImageElement`, `HTMLCanvasElement`, `HTMLVideoElement`, `DSImageData`, `string`.
1159
+ * @param templateName [Optional] Specifies a "CaptureVisionTemplate" to use.
1160
+ *
1161
+ * @returns A promise that resolves with a `CapturedResult` object which contains the derived information from the image processed.
1162
+ */
1163
+ async capture(imageOrFile, templateName) {
1164
+ var _a, _b;
1165
+ checkIsDisposed(this);
1166
+ if (!templateName)
1167
+ templateName = CaptureVisionRouter._defaultTemplate;
1168
+ const tasks = await this.containsTask(templateName);
1169
+ await loadWasm(tasks);
1170
+ if (tasks.includes("dlr") && !((_a = mapPackageRegister.dlr) === null || _a === void 0 ? void 0 : _a.bLoadConfusableCharsData)) {
1171
+ const _engineResourcePaths = handleEngineResourcePaths(CoreModule.engineResourcePaths);
1172
+ await ((_b = mapPackageRegister.dlr) === null || _b === void 0 ? void 0 : _b.loadRecognitionData("ConfusableChars", _engineResourcePaths.dlr));
1173
+ }
1174
+ let result;
1175
+ __classPrivateFieldSet(this, _CaptureVisionRouter_isScanner, false, "f");
1176
+ if (isDSImageData(imageOrFile)) {
1177
+ result = await this._captureDsimage(imageOrFile, templateName);
1178
+ }
1179
+ else if (typeof imageOrFile === "string") {
1180
+ if (imageOrFile.substring(0, 11) == "data:image/") {
1181
+ result = await this._captureBase64(imageOrFile, templateName);
1182
+ }
1183
+ else {
1184
+ result = await this._captureUrl(imageOrFile, templateName);
1185
+ }
1186
+ }
1187
+ else if (imageOrFile instanceof Blob) {
1188
+ result = await this._captureBlob(imageOrFile, templateName);
1189
+ }
1190
+ else if (imageOrFile instanceof HTMLImageElement) {
1191
+ result = await this._captureImage(imageOrFile, templateName);
1192
+ }
1193
+ else if (imageOrFile instanceof HTMLCanvasElement) {
1194
+ result = await this._captureCanvas(imageOrFile, templateName);
1195
+ }
1196
+ else if (imageOrFile instanceof HTMLVideoElement) {
1197
+ result = await this._captureVideo(imageOrFile, templateName);
1198
+ }
1199
+ else {
1200
+ throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");
1201
+ }
1202
+ return result;
1203
+ }
1204
+ ;
1205
+ async _captureDsimage(imageOrFile, templateName) {
1206
+ return await this._captureInWorker(imageOrFile, templateName);
1207
+ }
1208
+ async _captureUrl(imageOrFile, templateName) {
1209
+ let blob = await requestResource(imageOrFile, "blob");
1210
+ return await this._captureBlob(blob, templateName);
1211
+ }
1212
+ async _captureBase64(base64Str, templateName) {
1213
+ base64Str = base64Str.substring(base64Str.indexOf(',') + 1);
1214
+ let binaryStr = atob(base64Str);
1215
+ let n = binaryStr.length;
1216
+ let u8arr = new Uint8Array(n);
1217
+ while (n--) {
1218
+ u8arr[n] = binaryStr.charCodeAt(n);
1219
+ }
1220
+ return await this._captureBlob(new Blob([u8arr]), templateName);
1221
+ }
1222
+ async _captureBlob(imageOrFile, templateName) {
1223
+ const useObjurlToDrawBlobToImg = async function (blob) {
1224
+ return await new Promise((rs, rj) => {
1225
+ let objUrl = URL.createObjectURL(blob);
1226
+ let image = new Image();
1227
+ image.src = objUrl;
1228
+ image.onload = () => {
1229
+ URL.revokeObjectURL(image.dbrObjUrl); // relese memory
1230
+ rs(image);
1231
+ };
1232
+ image.onerror = ev => {
1233
+ rj(new Error("Can't convert blob to image : " + (ev instanceof Event ? ev.type : ev)));
1234
+ };
1235
+ });
1236
+ };
1237
+ let imageBitmap = null;
1238
+ let img = null;
1239
+ if (typeof createImageBitmap !== "undefined") {
1240
+ try {
1241
+ imageBitmap = await createImageBitmap(imageOrFile);
1242
+ }
1243
+ catch (ex) {
1244
+ // createImageBitmap maybe fail in a lot of sense
1245
+ // although objurl can pass
1246
+ }
1247
+ }
1248
+ if (!imageBitmap) {
1249
+ img = await useObjurlToDrawBlobToImg(imageOrFile);
1250
+ }
1251
+ let results = await this._captureImage(imageBitmap || img, templateName);
1252
+ if (imageBitmap) {
1253
+ imageBitmap.close();
1254
+ } // release memory
1255
+ return results;
1256
+ }
1257
+ async _captureImage(image, templateName) {
1258
+ let imgW = image instanceof HTMLImageElement ? image.naturalWidth : image.width;
1259
+ let imgH = image instanceof HTMLImageElement ? image.naturalHeight : image.height;
1260
+ let maxNaturalWH = Math.max(imgW, imgH);
1261
+ let acceptW, acceptH;
1262
+ if (maxNaturalWH > this.maxImageSideLength) {
1263
+ __classPrivateFieldSet(this, _CaptureVisionRouter_compressRate, this.maxImageSideLength / maxNaturalWH, "f");
1264
+ acceptW = Math.round(imgW * __classPrivateFieldGet(this, _CaptureVisionRouter_compressRate, "f"));
1265
+ acceptH = Math.round(imgH * __classPrivateFieldGet(this, _CaptureVisionRouter_compressRate, "f"));
1266
+ }
1267
+ else {
1268
+ acceptW = imgW;
1269
+ acceptH = imgH;
1270
+ }
1271
+ if (!__classPrivateFieldGet(this, _CaptureVisionRouter_canvas, "f")) {
1272
+ __classPrivateFieldSet(this, _CaptureVisionRouter_canvas, document.createElement('canvas'), "f");
1273
+ }
1274
+ const cvs = __classPrivateFieldGet(this, _CaptureVisionRouter_canvas, "f");
1275
+ if (cvs.width !== acceptW || cvs.height !== acceptH) {
1276
+ cvs.width = acceptW;
1277
+ cvs.height = acceptH;
1278
+ }
1279
+ if (!cvs.ctx2d) {
1280
+ cvs.ctx2d = cvs.getContext('2d', { willReadFrequently: true });
1281
+ }
1282
+ const ctx = cvs.ctx2d;
1283
+ ctx.drawImage(image, 0, 0, imgW, imgH, 0, 0, acceptW, acceptH);
1284
+ if (image.dbrObjUrl) {
1285
+ URL.revokeObjectURL(image.dbrObjUrl); // relese memory
1286
+ }
1287
+ return await this._captureCanvas(cvs, templateName);
1288
+ }
1289
+ async _captureCanvas(canvas, templateName) {
1290
+ if (canvas.crossOrigin && "anonymous" != canvas.crossOrigin) { // canvas has crossOrigin to detect if cors, is native api
1291
+ throw "cors";
1292
+ }
1293
+ if ([canvas.width, canvas.height].includes(0)) {
1294
+ throw Error(`The width or height of the 'canvas' is 0.`);
1295
+ }
1296
+ const ctx = canvas.ctx2d || canvas.getContext("2d", { willReadFrequently: true });
1297
+ const imgData = Uint8Array.from(ctx.getImageData(0, 0, canvas.width, canvas.height).data);
1298
+ const DsImageData = {
1299
+ bytes: imgData,
1300
+ width: canvas.width,
1301
+ height: canvas.height,
1302
+ stride: canvas.width * 4,
1303
+ format: 10,
1304
+ };
1305
+ return await this._captureInWorker(DsImageData, templateName);
1306
+ }
1307
+ async _captureVideo(video, templateName) {
1308
+ if (video.crossOrigin && "anonymous" != video.crossOrigin) {
1309
+ throw "cors";
1310
+ }
1311
+ let imgW = video.videoWidth;
1312
+ let imgH = video.videoHeight;
1313
+ let maxNaturalWH = Math.max(imgW, imgH);
1314
+ let acceptW, acceptH;
1315
+ if (maxNaturalWH > this.maxImageSideLength) {
1316
+ __classPrivateFieldSet(this, _CaptureVisionRouter_compressRate, this.maxImageSideLength / maxNaturalWH, "f");
1317
+ acceptW = Math.round(imgW * __classPrivateFieldGet(this, _CaptureVisionRouter_compressRate, "f"));
1318
+ acceptH = Math.round(imgH * __classPrivateFieldGet(this, _CaptureVisionRouter_compressRate, "f"));
1319
+ }
1320
+ else {
1321
+ acceptW = imgW;
1322
+ acceptH = imgH;
1323
+ }
1324
+ if (!__classPrivateFieldGet(this, _CaptureVisionRouter_canvas, "f")) {
1325
+ __classPrivateFieldSet(this, _CaptureVisionRouter_canvas, document.createElement('canvas'), "f");
1326
+ }
1327
+ const cvs = __classPrivateFieldGet(this, _CaptureVisionRouter_canvas, "f");
1328
+ if (cvs.width !== acceptW || cvs.height !== acceptH) {
1329
+ cvs.width = acceptW;
1330
+ cvs.height = acceptH;
1331
+ }
1332
+ if (!cvs.ctx2d) {
1333
+ cvs.ctx2d = cvs.getContext('2d', { willReadFrequently: true });
1334
+ }
1335
+ const ctx = cvs.ctx2d;
1336
+ ctx.drawImage(video, 0, 0, imgW, imgH, 0, 0, acceptW, acceptH);
1337
+ return await this._captureCanvas(cvs, templateName);
1338
+ }
1339
+ async _captureInWorker(DsImageData, templateName) {
1340
+ const { bytes, width, height, stride, format } = DsImageData;
1341
+ let taskID = getNextTaskID();
1342
+ const p = new MutablePromise();
1343
+ mapTaskCallBack[taskID] = async (body) => {
1344
+ var _a, _b;
1345
+ if (body.success) {
1346
+ const getResultFromWorkerTime = Date.now();
1347
+ if (CaptureVisionRouter._onLog) {
1348
+ CaptureVisionRouter._onLog(`get result time from worker: ${getResultFromWorkerTime}`);
1349
+ CaptureVisionRouter._onLog(`worker to main time consume: ${getResultFromWorkerTime - body.workerReturnMsgTime}`);
1350
+ }
1351
+ try {
1352
+ const captureResult = body.captureResult;
1353
+ if (captureResult.errorCode !== 0) {
1354
+ let error = new Error(captureResult.errorString);
1355
+ error.errorCode = captureResult.errorCode;
1356
+ return p.reject(error);
1357
+ }
1358
+ DsImageData.bytes = body.bytes;
1359
+ for (let item of captureResult.items) {
1360
+ if (__classPrivateFieldGet(this, _CaptureVisionRouter_compressRate, "f") !== 0) {
1361
+ convertCoordinates(item, __classPrivateFieldGet(this, _CaptureVisionRouter_compressRate, "f"));
1362
+ }
1363
+ if (item.type === EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE) {
1364
+ item.imageData = DsImageData;
1365
+ }
1366
+ else if (item.type === EnumCapturedResultItemType.CRIT_NORMALIZED_IMAGE) {
1367
+ (_a = mapPackageRegister.ddn) === null || _a === void 0 ? void 0 : _a.handleNormalizedImageResultItem(item);
1368
+ }
1369
+ else if (item.type === EnumCapturedResultItemType.CRIT_PARSED_RESULT) {
1370
+ (_b = mapPackageRegister.dcp) === null || _b === void 0 ? void 0 : _b.handleParsedResultItem(item);
1371
+ }
1372
+ }
1373
+ if (__classPrivateFieldGet(this, _CaptureVisionRouter_isScanner, "f")) {
1374
+ for (let filter of __classPrivateFieldGet(this, _CaptureVisionRouter_resultFilterSet, "f")) {
1375
+ filter.onDecodedBarcodesReceived(captureResult);
1376
+ filter.onRecognizedTextLinesReceived(captureResult);
1377
+ filter.onDetectedQuadsReceived(captureResult);
1378
+ filter.onNormalizedImagesReceived(captureResult);
1379
+ }
1380
+ }
1381
+ for (let itemName in resultItemMapConfig) {
1382
+ const _itemName = itemName;
1383
+ const filterItems = captureResult.items.filter((item) => {
1384
+ return item.type === resultItemMapConfig[_itemName].type;
1385
+ });
1386
+ if (filterItems.length) {
1387
+ captureResult[itemName] = filterItems;
1388
+ }
1389
+ }
1390
+ if (!this._isPauseScan || !__classPrivateFieldGet(this, _CaptureVisionRouter_isScanner, "f")) {
1391
+ const irs = captureResult.intermediateResult; // irs => intermediateResults
1392
+ if (irs) {
1393
+ let irrSetCount = 0;
1394
+ for (let irr of __classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f")._intermediateResultReceiverSet) {
1395
+ irrSetCount++;
1396
+ for (let cb of irs) {
1397
+ if (cb.info.callbackName === "onTaskResultsReceived") {
1398
+ for (let unit of cb.intermediateResultUnits) {
1399
+ unit.originalImageTag = DsImageData.tag ? DsImageData.tag : null;
1400
+ }
1401
+ if (irr[cb.info.callbackName]) {
1402
+ irr[cb.info.callbackName]({ intermediateResultUnits: cb.intermediateResultUnits }, cb.info);
1403
+ }
1404
+ }
1405
+ else {
1406
+ if (irr[cb.info.callbackName]) {
1407
+ irr[cb.info.callbackName](cb.result, cb.info);
1408
+ }
1409
+ }
1410
+ if (irrSetCount === __classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f")._intermediateResultReceiverSet.size) {
1411
+ delete cb.info.callbackName;
1412
+ }
1413
+ }
1414
+ }
1415
+ }
1416
+ }
1417
+ captureResult && captureResult.hasOwnProperty("intermediateResult") && delete captureResult.intermediateResult;
1418
+ __classPrivateFieldSet(this, _CaptureVisionRouter_compressRate, 0, "f");
1419
+ return p.resolve(captureResult);
1420
+ }
1421
+ catch (ex) {
1422
+ return p.reject(ex);
1423
+ }
1424
+ }
1425
+ else {
1426
+ let ex = new Error(body.message);
1427
+ ex.stack = body.stack + '\n' + ex.stack;
1428
+ return p.reject(ex);
1429
+ }
1430
+ };
1431
+ if (CaptureVisionRouter._onLog) {
1432
+ CaptureVisionRouter._onLog(`send buffer to worker: ${Date.now()}`);
1433
+ }
1434
+ worker.postMessage({
1435
+ type: "cvr_capture",
1436
+ id: taskID,
1437
+ instanceID: this._instanceID,
1438
+ body: {
1439
+ bytes,
1440
+ width,
1441
+ height,
1442
+ stride,
1443
+ format,
1444
+ templateName: templateName ? templateName : "",
1445
+ isScanner: __classPrivateFieldGet(this, _CaptureVisionRouter_isScanner, "f")
1446
+ }
1447
+ }, [bytes.buffer]);
1448
+ return p;
1449
+ }
1450
+ ;
1451
+ /**
1452
+ * Configures runtime settings using a provided JSON string, an object, or a URL pointing to an object, which contains settings for one or more `CaptureVisionTemplates`.
1453
+ * @param settings A JSON string, an object, or a URL pointing to an object that contains settings for one or more `CaptureVisionTemplates`.
1454
+ *
1455
+ * @returns A promise that resolves when the operation has completed. It provides an object that describes the result.
1456
+ */
1457
+ async initSettings(settings) {
1458
+ checkIsDisposed(this);
1459
+ if (!settings || !["string", "object"].includes(typeof settings)) {
1460
+ return console.error("Invalid template.");
1461
+ }
1462
+ if (typeof settings === "string") {
1463
+ if (!settings.trimStart().startsWith("{")) {
1464
+ settings = await requestResource(settings, "text");
1465
+ }
1466
+ }
1467
+ else if (typeof settings === "object") {
1468
+ settings = JSON.stringify(settings);
1469
+ }
1470
+ return await new Promise((rs, rj) => {
1471
+ let taskID = getNextTaskID();
1472
+ mapTaskCallBack[taskID] = async (body) => {
1473
+ if (body.success) {
1474
+ const response = JSON.parse(body.response);
1475
+ if (response.errorCode !== 0) {
1476
+ let error = new Error(response.errorString ? response.errorString : "Init Settings Failed.");
1477
+ error.errorCode = response.errorCode;
1478
+ return rj(error);
1479
+ }
1480
+ const _parsedSettings = JSON.parse(settings);
1481
+ this._currentSettings = _parsedSettings;
1482
+ let modules = [];
1483
+ let templateNames = _parsedSettings.CaptureVisionTemplates;
1484
+ for (let i = 0; i < templateNames.length; i++) {
1485
+ let tasks = await this.containsTask(templateNames[i].Name);
1486
+ modules = modules.concat(tasks);
1487
+ }
1488
+ await loadWasm([...new Set(modules)]);
1489
+ this._isOutputOriginalImage = (this._currentSettings.CaptureVisionTemplates[0].OutputOriginalImage === 1);
1490
+ CaptureVisionRouter._defaultTemplate = this._currentSettings.CaptureVisionTemplates[0].Name;
1491
+ return rs(response);
1492
+ }
1493
+ else {
1494
+ let ex = new Error(body.message);
1495
+ ex.stack = body.stack + '\n' + ex.stack;
1496
+ return rj(ex);
1497
+ }
1498
+ };
1499
+ worker.postMessage({
1500
+ type: "cvr_initSettings",
1501
+ id: taskID,
1502
+ instanceID: this._instanceID,
1503
+ body: { settings },
1504
+ });
1505
+ });
1506
+ }
1507
+ ;
1508
+ /**
1509
+ * Returns an object that contains settings for the specified `CaptureVisionTemplate`.
1510
+ * @param templateName Specifies a `CaptureVisionTemplate` by its name. If passed "*", the returned object will contain all templates.
1511
+ *
1512
+ * @returns A promise that resolves with the object that contains settings for the specified template or all templates.
1513
+ */
1514
+ async outputSettings(templateName) {
1515
+ checkIsDisposed(this);
1516
+ return await new Promise((rs, rj) => {
1517
+ let taskID = getNextTaskID();
1518
+ mapTaskCallBack[taskID] = async (body) => {
1519
+ if (body.success) {
1520
+ const response = JSON.parse(body.response);
1521
+ if (response.errorCode !== 0) {
1522
+ let error = new Error(response.errorString);
1523
+ error.errorCode = response.errorCode;
1524
+ return rj(error);
1525
+ }
1526
+ return rs(JSON.parse(response.data));
1527
+ }
1528
+ else {
1529
+ let ex = new Error(body.message);
1530
+ ex.stack = body.stack + '\n' + ex.stack;
1531
+ return rj(ex);
1532
+ }
1533
+ };
1534
+ worker.postMessage({
1535
+ type: "cvr_outputSettings",
1536
+ id: taskID,
1537
+ instanceID: this._instanceID,
1538
+ body: {
1539
+ templateName: templateName ? templateName : "*"
1540
+ }
1541
+ });
1542
+ });
1543
+ }
1544
+ ;
1545
+ /**
1546
+ * Generates a Blob object or initiates a JSON file download containing the settings for the specified `CaptureVisionTemplate`.
1547
+ * @param templateName Specifies a `CaptureVisionTemplate` by its name. If passed "*", the returned object will contain all templates.
1548
+ * @param fileName Specifies the name of the file.
1549
+ * @param download Boolean that specifies whether to initiates a file download.
1550
+ *
1551
+ * @returns A promise that resolves with the Blob object that contains settings for the specified template or all templates.
1552
+ */
1553
+ async outputSettingsToFile(templateName, fileName, download) {
1554
+ const settings = await this.outputSettings(templateName);
1555
+ const jsonBlob = new Blob([JSON.stringify(settings, null, 2, function (_, value) {
1556
+ if (value instanceof Array) {
1557
+ return JSON.stringify(value);
1558
+ }
1559
+ else {
1560
+ return value;
1561
+ }
1562
+ }, 2)], { type: "application/json" });
1563
+ if (download) {
1564
+ const downloadLink = document.createElement("a");
1565
+ downloadLink.href = URL.createObjectURL(jsonBlob);
1566
+ if (fileName.endsWith(".json")) {
1567
+ fileName = fileName.replace(".json", "");
1568
+ }
1569
+ downloadLink.download = `${fileName}.json`;
1570
+ downloadLink.onclick = () => {
1571
+ setTimeout(() => {
1572
+ URL.revokeObjectURL(downloadLink.href);
1573
+ }, 500);
1574
+ };
1575
+ downloadLink.click();
1576
+ }
1577
+ return jsonBlob;
1578
+ }
1579
+ async getTemplateNames() {
1580
+ checkIsDisposed(this);
1581
+ return await new Promise((rs, rj) => {
1582
+ let taskID = getNextTaskID();
1583
+ mapTaskCallBack[taskID] = async (body) => {
1584
+ if (body.success) {
1585
+ const response = JSON.parse(body.response);
1586
+ if (response.errorCode !== 0) {
1587
+ let error = new Error(response.errorString);
1588
+ error.errorCode = response.errorCode;
1589
+ return rj(error);
1590
+ }
1591
+ return rs(JSON.parse(response.data));
1592
+ }
1593
+ else {
1594
+ let ex = new Error(body.message);
1595
+ ex.stack = body.stack + '\n' + ex.stack;
1596
+ return rj(ex);
1597
+ }
1598
+ };
1599
+ worker.postMessage({
1600
+ type: "cvr_getTemplateNames",
1601
+ id: taskID,
1602
+ instanceID: this._instanceID
1603
+ });
1604
+ });
1605
+ }
1606
+ /**
1607
+ * Retrieves a JSON object that contains simplified settings for the specified `CaptureVisionTemplate`.
1608
+ * @param templateName Specifies a `CaptureVisionTemplate` by its name.
1609
+ *
1610
+ * @returns A promise that resolves with a JSON object, of type `SimplifiedCaptureVisionSettings`, which represents the simplified settings for the specified template.
1611
+ * @remarks If the settings of the specified template are too complex, we cannot create a SimplifiedCaptureVisionSettings, and as a result, it will return an error.
1612
+ */
1613
+ async getSimplifiedSettings(templateName) {
1614
+ checkIsDisposed(this);
1615
+ if (!templateName)
1616
+ templateName = this._currentSettings.CaptureVisionTemplates[0].Name;
1617
+ const tasks = await this.containsTask(templateName);
1618
+ await loadWasm(tasks);
1619
+ return await new Promise((rs, rj) => {
1620
+ let taskID = getNextTaskID();
1621
+ mapTaskCallBack[taskID] = async (body) => {
1622
+ if (body.success) {
1623
+ const response = JSON.parse(body.response);
1624
+ if (response.errorCode !== 0) {
1625
+ let error = new Error(response.errorString);
1626
+ error.errorCode = response.errorCode;
1627
+ return rj(error);
1628
+ }
1629
+ const responseData = JSON.parse(response.data, (k, v) => {
1630
+ if (k === "barcodeFormatIds") {
1631
+ return BigInt(v);
1632
+ }
1633
+ return v;
1634
+ });
1635
+ responseData.minImageCaptureInterval = this._minImageCaptureInterval;
1636
+ return rs(responseData);
1637
+ }
1638
+ else {
1639
+ let ex = new Error(body.message);
1640
+ ex.stack = body.stack + '\n' + ex.stack;
1641
+ return rj(ex);
1642
+ }
1643
+ };
1644
+ worker.postMessage({
1645
+ type: "cvr_getSimplifiedSettings",
1646
+ id: taskID,
1647
+ instanceID: this._instanceID,
1648
+ body: { templateName }
1649
+ });
1650
+ });
1651
+ }
1652
+ ;
1653
+ /**
1654
+ * Updates the specified `CaptureVisionTemplate` with an updated `SimplifiedCaptureVisionSettings` object.
1655
+ * @param templateName Specifies a `CaptureVisionTemplate` by its name.
1656
+ * @param settings The `SimplifiedCaptureVisionSettings` object that contains updated settings.
1657
+ *
1658
+ * @returns A promise that resolves when the operation has completed. It provides an object that describes the result.
1659
+ */
1660
+ async updateSettings(templateName, settings) {
1661
+ checkIsDisposed(this);
1662
+ const tasks = await this.containsTask(templateName);
1663
+ await loadWasm(tasks);
1664
+ return await new Promise((rs, rj) => {
1665
+ let taskID = getNextTaskID();
1666
+ mapTaskCallBack[taskID] = async (body) => {
1667
+ if (body.success) {
1668
+ const response = JSON.parse(body.response);
1669
+ if (settings.minImageCaptureInterval && settings.minImageCaptureInterval >= -1) {
1670
+ this._minImageCaptureInterval = settings.minImageCaptureInterval;
1671
+ }
1672
+ this._isOutputOriginalImage = body.isOutputOriginalImage;
1673
+ if (response.errorCode !== 0) {
1674
+ let error = new Error(response.errorString ? response.errorString : "Update Settings Failed.");
1675
+ error.errorCode = response.errorCode;
1676
+ return rj(error);
1677
+ }
1678
+ this._currentSettings = await this.outputSettings("*");
1679
+ return rs(response);
1680
+ }
1681
+ else {
1682
+ let ex = new Error(body.message);
1683
+ ex.stack = body.stack + '\n' + ex.stack;
1684
+ return rj(ex);
1685
+ }
1686
+ };
1687
+ worker.postMessage({
1688
+ type: "cvr_updateSettings",
1689
+ id: taskID,
1690
+ instanceID: this._instanceID,
1691
+ body: {
1692
+ settings,
1693
+ templateName
1694
+ }
1695
+ });
1696
+ });
1697
+ }
1698
+ /**
1699
+ * Restores all runtime settings to their original default values.
1700
+ *
1701
+ * @returns A promise that resolves when the operation has completed. It provides an object that describes the result.
1702
+ */
1703
+ async resetSettings() {
1704
+ checkIsDisposed(this);
1705
+ return await new Promise((rs, rj) => {
1706
+ let taskID = getNextTaskID();
1707
+ mapTaskCallBack[taskID] = async (body) => {
1708
+ if (body.success) {
1709
+ const response = JSON.parse(body.response);
1710
+ if (response.errorCode !== 0) {
1711
+ let error = new Error(response.errorString ? response.errorString : "Reset Settings Failed.");
1712
+ error.errorCode = response.errorCode;
1713
+ return rj(error);
1714
+ }
1715
+ this._currentSettings = await this.outputSettings("*");
1716
+ return rs(response);
1717
+ }
1718
+ else {
1719
+ let ex = new Error(body.message);
1720
+ ex.stack = body.stack + '\n' + ex.stack;
1721
+ return rj(ex);
1722
+ }
1723
+ };
1724
+ worker.postMessage({
1725
+ type: "cvr_resetSettings",
1726
+ id: taskID,
1727
+ instanceID: this._instanceID
1728
+ });
1729
+ });
1730
+ }
1731
+ ;
1732
+ /**
1733
+ * Returns an object, of type `BufferedItemsManager`, that manages buffered items.
1734
+ * @returns The `BufferedItemsManager` object.
1735
+ */
1736
+ getBufferedItemsManager() {
1737
+ if (!__classPrivateFieldGet(this, _CaptureVisionRouter_bufferdItemsManager, "f")) {
1738
+ __classPrivateFieldSet(this, _CaptureVisionRouter_bufferdItemsManager, new BufferedItemsManager(this), "f");
1739
+ }
1740
+ return __classPrivateFieldGet(this, _CaptureVisionRouter_bufferdItemsManager, "f");
1741
+ }
1742
+ /**
1743
+ * Returns an object, of type `IntermediateResultManager`, that manages intermediate results.
1744
+ *
1745
+ * @returns The `IntermediateResultManager` object.
1746
+ */
1747
+ getIntermediateResultManager() {
1748
+ checkIsDisposed(this);
1749
+ if (!__classPrivateFieldGet(this, _CaptureVisionRouter_innerUseTag, "f") && CoreModule.bSupportIRTModule !== 0) {
1750
+ throw new Error("The current license does not support the use of intermediate results.");
1751
+ }
1752
+ if (!__classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f")) {
1753
+ __classPrivateFieldSet(this, _CaptureVisionRouter_intermediateResultManager, new IntermediateResultManager(this), "f");
1754
+ }
1755
+ return __classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f");
1756
+ }
1757
+ ;
1758
+ async parseRequiredResources(templateName) {
1759
+ checkIsDisposed(this);
1760
+ return await new Promise((rs, rj) => {
1761
+ let taskID = getNextTaskID();
1762
+ mapTaskCallBack[taskID] = async (body) => {
1763
+ if (body.success) {
1764
+ return rs(JSON.parse(body.resources));
1765
+ }
1766
+ else {
1767
+ let ex = new Error(body.message);
1768
+ ex.stack = body.stack + '\n' + ex.stack;
1769
+ return rj(ex);
1770
+ }
1771
+ };
1772
+ worker.postMessage({
1773
+ type: "cvr_parseRequiredResources",
1774
+ id: taskID,
1775
+ instanceID: this._instanceID,
1776
+ body: {
1777
+ templateName
1778
+ }
1779
+ });
1780
+ });
1781
+ }
1782
+ /**
1783
+ * Releases all resources used by the `CaptureVisionRouter` instance.
1784
+ *
1785
+ * @returns A promise that resolves when the resources have been successfully released. It does not provide any value upon resolution.
1786
+ */
1787
+ async dispose() {
1788
+ checkIsDisposed(this);
1789
+ if (__classPrivateFieldGet(this, _CaptureVisionRouter_promiseStartScan, "f")) {
1790
+ this.stopCapturing();
1791
+ }
1792
+ __classPrivateFieldSet(this, _CaptureVisionRouter_isa, null, "f");
1793
+ __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f").clear();
1794
+ __classPrivateFieldGet(this, _CaptureVisionRouter_isaStateListenerSet, "f").clear();
1795
+ __classPrivateFieldGet(this, _CaptureVisionRouter_resultFilterSet, "f").clear();
1796
+ __classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f")._intermediateResultReceiverSet.clear();
1797
+ __classPrivateFieldSet(this, _CaptureVisionRouter_isDestroyed, true, "f");
1798
+ // this._captureStateListenerSet.clear();
1799
+ let taskID = getNextTaskID();
1800
+ mapTaskCallBack[taskID] = (body) => {
1801
+ if (body.success) ;
1802
+ else {
1803
+ let ex = new Error(body.message);
1804
+ ex.stack = body.stack + '\n' + ex.stack;
1805
+ throw ex;
1806
+ }
1807
+ };
1808
+ worker.postMessage({
1809
+ type: 'cvr_dispose',
1810
+ id: taskID,
1811
+ instanceID: this._instanceID
1812
+ });
1813
+ }
1814
+ ;
1815
+ /**
1816
+ * For Debug
1817
+ */
1818
+ _getInternalData() {
1819
+ return {
1820
+ isa: __classPrivateFieldGet(this, _CaptureVisionRouter_isa, "f"),
1821
+ promiseStartScan: __classPrivateFieldGet(this, _CaptureVisionRouter_promiseStartScan, "f"),
1822
+ intermediateResultManager: __classPrivateFieldGet(this, _CaptureVisionRouter_intermediateResultManager, "f"),
1823
+ bufferdItemsManager: __classPrivateFieldGet(this, _CaptureVisionRouter_bufferdItemsManager, "f"),
1824
+ resultReceiverSet: __classPrivateFieldGet(this, _CaptureVisionRouter_resultReceiverSet, "f"),
1825
+ isaStateListenerSet: __classPrivateFieldGet(this, _CaptureVisionRouter_isaStateListenerSet, "f"),
1826
+ resultFilterSet: __classPrivateFieldGet(this, _CaptureVisionRouter_resultFilterSet, "f"),
1827
+ compressRate: __classPrivateFieldGet(this, _CaptureVisionRouter_compressRate, "f"),
1828
+ canvas: __classPrivateFieldGet(this, _CaptureVisionRouter_canvas, "f"),
1829
+ isScanner: __classPrivateFieldGet(this, _CaptureVisionRouter_isScanner, "f"),
1830
+ innerUseTag: __classPrivateFieldGet(this, _CaptureVisionRouter_innerUseTag, "f"),
1831
+ isDestroyed: __classPrivateFieldGet(this, _CaptureVisionRouter_isDestroyed, "f")
1832
+ };
1833
+ }
1834
+ async _getWasmFilterState() {
1835
+ return await new Promise((rs, rj) => {
1836
+ let taskID = getNextTaskID();
1837
+ mapTaskCallBack[taskID] = async (body) => {
1838
+ if (body.success) {
1839
+ const response = JSON.parse(body.response);
1840
+ return rs(response);
1841
+ }
1842
+ else {
1843
+ let ex = new Error(body.message);
1844
+ ex.stack = body.stack + '\n' + ex.stack;
1845
+ return rj(ex);
1846
+ }
1847
+ };
1848
+ worker.postMessage({
1849
+ type: "cvr_getWasmFilterState",
1850
+ id: taskID,
1851
+ instanceID: this._instanceID
1852
+ });
1853
+ });
1854
+ }
1855
+ }
1856
+ _CaptureVisionRouter_isa = new WeakMap(), _CaptureVisionRouter_canvas = new WeakMap(), _CaptureVisionRouter_promiseStartScan = new WeakMap(), _CaptureVisionRouter_intermediateResultManager = new WeakMap(), _CaptureVisionRouter_bufferdItemsManager = new WeakMap(), _CaptureVisionRouter_resultReceiverSet = new WeakMap(), _CaptureVisionRouter_isaStateListenerSet = new WeakMap(), _CaptureVisionRouter_resultFilterSet = new WeakMap(), _CaptureVisionRouter_compressRate = new WeakMap(), _CaptureVisionRouter_isScanner = new WeakMap(), _CaptureVisionRouter_innerUseTag = new WeakMap(), _CaptureVisionRouter_isDestroyed = new WeakMap();
1857
+ CaptureVisionRouter._defaultTemplate = "Default";
1858
+ async function _enableResultCrossVerification(cvr, verificationEnabled) {
1859
+ checkIsDisposed(cvr);
1860
+ return await new Promise((rs, rj) => {
1861
+ let taskID = getNextTaskID();
1862
+ mapTaskCallBack[taskID] = async (body) => {
1863
+ if (body.success) {
1864
+ return rs(body.result);
1865
+ }
1866
+ else {
1867
+ let ex = new Error(body.message);
1868
+ ex.stack = body.stack + '\n' + ex.stack;
1869
+ return rj(ex);
1870
+ }
1871
+ };
1872
+ worker.postMessage({
1873
+ type: "cvr_enableResultCrossVerification",
1874
+ id: taskID,
1875
+ instanceID: cvr._instanceID,
1876
+ body: {
1877
+ verificationEnabled
1878
+ }
1879
+ });
1880
+ });
1881
+ }
1882
+ async function _enableResultDeduplication(cvr, duplicateFilterEnabled) {
1883
+ checkIsDisposed(cvr);
1884
+ return await new Promise((rs, rj) => {
1885
+ let taskID = getNextTaskID();
1886
+ mapTaskCallBack[taskID] = async (body) => {
1887
+ if (body.success) {
1888
+ return rs(body.result);
1889
+ }
1890
+ else {
1891
+ let ex = new Error(body.message);
1892
+ ex.stack = body.stack + '\n' + ex.stack;
1893
+ return rj(ex);
1894
+ }
1895
+ };
1896
+ worker.postMessage({
1897
+ type: "cvr_enableResultDeduplication",
1898
+ id: taskID,
1899
+ instanceID: cvr._instanceID,
1900
+ body: {
1901
+ duplicateFilterEnabled
1902
+ }
1903
+ });
1904
+ });
1905
+ }
1906
+ async function _setDuplicateForgetTime(cvr, duplicateForgetTime) {
1907
+ checkIsDisposed(cvr);
1908
+ return await new Promise((rs, rj) => {
1909
+ let taskID = getNextTaskID();
1910
+ mapTaskCallBack[taskID] = async (body) => {
1911
+ if (body.success) {
1912
+ return rs(body.result);
1913
+ }
1914
+ else {
1915
+ let ex = new Error(body.message);
1916
+ ex.stack = body.stack + '\n' + ex.stack;
1917
+ return rj(ex);
1918
+ }
1919
+ };
1920
+ worker.postMessage({
1921
+ type: "cvr_setDuplicateForgetTime",
1922
+ id: taskID,
1923
+ instanceID: cvr._instanceID,
1924
+ body: {
1925
+ duplicateForgetTime
1926
+ }
1927
+ });
1928
+ });
1929
+ }
1930
+ async function _clearVerifyList(cvr) {
1931
+ let taskID = getNextTaskID();
1932
+ const p = new MutablePromise();
1933
+ mapTaskCallBack[taskID] = async (body) => {
1934
+ if (body.success) {
1935
+ return p.resolve();
1936
+ }
1937
+ else {
1938
+ let ex = new Error(body.message);
1939
+ ex.stack = body.stack + '\n' + ex.stack;
1940
+ return p.reject(ex);
1941
+ }
1942
+ };
1943
+ worker.postMessage({
1944
+ type: "cvr_clearVerifyList",
1945
+ id: taskID,
1946
+ instanceID: cvr._instanceID
1947
+ });
1948
+ return p;
1949
+ }
1950
+
1951
+ // TODO
1952
+ class CapturedResultReceiver {
1953
+ constructor() {
1954
+ /**
1955
+ * Event triggered when a generic captured result is available, occurring each time an image finishes its processing.
1956
+ * This event can be used for any result that does not fit into the specific categories of the other callback events.
1957
+ * @param result The captured result, an instance of `CapturedResult`.
1958
+ */
1959
+ this.onCapturedResultReceived = null;
1960
+ /**
1961
+ * Event triggered when the original image result is available.
1962
+ * This event is used to handle the original image captured by an image source such as Dynamsoft Camera Enhancer.
1963
+ * @param result The original image result, an instance of `OriginalImageResultItem`.
1964
+ */
1965
+ this.onOriginalImageResultReceived = null;
1966
+ }
1967
+ }
1968
+
1969
+ class IntermediateResultReceiver {
1970
+ constructor() {
1971
+ this._observedResultUnitTypes = EnumIntermediateResultUnitType.IRUT_ALL;
1972
+ this._observedTaskMap = new Map();
1973
+ this._parameters = {
1974
+ setObservedResultUnitTypes: (types) => {
1975
+ this._observedResultUnitTypes = types;
1976
+ },
1977
+ getObservedResultUnitTypes: () => {
1978
+ return this._observedResultUnitTypes;
1979
+ },
1980
+ isResultUnitTypeObserved: (type) => {
1981
+ return !!(type & this._observedResultUnitTypes);
1982
+ },
1983
+ addObservedTask: (taskName) => {
1984
+ this._observedTaskMap.set(taskName, true);
1985
+ },
1986
+ removeObservedTask: (taskName) => {
1987
+ this._observedTaskMap.set(taskName, false);
1988
+ },
1989
+ isTaskObserved: (taskName) => {
1990
+ if (this._observedTaskMap.size === 0)
1991
+ return true;
1992
+ return !!(this._observedTaskMap.get(taskName));
1993
+ }
1994
+ };
1995
+ this.onTaskResultsReceived = null;
1996
+ // section
1997
+ this.onPredetectedRegionsReceived = null;
1998
+ // The remaining callback definitions will be automatically injected when imported into other modules
1999
+ // stage
2000
+ this.onColourImageUnitReceived = null;
2001
+ this.onScaledDownColourImageUnitReceived = null;
2002
+ this.onGrayscaleImageUnitReceived = null;
2003
+ this.onTransformedGrayscaleImageUnitReceived = null;
2004
+ this.onEnhancedGrayscaleImageUnitReceived = null;
2005
+ this.onBinaryImageUnitReceived = null;
2006
+ this.onTextureDetectionResultUnitReceived = null;
2007
+ this.onTextureRemovedGrayscaleImageUnitReceived = null;
2008
+ this.onTextureRemovedBinaryImageUnitReceived = null;
2009
+ this.onContoursUnitReceived = null;
2010
+ this.onLineSegmentsUnitReceived = null;
2011
+ this.onTextZonesUnitReceived = null;
2012
+ this.onTextRemovedBinaryImageUnitReceived = null;
2013
+ this.onShortLinesUnitReceived = null;
2014
+ // The remaining callback definitions will be automatically injected when imported into other modules
2015
+ }
2016
+ /**
2017
+ * Gets the observed parameters of the intermediate result receiver. Allowing for configuration of intermediate result observation.
2018
+ * @return The observed parameters, of type ObservationParameters. The default parameters are to observe all intermediate result unit types and all tasks.
2019
+ */
2020
+ getObservationParameters() {
2021
+ return this._parameters;
2022
+ }
2023
+ }
2024
+
2025
+ var EnumPresetTemplate;
2026
+ (function (EnumPresetTemplate) {
2027
+ /**
2028
+ * @brief Versatile function for barcode reading, document detection, or text recognition.
2029
+ */
2030
+ EnumPresetTemplate["PT_DEFAULT"] = "Default";
2031
+ /**
2032
+ * @brief Scans a single barcode.
2033
+ */
2034
+ EnumPresetTemplate["PT_READ_BARCODES"] = "ReadBarcodes_Default";
2035
+ /**
2036
+ * @brief Identifies and reads any text present.
2037
+ */
2038
+ EnumPresetTemplate["PT_RECOGNIZE_TEXT_LINES"] = "RecognizeTextLines_Default";
2039
+ /**
2040
+ * @brief RIdentifies the edges of a document.
2041
+ */
2042
+ EnumPresetTemplate["PT_DETECT_DOCUMENT_BOUNDARIES"] = "DetectDocumentBoundaries_Default";
2043
+ /**
2044
+ * @brief Detects document edges and standardizes its format.
2045
+ */
2046
+ EnumPresetTemplate["PT_DETECT_AND_NORMALIZE_DOCUMENT"] = "DetectAndNormalizeDocument_Default";
2047
+ /**
2048
+ * @brief Adjusts a document to a standard format using detected borders.
2049
+ */
2050
+ EnumPresetTemplate["PT_NORMALIZE_DOCUMENT"] = "NormalizeDocument_Default";
2051
+ /**
2052
+ * @brief Represents a barcode reading mode where speed is prioritized.
2053
+ *
2054
+ * In this mode, the barcode reader will optimize for faster barcode detection
2055
+ * and decoding, sacrificing some level of accuracy and read rate. It is suitable
2056
+ * for situations where a quick response time is more important than perfect
2057
+ * barcode recognition.
2058
+ */
2059
+ EnumPresetTemplate["PT_READ_BARCODES_SPEED_FIRST"] = "ReadBarcodes_SpeedFirst";
2060
+ /**
2061
+ * @brief Represents a barcode reading mode where barcode read rate is prioritized.
2062
+ *
2063
+ * In this mode, the barcode reader will optimize for higher barcode read rates,
2064
+ * even if it may sometimes result in reduced accuracy and speed. It is suitable for
2065
+ * scenarios where maximizing the number of successfully read barcodes is critical.
2066
+ */
2067
+ EnumPresetTemplate["PT_READ_BARCODES_READ_RATE_FIRST"] = "ReadBarcodes_ReadRateFirst";
2068
+ /**
2069
+ * @brief Represents a balanced barcode reading mode.
2070
+ *
2071
+ * This mode aims for a reasonable balance between speed and read rate in barcode
2072
+ * recognition. It is suitable for most common use cases where a compromise between
2073
+ * speed and read rate is acceptable.
2074
+ */
2075
+ EnumPresetTemplate["PT_READ_BARCODES_BALANCE"] = "ReadBarcodes_Balance";
2076
+ /**
2077
+ * @brief Represents a barcode reading mode for single barcode code detection.
2078
+ *
2079
+ * In this mode, the barcode reader will focus on detecting and decoding a single
2080
+ * barcode code, ignoring any additional codes in the same image. It is efficient
2081
+ * when the target image has only one barcode.
2082
+ */
2083
+ EnumPresetTemplate["PT_READ_SINGLE_BARCODE"] = "ReadBarcodes_Balanced";
2084
+ /**
2085
+ * @brief Represents a barcode reading mode optimized for dense barcode codes.
2086
+ *
2087
+ * This mode is designed to handle dense or closely packed barcode codes where
2088
+ * accuracy is paramount. It may operate slower than other modes but is suitable
2089
+ * for challenging scenarios where code density is high.
2090
+ */
2091
+ EnumPresetTemplate["PT_READ_DENSE_BARCODES"] = "ReadDenseBarcodes";
2092
+ /**
2093
+ * @brief Represents a barcode reading mode optimized for distant barcode codes.
2094
+ *
2095
+ * This mode is designed to scanning a barcode that is placed far from the device.
2096
+ */
2097
+ EnumPresetTemplate["PT_READ_DISTANT_BARCODES"] = "ReadDistantBarcodes";
2098
+ /**
2099
+ * @brief Represents a text recognition mode focused on recognizing numbers.
2100
+ */
2101
+ EnumPresetTemplate["PT_RECOGNIZE_NUMBERS"] = "RecognizeNumbers";
2102
+ /**
2103
+ * @brief Represents a text recognition mode focused on recognizing alphabetic characters (letters).
2104
+ *
2105
+ */
2106
+ EnumPresetTemplate["PT_RECOGNIZE_LETTERS"] = "RecognizeLetters";
2107
+ /**
2108
+ * @brief Represents a text recognition mode that combines numbers and alphabetic characters (letters) recognition.
2109
+ */
2110
+ EnumPresetTemplate["PT_RECOGNIZE_NUMBERS_AND_LETTERS"] = "RecognizeNumbersAndLetters";
2111
+ /**
2112
+ * @brief Represents a text recognition mode that combines numbers and uppercase letters recognition.
2113
+ */
2114
+ EnumPresetTemplate["PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS"] = "RecognizeNumbersAndUppercaseLetters";
2115
+ /**
2116
+ * @brief Represents a text recognition mode focused on recognizing uppercase letters.
2117
+ */
2118
+ EnumPresetTemplate["PT_RECOGNIZE_UPPERCASE_LETTERS"] = "RecognizeUppercaseLetters";
2119
+ })(EnumPresetTemplate || (EnumPresetTemplate = {}));
2120
+
2121
+ export { CaptureVisionRouter, CaptureVisionRouterModule, CapturedResultReceiver, EnumImageSourceState, EnumPresetTemplate, IntermediateResultReceiver };