@microblink/blinkid-in-browser-sdk
Version:
A simple ID scanning library for WebAssembly-enabled browsers.
16 lines (13 loc) • 17.1 kB
JavaScript
!function(){"use strict";
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */function e(e,t,s,r){return new(s||(s=Promise))((function(n,i){function o(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((r=r.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 r extends s{constructor(e,t){super(r.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}}var n,i,o,a;r.action="init",function(e){e[e.Any=0]="Any",e[e.Recognizer=1]="Recognizer",e[e.RecognizerSettings=2]="RecognizerSettings",e[e.Callback=3]="Callback"}(n||(n={}));class c extends s{constructor(e,t){super(c.action),this.funcName=e,this.params=t}}c.action="invokeFunction";class l extends s{constructor(e,t){super(l.action),this.className=e,this.params=t}}l.action="createNewNativeObject";class u extends s{constructor(e,t,s){super(u.action),this.recognizerHandles=e,this.allowMultipleResults=t,this.registeredMetadataCallbacks=s}}u.action="createRecognizerRunner";class h extends s{constructor(e,t){super(h.action),this.recognizerHandles=e,this.allowMultipleResults=t}}h.action="reconfigureRecognizerRunner";class d extends s{constructor(){super(d.action)}}d.action="deleteRecognizerRunner";class g extends s{constructor(e,t,s){super(g.action),this.objectHandle=e,this.methodName=t,this.params=s}}g.action="invokeObject";class m extends s{constructor(e){super(m.action),this.frame=e}getTransferrables(){return[this.frame.imageData.data.buffer]}}m.action="processImage";class f extends s{constructor(e){super(f.action),this.hardReset=e}}f.action="resetRecognizers";class p extends s{constructor(e){super(p.action),this.registeredMetadataCallbacks=e}}p.action="registerMetadataCallbacks";class R extends s{constructor(e){super(R.action),this.detectionOnlyMode=e}}R.action="setDetectionOnly";class b extends s{constructor(e){super(b.action),this.callbackNonEmpty=e}}b.action="setClearTimeoutCallback";class k extends s{constructor(e){super(k.action),this.cameraPreviewMirrored=e}}k.action="setCameraPreviewMirrored";class y{constructor(e,t,s){this.success=!0,this.error=null,this.messageID=e,this.success=t,this.error=s}}class w{constructor(e,t,s){this.success=!0,this.showOverlay=!0,this.messageID=e,this.showOverlay=s}}class v extends y{constructor(e,t){super(e,!0,null),this.result=t}}class C extends y{constructor(e,t){super(e,!0,null),this.objectHandle=t}}class z extends y{constructor(e,t){super(e,!0,null),this.recognitionState=t}}class E{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 I(e,t){return t=t||"",""===(e=e||"")?t:e.endsWith("/")?t.startsWith("/")?e+t.substring(1):e+t:t.startsWith("/")?e+t:e+"/"+t}!function(e){e[e.Invalid=0]="Invalid",e[e.RequiresServerPermission=1]="RequiresServerPermission",e[e.Valid=2]="Valid"}(o||(o={})),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"}(a||(a={}));class S{constructor(e,t){this.code="UNLOCK_LICENSE_ERROR",this.message=null,this.type=e,t&&(this.message=t)}}function x(e){return{licenseId:e.licenseId,licensee:e.licensee,packageName:e.packageName,platform:"Browser",sdkName:e.sdkName,sdkVersion:e.sdkVersion}}var T;function P(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(x(t))});if(e.ok){const t=""+(yield e.text());return s.submitServerPermission(t)}return{status:T.NetworkError,lease:0,networkErrorDescription:"Server responded with status "+e.status}}catch(e){return{status:T.NetworkError,lease:0,networkErrorDescription:"Unexpected error: "+JSON.stringify(e)}}}))}!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"}(T||(T={}));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 r.action:this.processInitMessage(t);break;case c.action:this.processInvokeFunction(t);break;case l.action:this.processCreateNewRecognizer(t);break;case g.action:this.processInvokeObject(t);break;case u.action:this.processCreateRecognizerRunner(t);break;case h.action:this.processReconfigureRecognizerRunner(t);break;case d.action:this.processDeleteRecognizerRunner(t);break;case m.action:this.processImage(t);break;case f.action:this.resetRecognizers(t);break;case R.action:this.setDetectionOnly(t);break;case k.action:this.setCameraPreviewMirrored(t);break;case p.action:this.registerMetadataCallbacks(t);break;case b.action:this.registerClearTimeoutCallback(t);break;default:throw Error("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 y(e.messageID,!1,t))}notifySuccess(e){this.context.postMessage(new y(e.messageID,!0,null))}notifyInitSuccess(e,t){this.context.postMessage(new w(e.messageID,!0,t))}unwrapParameters(e){const t=[];for(const s of e.params){let r=s.parameter;s.type===n.Recognizer?(r=this.objects[r],void 0===r&&this.notifyError(e,"Cannot find object with handle: undefined")):s.type===n.RecognizerSettings&&(r=this.restoreFunctions(r)),t.push(r)}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===n.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 r of t){const t=e[r];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 P(e,this.wasmModule);switch(s.status){case T.Ok:case T.RemoteLock:this.registerHeartBeat(s.lease);break;case T.NetworkError:case T.PayloadSignatureVerificationFailed:case T.PayloadCorrupted:t?(console.warn("Problem with obtaining server permission. Will attempt in 10 seconds "+T[s.status]),this.inFlightHeartBeatTimeoutId=setTimeout(()=>{this.obtainNewServerPermission(!1)},1e4)):console.error("Problem with obtaining server permission. "+T[s.status]);break;case T.IncorrectTokenState:case T.PermissionExpired:console.error("Internal error: "+T[s.status])}return s.status}return console.error("Internal inconsistency! Wasm module not initialized where it's expected to be!"),T.IncorrectTokenState}))}willSoonExpire(){if(this.lease){if(this.wasmModule.getActiveLicenseTokenInfo().unlockResult===o.Valid){const e=Math.floor(Date.now()/1e3);return 30>this.lease-e}return!0}return!1}processInitMessage(t){let s={locateFile:e=>I(""===t.engineLocation?self.location.origin:t.engineLocation,e)};t.registerLoadCallback&&(s=Object.assign(s,{setStatus:e=>{const t=new E(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 r=""===t.engineLocation?self.location.origin:t.engineLocation,n=I(r,t.wasmModuleName+".js");importScripts(n);(0,self[t.wasmModuleName])(s).then(s=>e(this,void 0,void 0,(function*(){const r=yield function(t,s,r,n){return e(this,void 0,void 0,(function*(){const e=n.initializeWithLicenseKey(t,r,s);switch(e.unlockResult){case o.Invalid:return{error:new S(a.LicenseTokenStateInvalid,e.licenseError)};case o.Valid:return{error:null,showOverlay:(i=e.isTrial,c=e.allowRemoveDemoOverlay,l=e.allowRemoveProductionOverlay,!(i&&c||!i&&l))};case o.RequiresServerPermission:{const t=yield P(e,n);switch(t.status){case T.Ok:return{error:null,lease:t.lease};case T.NetworkError:{let e="";return t.networkErrorDescription&&(e=" "+t.networkErrorDescription),{error:new S(a.NetworkError,"There has been a network error while obtaining the server permission!"+e)}}case T.RemoteLock:return{error:new S(a.RemoteLock,"Provided license key has been remotely locked.Please contact support for more information!"),lease:t.lease};case T.PermissionExpired:return{error:new S(a.PermissionExpired,"Internal error (server permission expired)"),lease:t.lease};case T.PayloadCorrupted:return{error:new S(a.PayloadCorrupted,"Server permission payload is corrupted!"),lease:t.lease};case T.PayloadSignatureVerificationFailed:return{error:new S(a.PayloadSignatureVerificationFailed,"Failed to verify server permission's digital signature!"),lease:t.lease};case T.IncorrectTokenState:return{error:new S(a.IncorrectTokenState,"Internal error (Incorrect token state)"),lease:t.lease}}}}var i,c,l}))}(t.licenseKey,t.allowHelloMessage,t.userId,s);null===r.error?(this.wasmModule=s,r.lease?this.registerHeartBeat(r.lease):this.unregisterHeartBeat(),this.notifyInitSuccess(t,!!r.showOverlay)):this.notifyError(t,r.error)})),e=>{this.notifyError(t,e)})}catch(e){this.notifyError(t,e)}}processInvokeFunction(e){if(null===this.wasmModule)return void this.notifyError(e,"WASM module is not initialized!");const t=e.funcName,s=this.unwrapParameters(e);try{const r=this.wasmModule[t](...s);this.context.postMessage(new v(e.messageID,r))}catch(t){this.notifyError(e,t)}}processCreateNewRecognizer(e){if(null===this.wasmModule)return void this.notifyError(e,"WASM module is not initialized!");const t=e.className,s=this.unwrapParameters(e);try{const r=new this.wasmModule[t](...s),n=this.getNextObjectHandle();this.objects[n]=r,this.context.postMessage(new C(e.messageID,n))}catch(t){this.notifyError(e,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,"WASM module is not initialized!");else if(null!==this.nativeRecognizerRunner)this.notifyError(t,"Recognizer runner is already created! Multiple instances are not allowed!");else{this.setupMetadataCallbacks(t.registeredMetadataCallbacks);try{if(this.willSoonExpire()){const e=yield this.obtainNewServerPermission(!1);if(e!==T.Ok){const s=T[e];return void this.notifyError(t,new S(a[s],"Cannot initialize recognizers because of invalid server permission: "+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,e)}}}))}processReconfigureRecognizerRunner(e){if(null===this.wasmModule)this.notifyError(e,"WASM module is not initialized!");else if(null===this.nativeRecognizerRunner)this.notifyError(e,"Recognizer runner is not created! There is nothing to reconfigure!");else try{const t=this.getRecognizers(e.recognizerHandles);this.nativeRecognizerRunner.reconfigureRecognizers(t,e.allowMultipleResults),this.notifySuccess(e)}catch(t){this.notifyError(e,t)}}processDeleteRecognizerRunner(e){if(null!==this.nativeRecognizerRunner)try{this.nativeRecognizerRunner.delete(),this.nativeRecognizerRunner=null,this.notifySuccess(e)}catch(t){this.notifyError(e,t)}else this.notifyError(e,"Recognizer runner is already deleted!")}processInvokeObject(e){try{const t=e.objectHandle,s=e.methodName,r=this.unwrapParameters(e),n=this.objects[t];if(void 0===n)this.notifyError(e,"Cannot find object with handle: "+t);else{const i=n[s](...r),o=this.scanForTransferrables(i);"delete"===s&&delete this.objects[t],this.context.postMessage(new v(e.messageID,i),o)}}catch(t){this.notifyError(e,t)}}processImage(e){if(null!==this.nativeRecognizerRunner)try{const t=this.nativeRecognizerRunner.processImage(e.frame);this.context.postMessage(new z(e.messageID,t))}catch(t){this.notifyError(e,t)}else this.notifyError(e,"Recognizer runner is not initialized! Cannot process image!")}resetRecognizers(e){if(null!==this.nativeRecognizerRunner)try{this.nativeRecognizerRunner.resetRecognizers(e.hardReset),this.notifySuccess(e)}catch(t){this.notifyError(e,t)}else this.notifyError(e,"Recognizer runner is not initialized! Cannot process image!")}setDetectionOnly(e){if(null!==this.nativeRecognizerRunner)try{this.nativeRecognizerRunner.setDetectionOnlyMode(e.detectionOnlyMode),this.notifySuccess(e)}catch(t){this.notifyError(e,t)}else this.notifyError(e,"Recognizer runner is not initialized! Cannot process image!")}setCameraPreviewMirrored(e){if(null!==this.nativeRecognizerRunner)try{this.nativeRecognizerRunner.setCameraPreviewMirrored(e.cameraPreviewMirrored),this.notifySuccess(e)}catch(t){this.notifyError(e,t)}else this.notifyError(e,"Recognizer runner is not initialized! Cannot process image!")}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,t)}}else this.notifyError(e,"Recognizer runner is not initialized! Cannot process image!")}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,t)}}else this.notifyError(e,"Recognizer runner is not initialized! Cannot process image!")}}}();