UNPKG

214 kBJavaScriptView Raw
1/*! ****************************************************************************
2Copyright (c) Microblink. All rights reserved.
3
4THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
5KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
6WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
7MERCHANTABLITY OR NON-INFRINGEMENT.
8***************************************************************************** */
9(function (global, factory) {
10typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
11typeof define === 'function' && define.amd ? define(['exports'], factory) :
12(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.BlinkIDSDK = {}));
13}(this, (function (exports) { 'use strict';
14
15/*! *****************************************************************************
16Copyright (c) Microsoft Corporation.
17
18Permission to use, copy, modify, and/or distribute this software for any
19purpose with or without fee is hereby granted.
20
21THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
22REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
23AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
24INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
25LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
26OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
27PERFORMANCE OF THIS SOFTWARE.
28***************************************************************************** */
29function __awaiter(thisArg, _arguments, P, generator) {
30 function adopt(value) {
31 return value instanceof P ? value : new P(function (resolve) {
32 resolve(value);
33 });
34 }
35
36 return new (P || (P = Promise))(function (resolve, reject) {
37 function fulfilled(value) {
38 try {
39 step(generator.next(value));
40 } catch (e) {
41 reject(e);
42 }
43 }
44
45 function rejected(value) {
46 try {
47 step(generator["throw"](value));
48 } catch (e) {
49 reject(e);
50 }
51 }
52
53 function step(result) {
54 result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
55 }
56
57 step((generator = generator.apply(thisArg, _arguments || [])).next());
58 });
59}
60
61/**
62 * Copyright (c) Microblink Ltd. All rights reserved.
63 */
64let nextMessageID = 0;
65function getNextMessageID() {
66 const msgId = nextMessageID;
67 nextMessageID = nextMessageID + 1;
68 return msgId;
69}
70class BaseRequestMessage {
71 constructor(action) {
72 this.action = action;
73 this.messageID = getNextMessageID();
74 }
75}
76class InitMessage extends BaseRequestMessage {
77 constructor(wasmLoadSettings, userId) {
78 super(InitMessage.action);
79 this.wasmModuleName = wasmLoadSettings.wasmModuleName;
80 this.licenseKey = wasmLoadSettings.licenseKey;
81 this.userId = userId;
82 this.registerLoadCallback = wasmLoadSettings.loadProgressCallback !== null;
83 this.allowHelloMessage = wasmLoadSettings.allowHelloMessage;
84 this.engineLocation = wasmLoadSettings.engineLocation;
85 this.wasmType = wasmLoadSettings.wasmType;
86 this.numberOfWorkers = wasmLoadSettings.numberOfWorkers;
87 }
88}
89InitMessage.action = "init";
90var ParameterType;
91(function (ParameterType) {
92 ParameterType[ParameterType["Any"] = 0] = "Any";
93 ParameterType[ParameterType["Recognizer"] = 1] = "Recognizer";
94 ParameterType[ParameterType["RecognizerSettings"] = 2] = "RecognizerSettings";
95 ParameterType[ParameterType["Callback"] = 3] = "Callback";
96})(ParameterType || (ParameterType = {}));
97class CreateNewRecognizer extends BaseRequestMessage {
98 constructor(className, params) {
99 super(CreateNewRecognizer.action);
100 this.className = className;
101 this.params = params;
102 }
103}
104CreateNewRecognizer.action = "createNewNativeObject";
105class CreateRecognizerRunner extends BaseRequestMessage {
106 constructor(recognizerHandles, allowMultipleResults, registeredMetadataCallbacks) {
107 super(CreateRecognizerRunner.action);
108 this.recognizerHandles = recognizerHandles;
109 this.allowMultipleResults = allowMultipleResults;
110 this.registeredMetadataCallbacks = registeredMetadataCallbacks;
111 }
112}
113CreateRecognizerRunner.action = "createRecognizerRunner";
114class ReconfigureRecognizerRunner extends BaseRequestMessage {
115 constructor(recognizerHandles, allowMultipleResults) {
116 super(ReconfigureRecognizerRunner.action);
117 this.recognizerHandles = recognizerHandles;
118 this.allowMultipleResults = allowMultipleResults;
119 }
120}
121ReconfigureRecognizerRunner.action = "reconfigureRecognizerRunner";
122class DeleteRecognizerRunner extends BaseRequestMessage {
123 constructor() {
124 super(DeleteRecognizerRunner.action);
125 }
126}
127DeleteRecognizerRunner.action = "deleteRecognizerRunner";
128class InvokeObjectMethod extends BaseRequestMessage {
129 constructor(objectHandle, methodName, params) {
130 super(InvokeObjectMethod.action);
131 this.objectHandle = objectHandle;
132 this.methodName = methodName;
133 this.params = params;
134 }
135}
136InvokeObjectMethod.action = "invokeObject";
137class ProcessImage extends BaseRequestMessage {
138 constructor(image) {
139 super(ProcessImage.action);
140 this.frame = image;
141 }
142 getTransferrables() {
143 return [this.frame.imageData.data.buffer];
144 }
145}
146ProcessImage.action = "processImage";
147class ResetRecognizers extends BaseRequestMessage {
148 constructor(hardReset) {
149 super(ResetRecognizers.action);
150 this.hardReset = hardReset;
151 }
152}
153ResetRecognizers.action = "resetRecognizers";
154class RegisteredMetadataCallbacks {
155 constructor() {
156 this.onDebugText = false;
157 this.onDetectionFailed = false;
158 this.onQuadDetection = false;
159 this.onPointsDetection = false;
160 this.onFirstSideResult = false;
161 this.onGlare = false;
162 }
163}
164class RegisterMetadataCallbacks extends BaseRequestMessage {
165 constructor(registeredMetadataCallbacks) {
166 super(RegisterMetadataCallbacks.action);
167 this.registeredMetadataCallbacks = registeredMetadataCallbacks;
168 }
169}
170RegisterMetadataCallbacks.action = "registerMetadataCallbacks";
171class SetDetectionOnly extends BaseRequestMessage {
172 constructor(detectionOnlyMode) {
173 super(SetDetectionOnly.action);
174 this.detectionOnlyMode = detectionOnlyMode;
175 }
176}
177SetDetectionOnly.action = "setDetectionOnly";
178class SetClearTimeoutCallback extends BaseRequestMessage {
179 constructor(callbackNonEmpty) {
180 super(SetClearTimeoutCallback.action);
181 this.callbackNonEmpty = callbackNonEmpty;
182 }
183}
184SetClearTimeoutCallback.action = "setClearTimeoutCallback";
185class SetCameraPreviewMirrored extends BaseRequestMessage {
186 constructor(cameraPreviewMirrored) {
187 super(SetCameraPreviewMirrored.action);
188 this.cameraPreviewMirrored = cameraPreviewMirrored;
189 }
190}
191SetCameraPreviewMirrored.action = "setCameraPreviewMirrored";
192class GetProductIntegrationInfo extends BaseRequestMessage {
193 constructor(userId) {
194 super(GetProductIntegrationInfo.action);
195 this.userId = userId;
196 }
197}
198GetProductIntegrationInfo.action = "getProductIntegrationInfo";
199// ===================================== /
200// Metadata callback messages
201// ===================================== /
202var MetadataCallback;
203(function (MetadataCallback) {
204 MetadataCallback[MetadataCallback["onDebugText"] = 0] = "onDebugText";
205 MetadataCallback[MetadataCallback["onDetectionFailed"] = 1] = "onDetectionFailed";
206 MetadataCallback[MetadataCallback["onQuadDetection"] = 2] = "onQuadDetection";
207 MetadataCallback[MetadataCallback["onPointsDetection"] = 3] = "onPointsDetection";
208 MetadataCallback[MetadataCallback["onFirstSideResult"] = 4] = "onFirstSideResult";
209 MetadataCallback[MetadataCallback["clearTimeoutCallback"] = 5] = "clearTimeoutCallback";
210 MetadataCallback[MetadataCallback["onGlare"] = 6] = "onGlare";
211 MetadataCallback[MetadataCallback["recognizerCallback"] = 7] = "recognizerCallback";
212})(MetadataCallback || (MetadataCallback = {}));
213/* eslint-enable @typescript-eslint/no-explicit-any */
214
215/**
216 * Copyright (c) Microblink Ltd. All rights reserved.
217 */
218(function (WasmType) {
219 /**
220 * The WASM that will be loaded will be most compatible with all browsers that
221 * support the WASM, but will lack features that could be used to improve performance.
222 */
223 WasmType["Basic"] = "BASIC";
224 /**
225 * The WASM that will be loaded will be built with advanced WASM features, such as
226 * bulk memory, SIMD, non-trapping floating point and sign extension. Such WASM can only
227 * be executed in browsers that support those features. Attempting to run this
228 * WASM in a non-compatible browser will crash your app.
229 */
230 WasmType["Advanced"] = "ADVANCED";
231 /**
232 * The WASM that will be loaded will be build with advanced WASM features, just
233 * like above. Additionally, it will be also built with support for multi-threaded
234 * processing. This feature requires a browser with support for both advanced WASM
235 * features and `SharedArrayBuffer`
236 */
237 WasmType["AdvancedWithThreads"] = "ADVANCED_WITH_THREADS";
238})(exports.WasmType || (exports.WasmType = {}));
239
240/**
241 * Copyright (c) Microblink Ltd. All rights reserved.
242 */
243const defaultWasmModuleName = "BlinkIDWasmSDK";
244
245/**
246 * Copyright (c) Microblink Ltd. All rights reserved.
247 */
248function defaultEventHandler(resolve, reject) {
249 return (msg) => {
250 const resultMsg = msg;
251 if (resultMsg.success) {
252 resolve();
253 }
254 else {
255 reject(resultMsg.error);
256 }
257 };
258}
259function defaultResultEventHandler(successResolver, reject) {
260 return (msg) => {
261 const resultMsg = msg;
262 if (resultMsg.success) {
263 successResolver(msg);
264 }
265 else {
266 reject(resultMsg.error);
267 }
268 };
269}
270/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment */
271function wrapParameters(params) {
272 // convert params
273 const wrappedPrameters = [];
274 for (let param of params) {
275 let paramType = ParameterType.Any;
276 if (param instanceof RemoteRecognizer) {
277 paramType = ParameterType.Recognizer;
278 param = param.getRemoteObjectHandle();
279 }
280 wrappedPrameters.push({
281 parameter: param,
282 type: paramType
283 });
284 }
285 return wrappedPrameters;
286}
287/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment */
288class RemoteRecognizer {
289 /* eslint-enable lines-between-class-members */
290 constructor(wasmWorker, recognizerName, remoteObjHandle) {
291 this.wasmSDKWorker = wasmWorker;
292 this.objectHandle = remoteObjHandle;
293 this.recognizerName = recognizerName;
294 this.callbacks = new Map();
295 }
296 /* eslint-enable @typescript-eslint/ban-types */
297 getRemoteObjectHandle() {
298 return this.objectHandle;
299 }
300 currentSettings() {
301 return new Promise((resolve, reject) => {
302 if (this.objectHandle < 0) {
303 reject("Invalid object handle: " + this.objectHandle.toString());
304 return;
305 }
306 const msg = new InvokeObjectMethod(this.objectHandle, "currentSettings", []);
307 const handler = defaultResultEventHandler((msg) => {
308 resolve(msg.result);
309 }, reject);
310 this.wasmSDKWorker.postMessage(msg, handler);
311 });
312 }
313 toSignedJSON() {
314 {
315 return new Promise((resolve, reject) => {
316 if (this.objectHandle < 0) {
317 reject("Invalid object handle: " + this.objectHandle.toString());
318 return;
319 }
320 const msg = new InvokeObjectMethod(this.objectHandle, "toSignedJSON", []);
321 const handler = defaultResultEventHandler((msg) => {
322 resolve(msg.result);
323 }, reject);
324 this.wasmSDKWorker.postMessage(msg, handler);
325 });
326 }
327 }
328 clearAllCallbacks() {
329 this.callbacks.clear();
330 this.wasmSDKWorker.unregisterRecognizerCallbacks(this.objectHandle);
331 }
332 /* eslint-disable @typescript-eslint/no-explicit-any,
333 @typescript-eslint/no-unsafe-assignment,
334 @typescript-eslint/no-unsafe-member-access,
335 @typescript-eslint/no-unsafe-return
336 */
337 // convert each function member into wrapped parameter, containing address where callback needs to be delivered
338 removeFunctions(settings) {
339 // clear any existing callbacks
340 this.clearAllCallbacks();
341 const keys = Object.keys(settings);
342 let needsRegistering = false;
343 for (const key of keys) {
344 const data = settings[key];
345 if (typeof data === "function") {
346 this.callbacks.set(key, data);
347 const wrappedFunction = {
348 parameter: {
349 recognizerHandle: this.objectHandle,
350 callbackName: key
351 },
352 type: ParameterType.Callback
353 };
354 settings[key] = wrappedFunction;
355 needsRegistering = true;
356 }
357 }
358 if (needsRegistering) {
359 this.wasmSDKWorker.registerRecognizerCallbacks(this.objectHandle, this);
360 }
361 return settings;
362 }
363 /* eslint-enable @typescript-eslint/no-explicit-any,
364 @typescript-eslint/no-unsafe-assignment,
365 @typescript-eslint/no-unsafe-member-access,
366 @typescript-eslint/no-unsafe-return
367 */
368 updateSettings(newSettings) {
369 return new Promise((resolve, reject) => {
370 if (this.objectHandle < 0) {
371 reject("Invalid object handle: " + this.objectHandle.toString());
372 return;
373 }
374 /* eslint-disable @typescript-eslint/no-unsafe-assignment */
375 const msg = new InvokeObjectMethod(this.objectHandle, "updateSettings", [
376 {
377 parameter: this.removeFunctions(newSettings),
378 type: ParameterType.RecognizerSettings
379 }
380 ]);
381 /* eslint-enable @typescript-eslint/no-unsafe-assignment */
382 const handler = defaultEventHandler(resolve, reject);
383 this.wasmSDKWorker.postMessage(msg, handler);
384 });
385 }
386 /* eslint-disable @typescript-eslint/no-explicit-any */
387 invokeCallback(callbackName, args) {
388 const callback = this.callbacks.get(callbackName);
389 if (callback !== undefined) {
390 callback(...args);
391 }
392 else {
393 console.warn("Cannot find callback", callbackName);
394 }
395 }
396 /* eslint-enable @typescript-eslint/no-explicit-any */
397 getResult() {
398 return new Promise((resolve, reject) => {
399 if (this.objectHandle < 0) {
400 reject("Invalid object handle: " + this.objectHandle.toString());
401 return;
402 }
403 const msg = new InvokeObjectMethod(this.objectHandle, "getResult", []);
404 const handler = defaultResultEventHandler((msg) => {
405 resolve(msg.result);
406 }, reject);
407 this.wasmSDKWorker.postMessage(msg, handler);
408 });
409 }
410 delete() {
411 return new Promise((resolve, reject) => {
412 if (this.objectHandle < 0) {
413 reject("Invalid object handle: " + this.objectHandle.toString());
414 return;
415 }
416 this.clearAllCallbacks();
417 const msg = new InvokeObjectMethod(this.objectHandle, "delete", []);
418 const handler = defaultEventHandler(() => {
419 this.objectHandle = -1;
420 resolve();
421 }, reject);
422 this.wasmSDKWorker.postMessage(msg, handler);
423 });
424 }
425}
426function createRegisteredCallbacks(metadataCallbacks) {
427 const msg = new RegisteredMetadataCallbacks();
428 // https://stackoverflow.com/a/20093686/213057
429 msg.onDebugText = !!metadataCallbacks.onDebugText;
430 msg.onDetectionFailed = !!metadataCallbacks.onDetectionFailed;
431 msg.onPointsDetection = !!metadataCallbacks.onPointsDetection;
432 msg.onQuadDetection = !!metadataCallbacks.onQuadDetection;
433 msg.onFirstSideResult = !!metadataCallbacks.onFirstSideResult;
434 msg.onGlare = !!metadataCallbacks.onGlare;
435 return msg;
436}
437class RemoteRecognizerRunner {
438 constructor(wasmWorker) {
439 this.deleted = false;
440 this.wasmSDKWorker = wasmWorker;
441 }
442 processImage(image) {
443 return new Promise((resolve, reject) => {
444 if (this.deleted) {
445 reject("Recognizer runner is deleted. It cannot be used anymore!");
446 return;
447 }
448 const msg = new ProcessImage(image);
449 const handler = defaultResultEventHandler((response) => {
450 const state = response.recognitionState;
451 resolve(state);
452 }, reject);
453 this.wasmSDKWorker.postTransferrableMessage(msg, handler);
454 });
455 }
456 reconfigureRecognizers(recognizers, allowMultipleResults) {
457 return new Promise((resolve, reject) => {
458 if (this.deleted) {
459 reject("Recognizer runner is deleted. It cannot be used anymore!");
460 return;
461 }
462 const recognizerHandles = getRecognizerHandles(recognizers);
463 const msg = new ReconfigureRecognizerRunner(recognizerHandles, allowMultipleResults);
464 const handler = defaultEventHandler(resolve, reject);
465 this.wasmSDKWorker.postMessage(msg, handler);
466 });
467 }
468 setMetadataCallbacks(metadataCallbacks) {
469 return new Promise((resolve, reject) => {
470 const msg = new RegisterMetadataCallbacks(createRegisteredCallbacks(metadataCallbacks));
471 const handler = defaultEventHandler(resolve, reject);
472 this.wasmSDKWorker.postMessageAndRegisterCallbacks(msg, metadataCallbacks, handler);
473 });
474 }
475 resetRecognizers(hardReset) {
476 return new Promise((resolve, reject) => {
477 const msg = new ResetRecognizers(hardReset);
478 const handler = defaultEventHandler(resolve, reject);
479 this.wasmSDKWorker.postMessage(msg, handler);
480 });
481 }
482 setDetectionOnlyMode(detectionOnly) {
483 return new Promise((resolve, reject) => {
484 const msg = new SetDetectionOnly(detectionOnly);
485 const handler = defaultEventHandler(resolve, reject);
486 this.wasmSDKWorker.postMessage(msg, handler);
487 });
488 }
489 setClearTimeoutCallback(clearTimeoutCallback) {
490 return new Promise((resolve, reject) => {
491 const msg = new SetClearTimeoutCallback(clearTimeoutCallback !== null);
492 const handler = defaultEventHandler(resolve, reject);
493 this.wasmSDKWorker.registerClearTimeoutCallback(clearTimeoutCallback);
494 this.wasmSDKWorker.postMessage(msg, handler);
495 });
496 }
497 setCameraPreviewMirrored(mirrored) {
498 return new Promise((resolve, reject) => {
499 const msg = new SetCameraPreviewMirrored(mirrored);
500 const handler = defaultEventHandler(resolve, reject);
501 this.wasmSDKWorker.postMessage(msg, handler);
502 });
503 }
504 delete() {
505 if (this.deleted) {
506 return Promise.reject("Recognizer runner is already deleted.");
507 }
508 return new Promise((resolve, reject) => {
509 const msg = new DeleteRecognizerRunner();
510 const handler = defaultEventHandler(() => {
511 this.deleted = true;
512 resolve();
513 }, reject);
514 this.wasmSDKWorker.postMessage(msg, handler);
515 });
516 }
517}
518function getRecognizerHandles(remoteRecognizers) {
519 const recognizerHandles = [];
520 for (const remoteRecognizer of remoteRecognizers) {
521 recognizerHandles.push(remoteRecognizer.getRemoteObjectHandle());
522 }
523 return recognizerHandles;
524}
525class WasmModuleWorkerProxy {
526 constructor(wasmSDKWorker) {
527 this.wasmSDKWorker = wasmSDKWorker;
528 }
529 createRecognizerRunner(recognizers, allowMultipleResults = false, metadataCallbacks = {}) {
530 return new Promise((resolve, reject) => {
531 const recognizerHandles = getRecognizerHandles(recognizers);
532 const msg = new CreateRecognizerRunner(recognizerHandles, allowMultipleResults, createRegisteredCallbacks(metadataCallbacks));
533 const handler = defaultEventHandler(() => {
534 resolve(new RemoteRecognizerRunner(this.wasmSDKWorker));
535 }, reject);
536 this.wasmSDKWorker.postMessageAndRegisterCallbacks(msg, metadataCallbacks, handler);
537 });
538 }
539 /* eslint-disable @typescript-eslint/no-explicit-any */
540 newRecognizer(className, ...constructorArgs) {
541 return new Promise((resolve, reject) => {
542 const msg = new CreateNewRecognizer(className, wrapParameters(constructorArgs));
543 const handler = defaultResultEventHandler((msg) => {
544 const remoteRecognizer = new RemoteRecognizer(this.wasmSDKWorker, className, msg.objectHandle);
545 resolve(remoteRecognizer);
546 }, reject);
547 this.wasmSDKWorker.postMessage(msg, handler);
548 });
549 }
550}
551class WasmSDKWorker {
552 /* eslint-enable lines-between-class-members */
553 constructor(worker, loadProgressCallback, userId, rejectHandler) {
554 this.eventHandlers = {};
555 this.metadataCallbacks = {};
556 this.clearTimeoutCallback = null;
557 this.loadedWasmType = exports.WasmType.Basic; // will be updated after WASM gets loaded
558 this.mbWasmWorker = worker;
559 this.mbWasmWorker.onmessage = (event) => { this.handleWorkerEvent(event); };
560 this.mbWasmWorker.onerror = () => {
561 rejectHandler("Problem during initialization of worker file!");
562 return;
563 };
564 this.mbWasmModule = new WasmModuleWorkerProxy(this);
565 this.loadCallback = loadProgressCallback;
566 this.recognizersWithCallbacks = new Map();
567 this.userId = userId;
568 this.showOverlay = false;
569 }
570 postMessage(message, eventHandler) {
571 this.eventHandlers[message.messageID] = eventHandler;
572 this.mbWasmWorker.postMessage(message);
573 }
574 postTransferrableMessage(message, eventHandler) {
575 this.eventHandlers[message.messageID] = eventHandler;
576 this.mbWasmWorker.postMessage(message, message.getTransferrables());
577 }
578 postMessageAndRegisterCallbacks(message, metadataCallbacks, eventHandler) {
579 this.eventHandlers[message.messageID] = eventHandler;
580 this.metadataCallbacks = metadataCallbacks;
581 this.mbWasmWorker.postMessage(message);
582 }
583 registerClearTimeoutCallback(callback) {
584 this.clearTimeoutCallback = callback;
585 }
586 registerRecognizerCallbacks(remoteRecognizerHandle, recognizer) {
587 this.recognizersWithCallbacks.set(remoteRecognizerHandle, recognizer);
588 }
589 unregisterRecognizerCallbacks(remoteRecognizerHandle) {
590 this.recognizersWithCallbacks.delete(remoteRecognizerHandle);
591 }
592 /**
593 * Clean up the active instance of the SDK.
594 *
595 * It's not possible to use the SDK after this method is called.
596 */
597 delete() {
598 this.mbWasmWorker.terminate();
599 }
600 getProductIntegrationInfo() {
601 return new Promise((resolve, reject) => {
602 const msg = new GetProductIntegrationInfo(this.userId);
603 const handler = defaultResultEventHandler((msg) => {
604 resolve(msg.result);
605 }, reject);
606 this.postMessage(msg, handler);
607 });
608 }
609 handleWorkerEvent(event) {
610 if ("isCallbackMessage" in event.data) {
611 const msg = event.data;
612 switch (msg.callbackType) {
613 case MetadataCallback.onDebugText:
614 if (typeof this.metadataCallbacks.onDebugText === "function") {
615 this.metadataCallbacks.onDebugText(msg.callbackParameters[0]);
616 }
617 break;
618 case MetadataCallback.onDetectionFailed:
619 if (typeof this.metadataCallbacks.onDetectionFailed === "function") {
620 this.metadataCallbacks.onDetectionFailed();
621 }
622 break;
623 case MetadataCallback.onPointsDetection:
624 if (typeof this.metadataCallbacks.onPointsDetection === "function") {
625 this.metadataCallbacks.onPointsDetection(msg.callbackParameters[0]);
626 }
627 break;
628 case MetadataCallback.onQuadDetection:
629 if (typeof this.metadataCallbacks.onQuadDetection === "function") {
630 this.metadataCallbacks.onQuadDetection(msg.callbackParameters[0]);
631 }
632 break;
633 case MetadataCallback.onFirstSideResult:
634 if (typeof this.metadataCallbacks.onFirstSideResult === "function") {
635 this.metadataCallbacks.onFirstSideResult();
636 }
637 break;
638 case MetadataCallback.clearTimeoutCallback:
639 if (this.clearTimeoutCallback && typeof this.clearTimeoutCallback.onClearTimeout === "function") {
640 this.clearTimeoutCallback.onClearTimeout();
641 }
642 break;
643 case MetadataCallback.onGlare:
644 if (typeof this.metadataCallbacks.onGlare === "function") {
645 this.metadataCallbacks.onGlare(msg.callbackParameters[0]);
646 }
647 break;
648 case MetadataCallback.recognizerCallback:
649 {
650 // first parameter is address, other parameters are callback parameters
651 const address = msg.callbackParameters.shift();
652 const recognizer = this.recognizersWithCallbacks.get(address.recognizerHandle);
653 if (recognizer !== undefined) {
654 recognizer.invokeCallback(address.callbackName, msg.callbackParameters);
655 }
656 else {
657 console.warn("Cannot find recognizer to deliver callback message. Maybe it's destroyed?", address);
658 }
659 break;
660 }
661 default:
662 throw new Error(`Unknown callback type: ${MetadataCallback[msg.callbackType]}`);
663 }
664 }
665 else if ("isLoadProgressMessage" in event.data) {
666 const msg = event.data;
667 if (typeof this.loadCallback === "function") {
668 this.loadCallback(msg.progress);
669 }
670 }
671 else {
672 const msg = event.data;
673 const eventHandler = this.eventHandlers[msg.messageID];
674 delete this.eventHandlers[msg.messageID];
675 eventHandler(msg);
676 }
677 }
678 static createWasmWorker(worker, wasmLoadSettings, userId) {
679 return __awaiter(this, void 0, void 0, function* () {
680 return new Promise((resolve, reject) => {
681 const wasmWorker = new WasmSDKWorker(worker, wasmLoadSettings.loadProgressCallback, userId, reject);
682 const initMessage = new InitMessage(wasmLoadSettings, userId);
683 const initEventHandler = defaultResultEventHandler((msg) => {
684 const successMsg = msg;
685 wasmWorker.showOverlay = successMsg.showOverlay;
686 wasmWorker.loadedWasmType = successMsg.wasmType;
687 resolve(wasmWorker);
688 },
689 /* eslint-disable @typescript-eslint/no-explicit-any */
690 (error) => {
691 if (wasmWorker && typeof wasmWorker.delete === "function") {
692 wasmWorker.delete();
693 }
694 reject(error);
695 }
696 /* eslint-enable @typescript-eslint/no-explicit-any */
697 );
698 wasmWorker.postMessage(initMessage, initEventHandler);
699 });
700 });
701 }
702}
703
704/**
705 * Copyright (c) Microblink Ltd. All rights reserved.
706 */
707/* eslint-disable @typescript-eslint/no-explicit-any,
708 @typescript-eslint/no-unsafe-assignment,
709 @typescript-eslint/explicit-module-boundary-types */
710class SDKError {
711 constructor(error, details) {
712 if (!error.code || !error.message) {
713 throw new Error("Instance of SDKError is required to have code and message.");
714 }
715 this.message = error.message;
716 this.code = error.code;
717 this.details = details;
718 }
719}
720
721/**
722 * Copyright (c) Microblink Ltd. All rights reserved.
723 */
724(function (ErrorCodes) {
725 ErrorCodes["WORKER_WASM_LOAD_FAILURE"] = "WORKER_WASM_LOAD_FAILURE";
726 ErrorCodes["WORKER_WASM_INIT_MISSING"] = "WORKER_WASM_INIT_MISSING";
727 ErrorCodes["WORKER_FUNCTION_INVOKE_FAILURE"] = "WORKER_FUNCTION_INVOKE_FAILURE";
728 ErrorCodes["WORKER_RECOGNIZER_CREATION_FAILURE"] = "WORKER_RECOGNIZER_CREATION_FAILURE";
729 ErrorCodes["WORKER_RUNNER_EXISTS"] = "WORKER_RUNNER_EXISTS";
730 ErrorCodes["WORKER_RUNNER_CREATION_FAILURE"] = "WORKER_RUNNER_CREATION_FAILURE";
731 ErrorCodes["WORKER_RUNNER_MISSING"] = "WORKER_RUNNER_MISSING";
732 ErrorCodes["WORKER_RUNNER_RECONFIGURE_FAILURE"] = "WORKER_RUNNER_RECONFIGURE_FAILURE";
733 ErrorCodes["WORKER_RUNNER_DELETED"] = "WORKER_RUNNER_DELETED";
734 ErrorCodes["WORKER_RUNNER_DELETE_FAILURE"] = "WORKER_RUNNER_DELETE_FAILURE";
735 ErrorCodes["WORKER_OBJECT_INVOKE_FAILURE"] = "WORKER_OBJECT_INVOKE_FAILURE";
736 ErrorCodes["WORKER_IMAGE_PROCESS_FAILURE"] = "WORKER_IMAGE_PROCESS_FAILURE";
737 ErrorCodes["WORKER_HANDLE_UNDEFINED"] = "WORKER_HANDLE_UNDEFINED";
738 ErrorCodes["WORKER_MESSAGE_ACTION_UNKNOWN"] = "WORKER_MESSAGE_ACTION_UNKNOWN";
739 ErrorCodes["WORKER_LICENSE_UNLOCK_ERROR"] = "WORKER_LICENSE_UNLOCK_ERROR";
740 ErrorCodes["WORKER_INTEGRATION_INFO_FAILURE"] = "WORKER_INTEGRATION_INFO_FAILURE";
741 ErrorCodes["LOCAL_SDK_RUNNER_MISSING"] = "LOCAL_SDK_RUNNER_MISSING";
742 ErrorCodes["LOCAL_SDK_RUNNER_EMPTY"] = "LOCAL_SDK_RUNNER_EMPTY";
743 ErrorCodes["LICENSE_UNLOCK_ERROR"] = "LICENSE_UNLOCK_ERROR";
744 ErrorCodes["FRAME_CAPTURE_SVG_UNSUPPORTED"] = "FRAME_CAPTURE_SVG_UNSUPPORTED";
745 ErrorCodes["FRAME_CAPTURE_CANVAS_MISSING"] = "FRAME_CAPTURE_CANVAS_MISSING";
746 ErrorCodes["SDK_WASM_SETTINGS_MISSING"] = "SDK_WASM_SETTINGS_MISSING";
747 ErrorCodes["SDK_LICENSE_KEY_MISSING"] = "SDK_LICENSE_KEY_MISSING";
748 ErrorCodes["SDK_WASM_MODULE_NAME_MISSING"] = "SDK_WASM_MODULE_NAME_MISSING";
749 ErrorCodes["SDK_ENGINE_LOCATION_INVALID"] = "SDK_ENGINE_LOCATION_INVALID";
750 ErrorCodes["SDK_MISSING"] = "SDK_MISSING";
751 ErrorCodes["SDK_RECOGNIZERS_MISSING"] = "SDK_RECOGNIZERS_MISSING";
752 ErrorCodes["VIDEO_RECOGNIZER_ELEMENT_MISSING"] = "VIDEO_RECOGNIZER_ELEMENT_MISSING";
753 ErrorCodes["VIDEO_RECOGNIZER_CAMERA_MISSING"] = "VIDEO_RECOGNIZER_CAMERA_MISSING";
754 ErrorCodes["VIDEO_RECOGNIZER_CAMERA_NOT_ALLOWED"] = "VIDEO_RECOGNIZER_CAMERA_NOT_ALLOWED";
755 ErrorCodes["VIDEO_RECOGNIZER_CAMERA_UNAVAILABLE"] = "VIDEO_RECOGNIZER_CAMERA_UNAVAILABLE";
756 ErrorCodes["VIDEO_RECOGNIZER_CAMERA_IN_USE"] = "VIDEO_RECOGNIZER_CAMERA_IN_USE";
757 ErrorCodes["VIDEO_RECOGNIZER_MEDIA_DEVICES_UNSUPPORTED"] = "VIDEO_RECOGNIZER_MEDIA_DEVICES_UNSUPPORTED";
758 ErrorCodes["VIDEO_RECOGNIZER_FEED_RELEASED"] = "VIDEO_RECOGNIZER_FEED_RELEASED";
759 ErrorCodes["VIDEO_RECOGNIZER_FEED_NOT_PAUSED"] = "VIDEO_RECOGNIZER_FEED_NOT_PAUSED";
760 ErrorCodes["VIDEO_RECOGNIZER_PLAY_REQUEST_INTERRUPTED"] = "VIDEO_RECOGNIZER_PLAY_REQUEST_INTERRUPTED";
761 ErrorCodes["VIDEO_RECOGNIZER_FEED_PAUSED"] = "VIDEO_RECOGNIZER_FEED_PAUSED";
762 ErrorCodes["VIDEO_RECOGNIZER_RECOGNIZERS_RESET_FAILURE"] = "VIDEO_RECOGNIZER_RECOGNIZERS_RESET_FAILURE";
763 ErrorCodes["VIDEO_RECOGNIZER_FEED_MISSING"] = "VIDEO_RECOGNIZER_FEED_MISSING";
764})(exports.ErrorCodes || (exports.ErrorCodes = {}));
765(function (ErrorMessages) {
766 ErrorMessages["WORKER_HANDLE_UNDEFINED"] = "Cannot find object with handle: undefined";
767 ErrorMessages["WORKER_WASM_LOAD_FAILURE"] = "Failed to load WASM in web worker!";
768 ErrorMessages["WORKER_WASM_INIT_MISSING"] = "WASM module is not initialized!";
769 ErrorMessages["WORKER_FUNCTION_INVOKE_FAILURE"] = "Failed to invoke function!";
770 ErrorMessages["WORKER_RECOGNIZER_CREATION_FAILURE"] = "Failed to create new recognizer!";
771 ErrorMessages["WORKER_RUNNER_EXISTS"] = "Recognizer runner is already created! Multiple instances are not allowed!";
772 ErrorMessages["WORKER_RUNNER_CREATION_FAILURE"] = "Failed to create new recognizer runner!";
773 ErrorMessages["WORKER_RUNNER_MISSING"] = "Recognizer runner is not created! There is nothing to reconfigure!";
774 ErrorMessages["WORKER_RUNNER_RECONFIGURE_FAILURE"] = "Failed to reconfigure recognizer runner!";
775 ErrorMessages["WORKER_RUNNER_DELETED"] = "Recognizer runner is already deleted!";
776 ErrorMessages["WORKER_RUNNER_DELETE_FAILURE"] = "Failed to delete recognizer runner!";
777 ErrorMessages["WORKER_OBJECT_INVOKE_FAILURE"] = "Failed to invoke object!";
778 ErrorMessages["WORKER_IMAGE_PROCESS_FAILURE"] = "Recognizer runner is not initialized! Cannot process image!";
779 ErrorMessages["WORKER_INTEGRATION_INFO_FAILURE"] = "Failed to get product integration info!";
780 ErrorMessages["LOCAL_SDK_RUNNER_MISSING"] = "Property nativeRecognizerRunner is not available!";
781 ErrorMessages["LOCAL_SDK_RUNNER_EMPTY"] = "Native RecognizerRunner cannot be empty!";
782 ErrorMessages["LICENSE_TOKEN_STATE_INCORRECT"] = "Internal error (Incorrect token state)";
783 ErrorMessages["LICENSE_PAYLOAD_VERIFICATION_FAILED"] = "Failed to verify server permission's digital signature!";
784 ErrorMessages["LICENSE_PAYLOAD_CORRUPTED"] = "Server permission payload is corrupted!";
785 ErrorMessages["LICENSE_PERMISSION_EXPIRED"] = "Internal error (server permission expired)";
786 ErrorMessages["LICENSE_REMOTE_LOCKED"] = "Provided license key has been remotely locked. Please contact support for more information!";
787 ErrorMessages["FRAME_CAPTURE_SVG_UNSUPPORTED"] = "Recognition of SVG elements not supported!";
788 ErrorMessages["FRAME_CAPTURE_CANVAS_MISSING"] = "Could not get canvas 2d context!";
789 ErrorMessages["SDK_WASM_SETTINGS_MISSING"] = "Missing WASM load settings!";
790 ErrorMessages["SDK_LICENSE_KEY_MISSING"] = "Missing license key!";
791 ErrorMessages["SDK_WASM_MODULE_NAME_MISSING"] = "Missing WASM module name!";
792 ErrorMessages["SDK_ENGINE_LOCATION_INVALID"] = "Setting property 'engineLocation' must be a string!";
793 ErrorMessages["SDK_MISSING"] = "SDK is not provided!";
794 ErrorMessages["SDK_RECOGNIZERS_MISSING"] = "To create RecognizerRunner at least 1 recognizer is required.";
795 ErrorMessages["VIDEO_RECOGNIZER_ELEMENT_MISSING"] = "Video element, i.e. camera feed is not provided!";
796 ErrorMessages["VIDEO_RECOGNIZER_CAMERA_MISSING"] = "Camera not found!";
797 ErrorMessages["VIDEO_RECOGNIZER_CAMERA_NOT_ALLOWED"] = "Camera not allowed!";
798 ErrorMessages["VIDEO_RECOGNIZER_CAMERA_UNAVAILABLE"] = "Camera not available!";
799 ErrorMessages["VIDEO_RECOGNIZER_CAMERA_IN_USE"] = "Camera in use!";
800 ErrorMessages["VIDEO_RECOGNIZER_MEDIA_DEVICES_UNSUPPORTED"] = "Media devices not supported by browser.";
801 ErrorMessages["VIDEO_RECOGNIZER_FEED_RELEASED"] = "The associated video feed has been released!";
802 ErrorMessages["VIDEO_RECOGNIZER_FEED_NOT_PAUSED"] = "The associated video feed is not paused. Use resumeRecognition instead!";
803 ErrorMessages["VIDEO_RECOGNIZER_PLAY_REQUEST_INTERRUPTED"] = "The play() request was interrupted or prevented by browser security rules!";
804 ErrorMessages["VIDEO_RECOGNIZER_FEED_PAUSED"] = "Cannot resume recognition while video feed is paused! Use recognize or startRecognition";
805 ErrorMessages["VIDEO_RECOGNIZER_RECOGNIZERS_RESET_FAILURE"] = "Could not reset recognizers!";
806 ErrorMessages["VIDEO_RECOGNIZER_FEED_MISSING"] = "Missing video feed!";
807})(exports.ErrorMessages || (exports.ErrorMessages = {}));
808const videoRecognizerErrors = {
809 feedMissing: {
810 message: exports.ErrorMessages.VIDEO_RECOGNIZER_FEED_MISSING,
811 code: exports.ErrorCodes.VIDEO_RECOGNIZER_FEED_MISSING,
812 },
813 recognizersResetFailure: {
814 message: exports.ErrorMessages.VIDEO_RECOGNIZER_RECOGNIZERS_RESET_FAILURE,
815 code: exports.ErrorCodes.VIDEO_RECOGNIZER_RECOGNIZERS_RESET_FAILURE,
816 },
817 feedPaused: {
818 message: exports.ErrorMessages.VIDEO_RECOGNIZER_FEED_PAUSED,
819 code: exports.ErrorCodes.VIDEO_RECOGNIZER_FEED_PAUSED,
820 },
821 playRequestInterrupted: {
822 message: exports.ErrorMessages.VIDEO_RECOGNIZER_PLAY_REQUEST_INTERRUPTED,
823 code: exports.ErrorCodes.VIDEO_RECOGNIZER_PLAY_REQUEST_INTERRUPTED,
824 },
825 videoFeedNotPaused: {
826 message: exports.ErrorMessages.VIDEO_RECOGNIZER_FEED_NOT_PAUSED,
827 code: exports.ErrorCodes.VIDEO_RECOGNIZER_FEED_NOT_PAUSED,
828 },
829 videoFeedReleased: {
830 message: exports.ErrorMessages.VIDEO_RECOGNIZER_FEED_RELEASED,
831 code: exports.ErrorCodes.VIDEO_RECOGNIZER_FEED_RELEASED,
832 },
833 mediaDevicesUnsupported: {
834 code: exports.ErrorCodes.VIDEO_RECOGNIZER_MEDIA_DEVICES_UNSUPPORTED,
835 message: exports.ErrorMessages.VIDEO_RECOGNIZER_MEDIA_DEVICES_UNSUPPORTED,
836 },
837 cameraMissing: {
838 code: exports.ErrorCodes.VIDEO_RECOGNIZER_CAMERA_MISSING,
839 message: exports.ErrorMessages.VIDEO_RECOGNIZER_CAMERA_MISSING,
840 },
841 elementMissing: {
842 message: exports.ErrorMessages.VIDEO_RECOGNIZER_ELEMENT_MISSING,
843 code: exports.ErrorCodes.VIDEO_RECOGNIZER_ELEMENT_MISSING,
844 },
845};
846const sdkErrors = {
847 wasmSettingsMissing: {
848 message: exports.ErrorMessages.SDK_WASM_SETTINGS_MISSING,
849 code: exports.ErrorCodes.SDK_WASM_SETTINGS_MISSING,
850 },
851 licenseKeyMissing: {
852 message: exports.ErrorMessages.SDK_LICENSE_KEY_MISSING,
853 code: exports.ErrorCodes.SDK_LICENSE_KEY_MISSING,
854 },
855 wasmModuleNameMissing: {
856 message: exports.ErrorMessages.SDK_WASM_MODULE_NAME_MISSING,
857 code: exports.ErrorCodes.SDK_WASM_MODULE_NAME_MISSING,
858 },
859 engineLocationInvalid: {
860 message: exports.ErrorMessages.SDK_ENGINE_LOCATION_INVALID,
861 code: exports.ErrorCodes.SDK_ENGINE_LOCATION_INVALID,
862 },
863 missing: {
864 message: exports.ErrorMessages.SDK_MISSING,
865 code: exports.ErrorCodes.SDK_MISSING,
866 },
867 recognizersMissing: {
868 message: exports.ErrorMessages.SDK_RECOGNIZERS_MISSING,
869 code: exports.ErrorCodes.SDK_RECOGNIZERS_MISSING,
870 },
871};
872const frameCaptureErrors = {
873 svgUnsupported: {
874 message: exports.ErrorMessages.FRAME_CAPTURE_SVG_UNSUPPORTED,
875 code: exports.ErrorCodes.FRAME_CAPTURE_SVG_UNSUPPORTED,
876 },
877 canvasMissing: {
878 message: exports.ErrorMessages.FRAME_CAPTURE_CANVAS_MISSING,
879 code: exports.ErrorCodes.FRAME_CAPTURE_CANVAS_MISSING,
880 },
881};
882const licenseErrors = {
883 licenseTokenStateIncorrect: {
884 code: exports.ErrorCodes.LICENSE_UNLOCK_ERROR,
885 message: exports.ErrorMessages.LICENSE_TOKEN_STATE_INCORRECT,
886 },
887 licensePayloadVerificationFailed: {
888 code: exports.ErrorCodes.LICENSE_UNLOCK_ERROR,
889 message: exports.ErrorMessages.LICENSE_PAYLOAD_VERIFICATION_FAILED,
890 },
891 licensePayloadCorrupted: {
892 code: exports.ErrorCodes.LICENSE_UNLOCK_ERROR,
893 message: exports.ErrorMessages.LICENSE_PAYLOAD_CORRUPTED,
894 },
895 licensePermissionExpired: {
896 code: exports.ErrorCodes.LICENSE_UNLOCK_ERROR,
897 message: exports.ErrorMessages.LICENSE_PERMISSION_EXPIRED,
898 },
899 licenseRemoteLocked: {
900 code: exports.ErrorCodes.LICENSE_UNLOCK_ERROR,
901 message: exports.ErrorMessages.LICENSE_REMOTE_LOCKED,
902 },
903 licenseNetworkError: {
904 code: exports.ErrorCodes.LICENSE_UNLOCK_ERROR,
905 },
906 licenseInvalid: {
907 code: exports.ErrorCodes.LICENSE_UNLOCK_ERROR,
908 },
909};
910const localSdkErrors = {
911 runnerMissing: {
912 message: exports.ErrorMessages.LOCAL_SDK_RUNNER_MISSING,
913 code: exports.ErrorCodes.LOCAL_SDK_RUNNER_MISSING,
914 },
915 runnerEmpty: {
916 message: exports.ErrorMessages.LOCAL_SDK_RUNNER_EMPTY,
917 code: exports.ErrorCodes.LOCAL_SDK_RUNNER_EMPTY,
918 },
919};
920const workerErrors = {
921 imageProcessFailure: {
922 message: exports.ErrorMessages.WORKER_IMAGE_PROCESS_FAILURE,
923 code: exports.ErrorCodes.WORKER_IMAGE_PROCESS_FAILURE,
924 },
925 objectInvokeFailure: {
926 message: exports.ErrorMessages.WORKER_OBJECT_INVOKE_FAILURE,
927 code: exports.ErrorCodes.WORKER_OBJECT_INVOKE_FAILURE,
928 },
929 runnerDeleteFailure: {
930 message: exports.ErrorMessages.WORKER_RUNNER_DELETE_FAILURE,
931 code: exports.ErrorCodes.WORKER_RUNNER_DELETE_FAILURE,
932 },
933 runnerDeleted: {
934 message: exports.ErrorMessages.WORKER_RUNNER_DELETED,
935 code: exports.ErrorCodes.WORKER_RUNNER_DELETED,
936 },
937 runnerReconfigureFailure: {
938 message: exports.ErrorMessages.WORKER_RUNNER_RECONFIGURE_FAILURE,
939 code: exports.ErrorCodes.WORKER_RUNNER_RECONFIGURE_FAILURE,
940 },
941 runnerMissing: {
942 message: exports.ErrorMessages.WORKER_RUNNER_MISSING,
943 code: exports.ErrorCodes.WORKER_RUNNER_MISSING,
944 },
945 runnerCreationFailure: {
946 message: exports.ErrorMessages.WORKER_RUNNER_CREATION_FAILURE,
947 code: exports.ErrorCodes.WORKER_RUNNER_CREATION_FAILURE,
948 },
949 runnerExists: {
950 message: exports.ErrorMessages.WORKER_RUNNER_EXISTS,
951 code: exports.ErrorCodes.WORKER_RUNNER_EXISTS,
952 },
953 recognizerCreationFailure: {
954 message: exports.ErrorMessages.WORKER_RECOGNIZER_CREATION_FAILURE,
955 code: exports.ErrorCodes.WORKER_RECOGNIZER_CREATION_FAILURE,
956 },
957 functionInvokeFailure: {
958 message: exports.ErrorMessages.WORKER_FUNCTION_INVOKE_FAILURE,
959 code: exports.ErrorCodes.WORKER_FUNCTION_INVOKE_FAILURE,
960 },
961 wasmInitMissing: {
962 message: exports.ErrorMessages.WORKER_WASM_INIT_MISSING,
963 code: exports.ErrorCodes.WORKER_WASM_INIT_MISSING,
964 },
965 wasmLoadFailure: {
966 message: exports.ErrorMessages.WORKER_WASM_LOAD_FAILURE,
967 code: exports.ErrorCodes.WORKER_WASM_LOAD_FAILURE,
968 },
969 handleUndefined: {
970 message: exports.ErrorMessages.WORKER_HANDLE_UNDEFINED,
971 code: exports.ErrorCodes.WORKER_HANDLE_UNDEFINED,
972 },
973 integrationInfoFailure: {
974 message: exports.ErrorMessages.WORKER_INTEGRATION_INFO_FAILURE,
975 code: exports.ErrorCodes.WORKER_INTEGRATION_INFO_FAILURE
976 }
977};
978
979/**
980 * Copyright (c) Microblink Ltd. All rights reserved.
981 */
982(function (PreferredCameraType) {
983 /** Prefer back facing camera */
984 PreferredCameraType[PreferredCameraType["BackFacingCamera"] = 0] = "BackFacingCamera";
985 /** Prefer front facing camera */
986 PreferredCameraType[PreferredCameraType["FrontFacingCamera"] = 1] = "FrontFacingCamera";
987})(exports.PreferredCameraType || (exports.PreferredCameraType = {}));
988// inspired by https://unpkg.com/browse/scandit-sdk@4.6.1/src/lib/cameraAccess.ts
989const backCameraKeywords = [
990 "rear",
991 "back",
992 "rück",
993 "arrière",
994 "trasera",
995 "trás",
996 "traseira",
997 "posteriore",
998 "后面",
999 "後面",
1000 "背面",
1001 "后置",
1002 "後置",
1003 "背置",
1004 "задней",
1005 "الخلفية",
1006 "후",
1007 "arka",
1008 "achterzijde",
1009 "หลัง",
1010 "baksidan",
1011 "bagside",
1012 "sau",
1013 "bak",
1014 "tylny",
1015 "takakamera",
1016 "belakang",
1017 "אחורית",
1018 "πίσω",
1019 "spate",
1020 "hátsó",
1021 "zadní",
1022 "darrere",
1023 "zadná",
1024 "задня",
1025 "stražnja",
1026 "belakang",
1027 "बैक"
1028];
1029function isBackCameraLabel(label) {
1030 const lowercaseLabel = label.toLowerCase();
1031 return backCameraKeywords.some(keyword => lowercaseLabel.includes(keyword));
1032}
1033class SelectedCamera {
1034 constructor(mdi, facing) {
1035 this.deviceId = mdi.deviceId;
1036 this.facing = facing;
1037 this.groupId = mdi.groupId;
1038 this.label = mdi.label;
1039 }
1040}
1041function getCameraDevices() {
1042 return __awaiter(this, void 0, void 0, function* () {
1043 const frontCameras = [];
1044 const backCameras = [];
1045 {
1046 let devices = yield navigator.mediaDevices.enumerateDevices();
1047 // if permission is not given, label of video devices will be empty string
1048 if (devices.filter(device => device.kind === "videoinput").every(device => device.label === "")) {
1049 const stream = yield navigator.mediaDevices.getUserMedia({
1050 video: {
1051 facingMode: { ideal: "environment" }
1052 },
1053 audio: false
1054 });
1055 // enumerate devices again - now the label field should be non-empty, as we have a stream active
1056 // (even if we didn't get persistent permission for camera)
1057 devices = yield navigator.mediaDevices.enumerateDevices();
1058 // close the stream, as we don't need it anymore
1059 stream.getTracks().forEach(track => track.stop());
1060 }
1061 const cameras = devices.filter(device => device.kind === "videoinput");
1062 for (const camera of cameras) {
1063 if (isBackCameraLabel(camera.label)) {
1064 backCameras.push(new SelectedCamera(camera, exports.PreferredCameraType.BackFacingCamera));
1065 }
1066 else {
1067 frontCameras.push(new SelectedCamera(camera, exports.PreferredCameraType.FrontFacingCamera));
1068 }
1069 }
1070 }
1071 return {
1072 frontCameras,
1073 backCameras
1074 };
1075 });
1076}
1077function selectCamera(cameraId, preferredCameraType) {
1078 return __awaiter(this, void 0, void 0, function* () {
1079 const { frontCameras, backCameras } = yield getCameraDevices();
1080 if (frontCameras.length > 0 || backCameras.length > 0) {
1081 // decide from which array the camera will be selected
1082 let cameraPool = (backCameras.length > 0 ? backCameras : frontCameras);
1083 // if there is at least one back facing camera and user prefers back facing camera, use that as a selection pool
1084 if (preferredCameraType === exports.PreferredCameraType.BackFacingCamera && backCameras.length > 0) {
1085 cameraPool = backCameras;
1086 }
1087 // if there is at least one front facing camera and is preferred by user, use that as a selection pool
1088 if (preferredCameraType === exports.PreferredCameraType.FrontFacingCamera && frontCameras.length > 0) {
1089 cameraPool = frontCameras;
1090 }
1091 // otherwise use whichever pool is non-empty
1092 // sort camera pool by label
1093 cameraPool = cameraPool.sort((camera1, camera2) => camera1.label.localeCompare(camera2.label));
1094 // Check if cameras are labeled with resolution information, take the higher-resolution one in that case
1095 // Otherwise pick the first camera
1096 {
1097 let selectedCameraIndex = 0;
1098 const cameraResolutions = cameraPool.map(camera => {
1099 const regExp = RegExp(/\b([0-9]+)MP?\b/, "i");
1100 const match = regExp.exec(camera.label);
1101 if (match !== null) {
1102 return parseInt(match[1], 10);
1103 }
1104 else {
1105 return NaN;
1106 }
1107 });
1108 if (!cameraResolutions.some(cameraResolution => isNaN(cameraResolution))) {
1109 selectedCameraIndex = cameraResolutions.lastIndexOf(Math.max(...cameraResolutions));
1110 }
1111 if (cameraId) {
1112 let cameraDevice = null;
1113 cameraDevice = frontCameras.filter(device => device.deviceId === cameraId)[0];
1114 if (!cameraDevice) {
1115 cameraDevice = backCameras.filter(device => device.deviceId === cameraId)[0];
1116 }
1117 return cameraDevice || null;
1118 }
1119 return cameraPool[selectedCameraIndex];
1120 }
1121 }
1122 else {
1123 // no cameras available on the device
1124 return null;
1125 }
1126 });
1127}
1128/**
1129 * Bind camera device to video feed (HTMLVideoElement).
1130 *
1131 * This function will return `true` in case that video feed of camera device has been flipped,
1132 * and `false` otherwise.
1133 *
1134 * @param camera Camera device which should be binded with the video element.
1135 * @param videoFeed HTMLVideoElement to which camera device should be binded.
1136 * @param preferredCameraType Enum representing whether to use front facing or back facing camera.
1137 */
1138function bindCameraToVideoFeed(camera, videoFeed, preferredCameraType = exports.PreferredCameraType.BackFacingCamera) {
1139 return __awaiter(this, void 0, void 0, function* () {
1140 const constraints = {
1141 audio: false,
1142 video: {
1143 width: {
1144 min: 640,
1145 ideal: 1920,
1146 max: 1920
1147 },
1148 height: {
1149 min: 480,
1150 ideal: 1080,
1151 max: 1080
1152 }
1153 }
1154 };
1155 if (camera.deviceId === "") {
1156 const isPreferredBackFacing = preferredCameraType === exports.PreferredCameraType.BackFacingCamera;
1157 constraints.video.facingMode =
1158 {
1159 ideal: isPreferredBackFacing ? "environment" : "user"
1160 };
1161 }
1162 else {
1163 constraints.video.deviceId =
1164 {
1165 exact: camera.deviceId
1166 };
1167 }
1168 const stream = yield navigator.mediaDevices.getUserMedia(constraints);
1169 videoFeed.controls = false;
1170 videoFeed.srcObject = stream;
1171 let cameraFlipped = false;
1172 if (camera.facing === exports.PreferredCameraType.FrontFacingCamera) {
1173 videoFeed.style.transform = "scaleX(-1)";
1174 cameraFlipped = true;
1175 }
1176 return cameraFlipped;
1177 });
1178}
1179function clearVideoFeed(videoFeed) {
1180 if (videoFeed && videoFeed.srcObject !== null) {
1181 videoFeed.srcObject.getTracks().forEach(track => track.stop());
1182 videoFeed.srcObject = null;
1183 }
1184}
1185
1186/**
1187 * Copyright (c) Microblink Ltd. All rights reserved.
1188 */
1189(function (ImageOrientation) {
1190 /**
1191 * Image contents are rotated 90 degrees left.
1192 * This usually happens on mobile devices when capturing image while
1193 * device is held in "portrait" orientation, while device camera sensor
1194 * is mounted horizontally (i.e. produced image is in "landscape" orienation).
1195 */
1196 ImageOrientation[ImageOrientation["RotatedLeft90"] = 0] = "RotatedLeft90";
1197 /**
1198 * Image contents are not rotated in any manner.
1199 * This is the default for images captured using HTML canvas, as
1200 * used in FrameCapture class.
1201 * This orientation also usually happens on mobile devices when capturing
1202 * image while device is held in "landscape" orientation, while device
1203 * camera sensor is mounted horizontally (i.e. also in same orientation).
1204 */
1205 ImageOrientation[ImageOrientation["NoRotation"] = 1] = "NoRotation";
1206 /**
1207 * Image contents are rotated 90 degrees right.
1208 * This usually happens on mobile devices when capturing image while
1209 * device is held in "reverse-portrait" orientation, while device camera sensor
1210 * is mounted horizontally (i.e. produced image is in "landscape" orienation).
1211 */
1212 ImageOrientation[ImageOrientation["RotatedRight90"] = 2] = "RotatedRight90";
1213 /**
1214 * Image contents are rotated 180 degrees, i.e. image contents are "upside down".
1215 * This usually happens on mobile devices when capturing image while
1216 * device is held in "reverse-landscape" orientation, while device camera sensor
1217 * is mounted horizontally (i.e. produced image is in "landscape" orienation).
1218 */
1219 ImageOrientation[ImageOrientation["Rotated180"] = 3] = "Rotated180";
1220})(exports.ImageOrientation || (exports.ImageOrientation = {}));
1221(function (RecognizerResultState) {
1222 /** Nothing has been recognized. */
1223 RecognizerResultState[RecognizerResultState["Empty"] = 0] = "Empty";
1224 /** Something has been recognized, but some mandatory data is still missing. */
1225 RecognizerResultState[RecognizerResultState["Uncertain"] = 1] = "Uncertain";
1226 /** All required data has been recognized. */
1227 RecognizerResultState[RecognizerResultState["Valid"] = 2] = "Valid";
1228 /** Single stage of a multi-stage recognition is finished. */
1229 RecognizerResultState[RecognizerResultState["StageValid"] = 3] = "StageValid";
1230})(exports.RecognizerResultState || (exports.RecognizerResultState = {}));
1231
1232/**
1233 * Copyright (c) Microblink Ltd. All rights reserved.
1234 */
1235/**
1236 * Checks if browser is supported by the SDK. The minimum requirements for the browser is
1237 * the support for WebAssembly. If your browser does not support executing WebAssembly,
1238 * this function will return `false`.
1239 */
1240function isBrowserSupported() {
1241 // based on https://stackoverflow.com/a/47880734
1242 try {
1243 if (typeof WebAssembly === "object" && typeof WebAssembly.instantiate === "function") {
1244 const module = new WebAssembly.Module(Uint8Array.of(0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00));
1245 if (module instanceof WebAssembly.Module)
1246 return new WebAssembly.Instance(module) instanceof WebAssembly.Instance;
1247 }
1248 }
1249 catch (ignored) {
1250 return false;
1251 }
1252 return false;
1253}
1254/**
1255 * Check if current browser is in-app / embedded.
1256 * Detects Instagram, Facebook, LinkedIn, Twitter, WeChat, Whatsapp, and Tiktok.
1257 * @returns Boolean whether the browser is in-app or not
1258 */
1259function isInAppBrowser() {
1260 const inAppRegex = /(instagram|fbav|linkedinapp|twitter|micromessenger|whatsapp|tiktok)[/\s]?([\w.]*)/i;
1261 const userAgent = navigator.userAgent || navigator.vendor;
1262 return !!inAppRegex.exec(userAgent);
1263}
1264/**
1265 * Check if browser supports ES6, which is prerequisite for this SDK to execute.
1266 *
1267 * IMPORTANT: it's not possible to run this function from MicroblinkSDK if browser doesn't support
1268 * ES6 since this file won't be able to load.
1269 *
1270 * This function is here as a placeholder so it can be copied to standalone JS file or directly into 'index.html'.
1271 */
1272// export function isES6Supported(): boolean
1273// {
1274// if ( typeof Symbol === "undefined" )
1275// {
1276// return false;
1277// }
1278// try
1279// {
1280// eval( "class Foo {}" );
1281// eval( "var bar = (x) => x+1" );
1282// }
1283// catch ( e )
1284// {
1285// return false;
1286// }
1287// return true;
1288// }
1289
1290/**
1291 * Copyright (c) Microblink Ltd. All rights reserved.
1292 */
1293// ============================================ /
1294// Frame capture and camera management support. /
1295// ============================================ /
1296let canvas;
1297/**
1298 * Represents a captured frame from HTMLVideoElement.
1299 */
1300class CapturedFrame {
1301 constructor(imageData, orientation, videoFrame) {
1302 this.imageData = imageData;
1303 this.orientation = orientation;
1304 this.videoFrame = videoFrame;
1305 }
1306}
1307/**
1308 * Captures a frame from any CanvasImageSource, such as HTMLVideoElement or HTMLImageElement.
1309 * @param imageSource image source from which frame should be captured
1310 * @returns instance of CapturedFrame
1311 */
1312function captureFrame(imageSource) {
1313 let imageWidth;
1314 let imageHeight;
1315 let videoFrame = false;
1316 if (imageSource instanceof HTMLVideoElement) {
1317 imageWidth = imageSource.videoWidth;
1318 imageHeight = imageSource.videoHeight;
1319 videoFrame = true;
1320 }
1321 else if (imageSource instanceof HTMLImageElement) {
1322 imageWidth = imageSource.naturalWidth;
1323 imageHeight = imageSource.naturalHeight;
1324 }
1325 else if (imageSource instanceof SVGImageElement) {
1326 throw new SDKError(frameCaptureErrors.svgUnsupported);
1327 }
1328 else {
1329 imageWidth = imageSource.width;
1330 imageHeight = imageSource.height;
1331 }
1332 canvas = canvas || document.createElement("canvas");
1333 canvas.width = imageWidth;
1334 canvas.height = imageHeight;
1335 const ctx = canvas.getContext("2d");
1336 if (!ctx) {
1337 throw new SDKError(frameCaptureErrors.canvasMissing);
1338 }
1339 ctx.drawImage(imageSource, 0, 0, canvas.width, canvas.height);
1340 const pixelData = ctx.getImageData(0, 0, canvas.width, canvas.height);
1341 return new CapturedFrame(pixelData,
1342 // TODO: https://developer.mozilla.org/en-US/docs/Web/API/Screen/orientation
1343 // or https://developer.mozilla.org/en-US/docs/Web/API/Window/orientation
1344 exports.ImageOrientation.NoRotation, videoFrame);
1345}
1346
1347/**
1348 * Copyright (c) Microblink Ltd. All rights reserved.
1349 */
1350(function (LicenseTokenState) {
1351 LicenseTokenState[LicenseTokenState["Invalid"] = 0] = "Invalid";
1352 LicenseTokenState[LicenseTokenState["RequiresServerPermission"] = 1] = "RequiresServerPermission";
1353 LicenseTokenState[LicenseTokenState["Valid"] = 2] = "Valid";
1354})(exports.LicenseTokenState || (exports.LicenseTokenState = {}));
1355(function (LicenseErrorType) {
1356 LicenseErrorType["LicenseTokenStateInvalid"] = "LICENSE_TOKEN_STATE_INVALID";
1357 LicenseErrorType["NetworkError"] = "NETWORK_ERROR";
1358 LicenseErrorType["RemoteLock"] = "REMOTE_LOCK";
1359 LicenseErrorType["PermissionExpired"] = "PERMISSION_EXPIRED";
1360 LicenseErrorType["PayloadCorrupted"] = "PAYLOAD_CORRUPTED";
1361 LicenseErrorType["PayloadSignatureVerificationFailed"] = "PAYLOAD_SIGNATURE_VERIFICATION_FAILED";
1362 LicenseErrorType["IncorrectTokenState"] = "INCORRECT_TOKEN_STATE";
1363})(exports.LicenseErrorType || (exports.LicenseErrorType = {}));
1364const baltazar = "https://baltazar.microblink.com/api/v1/status/check";
1365function toBaltazarRequest(unlockResult) {
1366 return {
1367 licenseId: unlockResult.licenseId,
1368 licensee: unlockResult.licensee,
1369 packageName: unlockResult.packageName,
1370 platform: "Browser",
1371 sdkName: unlockResult.sdkName,
1372 sdkVersion: unlockResult.sdkVersion
1373 };
1374}
1375function shouldShowOverlay(isTrial, allowRemoveDemoOverlay, allowRemoveProductionOverlay) {
1376 if (isTrial && allowRemoveDemoOverlay) {
1377 return false;
1378 }
1379 if (!isTrial && allowRemoveProductionOverlay) {
1380 return false;
1381 }
1382 return true;
1383}
1384(function (ServerPermissionSubmitResultStatus) {
1385 ServerPermissionSubmitResultStatus[ServerPermissionSubmitResultStatus["Ok"] = 0] = "Ok";
1386 ServerPermissionSubmitResultStatus[ServerPermissionSubmitResultStatus["NetworkError"] = 1] = "NetworkError";
1387 ServerPermissionSubmitResultStatus[ServerPermissionSubmitResultStatus["RemoteLock"] = 2] = "RemoteLock";
1388 ServerPermissionSubmitResultStatus[ServerPermissionSubmitResultStatus["PermissionExpired"] = 3] = "PermissionExpired";
1389 ServerPermissionSubmitResultStatus[ServerPermissionSubmitResultStatus["PayloadCorrupted"] = 4] = "PayloadCorrupted";
1390 ServerPermissionSubmitResultStatus[ServerPermissionSubmitResultStatus["PayloadSignatureVerificationFailed"] = 5] = "PayloadSignatureVerificationFailed";
1391 ServerPermissionSubmitResultStatus[ServerPermissionSubmitResultStatus["IncorrectTokenState"] = 6] = "IncorrectTokenState";
1392})(exports.ServerPermissionSubmitResultStatus || (exports.ServerPermissionSubmitResultStatus = {}));
1393/* eslint-disable @typescript-eslint/no-explicit-any,
1394 @typescript-eslint/explicit-module-boundary-types,
1395 @typescript-eslint/no-unsafe-member-access,
1396 @typescript-eslint/no-unsafe-call
1397*/
1398function obtainNewServerPermission(unlockResult, wasmModule) {
1399 return __awaiter(this, void 0, void 0, function* () {
1400 // request permission from Baltazar service
1401 try {
1402 const response = yield fetch(baltazar, {
1403 method: "POST",
1404 headers: {
1405 "Content-Type": "application/json"
1406 },
1407 cache: "no-cache",
1408 body: JSON.stringify(toBaltazarRequest(unlockResult))
1409 });
1410 if (response.ok) {
1411 const serverPermission = (yield response.text()).toString();
1412 const result = wasmModule.submitServerPermission(serverPermission);
1413 return result;
1414 }
1415 else {
1416 return {
1417 status: exports.ServerPermissionSubmitResultStatus.NetworkError,
1418 lease: 0,
1419 networkErrorDescription: `Server responded with status ${response.status}`
1420 };
1421 }
1422 }
1423 catch (error) {
1424 return {
1425 status: exports.ServerPermissionSubmitResultStatus.NetworkError,
1426 lease: 0,
1427 networkErrorDescription: `Unexpected error: ${JSON.stringify(error)}`
1428 };
1429 }
1430 });
1431}
1432function unlockWasmSDK(licenseKey, allowHelloMessage, userId, wasmModule) {
1433 return __awaiter(this, void 0, void 0, function* () {
1434 const unlockResult = wasmModule.initializeWithLicenseKey(licenseKey, userId, allowHelloMessage);
1435 switch (unlockResult.unlockResult) {
1436 case exports.LicenseTokenState.Invalid:
1437 return {
1438 error: new SDKError(Object.assign(Object.assign({}, licenseErrors.licenseInvalid), { message: unlockResult.licenseError }), {
1439 type: exports.LicenseErrorType.LicenseTokenStateInvalid,
1440 }),
1441 };
1442 case exports.LicenseTokenState.Valid:
1443 return {
1444 error: null,
1445 showOverlay: shouldShowOverlay(unlockResult.isTrial, unlockResult.allowRemoveDemoOverlay, unlockResult.allowRemoveProductionOverlay)
1446 };
1447 case exports.LicenseTokenState.RequiresServerPermission:
1448 {
1449 const serverPermission = yield obtainNewServerPermission(unlockResult, wasmModule);
1450 switch (serverPermission.status) {
1451 case exports.ServerPermissionSubmitResultStatus.Ok:
1452 return {
1453 error: null,
1454 lease: serverPermission.lease
1455 };
1456 case exports.ServerPermissionSubmitResultStatus.NetworkError:
1457 {
1458 let additionalInfo = "";
1459 if (serverPermission.networkErrorDescription) {
1460 additionalInfo = " " + serverPermission.networkErrorDescription;
1461 }
1462 return {
1463 error: new SDKError(Object.assign(Object.assign({}, licenseErrors.licenseNetworkError), { message: "There has been a network error while obtaining the server permission!"
1464 + additionalInfo }), {
1465 type: exports.LicenseErrorType.NetworkError,
1466 })
1467 };
1468 }
1469 case exports.ServerPermissionSubmitResultStatus.RemoteLock:
1470 return {
1471 error: new SDKError(licenseErrors.licenseRemoteLocked, {
1472 type: exports.LicenseErrorType.RemoteLock,
1473 }),
1474 lease: serverPermission.lease
1475 };
1476 case exports.ServerPermissionSubmitResultStatus.PermissionExpired:
1477 return {
1478 error: new SDKError(licenseErrors.licensePermissionExpired, {
1479 type: exports.LicenseErrorType.PermissionExpired
1480 }),
1481 lease: serverPermission.lease
1482 };
1483 case exports.ServerPermissionSubmitResultStatus.PayloadCorrupted:
1484 return {
1485 error: new SDKError(licenseErrors.licensePayloadCorrupted, {
1486 type: exports.LicenseErrorType.PayloadCorrupted
1487 }),
1488 lease: serverPermission.lease
1489 };
1490 case exports.ServerPermissionSubmitResultStatus.PayloadSignatureVerificationFailed:
1491 return {
1492 error: new SDKError(licenseErrors.licensePayloadVerificationFailed, {
1493 type: exports.LicenseErrorType.PayloadSignatureVerificationFailed
1494 }),
1495 lease: serverPermission.lease
1496 };
1497 case exports.ServerPermissionSubmitResultStatus.IncorrectTokenState:
1498 return {
1499 error: new SDKError(licenseErrors.licenseTokenStateIncorrect, {
1500 type: exports.LicenseErrorType.IncorrectTokenState
1501 }),
1502 lease: serverPermission.lease
1503 };
1504 }
1505 }
1506 }
1507 });
1508}
1509/* eslint-enable @typescript-eslint/no-explicit-any,
1510 @typescript-eslint/explicit-module-boundary-types,
1511 @typescript-eslint/no-unsafe-member-access,
1512 @typescript-eslint/no-unsafe-call
1513*/
1514
1515/**
1516 * Copyright (c) Microblink Ltd. All rights reserved.
1517 */
1518(function (DetectionStatus) {
1519 /** Detection failed, form not detected */
1520 DetectionStatus[DetectionStatus["Fail"] = 0] = "Fail";
1521 /** Object was successfully detected */
1522 DetectionStatus[DetectionStatus["Success"] = 1] = "Success";
1523 /** Object detected, but the camera is too far above it */
1524 DetectionStatus[DetectionStatus["CameraTooHigh"] = 2] = "CameraTooHigh";
1525 /** Fallback detection of an object was successful */
1526 DetectionStatus[DetectionStatus["FallbackSuccess"] = 3] = "FallbackSuccess";
1527 /** Object is detected, but parts of it are not in image */
1528 DetectionStatus[DetectionStatus["Partial"] = 4] = "Partial";
1529 /** Object detected, but camera is at too big angle */
1530 DetectionStatus[DetectionStatus["CameraAtAngle"] = 5] = "CameraAtAngle";
1531 /** Object detected, but the camera is too near to it */
1532 DetectionStatus[DetectionStatus["CameraTooNear"] = 6] = "CameraTooNear";
1533 /** Document detected, but document is too close to the edge of the frame */
1534 DetectionStatus[DetectionStatus["DocumentTooCloseToEdge"] = 7] = "DocumentTooCloseToEdge";
1535})(exports.DetectionStatus || (exports.DetectionStatus = {}));
1536
1537/**
1538 * Copyright (c) Microblink Ltd. All rights reserved.
1539 */
1540(function (NotSupportedReason) {
1541 /** navigator.mediaDevices.getUserMedia is not supported by current browser for current context. */
1542 NotSupportedReason["MediaDevicesNotSupported"] = "MediaDevicesNotSupported";
1543 /** Camera with requested features is not available on current device. */
1544 NotSupportedReason["CameraNotFound"] = "CameraNotFound";
1545 /** Camera access was not granted by the user. */
1546 NotSupportedReason["CameraNotAllowed"] = "CameraNotAllowed";
1547 /** Unable to start playing because camera is already in use. */
1548 NotSupportedReason["CameraInUse"] = "CameraInUse";
1549 /** Camera is currently not available due to a OS or hardware error. */
1550 NotSupportedReason["CameraNotAvailable"] = "CameraNotAvailable";
1551 /** There is no provided video element to which the camera feed should be redirected. */
1552 NotSupportedReason["VideoElementNotProvided"] = "VideoElementNotProvided";
1553})(exports.NotSupportedReason || (exports.NotSupportedReason = {}));
1554(function (VideoRecognitionMode) {
1555 /** Normal recognition */
1556 VideoRecognitionMode[VideoRecognitionMode["Recognition"] = 0] = "Recognition";
1557 /** Indefinite scan. Useful for profiling the performance of scan (using onDebugText metadata callback) */
1558 VideoRecognitionMode[VideoRecognitionMode["RecognitionTest"] = 1] = "RecognitionTest";
1559 /** Only detection. Useful for profiling the performance of detection (using onDebugText metadata callback) */
1560 VideoRecognitionMode[VideoRecognitionMode["DetectionTest"] = 2] = "DetectionTest";
1561})(exports.VideoRecognitionMode || (exports.VideoRecognitionMode = {}));
1562/**
1563 * A wrapper around RecognizerRunner that can use it to perform recognition of video feeds - either from live camera or
1564 * from predefined video file.
1565 */
1566class VideoRecognizer {
1567 /**
1568 * **Use only if provided factory functions are not well-suited for your use case.**
1569 *
1570 * Creates a new VideoRecognizer with provided HTMLVideoElement.
1571 *
1572 * Keep in mind that HTMLVideoElement **must have** a video feed which is ready to use.
1573 *
1574 * - If you want to take advantage of provided camera management, use `createVideoRecognizerFromCameraStream`
1575 * - In case that static video file should be processed, use `createVideoRecognizerFromVideoPath`
1576 *
1577 * @param videoFeed HTMLVideoElement with video feed which is going to be processed
1578 * @param recognizerRunner RecognizerRunner that should be used for video stream recognition
1579 * @param cameraFlipped Whether the camera is flipped, e.g. if front-facing camera is used
1580 * @param allowManualVideoPlayout Whether to allow manual video playout. Default value is `false`
1581 */
1582 constructor(videoFeed, recognizerRunner, cameraFlipped = false, allowManualVideoPlayout = false, deviceId = null) {
1583 this.deviceId = null;
1584 /** *********************************************************************************************
1585 * PRIVATE AREA
1586 */
1587 this.videoFeed = null;
1588 this.cancelled = false;
1589 this.timedOut = false;
1590 this.recognitionPaused = false;
1591 this.recognitionTimeoutMs = 20000;
1592 this.timeoutID = 0;
1593 this.videoRecognitionMode = exports.VideoRecognitionMode.Recognition;
1594 this.onScanningDone = null;
1595 this.allowManualVideoPlayout = false;
1596 this.cameraFlipped = false;
1597 this.shouldReleaseVideoFeed = false;
1598 this.videoFeed = videoFeed;
1599 this.recognizerRunner = recognizerRunner;
1600 this.cameraFlipped = cameraFlipped;
1601 this.allowManualVideoPlayout = allowManualVideoPlayout;
1602 this.deviceId = deviceId;
1603 }
1604 /**
1605 * Creates a new VideoRecognizer by opening a camera stream and attaching it to given HTMLVideoElement. If camera
1606 * cannot be accessed, the returned promise will be rejected.
1607 *
1608 * @param cameraFeed HTMLVideoELement to which camera stream should be attached
1609 * @param recognizerRunner RecognizerRunner that should be used for video stream recognition
1610 * @param cameraId User can provide specific camera ID to be selected and used
1611 * @param preferredCameraType Whether back facing or front facing camera is preferred. Obeyed only if there is
1612 * a choice (i.e. if device has only front-facing camera, the opened camera will be a front-facing camera,
1613 * regardless of preference)
1614 */
1615 static createVideoRecognizerFromCameraStream(cameraFeed, recognizerRunner, cameraId = null, preferredCameraType = exports.PreferredCameraType.BackFacingCamera) {
1616 return __awaiter(this, void 0, void 0, function* () {
1617 // TODO: refactor this function into async/await syntax, instead of reject use throw
1618 /* eslint-disable */
1619 return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
1620 // Check for tag name intentionally left out, so it's possible to use VideoRecognizer with custom elements.
1621 if (!cameraFeed || !(cameraFeed instanceof Element)) {
1622 reject(new SDKError(videoRecognizerErrors.elementMissing, {
1623 reason: exports.NotSupportedReason.VideoElementNotProvided,
1624 }));
1625 return;
1626 }
1627 if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia !== undefined) {
1628 try {
1629 const selectedCamera = yield selectCamera(cameraId, preferredCameraType);
1630 if (selectedCamera === null) {
1631 reject(new SDKError(videoRecognizerErrors.cameraMissing, {
1632 reason: exports.NotSupportedReason.CameraNotFound,
1633 }));
1634 return;
1635 }
1636 const cameraFlipped = yield bindCameraToVideoFeed(selectedCamera, cameraFeed, preferredCameraType);
1637 // TODO: await maybe not needed here
1638 yield recognizerRunner.setCameraPreviewMirrored(cameraFlipped);
1639 resolve(new VideoRecognizer(cameraFeed, recognizerRunner, cameraFlipped, false, selectedCamera.deviceId));
1640 }
1641 catch (error) {
1642 let errorReason = exports.NotSupportedReason.CameraInUse;
1643 let errorCode = exports.ErrorCodes.VIDEO_RECOGNIZER_CAMERA_IN_USE;
1644 switch (error.name) {
1645 case "NotFoundError":
1646 case "OverconstrainedError":
1647 errorReason = exports.NotSupportedReason.CameraNotFound;
1648 errorCode = exports.ErrorCodes.VIDEO_RECOGNIZER_CAMERA_MISSING;
1649 break;
1650 case "NotAllowedError":
1651 case "SecurityError":
1652 errorReason = exports.NotSupportedReason.CameraNotAllowed;
1653 errorCode = exports.ErrorCodes.VIDEO_RECOGNIZER_CAMERA_NOT_ALLOWED;
1654 break;
1655 case "AbortError":
1656 case "NotReadableError":
1657 errorReason = exports.NotSupportedReason.CameraNotAvailable;
1658 errorCode = exports.ErrorCodes.VIDEO_RECOGNIZER_CAMERA_UNAVAILABLE;
1659 break;
1660 case "TypeError": // this should never happen. If it does, rethrow it
1661 throw error;
1662 }
1663 reject(new SDKError({
1664 message: error.message,
1665 code: errorCode,
1666 }, {
1667 reason: errorReason,
1668 }));
1669 }
1670 }
1671 else {
1672 reject(new SDKError(videoRecognizerErrors.mediaDevicesUnsupported, {
1673 reason: exports.NotSupportedReason.MediaDevicesNotSupported
1674 }));
1675 }
1676 }));
1677 /* eslint-enable */
1678 });
1679 }
1680 /**
1681 * Creates a new VideoRecognizer by attaching the given URL to video to given HTMLVideoElement and using it to
1682 * display video frames while processing them.
1683 *
1684 * @param videoPath URL of the video file that should be recognized.
1685 * @param videoFeed HTMLVideoElement to which video file will be attached
1686 * @param recognizerRunner RecognizerRunner that should be used for video stream recognition.
1687 */
1688 static createVideoRecognizerFromVideoPath(videoPath, videoFeed, recognizerRunner) {
1689 return __awaiter(this, void 0, void 0, function* () {
1690 return new Promise((resolve) => {
1691 videoFeed.src = videoPath;
1692 videoFeed.currentTime = 0;
1693 videoFeed.onended = () => {
1694 videoRecognizer.cancelRecognition();
1695 };
1696 const videoRecognizer = new VideoRecognizer(videoFeed, recognizerRunner);
1697 resolve(videoRecognizer);
1698 });
1699 });
1700 }
1701 flipCamera() {
1702 return __awaiter(this, void 0, void 0, function* () {
1703 if (this.videoFeed) {
1704 if (!this.cameraFlipped) {
1705 this.videoFeed.style.transform = "scaleX(-1)";
1706 this.cameraFlipped = true;
1707 }
1708 else {
1709 this.videoFeed.style.transform = "scaleX(1)";
1710 this.cameraFlipped = false;
1711 }
1712 yield this.recognizerRunner.setCameraPreviewMirrored(this.cameraFlipped);
1713 }
1714 });
1715 }
1716 isCameraFlipped() {
1717 return this.cameraFlipped;
1718 }
1719 /**
1720 * Sets the video recognition mode to be used.
1721 *
1722 * @param videoRecognitionMode the video recognition mode to be used.
1723 */
1724 setVideoRecognitionMode(videoRecognitionMode) {
1725 return __awaiter(this, void 0, void 0, function* () {
1726 this.videoRecognitionMode = videoRecognitionMode;
1727 const isDetectionMode = this.videoRecognitionMode === exports.VideoRecognitionMode.DetectionTest;
1728 yield this.recognizerRunner.setDetectionOnlyMode(isDetectionMode);
1729 });
1730 }
1731 /**
1732 * Starts the recognition of the video stream associated with this VideoRecognizer. The stream will be unpaused and
1733 * recognition loop will start. After recognition completes, a onScanningDone callback will be invoked with state of
1734 * the recognition.
1735 *
1736 * NOTE: As soon as the execution of the callback completes, the recognition loop will continue and recognition
1737 * state will be retained. To clear the recognition state, use resetRecognizers (within your callback). To
1738 * pause the recognition loop, use pauseRecognition (within your callback) - to resume it later use
1739 * resumeRecognition. To completely stop the recognition and video feed, while keeping the ability to use this
1740 * VideoRecognizer later, use pauseVideoFeed. To completely stop the recognition and video feed and release
1741 * all the resources involved with video stream, use releaseVideoFeed.
1742 *
1743 * @param onScanningDone Callback that will be invoked when recognition completes.
1744 * @param recognitionTimeoutMs Amount of time before returned promise will be resolved regardless of whether
1745 * recognition was successful or not.
1746 */
1747 startRecognition(onScanningDone, recognitionTimeoutMs = 20000) {
1748 return new Promise((resolve, reject) => {
1749 if (this.videoFeed === null) {
1750 reject(new SDKError(videoRecognizerErrors.videoFeedReleased));
1751 return;
1752 }
1753 if (!this.videoFeed.paused) {
1754 reject(new SDKError(videoRecognizerErrors.videoFeedNotPaused));
1755 return;
1756 }
1757 this.cancelled = false;
1758 this.recognitionPaused = false;
1759 this.clearTimeout();
1760 this.recognitionTimeoutMs = recognitionTimeoutMs;
1761 this.onScanningDone = onScanningDone;
1762 void this.recognizerRunner.setClearTimeoutCallback({ onClearTimeout: () => this.clearTimeout() });
1763 this.videoFeed.play().then(() => this.playPauseEvent().then(() => resolve()).catch((error) => reject(error)),
1764 /* eslint-disable @typescript-eslint/no-explicit-any */
1765 (nativeError) => {
1766 if (!this.allowManualVideoPlayout) {
1767 reject(new SDKError(videoRecognizerErrors.playRequestInterrupted, nativeError));
1768 return;
1769 }
1770 if (!this.videoFeed) {
1771 return;
1772 }
1773 this.videoFeed.controls = true;
1774 this.videoFeed.addEventListener("play", () => void this.playPauseEvent().then().catch((error) => reject(error)));
1775 this.videoFeed.addEventListener("pause", () => void this.playPauseEvent().then().catch((error) => reject(error)));
1776 }
1777 /* eslint-enable @typescript-eslint/no-explicit-any */
1778 );
1779 });
1780 }
1781 /**
1782 * Performs the recognition of the video stream associated with this VideoRecognizer. The stream will be
1783 * unpaused, recognition will be performed and promise will be resolved with recognition status. After
1784 * the resolution of returned promise, the video stream will be paused, but not released. To release the
1785 * stream, use function releaseVideoFeed.
1786 *
1787 * This is a simple version of startRecognition that should be used for most cases, like when you only need
1788 * to perform one scan per video session.
1789 *
1790 * @param recognitionTimeoutMs Amount of time before returned promise will be resolved regardless of whether
1791 * recognition was successful or not.
1792 */
1793 recognize(recognitionTimeoutMs = 20000) {
1794 return new Promise((resolve, reject) => {
1795 try {
1796 void this.startRecognition((recognitionState) => {
1797 this.pauseVideoFeed();
1798 resolve(recognitionState);
1799 }, recognitionTimeoutMs).then(
1800 // Do nothing, callback is used for resolving
1801 ).catch((error) => reject(error));
1802 }
1803 catch (error) {
1804 reject(error);
1805 }
1806 });
1807 }
1808 /**
1809 * Cancels current ongoing recognition. Note that after cancelling the recognition, the callback given to
1810 * startRecognition will be immediately called. This also means that the promise returned from method
1811 * recognize will be resolved immediately.
1812 */
1813 cancelRecognition() {
1814 this.cancelled = true;
1815 }
1816 /**
1817 * Pauses the video feed. You can resume the feed by calling recognize or startRecognition.
1818 * Note that this pauses both the camera feed and recognition. If you just want to pause
1819 * recognition, while keeping the camera feed active, call method pauseRecognition.
1820 */
1821 pauseVideoFeed() {
1822 this.pauseRecognition();
1823 if (this.videoFeed) {
1824 this.videoFeed.pause();
1825 }
1826 }
1827 /**
1828 * Pauses the recognition. This means that video frames that arrive from given video source
1829 * will not be recognized. To resume recognition, call resumeRecognition(boolean).
1830 * Unlike cancelRecognition, the callback given to startRecognition will not be invoked after pausing
1831 * the recognition (unless there is already processing in-flight that may call the callback just before
1832 * pausing the actual recognition loop).
1833 */
1834 pauseRecognition() {
1835 this.recognitionPaused = true;
1836 }
1837 /**
1838 * Convenience method for invoking resetRecognizers on associated RecognizerRunner.
1839 * @param hardReset Same as in RecognizerRunner.resetRecognizers.
1840 */
1841 resetRecognizers(hardReset) {
1842 return __awaiter(this, void 0, void 0, function* () {
1843 yield this.recognizerRunner.resetRecognizers(hardReset);
1844 });
1845 }
1846 /**
1847 * Convenience method for accessing RecognizerRunner associated with this VideoRecognizer.
1848 * Sometimes it's useful to reconfigure RecognizerRunner while handling onScanningDone callback
1849 * and this method makes that much more convenient.
1850 */
1851 getRecognizerRunner() {
1852 return this.recognizerRunner;
1853 }
1854 /**
1855 * Resumes the recognition. The video feed must not be paused. If it is, an error will be thrown.
1856 * If video feed is paused, you should use recognize or startRecognition methods.
1857 * @param resetRecognizers Indicates whether resetRecognizers should be invoked while resuming the recognition
1858 */
1859 resumeRecognition(resetRecognizers) {
1860 return new Promise((resolve, reject) => {
1861 this.cancelled = false;
1862 this.timedOut = false;
1863 this.recognitionPaused = false;
1864 if (this.videoFeed && this.videoFeed.paused) {
1865 reject(new SDKError(videoRecognizerErrors.feedPaused));
1866 return;
1867 }
1868 setTimeout(() => {
1869 if (resetRecognizers) {
1870 this.resetRecognizers(true).then(() => {
1871 this.recognitionLoop().then(() => resolve()).catch((error) => reject(error));
1872 }).catch(() => {
1873 reject(new SDKError(videoRecognizerErrors.recognizersResetFailure));
1874 });
1875 }
1876 else {
1877 void this.recognitionLoop().then(() => resolve()).catch((error) => reject(error));
1878 }
1879 }, 1);
1880 });
1881 }
1882 /**
1883 * Stops all media stream tracks associated with current HTMLVideoElement and removes any references to it.
1884 * Note that after calling this method you can no longer use this VideoRecognizer for recognition.
1885 * This method should be called after you no longer plan on performing video recognition to let browser know
1886 * that it can release resources related to any media streams used.
1887 */
1888 releaseVideoFeed() {
1889 var _a, _b;
1890 if (!this.videoFeed || ((_a = this.videoFeed) === null || _a === void 0 ? void 0 : _a.readyState) < ((_b = this.videoFeed) === null || _b === void 0 ? void 0 : _b.HAVE_CURRENT_DATA)) {
1891 this.shouldReleaseVideoFeed = true;
1892 return;
1893 }
1894 if (!this.videoFeed.paused) {
1895 this.cancelRecognition();
1896 }
1897 clearVideoFeed(this.videoFeed);
1898 this.videoFeed = null;
1899 this.shouldReleaseVideoFeed = false;
1900 }
1901 /**
1902 * Change currently used camera device for recognition. To get list of available camera devices
1903 * use "getCameraDevices" method.
1904 *
1905 * Keep in mind that this method will reset recognizers.
1906 *
1907 * @param camera Desired camera device which should be used for recognition.
1908 */
1909 changeCameraDevice(camera) {
1910 return new Promise((resolve, reject) => {
1911 if (this.videoFeed === null) {
1912 reject(new SDKError(videoRecognizerErrors.feedMissing));
1913 return;
1914 }
1915 this.pauseRecognition();
1916 clearVideoFeed(this.videoFeed);
1917 bindCameraToVideoFeed(camera, this.videoFeed).then(() => {
1918 if (this.videoFeed === null) {
1919 reject(new SDKError(videoRecognizerErrors.feedMissing));
1920 return;
1921 }
1922 this.videoFeed.play().then(() => {
1923 // Recognition errors should be handled by `startRecognition` or `recognize` method
1924 void this.resumeRecognition(true);
1925 resolve();
1926 },
1927 /* eslint-disable @typescript-eslint/no-explicit-any */
1928 (nativeError) => {
1929 if (!this.allowManualVideoPlayout) {
1930 reject(new SDKError(videoRecognizerErrors.playRequestInterrupted, nativeError));
1931 return;
1932 }
1933 if (!this.videoFeed) {
1934 reject(new SDKError(videoRecognizerErrors.feedMissing));
1935 return;
1936 }
1937 this.videoFeed.controls = true;
1938 }
1939 /* eslint-enable @typescript-eslint/no-explicit-any */
1940 );
1941 }).catch((error) => reject(error));
1942 });
1943 }
1944 playPauseEvent() {
1945 return new Promise((resolve, reject) => {
1946 if (this.videoFeed && this.videoFeed.paused) {
1947 this.cancelRecognition();
1948 resolve();
1949 return;
1950 }
1951 else {
1952 this.resumeRecognition(true).then(() => resolve()).catch((error) => reject(error));
1953 }
1954 });
1955 }
1956 recognitionLoop() {
1957 return new Promise((resolve, reject) => {
1958 if (!this.videoFeed) {
1959 reject(new SDKError(videoRecognizerErrors.feedMissing));
1960 return;
1961 }
1962 if (this.shouldReleaseVideoFeed && this.videoFeed.readyState > this.videoFeed.HAVE_CURRENT_DATA) {
1963 this.releaseVideoFeed();
1964 resolve();
1965 return;
1966 }
1967 const cameraFrame = captureFrame(this.videoFeed);
1968 this.recognizerRunner.processImage(cameraFrame).then((processResult) => {
1969 const completeFn = () => {
1970 if (!this.recognitionPaused) {
1971 // ensure browser events are processed and then recognize another frame
1972 setTimeout(() => {
1973 this.recognitionLoop().then(() => resolve()).catch((error) => reject(error));
1974 }, 1);
1975 }
1976 else {
1977 resolve();
1978 }
1979 };
1980 if (processResult === exports.RecognizerResultState.Valid || this.cancelled || this.timedOut) {
1981 if (this.videoRecognitionMode === exports.VideoRecognitionMode.Recognition || this.cancelled) {
1982 // valid results, clear the timeout and invoke the callback
1983 this.clearTimeout();
1984 if (this.onScanningDone) {
1985 void this.onScanningDone(processResult);
1986 }
1987 // after returning from callback, resume scanning if not paused
1988 }
1989 else {
1990 // in test mode - reset the recognizers and continue the loop indefinitely
1991 this.recognizerRunner.resetRecognizers(true).then(() => {
1992 // clear any time outs
1993 this.clearTimeout();
1994 completeFn();
1995 }).catch((error) => reject(error));
1996 return;
1997 }
1998 }
1999 else if (processResult === exports.RecognizerResultState.Uncertain) {
2000 if (this.timeoutID === 0) {
2001 // first non-empty result - start timeout
2002 this.timeoutID = window.setTimeout(() => { this.timedOut = true; }, this.recognitionTimeoutMs);
2003 }
2004 completeFn();
2005 return;
2006 }
2007 else if (processResult === exports.RecognizerResultState.StageValid) {
2008 // stage recognition is finished, clear timeout and resume recognition
2009 this.clearTimeout();
2010 completeFn();
2011 return;
2012 }
2013 completeFn();
2014 }).catch((error) => reject(error));
2015 });
2016 }
2017 clearTimeout() {
2018 if (this.timeoutID > 0) {
2019 window.clearTimeout(this.timeoutID);
2020 this.timeoutID = 0;
2021 }
2022 }
2023}
2024
2025/**
2026 * Copyright (c) Microblink Ltd. All rights reserved.
2027 */
2028/**
2029 * Settings object for function loadWasmModule.
2030 */
2031class WasmSDKLoadSettings {
2032 /**
2033 * @param licenseKey License key for unlocking the WebAssembly module.
2034 */
2035 constructor(licenseKey) {
2036 /**
2037 * Write a hello message to the browser console when license check is successfully performed.
2038 *
2039 * Hello message will contain the name and version of the SDK, which are required information for all support
2040 * tickets.
2041 *
2042 * The default value is true.
2043 */
2044 this.allowHelloMessage = true;
2045 /**
2046 * Absolute location of WASM and related JS/data files. Useful when resource files should be loaded over CDN, or
2047 * when web frameworks/libraries are used which store resources in specific locations, e.g. inside "assets" folder.
2048 *
2049 * Important: if the engine is hosted on another origin, CORS must be enabled between two hosts. That is, server
2050 * where engine is hosted must have 'Access-Control-Allow-Origin' header for the location of the web app.
2051 *
2052 * Important: SDK and WASM resources must be from the same version of a package.
2053 *
2054 * Default value is empty string, i.e. "". In case of empty string, value of "window.location.origin" property is
2055 * going to be used.
2056 */
2057 this.engineLocation = "";
2058 /**
2059 * Type of the WASM that will be loaded. By default, if not set, the SDK will automatically determine the best WASM
2060 * to load.
2061 */
2062 this.wasmType = null;
2063 /**
2064 * Defines the number of workers that will be used for multi-threaded processing of the images. If not set, the
2065 * number of worker used will match the number of detected CPU cores on a device.
2066 *
2067 * If the browser does not support multi-threaded processing or it was deliberately disabled using the `wasmType`
2068 * property, then this property will be ignored.
2069 */
2070 this.numberOfWorkers = null;
2071 /**
2072 * Optional callback function that will report the SDK loading progress.
2073 *
2074 * This can be useful for displaying progress bar to users with slow connections.
2075 *
2076 * The default value is null.
2077 */
2078 this.loadProgressCallback = null;
2079 /**
2080 * Name of the file containing the WebAssembly module.
2081 *
2082 * Change this only if you have renamed the original WASM and its support JS file for your purposes.
2083 */
2084 this.wasmModuleName = defaultWasmModuleName;
2085 if (!licenseKey) {
2086 throw new SDKError(sdkErrors.licenseKeyMissing);
2087 }
2088 this.licenseKey = licenseKey;
2089 }
2090}
2091
2092const bulkMemory = async () => WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 3, 1, 0, 1, 10, 14, 1, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0, 11])),
2093 saturatedFloatToInt = async () => WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 12, 1, 10, 0, 67, 0, 0, 0, 0, 252, 0, 26, 11])),
2094 signExtensions = async () => WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 8, 1, 6, 0, 65, 0, 192, 26, 11])),
2095 simd = async () => WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0, 253, 15, 253, 98, 11])),
2096 threads = () => (async e => {
2097 try {
2098 return "undefined" != typeof MessageChannel && new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)), WebAssembly.validate(e);
2099 } catch (e) {
2100 return !1;
2101 }
2102})(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11]));
2103
2104/**
2105 * Copyright (c) Microblink Ltd. All rights reserved.
2106 */
2107function detectWasmType(engineLocation) {
2108 return __awaiter(this, void 0, void 0, function* () {
2109 // determine if all features required for advanced WASM are available
2110 // currently, advanced wasm requires bulk memory, non-trapping floating point
2111 // and sign extension (this may change in the future).
2112 const haveBulkMemory = yield bulkMemory();
2113 const haveNonTrappingFloatingPoint = yield saturatedFloatToInt();
2114 const haveSignExtension = yield signExtensions();
2115 const haveSIMD = yield simd();
2116 const haveThreads = yield threads();
2117 if (haveBulkMemory && haveNonTrappingFloatingPoint && haveSignExtension && haveSIMD) {
2118 if (haveThreads) {
2119 /* The external worker files are loaded by the Emscripten’s thread support code - each
2120 * worker represents a thread. It’s not currently possible to put all those workers
2121 * inline.
2122 *
2123 * Also, due to browser security rules, it's not possible to load external worker files
2124 * from a different origin.
2125 *
2126 * Therefore, we need to ensure that remote workers are accessible. For that reason,
2127 * there is a dummy `Worker.test.js` file. If that file is loaded successfully, we can
2128 * say that `AdvancedWithThreads` bundle is available.
2129 */
2130 try {
2131 const worker = new Worker(`${engineLocation}/Worker.test.js`);
2132 worker.terminate();
2133 return exports.WasmType.AdvancedWithThreads;
2134 }
2135 catch (_a) {
2136 return exports.WasmType.Advanced;
2137 }
2138 }
2139 else {
2140 return exports.WasmType.Advanced;
2141 }
2142 }
2143 else {
2144 return exports.WasmType.Basic;
2145 }
2146 });
2147}
2148function wasmFolder(wasmType) {
2149 switch (wasmType) {
2150 case exports.WasmType.AdvancedWithThreads: return "advanced-threads";
2151 case exports.WasmType.Advanced: return "advanced";
2152 case exports.WasmType.Basic: return "basic";
2153 }
2154}
2155
2156/**
2157 * Copyright (c) Microblink Ltd. All rights reserved.
2158 */
2159// taken from https://stackoverflow.com/a/2117523/213057
2160/* eslint-disable */
2161function uuidv4() {
2162 return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16));
2163}
2164/* eslint-enable */
2165function getUserID() {
2166 try {
2167 let userId = localStorage.getItem("mb-user-id");
2168 if (userId === null) {
2169 userId = uuidv4();
2170 localStorage.setItem("mb-user-id", userId);
2171 }
2172 return userId;
2173 }
2174 catch (error) {
2175 // local storage is disabled, generate new user ID every time
2176 return uuidv4();
2177 }
2178}
2179/**
2180 * Asynchronously loads and compiles the WebAssembly module.
2181 * @param loadSettings Object defining the settings for loading the WebAssembly module.
2182 * @returns Promise that resolves if WebAssembly module was successfully loaded and rejects if not.
2183 */
2184/* eslint-disable @typescript-eslint/no-explicit-any,
2185 @typescript-eslint/no-unsafe-assignment,
2186 @typescript-eslint/no-unsafe-member-access,
2187 @typescript-eslint/no-unsafe-call */
2188function loadWasmModule(loadSettings) {
2189 return __awaiter(this, void 0, void 0, function* () {
2190 return new Promise((resolve, reject) => {
2191 if (!loadSettings || typeof loadSettings !== "object") {
2192 reject(new SDKError(sdkErrors.wasmSettingsMissing));
2193 return;
2194 }
2195 if (typeof loadSettings.licenseKey !== "string") {
2196 reject(new SDKError(sdkErrors.licenseKeyMissing));
2197 return;
2198 }
2199 if (!loadSettings.wasmModuleName) {
2200 reject(new SDKError(sdkErrors.wasmModuleNameMissing));
2201 return;
2202 }
2203 if (typeof loadSettings.engineLocation !== "string") {
2204 reject(new SDKError(sdkErrors.engineLocationInvalid));
2205 return;
2206 }
2207 // obtain user ID from local storage
2208 const userId = getUserID();
2209 try {
2210 const blob = new Blob([String.raw `!function(){"use strict";
2211/*! *****************************************************************************
2212 Copyright (c) Microsoft Corporation.
2213
2214 Permission to use, copy, modify, and/or distribute this software for any
2215 purpose with or without fee is hereby granted.
2216
2217 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
2218 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
2219 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
2220 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
2221 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2222 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2223 PERFORMANCE OF THIS SOFTWARE.
2224 ***************************************************************************** */function e(e,t,s,n){return new(s||(s=Promise))((function(r,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}let t=0;class s{constructor(e){this.action=e,this.messageID=function(){const e=t;return t+=1,e}()}}class n extends s{constructor(e,t){super(n.action),this.wasmModuleName=e.wasmModuleName,this.licenseKey=e.licenseKey,this.userId=t,this.registerLoadCallback=null!==e.loadProgressCallback,this.allowHelloMessage=e.allowHelloMessage,this.engineLocation=e.engineLocation,this.wasmType=e.wasmType,this.numberOfWorkers=e.numberOfWorkers}}var r,i;n.action="init",function(e){e[e.Any=0]="Any",e[e.Recognizer=1]="Recognizer",e[e.RecognizerSettings=2]="RecognizerSettings",e[e.Callback=3]="Callback"}(r||(r={}));class o extends s{constructor(e,t){super(o.action),this.funcName=e,this.params=t}}o.action="invokeFunction";class a extends s{constructor(e,t){super(a.action),this.className=e,this.params=t}}a.action="createNewNativeObject";class c extends s{constructor(e,t,s){super(c.action),this.recognizerHandles=e,this.allowMultipleResults=t,this.registeredMetadataCallbacks=s}}c.action="createRecognizerRunner";class E extends s{constructor(e,t){super(E.action),this.recognizerHandles=e,this.allowMultipleResults=t}}E.action="reconfigureRecognizerRunner";class R extends s{constructor(){super(R.action)}}R.action="deleteRecognizerRunner";class l extends s{constructor(e,t,s){super(l.action),this.objectHandle=e,this.methodName=t,this.params=s}}l.action="invokeObject";class _ extends s{constructor(e){super(_.action),this.frame=e}getTransferrables(){return[this.frame.imageData.data.buffer]}}_.action="processImage";class u extends s{constructor(e){super(u.action),this.hardReset=e}}u.action="resetRecognizers";class I extends s{constructor(e){super(I.action),this.registeredMetadataCallbacks=e}}I.action="registerMetadataCallbacks";class d extends s{constructor(e){super(d.action),this.detectionOnlyMode=e}}d.action="setDetectionOnly";class N extends s{constructor(e){super(N.action),this.callbackNonEmpty=e}}N.action="setClearTimeoutCallback";class O extends s{constructor(e){super(O.action),this.cameraPreviewMirrored=e}}O.action="setCameraPreviewMirrored";class h extends s{constructor(e){super(h.action),this.userId=e}}h.action="getProductIntegrationInfo";class S{constructor(e,t,s){this.success=!0,this.error=null,this.messageID=e,this.success=t,this.error=s}}class g{constructor(e,t,s,n){this.success=!0,this.showOverlay=!0,this.messageID=e,this.success=t,this.showOverlay=s,this.wasmType=n}}class C extends S{constructor(e,t){super(e,!0,null),this.result=t}}class m extends S{constructor(e,t){super(e,!0,null),this.objectHandle=t}}class A extends S{constructor(e,t){super(e,!0,null),this.recognitionState=t}}class D extends S{constructor(e,t){super(e,!0,null),this.result=t}}class f{constructor(e){this.isLoadProgressMessage=!0,this.progress=e}}!function(e){e[e.onDebugText=0]="onDebugText",e[e.onDetectionFailed=1]="onDetectionFailed",e[e.onQuadDetection=2]="onQuadDetection",e[e.onPointsDetection=3]="onPointsDetection",e[e.onFirstSideResult=4]="onFirstSideResult",e[e.clearTimeoutCallback=5]="clearTimeoutCallback",e[e.onGlare=6]="onGlare",e[e.recognizerCallback=7]="recognizerCallback"}(i||(i={}));class M{constructor(e,t){this.isCallbackMessage=!0,this.callbackType=e,this.callbackParameters=t}}function T(e,t){return t=t||"",""===(e=e||"")?t:e.endsWith("/")?t.startsWith("/")?e+t.substring(1):e+t:t.startsWith("/")?e+t:e+"/"+t}var p,L,w;function y(t){return e(this,void 0,void 0,(function*(){const e=yield(async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,3,1,0,1,10,14,1,12,0,65,0,65,0,65,0,252,10,0,0,11])))(),s=yield(async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,12,1,10,0,67,0,0,0,0,252,0,26,11])))(),n=yield(async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,8,1,6,0,65,0,192,26,11])))(),r=yield(async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])))(),i=yield(async e=>{try{return"undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(e)}catch(e){return!1}})(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]));if(!(e&&s&&n&&r))return p.Basic;if(!i)return p.Advanced;try{return new Worker(t+"/Worker.test.js").terminate(),p.AdvancedWithThreads}catch(e){return p.Advanced}}))}!function(e){e.Basic="BASIC",e.Advanced="ADVANCED",e.AdvancedWithThreads="ADVANCED_WITH_THREADS"}(p||(p={}));class U{constructor(e,t){if(!e.code||!e.message)throw Error("Instance of SDKError is required to have code and message.");this.message=e.message,this.code=e.code,this.details=t}}!function(e){e.WORKER_WASM_LOAD_FAILURE="WORKER_WASM_LOAD_FAILURE",e.WORKER_WASM_INIT_MISSING="WORKER_WASM_INIT_MISSING",e.WORKER_FUNCTION_INVOKE_FAILURE="WORKER_FUNCTION_INVOKE_FAILURE",e.WORKER_RECOGNIZER_CREATION_FAILURE="WORKER_RECOGNIZER_CREATION_FAILURE",e.WORKER_RUNNER_EXISTS="WORKER_RUNNER_EXISTS",e.WORKER_RUNNER_CREATION_FAILURE="WORKER_RUNNER_CREATION_FAILURE",e.WORKER_RUNNER_MISSING="WORKER_RUNNER_MISSING",e.WORKER_RUNNER_RECONFIGURE_FAILURE="WORKER_RUNNER_RECONFIGURE_FAILURE",e.WORKER_RUNNER_DELETED="WORKER_RUNNER_DELETED",e.WORKER_RUNNER_DELETE_FAILURE="WORKER_RUNNER_DELETE_FAILURE",e.WORKER_OBJECT_INVOKE_FAILURE="WORKER_OBJECT_INVOKE_FAILURE",e.WORKER_IMAGE_PROCESS_FAILURE="WORKER_IMAGE_PROCESS_FAILURE",e.WORKER_HANDLE_UNDEFINED="WORKER_HANDLE_UNDEFINED",e.WORKER_MESSAGE_ACTION_UNKNOWN="WORKER_MESSAGE_ACTION_UNKNOWN",e.WORKER_LICENSE_UNLOCK_ERROR="WORKER_LICENSE_UNLOCK_ERROR",e.WORKER_INTEGRATION_INFO_FAILURE="WORKER_INTEGRATION_INFO_FAILURE",e.LOCAL_SDK_RUNNER_MISSING="LOCAL_SDK_RUNNER_MISSING",e.LOCAL_SDK_RUNNER_EMPTY="LOCAL_SDK_RUNNER_EMPTY",e.LICENSE_UNLOCK_ERROR="LICENSE_UNLOCK_ERROR",e.FRAME_CAPTURE_SVG_UNSUPPORTED="FRAME_CAPTURE_SVG_UNSUPPORTED",e.FRAME_CAPTURE_CANVAS_MISSING="FRAME_CAPTURE_CANVAS_MISSING",e.SDK_WASM_SETTINGS_MISSING="SDK_WASM_SETTINGS_MISSING",e.SDK_LICENSE_KEY_MISSING="SDK_LICENSE_KEY_MISSING",e.SDK_WASM_MODULE_NAME_MISSING="SDK_WASM_MODULE_NAME_MISSING",e.SDK_ENGINE_LOCATION_INVALID="SDK_ENGINE_LOCATION_INVALID",e.SDK_MISSING="SDK_MISSING",e.SDK_RECOGNIZERS_MISSING="SDK_RECOGNIZERS_MISSING",e.VIDEO_RECOGNIZER_ELEMENT_MISSING="VIDEO_RECOGNIZER_ELEMENT_MISSING",e.VIDEO_RECOGNIZER_CAMERA_MISSING="VIDEO_RECOGNIZER_CAMERA_MISSING",e.VIDEO_RECOGNIZER_CAMERA_NOT_ALLOWED="VIDEO_RECOGNIZER_CAMERA_NOT_ALLOWED",e.VIDEO_RECOGNIZER_CAMERA_UNAVAILABLE="VIDEO_RECOGNIZER_CAMERA_UNAVAILABLE",e.VIDEO_RECOGNIZER_CAMERA_IN_USE="VIDEO_RECOGNIZER_CAMERA_IN_USE",e.VIDEO_RECOGNIZER_MEDIA_DEVICES_UNSUPPORTED="VIDEO_RECOGNIZER_MEDIA_DEVICES_UNSUPPORTED",e.VIDEO_RECOGNIZER_FEED_RELEASED="VIDEO_RECOGNIZER_FEED_RELEASED",e.VIDEO_RECOGNIZER_FEED_NOT_PAUSED="VIDEO_RECOGNIZER_FEED_NOT_PAUSED",e.VIDEO_RECOGNIZER_PLAY_REQUEST_INTERRUPTED="VIDEO_RECOGNIZER_PLAY_REQUEST_INTERRUPTED",e.VIDEO_RECOGNIZER_FEED_PAUSED="VIDEO_RECOGNIZER_FEED_PAUSED",e.VIDEO_RECOGNIZER_RECOGNIZERS_RESET_FAILURE="VIDEO_RECOGNIZER_RECOGNIZERS_RESET_FAILURE",e.VIDEO_RECOGNIZER_FEED_MISSING="VIDEO_RECOGNIZER_FEED_MISSING"}(L||(L={})),function(e){e.WORKER_HANDLE_UNDEFINED="Cannot find object with handle: undefined",e.WORKER_WASM_LOAD_FAILURE="Failed to load WASM in web worker!",e.WORKER_WASM_INIT_MISSING="WASM module is not initialized!",e.WORKER_FUNCTION_INVOKE_FAILURE="Failed to invoke function!",e.WORKER_RECOGNIZER_CREATION_FAILURE="Failed to create new recognizer!",e.WORKER_RUNNER_EXISTS="Recognizer runner is already created! Multiple instances are not allowed!",e.WORKER_RUNNER_CREATION_FAILURE="Failed to create new recognizer runner!",e.WORKER_RUNNER_MISSING="Recognizer runner is not created! There is nothing to reconfigure!",e.WORKER_RUNNER_RECONFIGURE_FAILURE="Failed to reconfigure recognizer runner!",e.WORKER_RUNNER_DELETED="Recognizer runner is already deleted!",e.WORKER_RUNNER_DELETE_FAILURE="Failed to delete recognizer runner!",e.WORKER_OBJECT_INVOKE_FAILURE="Failed to invoke object!",e.WORKER_IMAGE_PROCESS_FAILURE="Recognizer runner is not initialized! Cannot process image!",e.WORKER_INTEGRATION_INFO_FAILURE="Failed to get product integration info!",e.LOCAL_SDK_RUNNER_MISSING="Property nativeRecognizerRunner is not available!",e.LOCAL_SDK_RUNNER_EMPTY="Native RecognizerRunner cannot be empty!",e.LICENSE_TOKEN_STATE_INCORRECT="Internal error (Incorrect token state)",e.LICENSE_PAYLOAD_VERIFICATION_FAILED="Failed to verify server permission's digital signature!",e.LICENSE_PAYLOAD_CORRUPTED="Server permission payload is corrupted!",e.LICENSE_PERMISSION_EXPIRED="Internal error (server permission expired)",e.LICENSE_REMOTE_LOCKED="Provided license key has been remotely locked. Please contact support for more information!",e.FRAME_CAPTURE_SVG_UNSUPPORTED="Recognition of SVG elements not supported!",e.FRAME_CAPTURE_CANVAS_MISSING="Could not get canvas 2d context!",e.SDK_WASM_SETTINGS_MISSING="Missing WASM load settings!",e.SDK_LICENSE_KEY_MISSING="Missing license key!",e.SDK_WASM_MODULE_NAME_MISSING="Missing WASM module name!",e.SDK_ENGINE_LOCATION_INVALID="Setting property 'engineLocation' must be a string!",e.SDK_MISSING="SDK is not provided!",e.SDK_RECOGNIZERS_MISSING="To create RecognizerRunner at least 1 recognizer is required.",e.VIDEO_RECOGNIZER_ELEMENT_MISSING="Video element, i.e. camera feed is not provided!",e.VIDEO_RECOGNIZER_CAMERA_MISSING="Camera not found!",e.VIDEO_RECOGNIZER_CAMERA_NOT_ALLOWED="Camera not allowed!",e.VIDEO_RECOGNIZER_CAMERA_UNAVAILABLE="Camera not available!",e.VIDEO_RECOGNIZER_CAMERA_IN_USE="Camera in use!",e.VIDEO_RECOGNIZER_MEDIA_DEVICES_UNSUPPORTED="Media devices not supported by browser.",e.VIDEO_RECOGNIZER_FEED_RELEASED="The associated video feed has been released!",e.VIDEO_RECOGNIZER_FEED_NOT_PAUSED="The associated video feed is not paused. Use resumeRecognition instead!",e.VIDEO_RECOGNIZER_PLAY_REQUEST_INTERRUPTED="The play() request was interrupted or prevented by browser security rules!",e.VIDEO_RECOGNIZER_FEED_PAUSED="Cannot resume recognition while video feed is paused! Use recognize or startRecognition",e.VIDEO_RECOGNIZER_RECOGNIZERS_RESET_FAILURE="Could not reset recognizers!",e.VIDEO_RECOGNIZER_FEED_MISSING="Missing video feed!"}(w||(w={}));const F={licenseTokenStateIncorrect:{code:L.LICENSE_UNLOCK_ERROR,message:w.LICENSE_TOKEN_STATE_INCORRECT},licensePayloadVerificationFailed:{code:L.LICENSE_UNLOCK_ERROR,message:w.LICENSE_PAYLOAD_VERIFICATION_FAILED},licensePayloadCorrupted:{code:L.LICENSE_UNLOCK_ERROR,message:w.LICENSE_PAYLOAD_CORRUPTED},licensePermissionExpired:{code:L.LICENSE_UNLOCK_ERROR,message:w.LICENSE_PERMISSION_EXPIRED},licenseRemoteLocked:{code:L.LICENSE_UNLOCK_ERROR,message:w.LICENSE_REMOTE_LOCKED},licenseNetworkError:{code:L.LICENSE_UNLOCK_ERROR},licenseInvalid:{code:L.LICENSE_UNLOCK_ERROR}},b={imageProcessFailure:{message:w.WORKER_IMAGE_PROCESS_FAILURE,code:L.WORKER_IMAGE_PROCESS_FAILURE},objectInvokeFailure:{message:w.WORKER_OBJECT_INVOKE_FAILURE,code:L.WORKER_OBJECT_INVOKE_FAILURE},runnerDeleteFailure:{message:w.WORKER_RUNNER_DELETE_FAILURE,code:L.WORKER_RUNNER_DELETE_FAILURE},runnerDeleted:{message:w.WORKER_RUNNER_DELETED,code:L.WORKER_RUNNER_DELETED},runnerReconfigureFailure:{message:w.WORKER_RUNNER_RECONFIGURE_FAILURE,code:L.WORKER_RUNNER_RECONFIGURE_FAILURE},runnerMissing:{message:w.WORKER_RUNNER_MISSING,code:L.WORKER_RUNNER_MISSING},runnerCreationFailure:{message:w.WORKER_RUNNER_CREATION_FAILURE,code:L.WORKER_RUNNER_CREATION_FAILURE},runnerExists:{message:w.WORKER_RUNNER_EXISTS,code:L.WORKER_RUNNER_EXISTS},recognizerCreationFailure:{message:w.WORKER_RECOGNIZER_CREATION_FAILURE,code:L.WORKER_RECOGNIZER_CREATION_FAILURE},functionInvokeFailure:{message:w.WORKER_FUNCTION_INVOKE_FAILURE,code:L.WORKER_FUNCTION_INVOKE_FAILURE},wasmInitMissing:{message:w.WORKER_WASM_INIT_MISSING,code:L.WORKER_WASM_INIT_MISSING},wasmLoadFailure:{message:w.WORKER_WASM_LOAD_FAILURE,code:L.WORKER_WASM_LOAD_FAILURE},handleUndefined:{message:w.WORKER_HANDLE_UNDEFINED,code:L.WORKER_HANDLE_UNDEFINED},integrationInfoFailure:{message:w.WORKER_INTEGRATION_INFO_FAILURE,code:L.WORKER_INTEGRATION_INFO_FAILURE}};var k,K;!function(e){e[e.Invalid=0]="Invalid",e[e.RequiresServerPermission=1]="RequiresServerPermission",e[e.Valid=2]="Valid"}(k||(k={})),function(e){e.LicenseTokenStateInvalid="LICENSE_TOKEN_STATE_INVALID",e.NetworkError="NETWORK_ERROR",e.RemoteLock="REMOTE_LOCK",e.PermissionExpired="PERMISSION_EXPIRED",e.PayloadCorrupted="PAYLOAD_CORRUPTED",e.PayloadSignatureVerificationFailed="PAYLOAD_SIGNATURE_VERIFICATION_FAILED",e.IncorrectTokenState="INCORRECT_TOKEN_STATE"}(K||(K={}));function v(e){return{licenseId:e.licenseId,licensee:e.licensee,packageName:e.packageName,platform:"Browser",sdkName:e.sdkName,sdkVersion:e.sdkVersion}}var P;function W(t,s){return e(this,void 0,void 0,(function*(){try{const e=yield fetch("https://baltazar.microblink.com/api/v1/status/check",{method:"POST",headers:{"Content-Type":"application/json"},cache:"no-cache",body:JSON.stringify(v(t))});if(e.ok){const t=""+(yield e.text());return s.submitServerPermission(t)}return{status:P.NetworkError,lease:0,networkErrorDescription:"Server responded with status "+e.status}}catch(e){return{status:P.NetworkError,lease:0,networkErrorDescription:"Unexpected error: "+JSON.stringify(e)}}}))}function G(e){return e===p.AdvancedWithThreads}!function(e){e[e.Ok=0]="Ok",e[e.NetworkError=1]="NetworkError",e[e.RemoteLock=2]="RemoteLock",e[e.PermissionExpired=3]="PermissionExpired",e[e.PayloadCorrupted=4]="PayloadCorrupted",e[e.PayloadSignatureVerificationFailed=5]="PayloadSignatureVerificationFailed",e[e.IncorrectTokenState=6]="IncorrectTokenState"}(P||(P={}));new class{constructor(){this.context=self,this.wasmModule=null,this.nativeRecognizerRunner=null,this.objects={},this.nextObjectHandle=0,this.metadataCallbacks={},this.clearTimeoutCallback=null,this.context.onmessage=e=>{const t=e.data;switch(t.action){case n.action:this.processInitMessage(t);break;case o.action:this.processInvokeFunction(t);break;case a.action:this.processCreateNewRecognizer(t);break;case l.action:this.processInvokeObject(t);break;case c.action:this.processCreateRecognizerRunner(t);break;case E.action:this.processReconfigureRecognizerRunner(t);break;case R.action:this.processDeleteRecognizerRunner(t);break;case _.action:this.processImage(t);break;case u.action:this.resetRecognizers(t);break;case d.action:this.setDetectionOnly(t);break;case O.action:this.setCameraPreviewMirrored(t);break;case I.action:this.registerMetadataCallbacks(t);break;case N.action:this.registerClearTimeoutCallback(t);break;case h.action:this.processGetProductIntegrationInfo(t);break;default:throw new U({code:L.WORKER_MESSAGE_ACTION_UNKNOWN,message:"Unknown message action: "+JSON.stringify(t.action)})}}}getNextObjectHandle(){const e=this.nextObjectHandle;return this.nextObjectHandle=this.nextObjectHandle+1,e}notifyError(e,t){this.context.postMessage(new S(e.messageID,!1,t))}notifySuccess(e){this.context.postMessage(new S(e.messageID,!0,null))}notifyInitSuccess(e,t,s){this.context.postMessage(new g(e.messageID,!0,t,s))}unwrapParameters(e){const t=[];for(const s of e.params){let n=s.parameter;s.type===r.Recognizer?(n=this.objects[n],void 0===n&&this.notifyError(e,new U(b.handleUndefined))):s.type===r.RecognizerSettings&&(n=this.restoreFunctions(n)),t.push(n)}return t}restoreFunctions(e){const t=Object.keys(e);for(const s of t){const t=e[s];"object"==typeof t&&null!==t&&"parameter"in t&&"type"in t&&t.type===r.Callback&&(e[s]=(...e)=>{const s=new M(i.recognizerCallback,[t.parameter].concat(e));this.context.postMessage(s)})}return e}scanForTransferrables(e){if("object"==typeof e){const t=Object.keys(e),s=[];for(const n of t){const t=e[n];t instanceof ImageData?s.push(t.data.buffer):t instanceof Uint8Array?s.push(t.buffer):null!==t&&"object"==typeof t&&s.push(...this.scanForTransferrables(t))}return s}return[]}registerHeartBeat(e){this.unregisterHeartBeat(),this.lease=e;let t=e-Math.floor(Date.now()/1e3);t>120?t-=120:t/=2,this.inFlightHeartBeatTimeoutId=setTimeout((()=>{this.obtainNewServerPermission(!0)}),1e3*t)}unregisterHeartBeat(){this.lease&&delete this.lease,this.inFlightHeartBeatTimeoutId&&(clearTimeout(this.inFlightHeartBeatTimeoutId),delete this.inFlightHeartBeatTimeoutId)}obtainNewServerPermission(t){return e(this,void 0,void 0,(function*(){if(this.wasmModule){const e=this.wasmModule.getActiveLicenseTokenInfo(),s=yield W(e,this.wasmModule);switch(s.status){case P.Ok:case P.RemoteLock:this.registerHeartBeat(s.lease);break;case P.NetworkError:case P.PayloadSignatureVerificationFailed:case P.PayloadCorrupted:t?(console.warn("Problem with obtaining server permission. Will attempt in 10 seconds "+P[s.status]),this.inFlightHeartBeatTimeoutId=setTimeout((()=>{this.obtainNewServerPermission(!1)}),1e4)):console.error("Problem with obtaining server permission. "+P[s.status]);break;case P.IncorrectTokenState:case P.PermissionExpired:console.error("Internal error: "+P[s.status])}return s.status}return console.error("Internal inconsistency! Wasm module not initialized where it's expected to be!"),P.IncorrectTokenState}))}willSoonExpire(){if(this.lease){if(this.wasmModule.getActiveLicenseTokenInfo().unlockResult===k.Valid){const e=Math.floor(Date.now()/1e3);return 30>this.lease-e}return!0}return!1}calculateWasmType(t){return e(this,void 0,void 0,(function*(){return null!==t.wasmType?t.wasmType:yield y(t.engineLocation)}))}calculateEngineLocationPrefix(e,t){const s=T(""===e.engineLocation?self.location.origin:e.engineLocation,function(e){switch(e){case p.AdvancedWithThreads:return"advanced-threads";case p.Advanced:return"advanced";case p.Basic:return"basic"}}(t));return e.allowHelloMessage&&console.log("Engine location prefix is:",s),s}processInitMessage(t){return e(this,void 0,void 0,(function*(){const s=yield this.calculateWasmType(t),n=this.calculateEngineLocationPrefix(t,s);let r={locateFile:e=>T(n,e)};t.registerLoadCallback&&(r=Object.assign(r,{setStatus:e=>{const t=new f(function(e){if("Running..."===e)return 100;if(0===e.length)return 0;const t=/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/.exec(e);if(t)return 100*parseInt(t[2])/parseInt(t[4]);return NaN}(e));this.context.postMessage(t)}}));try{const i=T(n,t.wasmModuleName+".js");G(s)&&(r=function(e,t,s){return t&&t>0&&(e=Object.assign(e,{allowedThreads:t})),null!==s&&(e=Object.assign(e,{mainScriptUrlOrBlob:s})),e}(r,t.numberOfWorkers,i)),importScripts(i);(0,self[t.wasmModuleName])(r).then((n=>e(this,void 0,void 0,(function*(){G(s)&&(t.allowHelloMessage&&console.log("Waiting for thread workers to boot..."),yield function(t){return e(this,void 0,void 0,(function*(){t.threadWorkersReadyPromise&&(yield t.threadWorkersReadyPromise)}))}(n));const r=yield function(t,s,n,r){return e(this,void 0,void 0,(function*(){const e=r.initializeWithLicenseKey(t,n,s);switch(e.unlockResult){case k.Invalid:return{error:new U(Object.assign(Object.assign({},F.licenseInvalid),{message:e.licenseError}),{type:K.LicenseTokenStateInvalid})};case k.Valid:return{error:null,showOverlay:(i=e.isTrial,o=e.allowRemoveDemoOverlay,a=e.allowRemoveProductionOverlay,!(i&&o||!i&&a))};case k.RequiresServerPermission:{const t=yield W(e,r);switch(t.status){case P.Ok:return{error:null,lease:t.lease};case P.NetworkError:{let e="";return t.networkErrorDescription&&(e=" "+t.networkErrorDescription),{error:new U(Object.assign(Object.assign({},F.licenseNetworkError),{message:"There has been a network error while obtaining the server permission!"+e}),{type:K.NetworkError})}}case P.RemoteLock:return{error:new U(F.licenseRemoteLocked,{type:K.RemoteLock}),lease:t.lease};case P.PermissionExpired:return{error:new U(F.licensePermissionExpired,{type:K.PermissionExpired}),lease:t.lease};case P.PayloadCorrupted:return{error:new U(F.licensePayloadCorrupted,{type:K.PayloadCorrupted}),lease:t.lease};case P.PayloadSignatureVerificationFailed:return{error:new U(F.licensePayloadVerificationFailed,{type:K.PayloadSignatureVerificationFailed}),lease:t.lease};case P.IncorrectTokenState:return{error:new U(F.licenseTokenStateIncorrect,{type:K.IncorrectTokenState}),lease:t.lease}}}}var i,o,a}))}(t.licenseKey,t.allowHelloMessage,t.userId,n);null===r.error?(this.wasmModule=n,r.lease?this.registerHeartBeat(r.lease):this.unregisterHeartBeat(),this.notifyInitSuccess(t,!!r.showOverlay,s)):this.notifyError(t,r.error)}))),(e=>{this.notifyError(t,new U(b.wasmLoadFailure,e))}))}catch(e){this.notifyError(t,new U(b.wasmLoadFailure,e))}}))}processInvokeFunction(e){if(null===this.wasmModule)return void this.notifyError(e,new U(b.wasmInitMissing));const t=e.funcName,s=this.unwrapParameters(e);try{const n=this.wasmModule[t](...s);this.context.postMessage(new C(e.messageID,n))}catch(t){this.notifyError(e,new U(b.functionInvokeFailure,t))}}processCreateNewRecognizer(e){if(null===this.wasmModule)return void this.notifyError(e,new U(b.wasmInitMissing));const t=e.className,s=this.unwrapParameters(e);try{const n=new this.wasmModule[t](...s),r=this.getNextObjectHandle();this.objects[r]=n,this.context.postMessage(new m(e.messageID,r))}catch(t){this.notifyError(e,new U(b.recognizerCreationFailure,t))}}getRecognizers(e){const t=[];for(const s of e){t.push(this.objects[s])}return t}processCreateRecognizerRunner(t){return e(this,void 0,void 0,(function*(){if(null===this.wasmModule)this.notifyError(t,new U(b.wasmInitMissing));else if(null!==this.nativeRecognizerRunner)this.notifyError(t,new U(b.runnerExists));else{this.setupMetadataCallbacks(t.registeredMetadataCallbacks);try{if(this.willSoonExpire()){const e=yield this.obtainNewServerPermission(!1);if(e!==P.Ok){const s=P[e];return void this.notifyError(t,new U({code:L.WORKER_LICENSE_UNLOCK_ERROR,message:"Cannot initialize recognizers because of invalid server permission: \n "+s},{type:K[s]}))}}const e=this.getRecognizers(t.recognizerHandles);this.nativeRecognizerRunner=new this.wasmModule.RecognizerRunner(e,t.allowMultipleResults,this.metadataCallbacks),this.notifySuccess(t)}catch(e){this.notifyError(t,new U(b.runnerCreationFailure,e))}}}))}processReconfigureRecognizerRunner(e){if(null===this.wasmModule)this.notifyError(e,new U(b.wasmInitMissing));else if(null===this.nativeRecognizerRunner)this.notifyError(e,new U(b.runnerMissing));else try{const t=this.getRecognizers(e.recognizerHandles);this.nativeRecognizerRunner.reconfigureRecognizers(t,e.allowMultipleResults),this.notifySuccess(e)}catch(t){this.notifyError(e,new U(b.runnerReconfigureFailure,t))}}processDeleteRecognizerRunner(e){if(null!==this.nativeRecognizerRunner)try{this.nativeRecognizerRunner.delete(),this.nativeRecognizerRunner=null,this.notifySuccess(e)}catch(t){this.notifyError(e,new U(b.runnerDeleteFailure,t))}else this.notifyError(e,new U(b.runnerDeleted))}wrapFunctions(e,t){if("object"!=typeof e)return e;const s=Object.assign({},e),n=Object.keys(s);for(const e of n){if("function"==typeof s[e]){s[e]={parameter:{recognizerHandle:t,callbackName:e},type:r.Callback}}}return s}processInvokeObject(e){try{const t=e.objectHandle,s=e.methodName,n=this.unwrapParameters(e),r=this.objects[t];if(void 0===r)this.notifyError(e,new U({message:"Cannot find object with handle: "+t,code:L.WORKER_HANDLE_UNDEFINED}));else{const i=this.wrapFunctions(r[s](...n),t),o=this.scanForTransferrables(i);"delete"===s&&delete this.objects[t],this.context.postMessage(new C(e.messageID,i),o)}}catch(t){this.notifyError(e,new U(b.objectInvokeFailure,t))}}processImage(e){if(null!==this.nativeRecognizerRunner)try{const t=this.nativeRecognizerRunner.processImage(e.frame);this.context.postMessage(new A(e.messageID,t))}catch(t){this.notifyError(e,new U(b.imageProcessFailure,t))}else this.notifyError(e,new U(b.imageProcessFailure))}resetRecognizers(e){if(null!==this.nativeRecognizerRunner)try{this.nativeRecognizerRunner.resetRecognizers(e.hardReset),this.notifySuccess(e)}catch(t){this.notifyError(e,new U(b.imageProcessFailure,t))}else this.notifyError(e,new U(b.imageProcessFailure))}setDetectionOnly(e){if(null!==this.nativeRecognizerRunner)try{this.nativeRecognizerRunner.setDetectionOnlyMode(e.detectionOnlyMode),this.notifySuccess(e)}catch(t){this.notifyError(e,new U(b.imageProcessFailure,t))}else this.notifyError(e,new U(b.imageProcessFailure))}setCameraPreviewMirrored(e){if(null!==this.nativeRecognizerRunner)try{this.nativeRecognizerRunner.setCameraPreviewMirrored(e.cameraPreviewMirrored),this.notifySuccess(e)}catch(t){this.notifyError(e,new U(b.imageProcessFailure,t))}else this.notifyError(e,new U(b.imageProcessFailure))}setupMetadataCallbacks(e){e.onDebugText?this.metadataCallbacks.onDebugText=e=>{const t=new M(i.onDebugText,[e]);this.context.postMessage(t)}:delete this.metadataCallbacks.onDebugText,e.onDetectionFailed?this.metadataCallbacks.onDetectionFailed=()=>{const e=new M(i.onDetectionFailed,[]);this.context.postMessage(e)}:delete this.metadataCallbacks.onDetectionFailed,e.onPointsDetection?this.metadataCallbacks.onPointsDetection=e=>{const t=new M(i.onPointsDetection,[e]);this.context.postMessage(t)}:delete this.metadataCallbacks.onPointsDetection,e.onQuadDetection?this.metadataCallbacks.onQuadDetection=e=>{const t=new M(i.onQuadDetection,[e]);this.context.postMessage(t)}:delete this.metadataCallbacks.onQuadDetection,e.onFirstSideResult?this.metadataCallbacks.onFirstSideResult=()=>{const e=new M(i.onFirstSideResult,[]);this.context.postMessage(e)}:delete this.metadataCallbacks.onFirstSideResult,e.onGlare?this.metadataCallbacks.onGlare=e=>{const t=new M(i.onGlare,[e]);this.context.postMessage(t)}:delete this.metadataCallbacks.onGlare}registerMetadataCallbacks(e){if(null!==this.nativeRecognizerRunner){this.setupMetadataCallbacks(e.registeredMetadataCallbacks);try{this.nativeRecognizerRunner.setJSDelegate(this.metadataCallbacks),this.notifySuccess(e)}catch(t){this.notifyError(e,new U(b.imageProcessFailure,t))}}else this.notifyError(e,new U(b.imageProcessFailure))}registerClearTimeoutCallback(e){if(null!==this.nativeRecognizerRunner){this.clearTimeoutCallback=e.callbackNonEmpty?{onClearTimeout:()=>{const e=new M(i.clearTimeoutCallback,[]);this.context.postMessage(e)}}:null;try{this.nativeRecognizerRunner.setClearTimeoutCallback(this.clearTimeoutCallback),this.notifySuccess(e)}catch(t){this.notifyError(e,new U(b.imageProcessFailure,t))}}else this.notifyError(e,new U(b.imageProcessFailure))}processGetProductIntegrationInfo(e){if(null!==this.wasmModule)try{const t=this.wasmModule.getActiveLicenseTokenInfo(),s={userId:e.userId,licenseId:t.licenseId,licensee:t.licensee,productName:t.sdkName,productVersion:t.sdkVersion,platform:"Browser",device:self.navigator.userAgent,packageName:t.packageName};this.context.postMessage(new D(e.messageID,s))}catch(t){this.notifyError(e,new U(b.objectInvokeFailure,t))}else this.notifyError(e,new U(b.wasmInitMissing))}}}();
2225`], { type: "application/javascript" });
2226 const url = URL.createObjectURL(blob);
2227 const worker = new Worker(url);
2228 WasmSDKWorker.createWasmWorker(worker, loadSettings, userId).then(wasmSDK => {
2229 resolve(wasmSDK);
2230 }, reject);
2231 }
2232 catch (initError) {
2233 reject(initError);
2234 }
2235 });
2236 });
2237}
2238/* eslint-enable @typescript-eslint/no-explicit-any,
2239 @typescript-eslint/no-unsafe-assignment,
2240 @typescript-eslint/no-unsafe-member-access,
2241 @typescript-eslint/no-unsafe-call */
2242/**
2243 * Function for creating a new RecognizerRunner.
2244 * Note that it is currently not possible to have multiple instances of RecognizerRunner per instance of WasmSDK.
2245 * Attempt to create new instance of RecognizerRunner prior deleting the previous one will fail.
2246 * @param wasmSDK Instance of WasmSDK which will be used to communicate with the WebAssembly module.
2247 * @param recognizers Array of recognizers that will be used by RecognizerRunner.
2248 * @param allowMultipleResults Whether or not it is allowed to return multiple results from single recognition session.
2249 * See README.md for more information.
2250 * @param metadataCallbacks
2251 */
2252function createRecognizerRunner(wasmSDK, recognizers, allowMultipleResults = false, metadataCallbacks = {}) {
2253 return __awaiter(this, void 0, void 0, function* () {
2254 if (typeof wasmSDK !== "object") {
2255 throw new SDKError(sdkErrors.missing);
2256 }
2257 if (typeof recognizers !== "object" || recognizers.length < 1) {
2258 throw new SDKError(sdkErrors.recognizersMissing);
2259 }
2260 return wasmSDK.mbWasmModule.createRecognizerRunner(recognizers, allowMultipleResults, metadataCallbacks);
2261 });
2262}
2263
2264/**
2265 * Copyright (c) Microblink Ltd. All rights reserved.
2266 */
2267/**
2268 * Creates a new instance of `SuccessFrameGrabberRecognizer`.
2269 * @param wasmSDK Instance of WasmSDK which will be used to communicate with the
2270 * WebAssembly module.
2271 * @param slaveRecognizer Instance of Recognizer that will be wrapped.
2272 */
2273function createSuccessFrameGrabberRecognizer(wasmSDK, slaveRecognizer) {
2274 return __awaiter(this, void 0, void 0, function* () {
2275 // taken from https://stackoverflow.com/a/53615996
2276 const sfgr = yield wasmSDK.mbWasmModule.newRecognizer("SuccessFrameGrabberRecognizer", slaveRecognizer);
2277 const mutableSFGR = sfgr;
2278 mutableSFGR.wrappedRecognizer = slaveRecognizer;
2279 return sfgr;
2280 });
2281}
2282
2283/**
2284 * Copyright (c) Microblink Ltd. All rights reserved.
2285 */
2286(function (BarcodeFormat) {
2287 /** Indicates that no barcode has been detected. */
2288 BarcodeFormat[BarcodeFormat["NONE"] = 0] = "NONE";
2289 /** Indicates that QR code has been detected. */
2290 BarcodeFormat[BarcodeFormat["QR_CODE"] = 1] = "QR_CODE";
2291 /** Indicates that Data Matrix 2D barcode has been detected. */
2292 BarcodeFormat[BarcodeFormat["DATA_MATRIX"] = 2] = "DATA_MATRIX";
2293 /** Indicates that UPC E 1D barcode has been detected. */
2294 BarcodeFormat[BarcodeFormat["UPC_E"] = 3] = "UPC_E";
2295 /** Indicates that UPC A 1D barcode has been detected. */
2296 BarcodeFormat[BarcodeFormat["UPC_A"] = 4] = "UPC_A";
2297 /** Indicates that EAN 8 1D barcode has been detected. */
2298 BarcodeFormat[BarcodeFormat["EAN_8"] = 5] = "EAN_8";
2299 /** Indicates that EAN 13 1D barcode has been detected. */
2300 BarcodeFormat[BarcodeFormat["EAN_13"] = 6] = "EAN_13";
2301 /** Indicates that Code 128 1D barcode has been detected. */
2302 BarcodeFormat[BarcodeFormat["CODE_128"] = 7] = "CODE_128";
2303 /** Indicates that Code 39 1D barcode has been detected. */
2304 BarcodeFormat[BarcodeFormat["CODE_39"] = 8] = "CODE_39";
2305 /** Indicates that ITF 1D barcode has been detected. */
2306 BarcodeFormat[BarcodeFormat["ITF"] = 9] = "ITF";
2307 /** Indicates that Aztec 2D barcode has been detected. */
2308 BarcodeFormat[BarcodeFormat["AZTEC_BARCODE"] = 10] = "AZTEC_BARCODE";
2309 /** Indicates that PDF417 2D barcode has been detected. */
2310 BarcodeFormat[BarcodeFormat["PDF417_BARCODE"] = 11] = "PDF417_BARCODE";
2311})(exports.BarcodeFormat || (exports.BarcodeFormat = {}));
2312
2313/**
2314 * Copyright (c) Microblink Ltd. All rights reserved.
2315 */
2316(function (AnonymizationMode) {
2317 /**
2318 * Anonymization will not be performed.
2319 */
2320 AnonymizationMode[AnonymizationMode["None"] = 0] = "None";
2321 /**
2322 * FullDocumentImage is anonymized with black boxes
2323 * covering sensitive data.
2324 */
2325 AnonymizationMode[AnonymizationMode["ImageOnly"] = 1] = "ImageOnly";
2326 /**
2327 * Result fields containing sensitive data are removed from result.
2328 */
2329 AnonymizationMode[AnonymizationMode["ResultFieldsOnly"] = 2] = "ResultFieldsOnly";
2330 /**
2331 * This mode is combination of ImageOnly and ResultFieldsOnly modes.
2332 */
2333 AnonymizationMode[AnonymizationMode["FullResult"] = 3] = "FullResult";
2334})(exports.AnonymizationMode || (exports.AnonymizationMode = {}));
2335
2336/**
2337 * Copyright (c) Microblink Ltd. All rights reserved.
2338 *
2339 * RecognitionModeFilter is used to enable/disable recognition of specific document groups.
2340 * Setting is taken into account only if the right for that document is purchased.
2341 */
2342class RecognitionModeFilter {
2343 constructor() {
2344 /** Enable scanning of MRZ IDs. Setting is taken into account only if the mrz_id right is purchased. */
2345 this.enableMrzId = true;
2346 /** Enable scanning of Passport MRZ. Setting is taken into account only if the passport right is purchased. */
2347 this.enableMrzPassport = true;
2348 /** Enable scanning of visa MRZ. Setting is taken into account only if the visa right is purchased. */
2349 this.enableMrzVisa = true;
2350 /** Enable scanning of Photo ID. Setting is taken into account only if the photo_id right is purchased. */
2351 this.enablePhotoId = true;
2352 /**
2353 * Enable scanning of barcode IDs. Setting is taken into account only if the barcode right to
2354 * scan that barcode is purchased.
2355 */
2356 this.enableBarcodeId = true;
2357 /**
2358 * Enable full document recognition. Setting is taken into account only if the document right to
2359 * scan that document is purchased.
2360 */
2361 this.enableFullDocumentRecognition = true;
2362 }
2363}
2364
2365/**
2366 * Copyright (c) Microblink Ltd. All rights reserved.
2367 */
2368/**
2369 * Extension factors relative to corresponding dimension of the full image. For example,
2370 * {@code upFactor} and {@code downFactor} define extensions relative to image height, e.g.
2371 * when {@code upFactor} is 0.5, upper image boundary will be extended for half of image's full
2372 * height.
2373 *
2374 * ._______________________________________.
2375 * | ↑ |
2376 * | upFactor |
2377 * .________. | .________. |
2378 * | | --> | ⃖ leftFactor | | rightFactor ⃗ |
2379 * |________| | |________| |
2380 * | ↓ |
2381 * | downFactor |
2382 * |_______________________________________|
2383 *
2384 */
2385class ExtensionFactors {
2386 /**
2387 * Constructor which accepts image extension factors which must be in range [-1.0f, 1.0f].
2388 * @param upFactor image extension factor relative to full image height in UP direction
2389 * @param downFactor image extension factor relative to full image height in DOWN direction
2390 * @param leftFactor image extension factor relative to full image width in LEFT direction
2391 * @param rightFactor image extension factor relative to full image width in RIGHT direction
2392 */
2393 constructor(upFactor = 0.0, downFactor = 0.0, leftFactor = 0.0, rightFactor = 0.0) {
2394 /**
2395 * Currently used image extension factor relative to full image height in UP direction.
2396 */
2397 this.upFactor = 0.0;
2398 /**
2399 * Currently used image extension factor relative to full image height in DOWN direction.
2400 */
2401 this.downFactor = 0.0;
2402 /**
2403 * Currently used image extension factor relative to full image height in LEFT direction.
2404 */
2405 this.leftFactor = 0.0;
2406 /**
2407 * Currently used image extension factor relative to full image height in RIGHT direction.
2408 */
2409 this.rightFactor = 0.0;
2410 this.checkExtensionFactor(upFactor);
2411 this.checkExtensionFactor(downFactor);
2412 this.checkExtensionFactor(leftFactor);
2413 this.checkExtensionFactor(rightFactor);
2414 this.upFactor = upFactor;
2415 this.downFactor = downFactor;
2416 this.leftFactor = leftFactor;
2417 this.rightFactor = rightFactor;
2418 }
2419 checkExtensionFactor(factor) {
2420 if (factor > 1.0 || factor < -1.0) {
2421 throw new Error("Extension factor must be in range [-1.0, 1.0]");
2422 }
2423 }
2424}
2425function validateDpi(dpi) {
2426 if (dpi < 100 || dpi > 400) {
2427 throw new Error("DPI must be from interval [100, 400]");
2428 }
2429}
2430
2431/**
2432 * Copyright (c) Microblink Ltd. All rights reserved.
2433 */
2434(function (BarcodeElementKey) {
2435 // ==============================================================/
2436 // ============== 1. DETERMINING BARCODE VERSION ================/
2437 // ==============================================================/
2438 /**
2439 Mandatory on all driver's licenses. All barcodes which are using 3-track magnetic
2440 stripe encoding used in the interest of smoothing a transition from legacy documents
2441 shall be designated as "Magnetic". All barcodes which are using compact encoding
2442 compliant with ISO/IEC 18013-2 shall be designated as "Compact". All barcodes (majority)
2443 compliant with Mandatory PDF417 Bar Code of the American Association of Motor Vehicle
2444 Administrators (AAMVA) Card Design Standard from AAMVA DL/ID-2000 standard to DL/ID-2013
2445 shall be designated as "AAMVA".
2446 */
2447 BarcodeElementKey[BarcodeElementKey["DocumentType"] = 0] = "DocumentType";
2448 /**
2449 Mandatory on all driver's licenses.
2450
2451 AAMVA Version Number: This is a decimal value between 0 and 99 that
2452 specifies the version level of the PDF417 bar code format. Version "0" and "00"
2453 is reserved for bar codes printed to the specification of the American Association
2454 of Motor Vehicle Administrators (AAMVA) prior to the adoption of the AAMVA DL/ID-2000
2455 standard.
2456
2457 - All barcodes compliant with AAMVA DL/ID-2000 standard shall be designated Version "01."
2458 - All barcodes compliant with AAMVA Card Design Specification version 1.0, dated 09-2003
2459 shall be designated Version "02."
2460 - All barcodes compliant with AAMVA Card Design Specification version 2.0, dated 03-2005
2461 shall be designated Version "03."
2462 - All barcodes compliant with AAMVA Card Design Standard version 1.0, dated 07-2009
2463 shall be designated Version "04."
2464 - All barcodes compliant with AAMVA Card Design Standard version 1.0, dated 07-2010
2465 shall be designated Version "05."
2466 - All barcodes compliant with AAMVA Card Design Standard version 1.0, dated 07-2011
2467 shall be designated Version "06".
2468 - All barcodes compliant with AAMVA Card Design Standard version 1.0, dated 06-2012
2469 shall be designated Version "07".
2470 - All barcodes compliant with this current AAMVA standard shall be designated "08".
2471
2472 Should a need arise requiring major revision to the format, this field provides the
2473 means to accommodate additional revision.
2474
2475 If the document type is not "AAMVA", this field defines the version number of the
2476 given document type's standard.
2477 */
2478 BarcodeElementKey[BarcodeElementKey["StandardVersionNumber"] = 1] = "StandardVersionNumber";
2479 // ==============================================================/
2480 // ========== 2. PERSONAL DATA KEYS ===========/
2481 // ==============================================================/
2482 /**
2483 Mandatory on all AAMVA, Magnetic and Compact barcodes.
2484
2485 Family name of the cardholder. (Family name is sometimes also called "last name" or "surname.")
2486 Collect full name for record, print as many characters as possible on portrait side of DL/ID.
2487 */
2488 BarcodeElementKey[BarcodeElementKey["CustomerFamilyName"] = 2] = "CustomerFamilyName";
2489 /**
2490 Mandatory on all AAMVA, Magnetic and Compact barcodes.
2491
2492 First name of the cardholder.
2493 */
2494 BarcodeElementKey[BarcodeElementKey["CustomerFirstName"] = 3] = "CustomerFirstName";
2495 /**
2496 Mandatory on all AAMVA, Magnetic and Compact barcodes.
2497
2498 Full name of the individual holding the Driver's License or ID.
2499
2500 The Name field contains up to four portions, separated with the "," delimiter:
2501 Last Name (required)
2502 , (required)
2503 First Name (required)
2504 , (required if other name portions follow, otherwise optional)
2505 Middle Name(s) (optional)
2506 , (required if other name portions follow, otherwise optional)
2507 Suffix (optional)
2508 , (optional)
2509
2510 If the individual has more than one middle name they are separated with space.
2511 */
2512 BarcodeElementKey[BarcodeElementKey["CustomerFullName"] = 4] = "CustomerFullName";
2513 /**
2514 Mandatory on all AAMVA, Magnetic and Compact barcodes.
2515
2516 Date on which the cardholder was born. (MMDDCCYY format)
2517 */
2518 BarcodeElementKey[BarcodeElementKey["DateOfBirth"] = 5] = "DateOfBirth";
2519 /**
2520 Mandatory on all AAMVA, Magnetic barcodes.
2521 Optional on Compact barcodes.
2522
2523 Gender of the cardholder. 1 = male, 2 = female.
2524 */
2525 BarcodeElementKey[BarcodeElementKey["Sex"] = 6] = "Sex";
2526 /**
2527 Mandatory on AAMVA 02, 03, 04, 05, 06, 07, 08 barcodes.
2528 Optional on AAMVA 01, Magnetic and Compact barcodes.
2529
2530 Color of cardholder's eyes. (ANSI D-20 codes)
2531
2532 Code Description
2533 BLK Black
2534 BLU Blue
2535 BRO Brown
2536 GRY Gray
2537 GRN Green
2538 HAZ Hazel
2539 MAR Maroon
2540 PNK Pink
2541 DIC Dichromatic
2542 UNK Unknown
2543 */
2544 BarcodeElementKey[BarcodeElementKey["EyeColor"] = 7] = "EyeColor";
2545 /**
2546 Mandatory on all AAMVA and Magnetic barcodes.
2547
2548 On compact barcodes, use kFullAddress.
2549
2550 Street portion of the cardholder address.
2551 The place where the registered driver of a vehicle (individual or corporation)
2552 may be contacted such as a house number, street address, etc.
2553 */
2554 BarcodeElementKey[BarcodeElementKey["AddressStreet"] = 8] = "AddressStreet";
2555 /**
2556 Mandatory on all AAMVA and Magnetic barcodes.
2557
2558 On compact barcodes, use kFullAddress.
2559
2560 City portion of the cardholder address.
2561 */
2562 BarcodeElementKey[BarcodeElementKey["AddressCity"] = 9] = "AddressCity";
2563 /**
2564 Mandatory on all AAMVA and Magnetic barcodes.
2565
2566 On compact barcodes, use kFullAddress.
2567
2568 State portion of the cardholder address.
2569 */
2570 BarcodeElementKey[BarcodeElementKey["AddressJurisdictionCode"] = 10] = "AddressJurisdictionCode";
2571 /**
2572 Mandatory on all AAMVA and Magnetic barcodes.
2573
2574 On compact barcodes, use FullAddress.
2575
2576 Postal code portion of the cardholder address in the U.S. and Canada. If the
2577 trailing portion of the postal code in the U.S. is not known, zeros can be used
2578 to fill the trailing set of numbers up to nine (9) digits.
2579 */
2580 BarcodeElementKey[BarcodeElementKey["AddressPostalCode"] = 11] = "AddressPostalCode";
2581 /**
2582 Mandatory on all AAMVA and Magnetic barcodes.
2583 Optional on Compact barcodes.
2584
2585 Full address of the individual holding the Driver's License or ID.
2586
2587 The full address field contains up to four portions, separated with the "," delimiter:
2588 Street Address (required)
2589 , (required if other address portions follow, otherwise optional)
2590 City (optional)
2591 , (required if other address portions follow, otherwise optional)
2592 Jurisdiction Code (optional)
2593 , (required if other address portions follow, otherwise optional)
2594 ZIP - Postal Code (optional)
2595
2596 */
2597 BarcodeElementKey[BarcodeElementKey["FullAddress"] = 12] = "FullAddress";
2598 /**
2599 Mandatory on AAMVA 02, 03, 04, 05, 06, 07, 08 and Compact barcodes.
2600 Optional on AAMVA 01 and Magnetic barcodes.
2601
2602 Height of cardholder, either in Inches or in Centimeters.
2603
2604 Inches (in): number of inches followed by " in"
2605 example: 6'1'' = "73 in"
2606
2607 Centimeters (cm): number of centimeters followed by " cm"
2608 example: 181 centimeters = "181 cm"
2609 */
2610 BarcodeElementKey[BarcodeElementKey["Height"] = 13] = "Height";
2611 /**
2612 Mandatory on AAMVA 02, 03, 04, 05, 06, 07, 08 and Compact barcodes.
2613 Optional on AAMVA 01 and Magnetic barcodes.
2614
2615 Height of cardholder in Inches.
2616 Example: 5'9'' = "69".
2617 */
2618 BarcodeElementKey[BarcodeElementKey["HeightIn"] = 14] = "HeightIn";
2619 /**
2620 Mandatory on AAMVA 02, 03, 04, 05, 06, 07, 08 Compact barcodes.
2621 Optional on AAMVA 01 and Magnetic barcodes.
2622
2623 Height of cardholder in Centimeters.
2624 Example: 180 Centimeters = "180".
2625 */
2626 BarcodeElementKey[BarcodeElementKey["HeightCm"] = 15] = "HeightCm";
2627 /**
2628 Mandatory on AAMVA 04, 05, 06, 07, 08 barcodes.
2629 Optional on AAMVA 01, 02, 03, Magnetic and Compcat barcodes.
2630
2631 Middle name(s) of the cardholder. In the case of multiple middle names they
2632 shall be separated by space " ".
2633 */
2634 BarcodeElementKey[BarcodeElementKey["CustomerMiddleName"] = 16] = "CustomerMiddleName";
2635 /**
2636 Optional on all AAMVA, Magnetic and Compact barcodes.
2637
2638 Bald, black, blonde, brown, gray, red/auburn, sandy, white, unknown. If the issuing
2639 jurisdiction wishes to abbreviate colors, the three-character codes provided in ANSI D20 must be
2640 used.
2641
2642 Code Description
2643 BAL Bald
2644 BLK Black
2645 BLN Blond
2646 BRO Brown
2647 GRY Grey
2648 RED Red/Auburn
2649 SDY Sandy
2650 WHI White
2651 UNK Unknown
2652 */
2653 BarcodeElementKey[BarcodeElementKey["HairColor"] = 17] = "HairColor";
2654 /**
2655 Mandatory on AAMVA 02 barcodes.
2656 Optional on AAMVA 01, 03, 04, 05, 06, 07, 08, Magnetic and Compact barcodes.
2657
2658 Name Suffix (If jurisdiction participates in systems requiring name suffix (PDPS, CDLIS, etc.),
2659 the suffix must be collected and displayed on the DL/ID and in the MRT).
2660 - JR (Junior)
2661 - SR (Senior)
2662 - 1ST or I (First)
2663 - 2ND or II (Second)
2664 - 3RD or III (Third)
2665 - 4TH or IV (Fourth)
2666 - 5TH or V (Fifth)
2667 - 6TH or VI (Sixth)
2668 - 7TH or VII (Seventh)
2669 - 8TH or VIII (Eighth)
2670 - 9TH or IX (Ninth)
2671 */
2672 BarcodeElementKey[BarcodeElementKey["NameSuffix"] = 18] = "NameSuffix";
2673 /**
2674 Optional on all AAMVA and Compact barcodes.
2675
2676 Other name by which the cardholder is known. ALTERNATIVE NAME(S) of the individual
2677 holding the Driver License or ID.
2678
2679 The Name field contains up to four portions, separated with the "," delimiter:
2680 AKA Last Name (required)
2681 , (required)
2682 AKA First Name (required)
2683 , (required if other name portions follow, otherwise optional)
2684 AKA Middle Name(s) (optional)
2685 , (required if other name portions follow, otherwise optional)
2686 AKA Suffix (optional)
2687 , (optional)
2688
2689 If the individual has more than one AKA middle name they are separated with space.
2690 */
2691 BarcodeElementKey[BarcodeElementKey["AKAFullName"] = 19] = "AKAFullName";
2692 /**
2693 Optional on all AAMVA and Compact barcodes.
2694
2695 Other family name by which the cardholder is known.
2696 */
2697 BarcodeElementKey[BarcodeElementKey["AKAFamilyName"] = 20] = "AKAFamilyName";
2698 /**
2699 Optional on all AAMVA and Compact barcodes.
2700
2701 Other given name by which the cardholder is known
2702 */
2703 BarcodeElementKey[BarcodeElementKey["AKAGivenName"] = 21] = "AKAGivenName";
2704 /**
2705 Optional on all AAMVA and Compact barcodes.
2706
2707 Other suffix by which the cardholder is known.
2708
2709 The Suffix Code Portion, if submitted, can contain only the Suffix Codes shown in the following
2710 table (e.g., Andrew Johnson, III = JOHNSON@ANDREW@@3RD):
2711
2712 Suffix Meaning or Synonym
2713 JR Junior
2714 SR Senior or Esquire 1ST First
2715 2ND Second
2716 3RD Third
2717 4TH Fourth
2718 5TH Fifth
2719 6TH Sixth
2720 7TH Seventh
2721 8TH Eighth
2722 9TH Ninth
2723 */
2724 BarcodeElementKey[BarcodeElementKey["AKASuffixName"] = 22] = "AKASuffixName";
2725 /**
2726 Mandatory on AAMVA 02 barcodes.
2727 Optional on AAMVA 01, 03, 04, 05, 06, 07, 08, Magnetic and Compact barcodes.
2728
2729 Indicates the approximate weight range of the cardholder:
2730 0 = up to 31 kg (up to 70 lbs)
2731 1 = 32 – 45 kg (71 – 100 lbs)
2732 2 = 46 - 59 kg (101 – 130 lbs)
2733 3 = 60 - 70 kg (131 – 160 lbs)
2734 4 = 71 - 86 kg (161 – 190 lbs)
2735 5 = 87 - 100 kg (191 – 220 lbs)
2736 6 = 101 - 113 kg (221 – 250 lbs)
2737 7 = 114 - 127 kg (251 – 280 lbs)
2738 8 = 128 – 145 kg (281 – 320 lbs)
2739 9 = 146+ kg (321+ lbs)
2740 */
2741 BarcodeElementKey[BarcodeElementKey["WeightRange"] = 23] = "WeightRange";
2742 /**
2743 Mandatory on AAMVA 02 barcodes.
2744 Optional on AAMVA 01, 03, 04, 05, 06, 07, 08, Magnetic and Compact barcodes.
2745
2746 Cardholder weight in pounds Example: 185 lb = "185"
2747 */
2748 BarcodeElementKey[BarcodeElementKey["WeightPounds"] = 24] = "WeightPounds";
2749 /**
2750 Mandatory on AAMVA 02 barcodes.
2751 Optional on AAMVA 01, 03, 04, 05, 06, 07, 08, Magnetic and Compact barcodes.
2752
2753 Cardholder weight in kilograms Example: 84 kg = "084"
2754 */
2755 BarcodeElementKey[BarcodeElementKey["WeightKilograms"] = 25] = "WeightKilograms";
2756 /**
2757 Mandatory on all AAMVA and Compact barcodes.
2758
2759 The number assigned or calculated by the issuing authority.
2760 */
2761 BarcodeElementKey[BarcodeElementKey["CustomerIdNumber"] = 26] = "CustomerIdNumber";
2762 /**
2763 Mandatory on AAMVA 04, 05, 06, 07, 08 barcodes.
2764 Optional on Compact barcodes.
2765
2766 A code that indicates whether a field has been truncated (T), has not been
2767 truncated (N), or – unknown whether truncated (U).
2768 */
2769 BarcodeElementKey[BarcodeElementKey["FamilyNameTruncation"] = 27] = "FamilyNameTruncation";
2770 /**
2771 Mandatory on AAMVA 04, 05, 06, 07, 08 barcodes.
2772 Optional on Compact barcodes.
2773
2774 A code that indicates whether a field has been truncated (T), has not been
2775 truncated (N), or – unknown whether truncated (U).
2776 */
2777 BarcodeElementKey[BarcodeElementKey["FirstNameTruncation"] = 28] = "FirstNameTruncation";
2778 /**
2779 Mandatory on AAMVA 04, 05, 06, 07, 08 barcodes.
2780
2781 A code that indicates whether a field has been truncated (T), has not been
2782 truncated (N), or – unknown whether truncated (U).
2783 */
2784 BarcodeElementKey[BarcodeElementKey["MiddleNameTruncation"] = 29] = "MiddleNameTruncation";
2785 /**
2786 Optional on AAMVA 02, 03, 04, 05, 06, 07, 08 and Compact barcodes.
2787
2788 Country and municipality and/or state/province.
2789 */
2790 BarcodeElementKey[BarcodeElementKey["PlaceOfBirth"] = 30] = "PlaceOfBirth";
2791 /**
2792 Optional on all AAMVA barcodes.
2793
2794 On Compact barcodes, use kFullAddress.
2795
2796 Second line of street portion of the cardholder address.
2797 */
2798 BarcodeElementKey[BarcodeElementKey["AddressStreet2"] = 31] = "AddressStreet2";
2799 /**
2800 Optional on AAMVA 02, 03, 04, 05, 06, 07, 08 and Compact barcodes.
2801
2802 Codes for race or ethnicity of the cardholder, as defined in ANSI D20.
2803
2804 Race:
2805 Code Description
2806 AI Alaskan or American Indian (Having Origins in Any of The Original Peoples of
2807 North America, and Maintaining Cultural Identification Through Tribal
2808 Affiliation of Community Recognition)
2809 AP Asian or Pacific Islander (Having Origins in Any of the Original Peoples of
2810 the Far East, Southeast Asia, or Pacific Islands. This Includes China, India,
2811 Japan, Korea, the Philippines Islands, and Samoa)
2812 BK Black (Having Origins in Any of the Black Racial Groups of Africa)
2813 W White (Having Origins in Any of The Original Peoples of Europe, North Africa,
2814 or the Middle East)
2815
2816 Ethnicity:
2817 Code Description
2818 H Hispanic Origin (A Person of Mexican, Puerto Rican, Cuban, Central or South
2819 American or Other Spanish Culture or Origin, Regardless of Race)
2820 O Not of Hispanic Origin (Any Person Other Than Hispanic)
2821 U Unknown
2822
2823 */
2824 BarcodeElementKey[BarcodeElementKey["RaceEthnicity"] = 32] = "RaceEthnicity";
2825 /**
2826 Optional on AAMVA 01 barcodes.
2827
2828 PREFIX to Driver Name. Freeform as defined by issuing jurisdiction.
2829 */
2830 BarcodeElementKey[BarcodeElementKey["NamePrefix"] = 33] = "NamePrefix";
2831 /**
2832 Mandatory on AAMVA 02, 03, 04, 05, 06, 07, 08 and Compact barcodes.
2833
2834 Country in which DL/ID is issued. U.S. = USA, Canada = CAN.
2835 */
2836 BarcodeElementKey[BarcodeElementKey["CountryIdentification"] = 34] = "CountryIdentification";
2837 /**
2838 Optional on AAMVA version 01.
2839
2840 Driver Residence Street Address 1.
2841 */
2842 BarcodeElementKey[BarcodeElementKey["ResidenceStreetAddress"] = 35] = "ResidenceStreetAddress";
2843 /**
2844 Optional on AAMVA version 01.
2845
2846 Driver Residence Street Address 2.
2847 */
2848 BarcodeElementKey[BarcodeElementKey["ResidenceStreetAddress2"] = 36] = "ResidenceStreetAddress2";
2849 /**
2850 Optional on AAMVA version 01.
2851
2852 Driver Residence City
2853 */
2854 BarcodeElementKey[BarcodeElementKey["ResidenceCity"] = 37] = "ResidenceCity";
2855 /**
2856 Optional on AAMVA version 01.
2857
2858 Driver Residence Jurisdiction Code.
2859 */
2860 BarcodeElementKey[BarcodeElementKey["ResidenceJurisdictionCode"] = 38] = "ResidenceJurisdictionCode";
2861 /**
2862 Optional on AAMVA 01 barcodes.
2863
2864 Driver Residence Postal Code.
2865 */
2866 BarcodeElementKey[BarcodeElementKey["ResidencePostalCode"] = 39] = "ResidencePostalCode";
2867 /**
2868 Optional on AAMVA 01 barcodes.
2869
2870 Full residence address of the individual holding the Driver's License or ID.
2871
2872 The full address field contains up to four portions, separated with the "," delimiter:
2873 Residence Street Address (required)
2874 , (required if other address portions follow, otherwise optional)
2875 Residence City (optional)
2876 , (required if other address portions follow, otherwise optional)
2877 Residence Jurisdiction Code (optional)
2878 , (required if other address portions follow, otherwise optional)
2879 Residence ZIP - Residence Postal Code (optional)
2880 */
2881 BarcodeElementKey[BarcodeElementKey["ResidenceFullAddress"] = 40] = "ResidenceFullAddress";
2882 /**
2883 Optional on AAMVA 05, 06, 07, 08 barcodes.
2884
2885 Date on which the cardholder turns 18 years old. (MMDDCCYY format)
2886 */
2887 BarcodeElementKey[BarcodeElementKey["Under18"] = 41] = "Under18";
2888 /**
2889 Optional on AAMVA 05, 06, 07, 08 barcodes.
2890
2891 Date on which the cardholder turns 19 years old. (MMDDCCYY format)
2892 */
2893 BarcodeElementKey[BarcodeElementKey["Under19"] = 42] = "Under19";
2894 /**
2895 Optional on AAMVA 05, 06, 07, 08 barcodes.
2896
2897 Date on which the cardholder turns 21 years old. (MMDDCCYY format)
2898 */
2899 BarcodeElementKey[BarcodeElementKey["Under21"] = 43] = "Under21";
2900 /**
2901 Optional on AAMVA version 01.
2902
2903 The number assigned to the individual by the Social Security Administration.
2904 */
2905 BarcodeElementKey[BarcodeElementKey["SocialSecurityNumber"] = 44] = "SocialSecurityNumber";
2906 /**
2907 Optional on AAMVA version 01.
2908
2909 Driver "AKA" Social Security Number. FORMAT SAME AS DRIVER SOC SEC NUM. ALTERNATIVE NUMBERS(S) used as SS NUM.
2910 */
2911 BarcodeElementKey[BarcodeElementKey["AKASocialSecurityNumber"] = 45] = "AKASocialSecurityNumber";
2912 /**
2913 Optional on AAMVA 01 barcodes.
2914
2915 ALTERNATIVE MIDDLE NAME(s) or INITIALS of the individual holding the Driver License or ID.
2916 Hyphenated names acceptable, spaces between names acceptable, but no other
2917 use of special symbols.
2918 */
2919 BarcodeElementKey[BarcodeElementKey["AKAMiddleName"] = 46] = "AKAMiddleName";
2920 /**
2921 Optional on AAMVA 01 barcodes.
2922
2923 ALTERNATIVE PREFIX to Driver Name. Freeform as defined by issuing jurisdiction.
2924 */
2925 BarcodeElementKey[BarcodeElementKey["AKAPrefixName"] = 47] = "AKAPrefixName";
2926 /**
2927 Optional on AAMVA 01, 06, 07, 08 barcodes.
2928
2929 Field that indicates that the cardholder is an organ donor = "1".
2930 */
2931 BarcodeElementKey[BarcodeElementKey["OrganDonor"] = 48] = "OrganDonor";
2932 /**
2933 Optional on AAMVA 07, 08 barcodes.
2934
2935 Field that indicates that the cardholder is a veteran = "1"
2936 */
2937 BarcodeElementKey[BarcodeElementKey["Veteran"] = 49] = "Veteran";
2938 /**
2939 Optional on AAMVA 01. (MMDDCCYY format)
2940
2941 ALTERNATIVE DATES(S) given as date of birth.
2942 */
2943 BarcodeElementKey[BarcodeElementKey["AKADateOfBirth"] = 50] = "AKADateOfBirth";
2944 // ==============================================================/
2945 // ========== 3. LICENSE DATA KEYS ============/
2946 // ==============================================================/
2947 /**
2948 Mandatory on all AAMVA, Magnetic and Compact barcodes.
2949
2950 This number uniquely identifies the issuing jurisdiction and can
2951 be obtained by contacting the ISO Issuing Authority (AAMVA)
2952 */
2953 BarcodeElementKey[BarcodeElementKey["IssuerIdentificationNumber"] = 51] = "IssuerIdentificationNumber";
2954 /**
2955 Mandatory on all AAMVA, Magnetic and Compact barcodes.
2956
2957 If the document is non expiring then "Non expiring" is written in this field.
2958
2959 Date on which the driving and identification privileges granted by the document are
2960 no longer valid. (MMDDCCYY format)
2961 */
2962 BarcodeElementKey[BarcodeElementKey["DocumentExpirationDate"] = 52] = "DocumentExpirationDate";
2963 /**
2964 Mandatory on all AAMVA and Compact barcodes.
2965 Optional on Magnetic barcodes.
2966
2967 Jurisdiction Version Number: This is a decimal value between 0 and 99 that
2968 specifies the jurisdiction version level of the PDF417 barcode format.
2969 Notwithstanding iterations of this standard, jurisdictions implement incremental
2970 changes to their barcodes, including new jurisdiction-specific data, compression
2971 algorithms for digitized images, digital signatures, or new truncation
2972 conventions used for names and addresses. Each change to the barcode format
2973 within each AAMVA version (above) must be noted, beginning with Jurisdiction
2974 Version 00.
2975 */
2976 BarcodeElementKey[BarcodeElementKey["JurisdictionVersionNumber"] = 53] = "JurisdictionVersionNumber";
2977 /**
2978 Mandatory on all AAMVA and Magnetic barcodes.
2979
2980 Jurisdiction-specific vehicle class / group code, designating the type
2981 of vehicle the cardholder has privilege to drive.
2982 */
2983 BarcodeElementKey[BarcodeElementKey["JurisdictionVehicleClass"] = 54] = "JurisdictionVehicleClass";
2984 /**
2985 Mandatory on all AAMVA barcodes.
2986 Optional on Magnetic barcodes.
2987
2988 Jurisdiction-specific codes that represent restrictions to driving
2989 privileges (such as airbrakes, automatic transmission, daylight only, etc.).
2990 */
2991 BarcodeElementKey[BarcodeElementKey["JurisdictionRestrictionCodes"] = 55] = "JurisdictionRestrictionCodes";
2992 /**
2993 Mandatory on all AAMVA barcodes.
2994 Optional on Magnetic barcodes.
2995
2996 Jurisdiction-specific codes that represent additional privileges
2997 granted to the cardholder beyond the vehicle class (such as transportation of
2998 passengers, hazardous materials, operation of motorcycles, etc.).
2999 */
3000 BarcodeElementKey[BarcodeElementKey["JurisdictionEndorsementCodes"] = 56] = "JurisdictionEndorsementCodes";
3001 /**
3002 Mandatory on all AAMVA and Compact barcodes.
3003
3004 Date on which the document was issued. (MMDDCCYY format)
3005 */
3006 BarcodeElementKey[BarcodeElementKey["DocumentIssueDate"] = 57] = "DocumentIssueDate";
3007 /**
3008 Mandatory on AAMVA versions 02 and 03.
3009
3010 Federally established codes for vehicle categories, endorsements, and restrictions
3011 that are generally applicable to commercial motor vehicles. If the vehicle is not a
3012 commercial vehicle, "NONE" is to be entered.
3013 */
3014 BarcodeElementKey[BarcodeElementKey["FederalCommercialVehicleCodes"] = 58] = "FederalCommercialVehicleCodes";
3015 /**
3016 Optional on all AAMVA barcodes.
3017 Mandatory on Compact barcodes.
3018
3019 Jurisdictions may define a subfile to contain jurisdiction-specific information.
3020 These subfiles are designated with the first character of “Z” and the second
3021 character is the first letter of the jurisdiction's name. For example, "ZC" would
3022 be the designator for a California or Colorado jurisdiction-defined subfile, "ZQ"
3023 would be the designator for a Quebec jurisdiction-defined subfile. In the case of
3024 a jurisdiction-defined subfile that has a first letter that could be more than
3025 one jurisdiction (e.g. California, Colorado, Connecticut) then other data, like
3026 the IIN or address, must be examined to determine the jurisdiction.
3027 */
3028 BarcodeElementKey[BarcodeElementKey["IssuingJurisdiction"] = 59] = "IssuingJurisdiction";
3029 /**
3030 Optional on all AAMVA barcodes.
3031 Mandatory on Compact barcodes.
3032
3033 Standard vehicle classification code(s) for cardholder. This data element is a
3034 placeholder for future efforts to standardize vehicle classifications.
3035 */
3036 BarcodeElementKey[BarcodeElementKey["StandardVehicleClassification"] = 60] = "StandardVehicleClassification";
3037 /**
3038 Optional on all AAMVA and Magnetic barcodes.
3039
3040 Name of issuing jurisdiction, for example: Alabama, Alaska ...
3041 */
3042 BarcodeElementKey[BarcodeElementKey["IssuingJurisdictionName"] = 61] = "IssuingJurisdictionName";
3043 /**
3044 Optional on all AAMVA barcodes.
3045
3046 Standard endorsement code(s) for cardholder. See codes in D20. This data element is a
3047 placeholder for future efforts to standardize endorsement codes.
3048
3049 Code Description
3050 H Hazardous Material - This endorsement is required for the operation of any vehicle
3051 transporting hazardous materials requiring placarding, as defined by U.S.
3052 Department of Transportation regulations.
3053 L Motorcycles – Including Mopeds/Motorized Bicycles.
3054 N Tank - This endorsement is required for the operation of any vehicle transporting,
3055 as its primary cargo, any liquid or gaseous material within a tank attached to the vehicle.
3056 O Other Jurisdiction Specific Endorsement(s) - This code indicates one or more
3057 additional jurisdiction assigned endorsements.
3058 P Passenger - This endorsement is required for the operation of any vehicle used for
3059 transportation of sixteen or more occupants, including the driver.
3060 S School Bus - This endorsement is required for the operation of a school bus. School bus means a
3061 CMV used to transport pre-primary, primary, or secondary school students from home to school,
3062 from school to home, or to and from school sponsored events. School bus does not include a
3063 bus used as common carrier (49 CRF 383.5).
3064 T Doubles/Triples - This endorsement is required for the operation of any vehicle that would be
3065 referred to as a double or triple.
3066 X Combined Tank/HAZ-MAT - This endorsement may be issued to any driver who qualifies for
3067 both the N and H endorsements.
3068 */
3069 BarcodeElementKey[BarcodeElementKey["StandardEndorsementCode"] = 62] = "StandardEndorsementCode";
3070 /**
3071 Optional on all AAMVA barcodes.
3072
3073 Standard restriction code(s) for cardholder. See codes in D20. This data element is a placeholder
3074 for future efforts to standardize restriction codes.
3075
3076 Code Description
3077 B Corrective Lenses
3078 C Mechanical Devices (Special Brakes, Hand Controls, or Other Adaptive Devices)
3079 D Prosthetic Aid
3080 E Automatic Transmission
3081 F Outside Mirror
3082 G Limit to Daylight Only
3083 H Limit to Employment
3084 I Limited Other
3085 J Other
3086 K CDL Intrastate Only
3087 L Vehicles without air brakes
3088 M Except Class A bus
3089 N Except Class A and Class B bus
3090 O Except Tractor-Trailer
3091 V Medical Variance Documentation Required
3092 W Farm Waiver
3093 */
3094 BarcodeElementKey[BarcodeElementKey["StandardRestrictionCode"] = 63] = "StandardRestrictionCode";
3095 /**
3096 Optional on AAMVA 02, 03, 04, 05, 06, 07, 08 and Compact barcodes.
3097
3098 Text that explains the jurisdiction-specific code(s) for classifications
3099 of vehicles cardholder is authorized to drive.
3100 */
3101 BarcodeElementKey[BarcodeElementKey["JurisdictionVehicleClassificationDescription"] = 64] = "JurisdictionVehicleClassificationDescription";
3102 /**
3103 Optional on AAMVA 02, 03, 04, 05, 06, 07, 08 and Compact barcodes.
3104
3105 Text that explains the jurisdiction-specific code(s) that indicates additional
3106 driving privileges granted to the cardholder beyond the vehicle class.
3107 */
3108 BarcodeElementKey[BarcodeElementKey["JurisdictionEndorsmentCodeDescription"] = 65] = "JurisdictionEndorsmentCodeDescription";
3109 /**
3110 Optional on AAMVA 02, 03, 04, 05, 06, 07, 08 and Compact barcodes.
3111
3112 Text describing the jurisdiction-specific restriction code(s) that curtail driving privileges.
3113 */
3114 BarcodeElementKey[BarcodeElementKey["JurisdictionRestrictionCodeDescription"] = 66] = "JurisdictionRestrictionCodeDescription";
3115 /**
3116 Optional on AAMVA 02, 03, 04, 05, 06, 07, 08 barcodes.
3117
3118 A string of letters and/or numbers that is affixed to the raw materials (card stock,
3119 laminate, etc.) used in producing driver's licenses and ID cards. (DHS recommended field)
3120 */
3121 BarcodeElementKey[BarcodeElementKey["InventoryControlNumber"] = 67] = "InventoryControlNumber";
3122 /**
3123 Optional on AAMVA 04, 05, 06, 07, 08 and Compact barcodes.
3124
3125 DHS required field that indicates date of the most recent version change or
3126 modification to the visible format of the DL/ID. (MMDDCCYY format)
3127 */
3128 BarcodeElementKey[BarcodeElementKey["CardRevisionDate"] = 68] = "CardRevisionDate";
3129 /**
3130 Mandatory on AAMVA 02, 03, 04, 05, 06, 07, 08 and Magnetic barcodes.
3131 Optional and Compact barcodes.
3132
3133 Number must uniquely identify a particular document issued to that customer
3134 from others that may have been issued in the past. This number may serve multiple
3135 purposes of document discrimination, audit information number, and/or inventory control.
3136 */
3137 BarcodeElementKey[BarcodeElementKey["DocumentDiscriminator"] = 69] = "DocumentDiscriminator";
3138 /**
3139 Optional on AAMVA 04, 05, 06, 07, 08 and Compact barcodes.
3140
3141 DHS required field that indicates that the cardholder has temporary lawful status = "1".
3142 */
3143 BarcodeElementKey[BarcodeElementKey["LimitedDurationDocument"] = 70] = "LimitedDurationDocument";
3144 /**
3145 Optional on AAMVA 02, 03, 04, 05, 06, 07, 08 and Compact barcodes.
3146
3147 A string of letters and/or numbers that identifies when, where, and by whom a driver's
3148 license/ID card was made. If audit information is not used on the card or the MRT, it
3149 must be included in the driver record.
3150 */
3151 BarcodeElementKey[BarcodeElementKey["AuditInformation"] = 71] = "AuditInformation";
3152 /**
3153 Optional on AAMVA 04, 05, 06, 07, 08 and Compact barcodes.
3154
3155 DHS required field that indicates compliance: "M" = materially compliant,
3156 "F" = fully compliant, and, "N" = non-compliant.
3157 */
3158 BarcodeElementKey[BarcodeElementKey["ComplianceType"] = 72] = "ComplianceType";
3159 /**
3160 Optional on AAMVA version 01 barcodes.
3161
3162 Issue Timestamp. A string used by some jurisdictions to validate the document against their data base.
3163 */
3164 BarcodeElementKey[BarcodeElementKey["IssueTimestamp"] = 73] = "IssueTimestamp";
3165 /**
3166 Optional on AAMVA version 01 barcodes.
3167
3168 Driver Permit Expiration Date. MMDDCCYY format. Date permit expires.
3169 */
3170 BarcodeElementKey[BarcodeElementKey["PermitExpirationDate"] = 74] = "PermitExpirationDate";
3171 /**
3172 Optional on AAMVA version 01 barcodes..
3173
3174 Type of permit.
3175 */
3176 BarcodeElementKey[BarcodeElementKey["PermitIdentifier"] = 75] = "PermitIdentifier";
3177 /**
3178 Optional on AAMVA version 01 barcodes..
3179
3180 Driver Permit Issue Date. MMDDCCYY format. Date permit was issued.
3181 */
3182 BarcodeElementKey[BarcodeElementKey["PermitIssueDate"] = 76] = "PermitIssueDate";
3183 /**
3184 Optional on AAMVA version 01.
3185
3186 Number of duplicate cards issued for a license or ID if any.
3187 */
3188 BarcodeElementKey[BarcodeElementKey["NumberOfDuplicates"] = 77] = "NumberOfDuplicates";
3189 /**
3190 Optional on AAMVA 04, 05, 06, 07, 08 and Compact barcodes.
3191
3192 Date on which the hazardous material endorsement granted by the document is
3193 no longer valid. (MMDDCCYY format)
3194 */
3195 BarcodeElementKey[BarcodeElementKey["HAZMATExpirationDate"] = 78] = "HAZMATExpirationDate";
3196 /**
3197 Optional on AAMVA version 01.
3198
3199 Medical Indicator/Codes.
3200 STATE SPECIFIC. Freeform, Standard "TBD"
3201 */
3202 BarcodeElementKey[BarcodeElementKey["MedicalIndicator"] = 79] = "MedicalIndicator";
3203 /**
3204 Optional on AAMVA version 01.
3205
3206 Non-Resident Indicator. "Y". Used by some jurisdictions to indicate holder of the document is a non-resident.
3207 */
3208 BarcodeElementKey[BarcodeElementKey["NonResident"] = 80] = "NonResident";
3209 /**
3210 Optional on AAMVA version 01.
3211
3212 A number or alphanumeric string used by some jurisdictions to identify a "customer" across multiple data bases.
3213 */
3214 BarcodeElementKey[BarcodeElementKey["UniqueCustomerId"] = 81] = "UniqueCustomerId";
3215 /**
3216 Optional on compact barcodes.
3217
3218 Document discriminator.
3219 */
3220 BarcodeElementKey[BarcodeElementKey["DataDiscriminator"] = 82] = "DataDiscriminator";
3221 /**
3222 Optional on Magnetic barcodes.
3223
3224 Month on which the driving and identification privileges granted by the document are
3225 no longer valid. (MMYY format)
3226 */
3227 BarcodeElementKey[BarcodeElementKey["DocumentExpirationMonth"] = 83] = "DocumentExpirationMonth";
3228 /**
3229 Optional on Magnetic barcodes.
3230
3231 Field that indicates that the driving and identification privileges granted by the
3232 document are nonexpiring = "1".
3233 */
3234 BarcodeElementKey[BarcodeElementKey["DocumentNonexpiring"] = 84] = "DocumentNonexpiring";
3235 /**
3236 Optional on Magnetic barcodes.
3237
3238 Security version beeing used.
3239 */
3240 BarcodeElementKey[BarcodeElementKey["SecurityVersion"] = 85] = "SecurityVersion";
3241 /**
3242 Number of keys in enum.
3243 */
3244 BarcodeElementKey[BarcodeElementKey["Count"] = 86] = "Count";
3245})(exports.BarcodeElementKey || (exports.BarcodeElementKey = {}));
3246
3247(function (Country) {
3248 Country[Country["NONE"] = 0] = "NONE";
3249 Country[Country["ALBANIA"] = 1] = "ALBANIA";
3250 Country[Country["ALGERIA"] = 2] = "ALGERIA";
3251 Country[Country["ARGENTINA"] = 3] = "ARGENTINA";
3252 Country[Country["AUSTRALIA"] = 4] = "AUSTRALIA";
3253 Country[Country["AUSTRIA"] = 5] = "AUSTRIA";
3254 Country[Country["AZERBAIJAN"] = 6] = "AZERBAIJAN";
3255 Country[Country["BAHRAIN"] = 7] = "BAHRAIN";
3256 Country[Country["BANGLADESH"] = 8] = "BANGLADESH";
3257 Country[Country["BELGIUM"] = 9] = "BELGIUM";
3258 Country[Country["BOSNIA_AND_HERZEGOVINA"] = 10] = "BOSNIA_AND_HERZEGOVINA";
3259 Country[Country["BRUNEI"] = 11] = "BRUNEI";
3260 Country[Country["BULGARIA"] = 12] = "BULGARIA";
3261 Country[Country["CAMBODIA"] = 13] = "CAMBODIA";
3262 Country[Country["CANADA"] = 14] = "CANADA";
3263 Country[Country["CHILE"] = 15] = "CHILE";
3264 Country[Country["COLOMBIA"] = 16] = "COLOMBIA";
3265 Country[Country["COSTA_RICA"] = 17] = "COSTA_RICA";
3266 Country[Country["CROATIA"] = 18] = "CROATIA";
3267 Country[Country["CYPRUS"] = 19] = "CYPRUS";
3268 Country[Country["CZECHIA"] = 20] = "CZECHIA";
3269 Country[Country["DENMARK"] = 21] = "DENMARK";
3270 Country[Country["DOMINICAN_REPUBLIC"] = 22] = "DOMINICAN_REPUBLIC";
3271 Country[Country["EGYPT"] = 23] = "EGYPT";
3272 Country[Country["ESTONIA"] = 24] = "ESTONIA";
3273 Country[Country["FINLAND"] = 25] = "FINLAND";
3274 Country[Country["FRANCE"] = 26] = "FRANCE";
3275 Country[Country["GEORGIA"] = 27] = "GEORGIA";
3276 Country[Country["GERMANY"] = 28] = "GERMANY";
3277 Country[Country["GHANA"] = 29] = "GHANA";
3278 Country[Country["GREECE"] = 30] = "GREECE";
3279 Country[Country["GUATEMALA"] = 31] = "GUATEMALA";
3280 Country[Country["HONG_KONG"] = 32] = "HONG_KONG";
3281 Country[Country["HUNGARY"] = 33] = "HUNGARY";
3282 Country[Country["INDIA"] = 34] = "INDIA";
3283 Country[Country["INDONESIA"] = 35] = "INDONESIA";
3284 Country[Country["IRELAND"] = 36] = "IRELAND";
3285 Country[Country["ISRAEL"] = 37] = "ISRAEL";
3286 Country[Country["ITALY"] = 38] = "ITALY";
3287 Country[Country["JORDAN"] = 39] = "JORDAN";
3288 Country[Country["KAZAKHSTAN"] = 40] = "KAZAKHSTAN";
3289 Country[Country["KENYA"] = 41] = "KENYA";
3290 Country[Country["KOSOVO"] = 42] = "KOSOVO";
3291 Country[Country["KUWAIT"] = 43] = "KUWAIT";
3292 Country[Country["LATVIA"] = 44] = "LATVIA";
3293 Country[Country["LITHUANIA"] = 45] = "LITHUANIA";
3294 Country[Country["MALAYSIA"] = 46] = "MALAYSIA";
3295 Country[Country["MALDIVES"] = 47] = "MALDIVES";
3296 Country[Country["MALTA"] = 48] = "MALTA";
3297 Country[Country["MAURITIUS"] = 49] = "MAURITIUS";
3298 Country[Country["MEXICO"] = 50] = "MEXICO";
3299 Country[Country["MOROCCO"] = 51] = "MOROCCO";
3300 Country[Country["NETHERLANDS"] = 52] = "NETHERLANDS";
3301 Country[Country["NEW_ZEALAND"] = 53] = "NEW_ZEALAND";
3302 Country[Country["NIGERIA"] = 54] = "NIGERIA";
3303 Country[Country["PAKISTAN"] = 55] = "PAKISTAN";
3304 Country[Country["PANAMA"] = 56] = "PANAMA";
3305 Country[Country["PARAGUAY"] = 57] = "PARAGUAY";
3306 Country[Country["PHILIPPINES"] = 58] = "PHILIPPINES";
3307 Country[Country["POLAND"] = 59] = "POLAND";
3308 Country[Country["PORTUGAL"] = 60] = "PORTUGAL";
3309 Country[Country["PUERTO_RICO"] = 61] = "PUERTO_RICO";
3310 Country[Country["QATAR"] = 62] = "QATAR";
3311 Country[Country["ROMANIA"] = 63] = "ROMANIA";
3312 Country[Country["RUSSIA"] = 64] = "RUSSIA";
3313 Country[Country["SAUDI_ARABIA"] = 65] = "SAUDI_ARABIA";
3314 Country[Country["SERBIA"] = 66] = "SERBIA";
3315 Country[Country["SINGAPORE"] = 67] = "SINGAPORE";
3316 Country[Country["SLOVAKIA"] = 68] = "SLOVAKIA";
3317 Country[Country["SLOVENIA"] = 69] = "SLOVENIA";
3318 Country[Country["SOUTH_AFRICA"] = 70] = "SOUTH_AFRICA";
3319 Country[Country["SPAIN"] = 71] = "SPAIN";
3320 Country[Country["SWEDEN"] = 72] = "SWEDEN";
3321 Country[Country["SWITZERLAND"] = 73] = "SWITZERLAND";
3322 Country[Country["TAIWAN"] = 74] = "TAIWAN";
3323 Country[Country["THAILAND"] = 75] = "THAILAND";
3324 Country[Country["TUNISIA"] = 76] = "TUNISIA";
3325 Country[Country["TURKEY"] = 77] = "TURKEY";
3326 Country[Country["UAE"] = 78] = "UAE";
3327 Country[Country["UGANDA"] = 79] = "UGANDA";
3328 Country[Country["UK"] = 80] = "UK";
3329 Country[Country["UKRAINE"] = 81] = "UKRAINE";
3330 Country[Country["USA"] = 82] = "USA";
3331 Country[Country["VIETNAM"] = 83] = "VIETNAM";
3332 Country[Country["BRAZIL"] = 84] = "BRAZIL";
3333 Country[Country["NORWAY"] = 85] = "NORWAY";
3334 Country[Country["OMAN"] = 86] = "OMAN";
3335 Country[Country["ECUADOR"] = 87] = "ECUADOR";
3336 Country[Country["EL_SALVADOR"] = 88] = "EL_SALVADOR";
3337 Country[Country["SRI_LANKA"] = 89] = "SRI_LANKA";
3338 Country[Country["PERU"] = 90] = "PERU";
3339 Country[Country["URUGUAY"] = 91] = "URUGUAY";
3340 Country[Country["BAHAMAS"] = 92] = "BAHAMAS";
3341 Country[Country["BERMUDA"] = 93] = "BERMUDA";
3342 Country[Country["BOLIVIA"] = 94] = "BOLIVIA";
3343 Country[Country["CHINA"] = 95] = "CHINA";
3344 Country[Country["EUROPEAN_UNION"] = 96] = "EUROPEAN_UNION";
3345 Country[Country["HAITI"] = 97] = "HAITI";
3346 Country[Country["HONDURAS"] = 98] = "HONDURAS";
3347 Country[Country["ICELAND"] = 99] = "ICELAND";
3348 Country[Country["JAPAN"] = 100] = "JAPAN";
3349 Country[Country["LUXEMBOURG"] = 101] = "LUXEMBOURG";
3350 Country[Country["MONTENEGRO"] = 102] = "MONTENEGRO";
3351 Country[Country["NICARAGUA"] = 103] = "NICARAGUA";
3352 Country[Country["SOUTH_KOREA"] = 104] = "SOUTH_KOREA";
3353 Country[Country["VENEZUELA"] = 105] = "VENEZUELA";
3354 Country[Country["AFGHANISTAN"] = 106] = "AFGHANISTAN";
3355 Country[Country["ALAND_ISLANDS"] = 107] = "ALAND_ISLANDS";
3356 Country[Country["AMERICAN_SAMOA"] = 108] = "AMERICAN_SAMOA";
3357 Country[Country["ANDORRA"] = 109] = "ANDORRA";
3358 Country[Country["ANGOLA"] = 110] = "ANGOLA";
3359 Country[Country["ANGUILLA"] = 111] = "ANGUILLA";
3360 Country[Country["ANTARCTICA"] = 112] = "ANTARCTICA";
3361 Country[Country["ANTIGUA_AND_BARBUDA"] = 113] = "ANTIGUA_AND_BARBUDA";
3362 Country[Country["ARMENIA"] = 114] = "ARMENIA";
3363 Country[Country["ARUBA"] = 115] = "ARUBA";
3364 Country[Country["BAILIWICK_OF_GUERNSEY"] = 116] = "BAILIWICK_OF_GUERNSEY";
3365 Country[Country["BAILIWICK_OF_JERSEY"] = 117] = "BAILIWICK_OF_JERSEY";
3366 Country[Country["BARBADOS"] = 118] = "BARBADOS";
3367 Country[Country["BELARUS"] = 119] = "BELARUS";
3368 Country[Country["BELIZE"] = 120] = "BELIZE";
3369 Country[Country["BENIN"] = 121] = "BENIN";
3370 Country[Country["BHUTAN"] = 122] = "BHUTAN";
3371 Country[Country["BONAIRE_SAINT_EUSTATIUS_AND_SABA"] = 123] = "BONAIRE_SAINT_EUSTATIUS_AND_SABA";
3372 Country[Country["BOTSWANA"] = 124] = "BOTSWANA";
3373 Country[Country["BOUVET_ISLAND"] = 125] = "BOUVET_ISLAND";
3374 Country[Country["BRITISH_INDIAN_OCEAN_TERRITORY"] = 126] = "BRITISH_INDIAN_OCEAN_TERRITORY";
3375 Country[Country["BURKINA_FASO"] = 127] = "BURKINA_FASO";
3376 Country[Country["BURUNDI"] = 128] = "BURUNDI";
3377 Country[Country["CAMEROON"] = 129] = "CAMEROON";
3378 Country[Country["CAPE_VERDE"] = 130] = "CAPE_VERDE";
3379 Country[Country["CARIBBEAN_NETHERLANDS"] = 131] = "CARIBBEAN_NETHERLANDS";
3380 Country[Country["CAYMAN_ISLANDS"] = 132] = "CAYMAN_ISLANDS";
3381 Country[Country["CENTRAL_AFRICAN_REPUBLIC"] = 133] = "CENTRAL_AFRICAN_REPUBLIC";
3382 Country[Country["CHAD"] = 134] = "CHAD";
3383 Country[Country["CHRISTMAS_ISLAND"] = 135] = "CHRISTMAS_ISLAND";
3384 Country[Country["COCOS_ISLANDS"] = 136] = "COCOS_ISLANDS";
3385 Country[Country["COMOROS"] = 137] = "COMOROS";
3386 Country[Country["CONGO"] = 138] = "CONGO";
3387 Country[Country["COOK_ISLANDS"] = 139] = "COOK_ISLANDS";
3388 Country[Country["CUBA"] = 140] = "CUBA";
3389 Country[Country["CURACAO"] = 141] = "CURACAO";
3390 Country[Country["DEMOCRATIC_REPUBLIC_OF_THE_CONGO"] = 142] = "DEMOCRATIC_REPUBLIC_OF_THE_CONGO";
3391 Country[Country["DJIBOUTI"] = 143] = "DJIBOUTI";
3392 Country[Country["DOMINICA"] = 144] = "DOMINICA";
3393 Country[Country["EAST_TIMOR"] = 145] = "EAST_TIMOR";
3394 Country[Country["EQUATORIAL_GUINEA"] = 146] = "EQUATORIAL_GUINEA";
3395 Country[Country["ERITREA"] = 147] = "ERITREA";
3396 Country[Country["ETHIOPIA"] = 148] = "ETHIOPIA";
3397 Country[Country["FALKLAND_ISLANDS"] = 149] = "FALKLAND_ISLANDS";
3398 Country[Country["FAROE_ISLANDS"] = 150] = "FAROE_ISLANDS";
3399 Country[Country["FEDERATED_STATES_OF_MICRONESIA"] = 151] = "FEDERATED_STATES_OF_MICRONESIA";
3400 Country[Country["FIJI"] = 152] = "FIJI";
3401 Country[Country["FRENCH_GUIANA"] = 153] = "FRENCH_GUIANA";
3402 Country[Country["FRENCH_POLYNESIA"] = 154] = "FRENCH_POLYNESIA";
3403 Country[Country["FRENCH_SOUTHERN_TERRITORIES"] = 155] = "FRENCH_SOUTHERN_TERRITORIES";
3404 Country[Country["GABON"] = 156] = "GABON";
3405 Country[Country["GAMBIA"] = 157] = "GAMBIA";
3406 Country[Country["GIBRALTAR"] = 158] = "GIBRALTAR";
3407 Country[Country["GREENLAND"] = 159] = "GREENLAND";
3408 Country[Country["GRENADA"] = 160] = "GRENADA";
3409 Country[Country["GUADELOUPE"] = 161] = "GUADELOUPE";
3410 Country[Country["GUAM"] = 162] = "GUAM";
3411 Country[Country["GUINEA"] = 163] = "GUINEA";
3412 Country[Country["GUINEA_BISSAU"] = 164] = "GUINEA_BISSAU";
3413 Country[Country["GUYANA"] = 165] = "GUYANA";
3414 Country[Country["HEARD_ISLAND_AND_MCDONALD_ISLANDS"] = 166] = "HEARD_ISLAND_AND_MCDONALD_ISLANDS";
3415 Country[Country["IRAN"] = 167] = "IRAN";
3416 Country[Country["IRAQ"] = 168] = "IRAQ";
3417 Country[Country["ISLE_OF_MAN"] = 169] = "ISLE_OF_MAN";
3418 Country[Country["IVORY_COAST"] = 170] = "IVORY_COAST";
3419 Country[Country["JAMAICA"] = 171] = "JAMAICA";
3420 Country[Country["KIRIBATI"] = 172] = "KIRIBATI";
3421 Country[Country["KYRGYZSTAN"] = 173] = "KYRGYZSTAN";
3422 Country[Country["LAOS"] = 174] = "LAOS";
3423 Country[Country["LEBANON"] = 175] = "LEBANON";
3424 Country[Country["LESOTHO"] = 176] = "LESOTHO";
3425 Country[Country["LIBERIA"] = 177] = "LIBERIA";
3426 Country[Country["LIBYA"] = 178] = "LIBYA";
3427 Country[Country["LIECHTENSTEIN"] = 179] = "LIECHTENSTEIN";
3428 Country[Country["MACAU"] = 180] = "MACAU";
3429 Country[Country["MADAGASCAR"] = 181] = "MADAGASCAR";
3430 Country[Country["MALAWI"] = 182] = "MALAWI";
3431 Country[Country["MALI"] = 183] = "MALI";
3432 Country[Country["MARSHALL_ISLANDS"] = 184] = "MARSHALL_ISLANDS";
3433 Country[Country["MARTINIQUE"] = 185] = "MARTINIQUE";
3434 Country[Country["MAURITANIA"] = 186] = "MAURITANIA";
3435 Country[Country["MAYOTTE"] = 187] = "MAYOTTE";
3436 Country[Country["MOLDOVA"] = 188] = "MOLDOVA";
3437 Country[Country["MONACO"] = 189] = "MONACO";
3438 Country[Country["MONGOLIA"] = 190] = "MONGOLIA";
3439 Country[Country["MONTSERRAT"] = 191] = "MONTSERRAT";
3440 Country[Country["MOZAMBIQUE"] = 192] = "MOZAMBIQUE";
3441 Country[Country["MYANMAR"] = 193] = "MYANMAR";
3442 Country[Country["NAMIBIA"] = 194] = "NAMIBIA";
3443 Country[Country["NAURU"] = 195] = "NAURU";
3444 Country[Country["NEPAL"] = 196] = "NEPAL";
3445 Country[Country["NEW_CALEDONIA"] = 197] = "NEW_CALEDONIA";
3446 Country[Country["NIGER"] = 198] = "NIGER";
3447 Country[Country["NIUE"] = 199] = "NIUE";
3448 Country[Country["NORFOLK_ISLAND"] = 200] = "NORFOLK_ISLAND";
3449 Country[Country["NORTHERN_CYPRUS"] = 201] = "NORTHERN_CYPRUS";
3450 Country[Country["NORTHERN_MARIANA_ISLANDS"] = 202] = "NORTHERN_MARIANA_ISLANDS";
3451 Country[Country["NORTH_KOREA"] = 203] = "NORTH_KOREA";
3452 Country[Country["NORTH_MACEDONIA"] = 204] = "NORTH_MACEDONIA";
3453 Country[Country["PALAU"] = 205] = "PALAU";
3454 Country[Country["PALESTINE"] = 206] = "PALESTINE";
3455 Country[Country["PAPUA_NEW_GUINEA"] = 207] = "PAPUA_NEW_GUINEA";
3456 Country[Country["PITCAIRN"] = 208] = "PITCAIRN";
3457 Country[Country["REUNION"] = 209] = "REUNION";
3458 Country[Country["RWANDA"] = 210] = "RWANDA";
3459 Country[Country["SAINT_BARTHELEMY"] = 211] = "SAINT_BARTHELEMY";
3460 Country[Country["SAINT_HELENA_ASCENSION_AND_TRISTIAN_DA_CUNHA"] = 212] = "SAINT_HELENA_ASCENSION_AND_TRISTIAN_DA_CUNHA";
3461 Country[Country["SAINT_KITTS_AND_NEVIS"] = 213] = "SAINT_KITTS_AND_NEVIS";
3462 Country[Country["SAINT_LUCIA"] = 214] = "SAINT_LUCIA";
3463 Country[Country["SAINT_MARTIN"] = 215] = "SAINT_MARTIN";
3464 Country[Country["SAINT_PIERRE_AND_MIQUELON"] = 216] = "SAINT_PIERRE_AND_MIQUELON";
3465 Country[Country["SAINT_VINCENT_AND_THE_GRENADINES"] = 217] = "SAINT_VINCENT_AND_THE_GRENADINES";
3466 Country[Country["SAMOA"] = 218] = "SAMOA";
3467 Country[Country["SAN_MARINO"] = 219] = "SAN_MARINO";
3468 Country[Country["SAO_TOME_AND_PRINCIPE"] = 220] = "SAO_TOME_AND_PRINCIPE";
3469 Country[Country["SENEGAL"] = 221] = "SENEGAL";
3470 Country[Country["SEYCHELLES"] = 222] = "SEYCHELLES";
3471 Country[Country["SIERRA_LEONE"] = 223] = "SIERRA_LEONE";
3472 Country[Country["SINT_MAARTEN"] = 224] = "SINT_MAARTEN";
3473 Country[Country["SOLOMON_ISLANDS"] = 225] = "SOLOMON_ISLANDS";
3474 Country[Country["SOMALIA"] = 226] = "SOMALIA";
3475 Country[Country["SOUTH_GEORGIA_AND_THE_SOUTH_SANDWICH_ISLANDS"] = 227] = "SOUTH_GEORGIA_AND_THE_SOUTH_SANDWICH_ISLANDS";
3476 Country[Country["SOUTH_SUDAN"] = 228] = "SOUTH_SUDAN";
3477 Country[Country["SUDAN"] = 229] = "SUDAN";
3478 Country[Country["SURINAME"] = 230] = "SURINAME";
3479 Country[Country["SVALBARD_AND_JAN_MAYEN"] = 231] = "SVALBARD_AND_JAN_MAYEN";
3480 Country[Country["ESWATINI"] = 232] = "ESWATINI";
3481 Country[Country["SYRIA"] = 233] = "SYRIA";
3482 Country[Country["TAJIKISTAN"] = 234] = "TAJIKISTAN";
3483 Country[Country["TANZANIA"] = 235] = "TANZANIA";
3484 Country[Country["TOGO"] = 236] = "TOGO";
3485 Country[Country["TOKELAU"] = 237] = "TOKELAU";
3486 Country[Country["TONGA"] = 238] = "TONGA";
3487 Country[Country["TRINIDAD_AND_TOBAGO"] = 239] = "TRINIDAD_AND_TOBAGO";
3488 Country[Country["TURKMENISTAN"] = 240] = "TURKMENISTAN";
3489 Country[Country["TURKS_AND_CAICOS_ISLANDS"] = 241] = "TURKS_AND_CAICOS_ISLANDS";
3490 Country[Country["TUVALU"] = 242] = "TUVALU";
3491 Country[Country["UNITED_STATES_MINOR_OUTLYING_ISLANDS"] = 243] = "UNITED_STATES_MINOR_OUTLYING_ISLANDS";
3492 Country[Country["UZBEKISTAN"] = 244] = "UZBEKISTAN";
3493 Country[Country["VANUATU"] = 245] = "VANUATU";
3494 Country[Country["VATICAN_CITY"] = 246] = "VATICAN_CITY";
3495 Country[Country["VIRGIN_ISLANDS_BRITISH"] = 247] = "VIRGIN_ISLANDS_BRITISH";
3496 Country[Country["VIRGIN_ISLANDS_US"] = 248] = "VIRGIN_ISLANDS_US";
3497 Country[Country["WALLIS_AND_FUTUNA"] = 249] = "WALLIS_AND_FUTUNA";
3498 Country[Country["WESTERN_SAHARA"] = 250] = "WESTERN_SAHARA";
3499 Country[Country["YEMEN"] = 251] = "YEMEN";
3500 Country[Country["YUGOSLAVIA"] = 252] = "YUGOSLAVIA";
3501 Country[Country["ZAMBIA"] = 253] = "ZAMBIA";
3502 Country[Country["ZIMBABWE"] = 254] = "ZIMBABWE";
3503 Country[Country["COUNT"] = 255] = "COUNT";
3504})(exports.Country || (exports.Country = {}));
3505(function (Region) {
3506 Region[Region["NONE"] = 0] = "NONE";
3507 Region[Region["ALABAMA"] = 1] = "ALABAMA";
3508 Region[Region["ALASKA"] = 2] = "ALASKA";
3509 Region[Region["ALBERTA"] = 3] = "ALBERTA";
3510 Region[Region["ARIZONA"] = 4] = "ARIZONA";
3511 Region[Region["ARKANSAS"] = 5] = "ARKANSAS";
3512 Region[Region["AUSTRALIAN_CAPITAL_TERRITORY"] = 6] = "AUSTRALIAN_CAPITAL_TERRITORY";
3513 Region[Region["BRITISH_COLUMBIA"] = 7] = "BRITISH_COLUMBIA";
3514 Region[Region["CALIFORNIA"] = 8] = "CALIFORNIA";
3515 Region[Region["COLORADO"] = 9] = "COLORADO";
3516 Region[Region["CONNECTICUT"] = 10] = "CONNECTICUT";
3517 Region[Region["DELAWARE"] = 11] = "DELAWARE";
3518 Region[Region["DISTRICT_OF_COLUMBIA"] = 12] = "DISTRICT_OF_COLUMBIA";
3519 Region[Region["FLORIDA"] = 13] = "FLORIDA";
3520 Region[Region["GEORGIA"] = 14] = "GEORGIA";
3521 Region[Region["HAWAII"] = 15] = "HAWAII";
3522 Region[Region["IDAHO"] = 16] = "IDAHO";
3523 Region[Region["ILLINOIS"] = 17] = "ILLINOIS";
3524 Region[Region["INDIANA"] = 18] = "INDIANA";
3525 Region[Region["IOWA"] = 19] = "IOWA";
3526 Region[Region["KANSAS"] = 20] = "KANSAS";
3527 Region[Region["KENTUCKY"] = 21] = "KENTUCKY";
3528 Region[Region["LOUISIANA"] = 22] = "LOUISIANA";
3529 Region[Region["MAINE"] = 23] = "MAINE";
3530 Region[Region["MANITOBA"] = 24] = "MANITOBA";
3531 Region[Region["MARYLAND"] = 25] = "MARYLAND";
3532 Region[Region["MASSACHUSETTS"] = 26] = "MASSACHUSETTS";
3533 Region[Region["MICHIGAN"] = 27] = "MICHIGAN";
3534 Region[Region["MINNESOTA"] = 28] = "MINNESOTA";
3535 Region[Region["MISSISSIPPI"] = 29] = "MISSISSIPPI";
3536 Region[Region["MISSOURI"] = 30] = "MISSOURI";
3537 Region[Region["MONTANA"] = 31] = "MONTANA";
3538 Region[Region["NEBRASKA"] = 32] = "NEBRASKA";
3539 Region[Region["NEVADA"] = 33] = "NEVADA";
3540 Region[Region["NEW_BRUNSWICK"] = 34] = "NEW_BRUNSWICK";
3541 Region[Region["NEW_HAMPSHIRE"] = 35] = "NEW_HAMPSHIRE";
3542 Region[Region["NEW_JERSEY"] = 36] = "NEW_JERSEY";
3543 Region[Region["NEW_MEXICO"] = 37] = "NEW_MEXICO";
3544 Region[Region["NEW_SOUTH_WALES"] = 38] = "NEW_SOUTH_WALES";
3545 Region[Region["NEW_YORK"] = 39] = "NEW_YORK";
3546 Region[Region["NORTHERN_TERRITORY"] = 40] = "NORTHERN_TERRITORY";
3547 Region[Region["NORTH_CAROLINA"] = 41] = "NORTH_CAROLINA";
3548 Region[Region["NORTH_DAKOTA"] = 42] = "NORTH_DAKOTA";
3549 Region[Region["NOVA_SCOTIA"] = 43] = "NOVA_SCOTIA";
3550 Region[Region["OHIO"] = 44] = "OHIO";
3551 Region[Region["OKLAHOMA"] = 45] = "OKLAHOMA";
3552 Region[Region["ONTARIO"] = 46] = "ONTARIO";
3553 Region[Region["OREGON"] = 47] = "OREGON";
3554 Region[Region["PENNSYLVANIA"] = 48] = "PENNSYLVANIA";
3555 Region[Region["QUEBEC"] = 49] = "QUEBEC";
3556 Region[Region["QUEENSLAND"] = 50] = "QUEENSLAND";
3557 Region[Region["RHODE_ISLAND"] = 51] = "RHODE_ISLAND";
3558 Region[Region["SASKATCHEWAN"] = 52] = "SASKATCHEWAN";
3559 Region[Region["SOUTH_AUSTRALIA"] = 53] = "SOUTH_AUSTRALIA";
3560 Region[Region["SOUTH_CAROLINA"] = 54] = "SOUTH_CAROLINA";
3561 Region[Region["SOUTH_DAKOTA"] = 55] = "SOUTH_DAKOTA";
3562 Region[Region["TASMANIA"] = 56] = "TASMANIA";
3563 Region[Region["TENNESSEE"] = 57] = "TENNESSEE";
3564 Region[Region["TEXAS"] = 58] = "TEXAS";
3565 Region[Region["UTAH"] = 59] = "UTAH";
3566 Region[Region["VERMONT"] = 60] = "VERMONT";
3567 Region[Region["VICTORIA"] = 61] = "VICTORIA";
3568 Region[Region["VIRGINIA"] = 62] = "VIRGINIA";
3569 Region[Region["WASHINGTON"] = 63] = "WASHINGTON";
3570 Region[Region["WESTERN_AUSTRALIA"] = 64] = "WESTERN_AUSTRALIA";
3571 Region[Region["WEST_VIRGINIA"] = 65] = "WEST_VIRGINIA";
3572 Region[Region["WISCONSIN"] = 66] = "WISCONSIN";
3573 Region[Region["WYOMING"] = 67] = "WYOMING";
3574 Region[Region["YUKON"] = 68] = "YUKON";
3575 Region[Region["CIUDAD_DE_MEXICO"] = 69] = "CIUDAD_DE_MEXICO";
3576 Region[Region["JALISCO"] = 70] = "JALISCO";
3577 Region[Region["NEWFOUNDLAND_AND_LABRADOR"] = 71] = "NEWFOUNDLAND_AND_LABRADOR";
3578 Region[Region["NUEVO_LEON"] = 72] = "NUEVO_LEON";
3579 Region[Region["BAJA_CALIFORNIA"] = 73] = "BAJA_CALIFORNIA";
3580 Region[Region["CHIHUAHUA"] = 74] = "CHIHUAHUA";
3581 Region[Region["GUANAJUATO"] = 75] = "GUANAJUATO";
3582 Region[Region["GUERRERO"] = 76] = "GUERRERO";
3583 Region[Region["MEXICO"] = 77] = "MEXICO";
3584 Region[Region["MICHOACAN"] = 78] = "MICHOACAN";
3585 Region[Region["NEW_YORK_CITY"] = 79] = "NEW_YORK_CITY";
3586 Region[Region["TAMAULIPAS"] = 80] = "TAMAULIPAS";
3587 Region[Region["VERACRUZ"] = 81] = "VERACRUZ";
3588 Region[Region["CHIAPAS"] = 82] = "CHIAPAS";
3589 Region[Region["COAHUILA"] = 83] = "COAHUILA";
3590 Region[Region["DURANGO"] = 84] = "DURANGO";
3591 Region[Region["GUERRERO_COCULA"] = 85] = "GUERRERO_COCULA";
3592 Region[Region["GUERRERO_JUCHITAN"] = 86] = "GUERRERO_JUCHITAN";
3593 Region[Region["GUERRERO_TEPECOACUILCO"] = 87] = "GUERRERO_TEPECOACUILCO";
3594 Region[Region["GUERRERO_TLACOAPA"] = 88] = "GUERRERO_TLACOAPA";
3595 Region[Region["GUJARAT"] = 89] = "GUJARAT";
3596 Region[Region["HIDALGO"] = 90] = "HIDALGO";
3597 Region[Region["KARNATAKA"] = 91] = "KARNATAKA";
3598 Region[Region["KERALA"] = 92] = "KERALA";
3599 Region[Region["KHYBER_PAKHTUNKHWA"] = 93] = "KHYBER_PAKHTUNKHWA";
3600 Region[Region["MADHYA_PRADESH"] = 94] = "MADHYA_PRADESH";
3601 Region[Region["MAHARASHTRA"] = 95] = "MAHARASHTRA";
3602 Region[Region["MORELOS"] = 96] = "MORELOS";
3603 Region[Region["NAYARIT"] = 97] = "NAYARIT";
3604 Region[Region["OAXACA"] = 98] = "OAXACA";
3605 Region[Region["PUEBLA"] = 99] = "PUEBLA";
3606 Region[Region["PUNJAB"] = 100] = "PUNJAB";
3607 Region[Region["QUERETARO"] = 101] = "QUERETARO";
3608 Region[Region["SAN_LUIS_POTOSI"] = 102] = "SAN_LUIS_POTOSI";
3609 Region[Region["SINALOA"] = 103] = "SINALOA";
3610 Region[Region["SONORA"] = 104] = "SONORA";
3611 Region[Region["TABASCO"] = 105] = "TABASCO";
3612 Region[Region["TAMIL_NADU"] = 106] = "TAMIL_NADU";
3613 Region[Region["YUCATAN"] = 107] = "YUCATAN";
3614 Region[Region["ZACATECAS"] = 108] = "ZACATECAS";
3615 Region[Region["AGUASCALIENTES"] = 109] = "AGUASCALIENTES";
3616 Region[Region["BAJA_CALIFORNIA_SUR"] = 110] = "BAJA_CALIFORNIA_SUR";
3617 Region[Region["CAMPECHE"] = 111] = "CAMPECHE";
3618 Region[Region["COLIMA"] = 112] = "COLIMA";
3619 Region[Region["QUINTANA_ROO_BENITO_JUAREZ"] = 113] = "QUINTANA_ROO_BENITO_JUAREZ";
3620 Region[Region["UINTANA_ROO"] = 114] = "UINTANA_ROO";
3621 Region[Region["QUINTANA_ROO_SOLIDARIDAD"] = 115] = "QUINTANA_ROO_SOLIDARIDAD";
3622 Region[Region["TLAXCALA"] = 116] = "TLAXCALA";
3623 Region[Region["COUNT"] = 117] = "COUNT";
3624})(exports.Region || (exports.Region = {}));
3625(function (DocumentType) {
3626 DocumentType[DocumentType["NONE"] = 0] = "NONE";
3627 DocumentType[DocumentType["CONSULAR_ID"] = 1] = "CONSULAR_ID";
3628 DocumentType[DocumentType["DL"] = 2] = "DL";
3629 DocumentType[DocumentType["DL_PUBLIC_SERVICES_CARD"] = 3] = "DL_PUBLIC_SERVICES_CARD";
3630 DocumentType[DocumentType["EMPLOYMENT_PASS"] = 4] = "EMPLOYMENT_PASS";
3631 DocumentType[DocumentType["FIN_CARD"] = 5] = "FIN_CARD";
3632 DocumentType[DocumentType["ID"] = 6] = "ID";
3633 DocumentType[DocumentType["MULTIPURPOSE_ID"] = 7] = "MULTIPURPOSE_ID";
3634 DocumentType[DocumentType["MyKad"] = 8] = "MyKad";
3635 DocumentType[DocumentType["MyKid"] = 9] = "MyKid";
3636 DocumentType[DocumentType["MyPR"] = 10] = "MyPR";
3637 DocumentType[DocumentType["MyTentera"] = 11] = "MyTentera";
3638 DocumentType[DocumentType["PAN_CARD"] = 12] = "PAN_CARD";
3639 DocumentType[DocumentType["PROFESSIONAL_ID"] = 13] = "PROFESSIONAL_ID";
3640 DocumentType[DocumentType["PUBLIC_SERVICES_CARD"] = 14] = "PUBLIC_SERVICES_CARD";
3641 DocumentType[DocumentType["RESIDENCE_PERMIT"] = 15] = "RESIDENCE_PERMIT";
3642 DocumentType[DocumentType["RESIDENT_ID"] = 16] = "RESIDENT_ID";
3643 DocumentType[DocumentType["TEMPORARY_RESIDENCE_PERMIT"] = 17] = "TEMPORARY_RESIDENCE_PERMIT";
3644 DocumentType[DocumentType["VOTER_ID"] = 18] = "VOTER_ID";
3645 DocumentType[DocumentType["WORK_PERMIT"] = 19] = "WORK_PERMIT";
3646 DocumentType[DocumentType["iKAD"] = 20] = "iKAD";
3647 DocumentType[DocumentType["MILITARY_ID"] = 21] = "MILITARY_ID";
3648 DocumentType[DocumentType["MyKAS"] = 22] = "MyKAS";
3649 DocumentType[DocumentType["SOCIAL_SECURITY_CARD"] = 23] = "SOCIAL_SECURITY_CARD";
3650 DocumentType[DocumentType["HEALTH_INSURANCE_CARD"] = 24] = "HEALTH_INSURANCE_CARD";
3651 DocumentType[DocumentType["PASSPORT"] = 25] = "PASSPORT";
3652 DocumentType[DocumentType["S_PASS"] = 26] = "S_PASS";
3653 DocumentType[DocumentType["ADDRESS_CARD"] = 27] = "ADDRESS_CARD";
3654 DocumentType[DocumentType["ALIEN_ID"] = 28] = "ALIEN_ID";
3655 DocumentType[DocumentType["ALIEN_PASSPORT"] = 29] = "ALIEN_PASSPORT";
3656 DocumentType[DocumentType["GREEN_CARD"] = 30] = "GREEN_CARD";
3657 DocumentType[DocumentType["MINORS_ID"] = 31] = "MINORS_ID";
3658 DocumentType[DocumentType["POSTAL_ID"] = 32] = "POSTAL_ID";
3659 DocumentType[DocumentType["PROFESSIONAL_DL"] = 33] = "PROFESSIONAL_DL";
3660 DocumentType[DocumentType["TAX_ID"] = 34] = "TAX_ID";
3661 DocumentType[DocumentType["WEAPON_PERMIT"] = 35] = "WEAPON_PERMIT";
3662 DocumentType[DocumentType["VISA"] = 36] = "VISA";
3663 DocumentType[DocumentType["BORDER_CROSSING_CARD"] = 37] = "BORDER_CROSSING_CARD";
3664 DocumentType[DocumentType["DRIVER_CARD"] = 38] = "DRIVER_CARD";
3665 DocumentType[DocumentType["GLOBAL_ENTRY_CARD"] = 39] = "GLOBAL_ENTRY_CARD";
3666 DocumentType[DocumentType["MyPolis"] = 40] = "MyPolis";
3667 DocumentType[DocumentType["NEXUS_CARD"] = 41] = "NEXUS_CARD";
3668 DocumentType[DocumentType["PASSPORT_CARD"] = 42] = "PASSPORT_CARD";
3669 DocumentType[DocumentType["PROOF_OF_AGE_CARD"] = 43] = "PROOF_OF_AGE_CARD";
3670 DocumentType[DocumentType["REFUGEE_ID"] = 44] = "REFUGEE_ID";
3671 DocumentType[DocumentType["TRIBAL_ID"] = 45] = "TRIBAL_ID";
3672 DocumentType[DocumentType["VETERAN_ID"] = 46] = "VETERAN_ID";
3673 DocumentType[DocumentType["CITIZENSHIP_CERTIFICATE"] = 47] = "CITIZENSHIP_CERTIFICATE";
3674 DocumentType[DocumentType["MY_NUMBER_CARD"] = 48] = "MY_NUMBER_CARD";
3675 DocumentType[DocumentType["COUNT"] = 49] = "COUNT";
3676})(exports.DocumentType || (exports.DocumentType = {}));
3677
3678/**
3679 * Copyright (c) Microblink Ltd. All rights reserved.
3680 */
3681(function (DocumentImageColorStatus) {
3682 /** Determining image color status was not performed */
3683 DocumentImageColorStatus[DocumentImageColorStatus["NotAvailable"] = 0] = "NotAvailable";
3684 /** Black-and-white image scanned */
3685 DocumentImageColorStatus[DocumentImageColorStatus["BlackAndWhite"] = 1] = "BlackAndWhite";
3686 /** Color image scanned */
3687 DocumentImageColorStatus[DocumentImageColorStatus["Color"] = 2] = "Color";
3688})(exports.DocumentImageColorStatus || (exports.DocumentImageColorStatus = {}));
3689(function (ImageAnalysisDetectionStatus) {
3690 /** Detection was not performed */
3691 ImageAnalysisDetectionStatus[ImageAnalysisDetectionStatus["NotAvailable"] = 0] = "NotAvailable";
3692 /** Object not detected on input image */
3693 ImageAnalysisDetectionStatus[ImageAnalysisDetectionStatus["NotDetected"] = 1] = "NotDetected";
3694 /** Object detected on input image */
3695 ImageAnalysisDetectionStatus[ImageAnalysisDetectionStatus["Detected"] = 2] = "Detected";
3696})(exports.ImageAnalysisDetectionStatus || (exports.ImageAnalysisDetectionStatus = {}));
3697
3698/**
3699 * Copyright (c) Microblink Ltd. All rights reserved.
3700 */
3701(function (ProcessingStatus) {
3702 /** Recognition was successful. */
3703 ProcessingStatus[ProcessingStatus["Success"] = 0] = "Success";
3704 /** Detection of the document failed. */
3705 ProcessingStatus[ProcessingStatus["DetectionFailed"] = 1] = "DetectionFailed";
3706 /** Preprocessing of the input image has failed. */
3707 ProcessingStatus[ProcessingStatus["ImagePreprocessingFailed"] = 2] = "ImagePreprocessingFailed";
3708 /** Recognizer has inconsistent results. */
3709 ProcessingStatus[ProcessingStatus["StabilityTestFailed"] = 3] = "StabilityTestFailed";
3710 /** Wrong side of the document has been scanned. */
3711 ProcessingStatus[ProcessingStatus["ScanningWrongSide"] = 4] = "ScanningWrongSide";
3712 /** Identification of the fields present on the document has failed. */
3713 ProcessingStatus[ProcessingStatus["FieldIdentificationFailed"] = 5] = "FieldIdentificationFailed";
3714 /** Mandatory field for the specific document is missing. */
3715 ProcessingStatus[ProcessingStatus["MandatoryFieldMissing"] = 6] = "MandatoryFieldMissing";
3716 /** Result contains invalid characters in some of the fields. */
3717 ProcessingStatus[ProcessingStatus["InvalidCharactersFound"] = 7] = "InvalidCharactersFound";
3718 /** Failed to return a requested image. */
3719 ProcessingStatus[ProcessingStatus["ImageReturnFailed"] = 8] = "ImageReturnFailed";
3720 /** Reading or parsing of the barcode has failed. */
3721 ProcessingStatus[ProcessingStatus["BarcodeRecognitionFailed"] = 9] = "BarcodeRecognitionFailed";
3722 /** Parsing of the MRZ has failed. */
3723 ProcessingStatus[ProcessingStatus["MrzParsingFailed"] = 10] = "MrzParsingFailed";
3724 /** Document class has been filtered out. */
3725 ProcessingStatus[ProcessingStatus["ClassFiltered"] = 11] = "ClassFiltered";
3726 /** Document currently not supported by the recognizer. */
3727 ProcessingStatus[ProcessingStatus["UnsupportedClass"] = 12] = "UnsupportedClass";
3728 /** License for the detected document is missing. */
3729 ProcessingStatus[ProcessingStatus["UnsupportedByLicense"] = 13] = "UnsupportedByLicense";
3730 /**
3731 * Front side recognition has completed successfully, and recognizer is waiting for the other
3732 * side to be scanned.
3733 */
3734 ProcessingStatus[ProcessingStatus["AwaitingOtherSide"] = 14] = "AwaitingOtherSide";
3735 /** Number of possible processing statuses. */
3736 ProcessingStatus[ProcessingStatus["Count"] = 15] = "Count";
3737})(exports.ProcessingStatus || (exports.ProcessingStatus = {}));
3738
3739/**
3740 * Copyright (c) Microblink Ltd. All rights reserved.
3741 */
3742(function (RecognitionMode) {
3743 /** No recognition performed. */
3744 RecognitionMode[RecognitionMode["None"] = 0] = "None";
3745 /** Recognition of mrz document (does not include visa and passport) */
3746 RecognitionMode[RecognitionMode["MrzId"] = 1] = "MrzId";
3747 /** Recognition of visa mrz. */
3748 RecognitionMode[RecognitionMode["MrzVisa"] = 2] = "MrzVisa";
3749 /** Recognition of passport mrz. */
3750 RecognitionMode[RecognitionMode["MrzPassport"] = 3] = "MrzPassport";
3751 /** Recognition of documents that have face photo on the front. */
3752 RecognitionMode[RecognitionMode["PhotoId"] = 4] = "PhotoId";
3753 /** Detailed document recognition. */
3754 RecognitionMode[RecognitionMode["FullRecognition"] = 5] = "FullRecognition";
3755 /** Recognition of barcode document. */
3756 RecognitionMode[RecognitionMode["BarcodeId"] = 6] = "BarcodeId";
3757 /** Number of possible values */
3758 RecognitionMode[RecognitionMode["Count"] = 7] = "Count";
3759})(exports.RecognitionMode || (exports.RecognitionMode = {}));
3760
3761/**
3762 * Copyright (c) Microblink Ltd. All rights reserved.
3763 */
3764/**
3765 * A settings object that is used for configuring the BlinkIdRecognizer.
3766 */
3767class BlinkIdRecognizerSettings {
3768 constructor() {
3769 /**
3770 * Defines whether blured frames filtering is allowed.
3771 */
3772 this.allowBlurFilter = true;
3773 /**
3774 * Defines whether returning of unparsed MRZ (Machine Readable Zone) results is allowed.
3775 */
3776 this.allowUnparsedMrzResults = false;
3777 /**
3778 * Defines whether returning unverified MRZ (Machine Readable Zone) results is allowed.
3779 * Unverified MRZ is parsed, but check digits are incorrect.
3780 */
3781 this.allowUnverifiedMrzResults = true;
3782 /**
3783 * Enable or disable recognition of specific document groups supported by the current license.
3784 * By default all modes are enabled.
3785 */
3786 this.recognitionModeFilter = new RecognitionModeFilter();
3787 /**
3788 * Enable or disable the saving of camera frames from which data is extracted.
3789 */
3790 this.saveCameraFrames = false;
3791 /**
3792 * Configure the recognizer to only work on already cropped and dewarped images.
3793 * This only works for still images - video feeds will ignore this setting.
3794 */
3795 this.scanCroppedDocumentImage = false;
3796 /**
3797 * Whether result characters validatation is performed.
3798 * If a result member contains invalid character, the result state cannot be valid.
3799 */
3800 this.validateResultCharacters = true;
3801 /**
3802 * Whether sensitive data should be removed from images, result fields or both.
3803 * The setting only applies to certain documents.
3804 */
3805 this.anonymizationMode = exports.AnonymizationMode.FullResult;
3806 /**
3807 * Called when barcode scanning step starts.
3808 */
3809 this.barcodeScanningStartedCallback = null;
3810 /**
3811 * Called when recognizer classifies a document.
3812 */
3813 this.classifierCallback = null;
3814 /**
3815 * If set to `null`, all supported documents will be recognized.
3816 * Otherwise, only classes from given array will be recognized and all other
3817 * documents will be treated as "not supported" (observable via classifierCallback).
3818 */
3819 this.allowedDocumentClasses = null;
3820 /**
3821 * Padding is a minimum distance from the edge of the frame and it is defined
3822 * as a percentage of the frame width. Recommended value is '0.02'.
3823 * By default, this is set to '0.0' which means that padding edge and image edge are the same.
3824 */
3825 this.paddingEdge = 0.0;
3826 // implementation of the FullDocumentImageOptions interface
3827 this.returnFullDocumentImage = false;
3828 this.returnEncodedFullDocumentImage = false;
3829 this._fullDocumentImageDpi = 250;
3830 this.fullDocumentImageExtensionFactors = new ExtensionFactors();
3831 // implementation of the FaceImageOptions interface
3832 this.returnFaceImage = false;
3833 this.returnEncodedFaceImage = false;
3834 this._faceImageDpi = 250;
3835 // implementation of the SignatureImageOptions interface
3836 this.returnSignatureImage = false;
3837 this.returnEncodedSignatureImage = false;
3838 this._signatureImageDpi = 250;
3839 }
3840 get fullDocumentImageDpi() { return this._fullDocumentImageDpi; }
3841 set fullDocumentImageDpi(value) {
3842 validateDpi(value);
3843 this._fullDocumentImageDpi = value;
3844 }
3845 get faceImageDpi() { return this._faceImageDpi; }
3846 set faceImageDpi(value) {
3847 validateDpi(value);
3848 this._faceImageDpi = value;
3849 }
3850 get signatureImageDpi() { return this._signatureImageDpi; }
3851 set signatureImageDpi(value) {
3852 validateDpi(value);
3853 this._signatureImageDpi = value;
3854 }
3855}
3856/**
3857 * This function is used to create a new instance of `BlinkIdRecognizer`.
3858 * @param wasmSDK Instance of WasmSDK which will be used to communicate with the WebAssembly module.
3859 */
3860function createBlinkIdRecognizer(wasmSDK) {
3861 return __awaiter(this, void 0, void 0, function* () {
3862 return wasmSDK.mbWasmModule.newRecognizer("BlinkIdRecognizer");
3863 });
3864}
3865
3866/**
3867 * Copyright (c) Microblink Ltd. All rights reserved.
3868 */
3869/**
3870 * A settings object that is used for configuring the BlinkIdCombinedRecognizer.
3871 */
3872class BlinkIdCombinedRecognizerSettings extends BlinkIdRecognizerSettings {
3873 constructor() {
3874 super(...arguments);
3875 /**
3876 * Proceed with scanning the back side even if the front side result is uncertain.
3877 * This only works for still images - video feeds will ignore this setting.
3878 */
3879 this.allowUncertainFrontSideScan = false;
3880 /**
3881 * Configure the number of characters per field that are allowed to be inconsistent in data match.
3882 */
3883 this.maxAllowedMismatchesPerField = 0;
3884 /**
3885 * Skip the scan of the back side for documents where back side scanning is not supported.
3886 */
3887 this.skipUnsupportedBack = false;
3888 }
3889}
3890/**
3891 * This function is used to create a new instance of `BlinkIdCombinedRecognizer`.
3892 * @param wasmSDK Instance of WasmSDK which will be used to communicate with the WebAssembly module.
3893 */
3894function createBlinkIdCombinedRecognizer(wasmSDK) {
3895 return __awaiter(this, void 0, void 0, function* () {
3896 return wasmSDK.mbWasmModule.newRecognizer("BlinkIdCombinedRecognizer");
3897 });
3898}
3899
3900/**
3901 * Copyright (c) Microblink Ltd. All rights reserved.
3902 */
3903/**
3904 * A settings object that is used for configuring the IdBarcodeRecognizer.
3905 */
3906class IdBarcodeRecognizerSettings {
3907}
3908/**
3909 * This function is used to create a new instance of `IdBarcodeRecognizer`.
3910 * @param wasmSDK Instance of WasmSDK which will be used to communicate with the WebAssembly module.
3911 */
3912function createIdBarcodeRecognizer(wasmSDK) {
3913 return __awaiter(this, void 0, void 0, function* () {
3914 return wasmSDK.mbWasmModule.newRecognizer("IdBarcodeRecognizer");
3915 });
3916}
3917(function (IdBarcodeDocumentType) {
3918 /**
3919 * No document was scanned
3920 */
3921 IdBarcodeDocumentType[IdBarcodeDocumentType["None"] = 0] = "None";
3922 /**
3923 * AAMVACompliant document was scanned
3924 */
3925 IdBarcodeDocumentType[IdBarcodeDocumentType["AAMVACompliant"] = 1] = "AAMVACompliant";
3926 /**
3927 * ArgentinaID document was scanned
3928 */
3929 IdBarcodeDocumentType[IdBarcodeDocumentType["ArgentinaID"] = 2] = "ArgentinaID";
3930 /**
3931 * ArgentinaAlienID document was scanned
3932 */
3933 IdBarcodeDocumentType[IdBarcodeDocumentType["ArgentinaAlienID"] = 3] = "ArgentinaAlienID";
3934 /**
3935 * ArgentinaDL document was scanned
3936 */
3937 IdBarcodeDocumentType[IdBarcodeDocumentType["ArgentinaDL"] = 4] = "ArgentinaDL";
3938 /**
3939 * ColombiaID document was scanned
3940 */
3941 IdBarcodeDocumentType[IdBarcodeDocumentType["ColombiaID"] = 5] = "ColombiaID";
3942 /**
3943 * ColombiaDL document was scanned
3944 */
3945 IdBarcodeDocumentType[IdBarcodeDocumentType["ColombiaDL"] = 6] = "ColombiaDL";
3946 /**
3947 * NigeriaVoterID document was scanned
3948 */
3949 IdBarcodeDocumentType[IdBarcodeDocumentType["NigeriaVoterID"] = 7] = "NigeriaVoterID";
3950 /**
3951 * NigeriaDL document was scanned
3952 */
3953 IdBarcodeDocumentType[IdBarcodeDocumentType["NigeriaDL"] = 8] = "NigeriaDL";
3954 /**
3955 * PanamaID document was scanned
3956 */
3957 IdBarcodeDocumentType[IdBarcodeDocumentType["PanamaID"] = 9] = "PanamaID";
3958 /**
3959 * SouthAfricaID document was scanned
3960 */
3961 IdBarcodeDocumentType[IdBarcodeDocumentType["SouthAfricaID"] = 10] = "SouthAfricaID";
3962})(exports.IdBarcodeDocumentType || (exports.IdBarcodeDocumentType = {}));
3963
3964exports.BlinkIdCombinedRecognizerSettings = BlinkIdCombinedRecognizerSettings;
3965exports.BlinkIdRecognizerSettings = BlinkIdRecognizerSettings;
3966exports.CapturedFrame = CapturedFrame;
3967exports.ExtensionFactors = ExtensionFactors;
3968exports.IdBarcodeRecognizerSettings = IdBarcodeRecognizerSettings;
3969exports.RecognitionModeFilter = RecognitionModeFilter;
3970exports.SDKError = SDKError;
3971exports.SelectedCamera = SelectedCamera;
3972exports.VideoRecognizer = VideoRecognizer;
3973exports.WasmSDKLoadSettings = WasmSDKLoadSettings;
3974exports.bindCameraToVideoFeed = bindCameraToVideoFeed;
3975exports.captureFrame = captureFrame;
3976exports.clearVideoFeed = clearVideoFeed;
3977exports.createBlinkIdCombinedRecognizer = createBlinkIdCombinedRecognizer;
3978exports.createBlinkIdRecognizer = createBlinkIdRecognizer;
3979exports.createIdBarcodeRecognizer = createIdBarcodeRecognizer;
3980exports.createRecognizerRunner = createRecognizerRunner;
3981exports.createSuccessFrameGrabberRecognizer = createSuccessFrameGrabberRecognizer;
3982exports.detectWasmType = detectWasmType;
3983exports.frameCaptureErrors = frameCaptureErrors;
3984exports.getCameraDevices = getCameraDevices;
3985exports.isBrowserSupported = isBrowserSupported;
3986exports.isInAppBrowser = isInAppBrowser;
3987exports.licenseErrors = licenseErrors;
3988exports.loadWasmModule = loadWasmModule;
3989exports.localSdkErrors = localSdkErrors;
3990exports.obtainNewServerPermission = obtainNewServerPermission;
3991exports.sdkErrors = sdkErrors;
3992exports.selectCamera = selectCamera;
3993exports.unlockWasmSDK = unlockWasmSDK;
3994exports.validateDpi = validateDpi;
3995exports.videoRecognizerErrors = videoRecognizerErrors;
3996exports.wasmFolder = wasmFolder;
3997exports.workerErrors = workerErrors;
3998
3999Object.defineProperty(exports, '__esModule', { value: true });
4000
4001})));