diff --git a/README.md b/README.md index acfc001..f855dc6 100644 --- a/README.md +++ b/README.md @@ -139,7 +139,7 @@ Let's now go through the code of the Hello World sample and understand the purpo Dynamsoft MRZ Scanner - Hello World - + diff --git a/dev-server/index.js b/dev-server/index.js index b16f43a..ae3612c 100644 --- a/dev-server/index.js +++ b/dev-server/index.js @@ -50,6 +50,10 @@ app.get("/hello-world", (req, res) => { res.sendFile(path.join(__dirname, "../samples/hello-world.html")); }); +app.get("/scenarios/use-file-input", (req, res) => { + res.sendFile(path.join(__dirname, "../samples/scenarios/use-file-input.html")); +}); + let httpPort = 3002; let httpsPort = 3003; @@ -113,6 +117,8 @@ httpServer.listen(httpPort, () => { console.log("\x1b[90m-------------------\x1b[0m"); console.log("\x1b[33m Hello World:\x1b[0m http://localhost:" + httpPort + "/hello-world"); console.log("\x1b[33m Demo:\x1b[0m http://localhost:" + httpPort + "/demo"); + console.log("\x1b[90m-------------------\x1b[0m"); + console.log("\x1b[33m Use File Input:\x1b[0m http://localhost:" + httpPort + "/scenarios/use-file-input"); }); httpsServer.listen(httpsPort, "0.0.0.0", () => { @@ -132,6 +138,8 @@ httpsServer.listen(httpsPort, "0.0.0.0", () => { ipv4Addresses.forEach((localIP) => { console.log("\x1b[32m Hello World:\x1b[0m https://" + localIP + ":" + httpsPort + "/hello-world"); console.log("\x1b[32m Demo:\x1b[0m https://" + localIP + ":" + httpsPort + "/demo"); + console.log("\x1b[90m-------------------\x1b[0m"); + console.log("\x1b[32m Use File Input:\x1b[0m https://" + localIP + ":" + httpsPort + "/scenarios/use-file-input"); }); console.log("\n"); console.log("\x1b[90mPress Ctrl+C to stop the server\x1b[0m\n"); diff --git a/dist/mrz-scanner.bundle.esm.d.ts b/dist/mrz-scanner.bundle.esm.d.ts index e0096c4..b544f99 100644 --- a/dist/mrz-scanner.bundle.esm.d.ts +++ b/dist/mrz-scanner.bundle.esm.d.ts @@ -67,7 +67,9 @@ declare enum EnumMRZData { Age = "age", Sex = "sex", IssuingState = "issuingState", + IssuingStateRaw = "issuingStateRaw", Nationality = "nationality", + NationalityRaw = "nationalityRaw", DateOfBirth = "dateOfBirth", DateOfExpiry = "dateOfExpiry" } @@ -75,6 +77,7 @@ interface MRZResult { status: ResultStatus; originalImageResult?: DSImageData; data?: MRZData; + imageData?: boolean; _imageData?: DSImageData; } interface MRZData { @@ -87,7 +90,9 @@ interface MRZData { [EnumMRZData.Age]: number; [EnumMRZData.Sex]: string; [EnumMRZData.IssuingState]: string; + [EnumMRZData.IssuingStateRaw]: string; [EnumMRZData.Nationality]: string; + [EnumMRZData.NationalityRaw]: string; [EnumMRZData.DateOfBirth]: MRZDate; [EnumMRZData.DateOfExpiry]: MRZDate; } @@ -109,7 +114,10 @@ interface MRZScannerViewConfig { showUploadImage?: boolean; showFormatSelector?: boolean; showSoundToggle?: boolean; + showPoweredByDynamsoft?: boolean; enableMultiFrameCrossFilter?: boolean; + uploadAcceptedTypes?: string; + uploadFileConverter?: (file: File) => Promise; } declare class MRZScannerView { private resources; @@ -137,7 +145,8 @@ declare class MRZScannerView { private attachOptionClickListeners; private highlightCameraAndResolutionOption; private toggleSelectCameraBox; - private uploadImage; + private relaunch; + private uploadFile; private toggleSoundFeedback; private calculateScanRegion; private toggleScanGuide; @@ -229,7 +238,13 @@ declare class MRZScanner { private initializeMRZScannerConfig; private createViewContainers; dispose(): void; - launch(): Promise; + /** + * Processes an uploaded image file + * @param imageOrFile The file to process + * @returns Promise with the document result + */ + private processUploadedFile; + launch(imageOrFile: Blob | string | DSImageData | HTMLImageElement | HTMLVideoElement | HTMLCanvasElement): Promise; } declare const DynamsoftMRZScanner: { diff --git a/dist/mrz-scanner.bundle.js b/dist/mrz-scanner.bundle.js index 4e62e7b..a76eb82 100644 --- a/dist/mrz-scanner.bundle.js +++ b/dist/mrz-scanner.bundle.js @@ -1 +1 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Dynamsoft=t.Dynamsoft||{})}(this,(function(t){"use strict";const e=t=>t&&"object"==typeof t&&"function"==typeof t.then,i=(async()=>{})().constructor;class n extends i{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let n;this._task=t,e(t)?n=t:"function"==typeof t&&(n=new i(t)),n&&(async()=>{try{const e=await n;t===this._task&&this.resolve(e)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let i,n;super(((t,e)=>{i=t,n=e})),this._s="pending",this.resolve=t=>{this.isPending&&(e(t)?this.task=t:(this._s="fulfilled",i(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",n(t))},this.task=t}}function r(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function s(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,i),i}var a,o,l;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(a||(a={})),function(t){t[t.CCUT_AUTO=0]="CCUT_AUTO",t[t.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",t[t.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",t[t.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",t[t.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",t[t.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(o||(o={})),function(t){t[t.IPF_BINARY=0]="IPF_BINARY",t[t.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",t[t.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",t[t.IPF_NV21=3]="IPF_NV21",t[t.IPF_RGB_565=4]="IPF_RGB_565",t[t.IPF_RGB_555=5]="IPF_RGB_555",t[t.IPF_RGB_888=6]="IPF_RGB_888",t[t.IPF_ARGB_8888=7]="IPF_ARGB_8888",t[t.IPF_RGB_161616=8]="IPF_RGB_161616",t[t.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",t[t.IPF_ABGR_8888=10]="IPF_ABGR_8888",t[t.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",t[t.IPF_BGR_888=12]="IPF_BGR_888",t[t.IPF_BINARY_8=13]="IPF_BINARY_8",t[t.IPF_NV12=14]="IPF_NV12",t[t.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(l||(l={}));const h="undefined"==typeof self,c="function"==typeof importScripts,u=(()=>{if(!c){if(!h&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),d=t=>{if(null==t&&(t="./"),h||c);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},f=t=>Object.prototype.toString.call(t),g=t=>Array.isArray?Array.isArray(t):"[object Array]"===f(t),m=t=>"[object Boolean]"===f(t),p=t=>"number"==typeof t&&!Number.isNaN(t),_=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),v=t=>!(!_(t)||!p(t.width)||t.width<=0||!p(t.height)||t.height<=0||!p(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!E(t.tag)),y=t=>!!v(t)&&t.bytes instanceof Uint8Array,w=t=>!(!_(t)||!p(t.left)||t.left<0||!p(t.top)||t.top<0||!p(t.right)||t.right<0||!p(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom||!m(t.isMeasuredInPercentage)),E=t=>null===t||!!_(t)&&!!p(t.imageId)&&"type"in t,C=t=>!(!_(t)||!S(t.startPoint)||!S(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),S=t=>!!_(t)&&!!p(t.x)&&!!p(t.y),T=t=>!!_(t)&&!!g(t.points)&&0!=t.points.length&&!t.points.some((t=>!S(t))),b=t=>!!_(t)&&!!g(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some((t=>!S(t))),x=t=>!(!_(t)||!p(t.x)||!p(t.y)||!p(t.width)||t.width<0||!p(t.height)||t.height<0||"isMeasuredInPercentage"in t&&!m(t.isMeasuredInPercentage)),I=async(t,e)=>await new Promise(((i,n)=>{let r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType=e,r.send(),r.onloadend=async()=>{r.status<200||r.status>=300?n(new Error(t+" "+r.status)):i(r.response)},r.onerror=()=>{n(new Error("Network Error: "+r.statusText))}})),R=(t,e)=>{let i=t.split("."),n=e.split(".");for(let t=0;t{const e={},i={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcpd:"dynamsoft-code-parser",dlrData:"dynamsoft-label-recognizer-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer"};for(let n in t){if("rootDirectory"===n)continue;let r=n,s=t[r],a=s&&"object"==typeof s&&s.path?s.path:s,o=t.rootDirectory;if(o&&!o.endsWith("/")&&(o+="/"),"object"==typeof s&&s.isInternal)o&&(a=t[r].version?`${o}${i[r]}@${t[r].version}/dist/${"ddv"===r?"engine":""}`:`${o}${i[r]}/dist/${"ddv"===r?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof a&&(a=a.replace(i,o||"")),"object"==typeof a&&"dwt"===r){const n=t[r].resourcesPath,s=t[r].serviceInstallerLocation;e[r]={resourcesPath:n.replace(i,o||""),serviceInstallerLocation:s.replace(i,o||"")};continue}}e[r]=d(a)}return e},D=async(t,e,i)=>await new Promise((async(n,r)=>{try{const r=e.split(".");let s=r[r.length-1];const a=await L(`image/${s}`,t);r.length<=1&&(s="png");const o=new File([a],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(o),i=document.createElement("a");i.href=t,i.download=e,i.click()}return n(o)}catch(t){return r()}})),A=t=>{y(t)&&(t=M(t));const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},L=async(t,e)=>{y(e)&&(e=M(e));const i=A(e);return new Promise(((e,n)=>{i.toBlob((t=>e(t)),t)}))},M=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===l.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n=r)break;e[a]=e[a+1]=e[a+2]=(128&n)/128*255,e[a+3]=255,n<<=1}}}else if(Number(t.format)===l.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n=r)break;e[a]=e[a+1]=e[a+2]=128&n?0:255,e[a+3]=255,n<<=1}}}return new ImageData(e,t.width,t.height)};var F,P,k,N,B,j,V,U;let G,W,Y,z,H,X=class t{get _isFetchingStarted(){return r(this,B,"f")}constructor(){F.add(this),P.set(this,[]),k.set(this,1),N.set(this,a.BOPM_BLOCK),B.set(this,!1),j.set(this,void 0),V.set(this,o.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!y(t))throw new TypeError("Invalid 'image'.");if((null===(e=t.tag)||void 0===e?void 0:e.hasOwnProperty("imageId"))&&"number"==typeof t.tag.imageId&&this.hasImage(t.tag.imageId))throw new Error("Existed imageId.");if(r(this,P,"f").length>=r(this,k,"f"))switch(r(this,N,"f")){case a.BOPM_BLOCK:break;case a.BOPM_UPDATE:if(r(this,P,"f").push(t),_(r(this,j,"f"))&&p(r(this,j,"f").imageId)&&1==r(this,j,"f").keepInBuffer)for(;r(this,P,"f").length>r(this,k,"f");){const t=r(this,P,"f").findIndex((t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==r(this,j,"f").imageId}));r(this,P,"f").splice(t,1)}else r(this,P,"f").splice(0,r(this,P,"f").length-r(this,k,"f"))}else r(this,P,"f").push(t)}getImage(){if(0===r(this,P,"f").length)return null;let e;if(r(this,j,"f")&&p(r(this,j,"f").imageId)){const t=r(this,F,"m",U).call(this,r(this,j,"f").imageId);if(t<0)throw new Error(`Image with id ${r(this,j,"f").imageId} doesn't exist.`);e=r(this,P,"f").slice(t,t+1)[0]}else e=r(this,P,"f").pop();if([l.IPF_RGB_565,l.IPF_RGB_555,l.IPF_RGB_888,l.IPF_ARGB_8888,l.IPF_RGB_161616,l.IPF_ARGB_16161616,l.IPF_ABGR_8888,l.IPF_ABGR_16161616,l.IPF_BGR_888].includes(e.format)){if(r(this,V,"f")===o.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t0!==t.length&&t.every((t=>p(t))))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&!m(e))throw new TypeError("Invalid 'keepInBuffer'.");s(this,j,{imageId:t,keepInBuffer:e})}_resetNextReturnedImage(){s(this,j,null)}hasImage(t){return r(this,F,"m",U).call(this,t)>=0}startFetching(){s(this,B,!0)}stopFetching(){s(this,B,!1)}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(s(this,k,t);r(this,P,"f")&&r(this,P,"f").length>t;)r(this,P,"f").shift()}getMaxImageCount(){return r(this,k,"f")}getImageCount(){return r(this,P,"f").length}clearBuffer(){r(this,P,"f").length=0}isBufferEmpty(){return 0===r(this,P,"f").length}setBufferOverflowProtectionMode(t){s(this,N,t)}getBufferOverflowProtectionMode(){return r(this,N,"f")}setColourChannelUsageType(t){s(this,V,t)}getColourChannelUsageType(){return r(this,V,"f")}};P=new WeakMap,k=new WeakMap,N=new WeakMap,B=new WeakMap,j=new WeakMap,V=new WeakMap,F=new WeakSet,U=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return r(this,P,"f").findIndex((e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t}))},"undefined"!=typeof navigator&&(G=navigator,W=G.userAgent,Y=G.platform,z=G.mediaDevices),function(){if(!h){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:G.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Y,search:"Win"},Mac:{str:Y},Linux:{str:Y}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||W,a=r.search||e,o=r.verStr||W,l=r.verSearch||e;if(l instanceof Array||(l=[l]),-1!=s.indexOf(a)){i=e;for(let t of l){let e=o.indexOf(t);if(-1!=e){n=parseFloat(o.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||W,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=W.indexOf("Windows NT")&&(r="HarmonyOS"),H={browser:i,version:n,OS:r}}h&&(H={browser:"ssr",version:0,OS:"ssr"})}();const Z="undefined"!=typeof WebAssembly&&W&&!(/Safari/.test(W)&&!/Chrome/.test(W)&&/\(.+\s11_2_([2-6]).*\)/.test(W)),q=!("undefined"==typeof Worker),J=!(!z||!z.getUserMedia),K=async()=>{let t=!1;if(J)try{(await z.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===H.browser&&H.version>66||"Safari"===H.browser&&H.version>13||"OPR"===H.browser&&H.version>43||"Edge"===H.browser&&H.version;const $={},Q=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push($[t]=$[t]||new n);await Promise.all(i)},tt=async(t,e)=>{let i,r="string"==typeof t?[t]:t,s=[];for(let t of r){let r;s.push(r=$[t]=$[t]||new n(i=i||e())),r.isEmpty&&(r.task=i=i||e())}await Promise.all(s)};let et,it=0;const nt=()=>it++,rt={};let st;const at=t=>{st=t,et&&et.postMessage({type:"setBLog",body:{value:!!t}})};let ot=!1;const lt=t=>{ot=t,et&&et.postMessage({type:"setBDebug",body:{value:!!t}})},ht={},ct={},ut={dip:{wasm:!0}},dt={std:{version:"1.4.21",path:d(u+"../../dynamsoft-capture-vision-std@1.4.21/dist/"),isInternal:!0},core:{version:"3.4.31",path:u,isInternal:!0}},ft=async t=>{let e;t instanceof Array||(t=t?[t]:[]);let i=$.core;e=!i||i.isEmpty;let r=new Map;const s=t=>{if("std"==(t=t.toLowerCase())||"core"==t)return;if(!ut[t])throw Error("The '"+t+"' module cannot be found.");let e=ut[t].deps;if(null==e?void 0:e.length)for(let t of e)s(t);let i=$[t];r.has(t)||r.set(t,!i||i.isEmpty)};for(let e of t)s(e);let a=[];e&&a.push("core"),a.push(...r.keys());const o=[...r.entries()].filter((t=>!t[1])).map((t=>t[0]));await tt(a,(async()=>{const t=[...r.entries()].filter((t=>t[1])).map((t=>t[0]));await Q(o);const i=O(dt),s={};for(let e of t)s[e]=ut[e];const a={engineResourcePaths:i,autoResources:s,names:t};let l=new n;if(e){a.needLoadCore=!0;let t=i.core+gt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),et=new Worker(t),et.onerror=t=>{let e=new Error(t.message);l.reject(e)},et.addEventListener("message",(t=>{let e=t.data?t.data:t,i=e.type,n=e.id,r=e.body;switch(i){case"log":st&&st(e.message);break;case"task":try{rt[n](r),delete rt[n]}catch(t){throw delete rt[n],t}break;case"event":try{rt[n](r)}catch(t){throw t}break;default:console.log(t)}})),a.bLog=!!st,a.bd=ot,a.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await Q("core");let h=it++;rt[h]=t=>{if(t.success)Object.assign(ht,t.versions),"{}"!==JSON.stringify(t.versions)&&(gt._versions=t.versions),l.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),l.reject(e)}},et.postMessage({type:"loadWasm",body:a,id:h}),await l}))};class gt{static get engineResourcePaths(){return dt}static set engineResourcePaths(t){Object.assign(dt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return st}static set _onLog(t){at(t)}static get _bDebug(){return ot}static set _bDebug(t){lt(t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!$[t]&&$[t].isFulfilled}static async loadWasm(t){return await ft(t)}static async detectEnvironment(){return await(async()=>({wasm:Z,worker:q,getUserMedia:J,camera:await K(),browser:H.browser,version:H.version,OS:H.OS}))()}static async getModuleVersion(){return await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success)return t(i.versions);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"getModuleVersion",id:i})}))}static getVersion(){return`3.4.31(Worker: ${ht.core&&ht.core.worker||"Not Loaded"}, Wasm: ${ht.core&&ht.core.wasm||"Not Loaded"})`}static enableLogging(){X._onLog=console.log,gt._onLog=console.log}static disableLogging(){X._onLog=null,gt._onLog=null}static async cfd(t){return await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cfd",id:n,body:{count:t}})}))}}var mt,pt,_t,vt,yt,wt,Et,Ct,St;gt._bSupportDce4Module=-1,gt._bSupportIRTModule=-1,gt._versions=null,gt._workerName="core.worker.js",gt.browserInfo=H,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT"}(mt||(mt={})),function(t){t[t.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",t[t.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",t[t.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",t[t.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(pt||(pt={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",t[t.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",t[t.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",t[t.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",t[t.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",t[t.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",t[t.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",t[t.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",t[t.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",t[t.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",t[t.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",t[t.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",t[t.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",t[t.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",t[t.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",t[t.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",t[t.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",t[t.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",t[t.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",t[t.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",t[t.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",t[t.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",t[t.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(_t||(_t={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV"}(vt||(vt={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV"}(yt||(yt={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(wt||(wt={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(Et||(Et={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(Ct||(Ct={})),function(t){t[t.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",t[t.CVS_PASSED=1]="CVS_PASSED",t[t.CVS_FAILED=2]="CVS_FAILED"}(St||(St={}));const Tt={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_DOWN_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_UP_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_NORMALIZED_IMAGES:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var bt,xt;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_NORMALIZED_IMAGE=6]="ROET_NORMALIZED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI"}(bt||(bt={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_NORMALIZATION=7]="ST_DOCUMENT_NORMALIZATION"}(xt||(xt={}));var It=Object.freeze({__proto__:null,CoreModule:gt,get EnumBufferOverflowProtectionMode(){return a},get EnumCapturedResultItemType(){return mt},get EnumColourChannelUsageType(){return o},get EnumCornerType(){return pt},get EnumCrossVerificationStatus(){return St},get EnumErrorCode(){return _t},get EnumGrayscaleEnhancementMode(){return vt},get EnumGrayscaleTransformationMode(){return yt},get EnumImagePixelFormat(){return l},get EnumImageTagType(){return wt},EnumIntermediateResultUnitType:Tt,get EnumPDFReadingMode(){return Et},get EnumRasterDataSource(){return Ct},get EnumRegionObjectElementType(){return bt},get EnumSectionType(){return xt},ImageSourceAdapter:X,_getNorImageData:M,_saveToFile:D,_toBlob:L,_toCanvas:A,_toImage:(t,e)=>{y(e)&&(e=M(e));const i=A(e);let n=new Image,r=i.toDataURL(t);return n.src=r,n},get bDebug(){return ot},checkIsLink:t=>/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t),compareVersion:R,doOrWaitAsyncDependency:tt,getNextTaskID:nt,handleEngineResourcePaths:O,innerVersions:ht,isArc:t=>!(!_(t)||!p(t.x)||!p(t.y)||!p(t.radius)||t.radius<0||!p(t.startAngle)||!p(t.endAngle)),isContour:t=>!!_(t)&&!!g(t.points)&&0!=t.points.length&&!t.points.some((t=>!S(t))),isDSImageData:y,isDSRect:w,isImageTag:E,isLineSegment:C,isObject:_,isOriginalDsImageData:t=>!(!v(t)||!p(t.bytes.length)&&!p(t.bytes.ptr)),isPoint:S,isPolygon:T,isQuad:b,isRect:x,loadWasm:ft,mapAsyncDependency:$,mapPackageRegister:ct,mapTaskCallBack:rt,get onLog(){return st},requestResource:I,setBDebug:lt,setOnLog:at,waitAsyncDependency:Q,get worker(){return et},workerAutoResources:ut});const Rt="undefined"==typeof self,Ot=Rt?{}:self,Dt="function"==typeof importScripts,At=(()=>{if(!Dt){if(!Rt&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),Lt=t=>t&&"object"==typeof t&&"function"==typeof t.then,Mt=(async()=>{})().constructor;let Ft=class extends Mt{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Lt(t)?e=t:"function"==typeof t&&(e=new Mt(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(Lt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Pt=" is not allowed to change after `createInstance` or `loadWasm` is called.",kt=!Rt&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",Nt=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Pt);i._license=e}};!Rt&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Bt=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=Bt(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Pt);i._licenseServer=e}},Vt=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Pt);i._deviceFriendlyName=e}};let Ut,Gt,Wt,Yt,zt;"undefined"!=typeof navigator&&(Ut=navigator,Gt=Ut.userAgent,Wt=Ut.platform,Yt=Ut.mediaDevices),function(){if(!Rt){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Ut.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Wt,search:"Win"},Mac:{str:Wt},Linux:{str:Wt}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Gt,a=r.search||e,o=r.verStr||Gt,l=r.verSearch||e;if(l instanceof Array||(l=[l]),-1!=s.indexOf(a)){i=e;for(let t of l){let e=o.indexOf(t);if(-1!=e){n=parseFloat(o.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Gt,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Gt.indexOf("Windows NT")&&(r="HarmonyOS"),zt={browser:i,version:n,OS:r}}Rt&&(zt={browser:"ssr",version:0,OS:"ssr"})}(),Yt&&Yt.getUserMedia,"Chrome"===zt.browser&&zt.version>66||"Safari"===zt.browser&&zt.version>13||"OPR"===zt.browser&&zt.version>43||"Edge"===zt.browser&&zt.version;const Ht=()=>(ft("license"),tt("dynamsoft_inited",(async()=>{let{lt:t,l:e,ls:i,sp:n,rmk:r,cv:s}=((t,e=!1)=>{const i=t;if(i._pLoad.isEmpty){let n,r,s,a=i._license||"",o=JSON.parse(JSON.stringify(i._licenseServer)),l=i._sessionPassword,h=0;if(a.startsWith("t")||a.startsWith("f"))h=0;else if(0===a.length||a.startsWith("P")||a.startsWith("L")||a.startsWith("Y")||a.startsWith("A"))h=1;else{h=2;const e=a.indexOf(":");-1!=e&&(a=a.substring(e+1));const i=a.indexOf("?");if(-1!=i&&(r=a.substring(i+1),a=a.substring(0,i)),a.startsWith("DLC2"))h=0;else{if(a.startsWith("DLS2")){let e;try{let t=a.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(a=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof a&&(a=JSON.stringify(a)),0===o.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),o=Bt(t)}!l&&e.sessionPassword&&(l=e.sessionPassword),n=e.remark}a&&"200001"!==a&&!a.startsWith("200001-")||(h=1)}}if(h&&(e||(Ot.crypto||(s="Please upgrade your browser to support online key."),Ot.crypto.subtle||(s="Require https to use online key in this browser."))),s)throw new Error(s);return 1===h&&(a="",console.warn("Applying for a public trial license ...")),{lt:h,l:a,ls:o,sp:l,rmk:n,cv:r}}throw new Error("Can't preprocess license again"+Pt)})(Zt),a=new Ft;Zt._pLoad.task=a,(async()=>{try{await Zt._pLoad}catch(t){}})();let o=nt();rt[o]=e=>{if(e.message&&Zt._onAuthMessage){let t=Zt._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,n=!1;if(1===t&&(n=!0),e.success?(st&&st("init license success"),e.message&&console.warn(e.message),gt._bSupportIRTModule=e.bSupportIRTModule,gt._bSupportDce4Module=e.bSupportDce4Module,Zt.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):a.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),n||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(n=!0)),n){const t=O(gt.engineResourcePaths);(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let n=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!n.ok)throw Error("Get license dialog fail. Network Error: "+n.statusText);let r=await n.text();if(!r.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.innerHTML=r;let a=[];for(let t=0;t{if(t==e.target){o.remove();for(let t of a)t.remove()}}));else if(!h&&t.classList.contains("dls-license-icon-close"))h=t,t.addEventListener("click",(()=>{o.remove();for(let t of a)t.remove()}));else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),n=e.indexOf("]",i),r=e.indexOf("(",n),s=e.indexOf(")",r);if(-1==i||-1==n||-1==r||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let a=document.createElement("a"),o=e.substring(i+1,n);a.innerText=o;let l=e.substring(r+1,s);a.setAttribute("href",l),a.setAttribute("target","_blank"),t.appendChild(a),e=e.substring(s+1)}}document.body.appendChild(o)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:Zt._bNeverShowDialog,engineResourcePath:t.license,_onLog:st},e.success?"warn":"error",e.message)}e.success?a.resolve(void 0):a.reject(i)},await Q("core"),et.postMessage({type:"license_dynamsoft",body:{v:"3.4.31",brtk:!!t,bptk:1===t,l:e,os:zt,fn:Zt.deviceFriendlyName,ls:i,sp:n,rmk:r,cv:s},id:o}),Zt.bCallInitLicense=!0,await a})));let Xt;ct.license={},ct.license.dynamsoft=Ht,ct.license.getAR=async()=>{{let t=$.dynamsoft_inited;t&&t.isRejected&&await t}return et?new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success){delete i.success;{let t=Zt.license;t&&(t.startsWith("t")||t.startsWith("f"))&&(i.pk=t)}if(Object.keys(i).length){if(i.lem){let t=Error(i.lem);t.ltsErrorCode=i.lec,delete i.lem,delete i.lec,i.ae=t}t(i)}else t(null)}else{let t=Error(i.message);i.stack&&(t.stack=i.stack),e(t)}},et.postMessage({type:"license_getAR",id:i})})):null};let Zt=class t{static setLicenseServer(e){jt(t,e)}static get license(){return this._license}static set license(e){Nt(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){jt(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){Vt(t,e)}static initLicense(e,i){if(Nt(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return Ht()}static setDeviceFriendlyName(e){Vt(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await tt("dynamsoft_uuid",(async()=>{await ft();let t=new Ft,e=nt();rt[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},et.postMessage({type:"license_getDeviceUUID",id:e}),Xt=await t})),Xt))()}};Zt._pLoad=new Ft,Zt.bPassValidation=!1,Zt.bCallInitLicense=!1,Zt._license=kt,Zt._licenseServer=[],Zt._deviceFriendlyName="",gt.engineResourcePaths.license={version:"3.4.31",path:At,isInternal:!0},ut.license={wasm:!0,js:!0},ct.license.LicenseManager=Zt;const qt="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&R(gt.engineResourcePaths.std.version,qt)<0&&(gt.engineResourcePaths.std={version:qt,path:(t=>{if(null==t&&(t="./"),Rt||Dt);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(At+`../../dynamsoft-capture-vision-std@${qt}/dist/`),isInternal:!0});var Jt=Object.freeze({__proto__:null,LicenseManager:Zt,LicenseModule:class{static getVersion(){return`3.4.31(Worker: ${ht.license&&ht.license.worker||"Not Loaded"}, Wasm: ${ht.license&&ht.license.wasm||"Not Loaded"})`}}});function Kt(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function $t(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const Qt=t=>t&&"object"==typeof t&&"function"==typeof t.then,te=(async()=>{})().constructor;class ee extends te{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Qt(t)?e=t:"function"==typeof t&&(e=new te(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(Qt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class ie{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success)return t(i.count);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})}))}async setMaxBufferedItems(t){return await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_setMaxBufferedItems",id:n,instanceID:this._cvr._instanceID,body:{count:t}})}))}async getBufferedCharacterItemSet(){return await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success)return t(i.itemSet);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})}))}}var ne={onTaskResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onColourImageUnitReceived:!1,onScaledDownColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledUpBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesReceived:!1};const re=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};class se{constructor(t){this._irrRegistryState=ne,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),re(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach(((t,e)=>{i[e]=t})),t._observedTaskMap.clear()}return await new Promise(((t,n)=>{let r=nt();rt[r]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},et.postMessage({type:"cvr_setIrrRegistry",id:r,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})}))}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),re(this),await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})}))}getOriginalImage(){return this._cvr._dsImage}}const ae="undefined"==typeof self,oe="function"==typeof importScripts,le=(()=>{if(!oe){if(!ae&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),he=t=>{if(null==t&&(t="./"),ae||oe);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var ce;gt.engineResourcePaths.cvr={version:"2.4.33",path:le,isInternal:!0},ut.cvr={js:!0,wasm:!0,deps:["license","dip"]},ct.cvr={};const ue="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&R(gt.engineResourcePaths.std.version,ue)<0&&(gt.engineResourcePaths.std={version:ue,path:he(le+`../../dynamsoft-capture-vision-std@${ue}/dist/`),isInternal:!0});const de="2.4.31";(!gt.engineResourcePaths.dip||"string"!=typeof gt.engineResourcePaths.dip&&R(gt.engineResourcePaths.dip.version,de)<0)&&(gt.engineResourcePaths.dip={version:de,path:he(le+`../../dynamsoft-image-processing@${de}/dist/`),isInternal:!0});class fe{static getVersion(){return this._version}}fe._version=`2.4.33(Worker: ${null===(ce=ht.cvr)||void 0===ce?void 0:ce.worker}, Wasm: loading...`;const ge={barcodeResultItems:{type:mt.CRIT_BARCODE,reveiver:"onDecodedBarcodesReceived",isNeedFilter:!0},textLineResultItems:{type:mt.CRIT_TEXT_LINE,reveiver:"onRecognizedTextLinesReceived",isNeedFilter:!0},detectedQuadResultItems:{type:mt.CRIT_DETECTED_QUAD,reveiver:"onDetectedQuadsReceived",isNeedFilter:!1},normalizedImageResultItems:{type:mt.CRIT_NORMALIZED_IMAGE,reveiver:"onNormalizedImagesReceived",isNeedFilter:!1},parsedResultItems:{type:mt.CRIT_PARSED_RESULT,reveiver:"onParsedResultsReceived",isNeedFilter:!1}};var me,pe,_e,ve,ye,we,Ee,Ce,Se,Te,be,xe,Ie;function Re(t,e){if(t&&t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;Re(t.referencedItem,e)}}function Oe(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}!function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(me||(me={}));const De={onTaskResultsReceived:()=>{},isFilter:!0};class Ae{constructor(){this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(gt.browserInfo.OS)?2048:4096,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,pe.set(this,null),_e.set(this,null),ve.set(this,null),ye.set(this,null),we.set(this,null),Ee.set(this,new Set),Ce.set(this,new Set),Se.set(this,new Set),Te.set(this,0),be.set(this,!1),xe.set(this,!1),Ie.set(this,!1),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return Kt(this,Ie,"f")}static async createInstance(){if(!ct.license)throw Error("Module `license` is not existed.");await ct.license.dynamsoft(),await ft(["cvr"]);const t=new Ae,e=new ee;let i=nt();return rt[i]=async i=>{var n;if(i.success)t._instanceID=i.instanceID,t._currentSettings=JSON.parse(JSON.parse(i.outputSettings).data),fe._version=`2.4.33(Worker: ${null===(n=ht.cvr)||void 0===n?void 0:n.worker}, Wasm: ${i.version})`,$t(t,xe,!0),$t(t,ye,t.getIntermediateResultManager()),$t(t,xe,!1),e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},et.postMessage({type:"cvr_createInstance",id:i}),e}async _singleFrameModeCallback(t){for(let e of Kt(this,Ee,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;const n={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of Kt(this,Ee,"f"))if(t.isDce)t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1});else{for(let e in ge){const r=e,s=ge[r];t[s.reveiver]&&i[r]&&t[s.reveiver](Object.assign(Object.assign({},n),{[r]:i[r]}))}t.onCapturedResultReceived&&t.onCapturedResultReceived(i)}}setInput(t){if(Oe(this),t){if($t(this,pe,t),t.isCameraEnhancer){Kt(this,ye,"f")&&(Kt(this,pe,"f")._intermediateResultReceiver.isDce=!0,Kt(this,ye,"f").addResultReceiver(Kt(this,pe,"f")._intermediateResultReceiver));const t=Kt(this,pe,"f").getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,Kt(this,Ee,"f").add(e)}}}else $t(this,pe,null)}getInput(){return Kt(this,pe,"f")}addImageSourceStateListener(t){if(Oe(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&Kt(this,Ce,"f").add(t)}removeImageSourceStateListener(t){return Oe(this),Kt(this,Ce,"f").delete(t)}addResultReceiver(t){if(Oe(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(Kt(this,Ee,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){Oe(this),Kt(this,Ee,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onParsedResultsReceived:!1};for(let e of Kt(this,Ee,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onDetectedQuadsReceived=!!e.onDetectedQuadsReceived,t.onNormalizedImagesReceived=!!e.onNormalizedImagesReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new ee;let i=nt();return rt[i]=async t=>{if(t.success)e.resolve();else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject()}},et.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(Oe(this),!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");Kt(this,Se,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){Oe(this),Kt(this,Se,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(Kt(this,ye,"f").removeResultReceiver(De),0===Kt(this,Se,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[mt.CRIT_BARCODE]:!1,[mt.CRIT_TEXT_LINE]:!1,[mt.CRIT_DETECTED_QUAD]:!1,[mt.CRIT_NORMALIZED_IMAGE]:!1},e={[mt.CRIT_BARCODE]:!1,[mt.CRIT_TEXT_LINE]:!1,[mt.CRIT_DETECTED_QUAD]:!1,[mt.CRIT_NORMALIZED_IMAGE]:!1};return await Le(this,t),void await Me(this,e)}for(let t of Kt(this,Se,"f")){if(this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(mt.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(mt.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(mt.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(mt.CRIT_NORMALIZED_IMAGE),t.isLatestOverlappingEnabled(mt.CRIT_BARCODE)){[...Kt(this,ye,"f")._intermediateResultReceiverSet.values()].find((t=>t.isFilter))||Kt(this,ye,"f").addResultReceiver(De)}await Le(this,t.verificationEnabled),await Me(this,t.duplicateFilterEnabled),await Fe(this,t.duplicateForgetTime)}}async startCapturing(t){var e,i;if(Oe(this),!this._isPauseScan)return;if(!Kt(this,pe,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");t||(t=Ae._defaultTemplate);const n=await this.containsTask(t);await ft(n);for(let t of Kt(this,Se,"f"))await this.addResultFilter(t);if(n.includes("dlr")&&!(null===(e=ct.dlr)||void 0===e?void 0:e.bLoadConfusableCharsData)){const t=O(gt.engineResourcePaths);await(null===(i=ct.dlr)||void 0===i?void 0:i.loadRecognitionData("ConfusableChars",t.dlr))}if(Kt(this,pe,"f").isCameraEnhancer&&(n.includes("ddn")?Kt(this,pe,"f").setPixelFormat(l.IPF_ABGR_8888):Kt(this,pe,"f").setPixelFormat(l.IPF_GRAYSCALED)),void 0!==Kt(this,pe,"f").singleFrameMode&&"disabled"!==Kt(this,pe,"f").singleFrameMode)return this._templateName=t,void Kt(this,pe,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind);return Kt(this,pe,"f").getColourChannelUsageType()===o.CCUT_AUTO&&Kt(this,pe,"f").setColourChannelUsageType(n.includes("ddn")?o.CCUT_FULL_CHANNEL:o.CCUT_Y_CHANNEL_ONLY),Kt(this,ve,"f")&&Kt(this,ve,"f").isPending?Kt(this,ve,"f"):($t(this,ve,new ee(((e,i)=>{if(this.disposed)return;let n=nt();rt[n]=async n=>{if(Kt(this,ve,"f")&&!Kt(this,ve,"f").isFulfilled){if(!n.success){let t=new Error(n.message);return t.stack=n.stack+"\n"+t.stack,i(t)}this._isPauseScan=!1,this._isOutputOriginalImage=n.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((async()=>{-1!==this._minImageCaptureInterval&&Kt(this,pe,"f").startFetching(),this._loopReadVideo(t),e()}),0)}},et.postMessage({type:"cvr_startCapturing",id:n,instanceID:this._instanceID,body:{templateName:t}})}))),await Kt(this,ve,"f"))}stopCapturing(){Oe(this),Kt(this,pe,"f")&&(Kt(this,pe,"f").isCameraEnhancer&&void 0!==Kt(this,pe,"f").singleFrameMode&&"disabled"!==Kt(this,pe,"f").singleFrameMode?Kt(this,pe,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(!async function(t){let e=nt();const i=new ee;rt[e]=async t=>{if(t.success)return i.resolve();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i.reject(e)}},et.postMessage({type:"cvr_clearVerifyList",id:e,instanceID:t._instanceID})}(this),Kt(this,pe,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,$t(this,ve,null),Kt(this,pe,"f").setColourChannelUsageType(o.CCUT_AUTO)))}async containsTask(t){return Oe(this),await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success)return e(JSON.parse(t.tasks));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_containsTask",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async _loopReadVideo(t){if(this.disposed||this._isPauseScan)return;if($t(this,be,!0),Kt(this,pe,"f").isBufferEmpty())if(Kt(this,pe,"f").hasNextImageToFetch())for(let t of Kt(this,Ce,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(me.ISS_BUFFER_EMPTY);else if(!Kt(this,pe,"f").hasNextImageToFetch())for(let t of Kt(this,Ce,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(me.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||Kt(this,pe,"f").isBufferEmpty())try{Kt(this,pe,"f").isBufferEmpty()&&Ae._onLog&&Ae._onLog("buffer is empty so fetch image"),Ae._onLog&&Ae._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=Kt(this,pe,"f").fetchImage(),Ae._onLog&&Ae._onLog(`DCE: finish fetching a frame: ${Date.now()}`),Kt(this,pe,"f").setImageFetchInterval(this._averageTime)}catch(e){return void this._reRunCurrnetFunc(t)}else if(Kt(this,pe,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=Kt(this,pe,"f").getImage(),this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(t);if(!this._dsImage)return void this._reRunCurrnetFunc(t);for(let t of Kt(this,Ee,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const e=Date.now();this._captureDsimage(this._dsImage,t).then((async i=>{if(Ae._onLog&&Ae._onLog("no js handle time: "+(Date.now()-e)),this._isPauseScan)return void this._reRunCurrnetFunc(t);i.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;const n={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of Kt(this,Ee,"f"))if(t.isDce){const e=Date.now();if(t.onCapturedResultReceived(i,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),Ae._onLog){const t=Date.now()-e;t>10&&Ae._onLog(`draw result time: ${t}`)}}else{for(let e in ge){const r=e,s=ge[r];t[s.reveiver],t[s.reveiver]&&i[r]&&t[s.reveiver](Object.assign(Object.assign({},n),{[r]:i[r].filter((t=>!s.isNeedFilter||!t.isFilter))})),i[r]&&(i[r]=i[r].filter((t=>!s.isNeedFilter||!t.isFilter)))}t.onCapturedResultReceived&&(i.items=i.items.filter((t=>[mt.CRIT_DETECTED_QUAD,mt.CRIT_NORMALIZED_IMAGE].includes(t.type)||!t.isFilter)),t.onCapturedResultReceived(i))}const r=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-e),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,Ae._onLog&&(Ae._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),Ae._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),Ae._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),Ae._onLog(`averageTime: ${this._averageTime}`))),Ae._onLog){const t=Date.now()-r;t>10&&Ae._onLog(`fetch image calculate time: ${t}`)}Ae._onLog&&Ae._onLog(`time finish decode: ${Date.now()}`),Ae._onLog&&Ae._onLog("main time: "+(Date.now()-e)),Ae._onLog&&Ae._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,0))})).catch((e=>{Kt(this,pe,"f").stopFetching(),e.errorCode&&0===e.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{Kt(this,pe,"f").startFetching(),this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,1e3))),"platform error"!==e.message&&setTimeout((()=>{throw e}),0)}))}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),0)}async capture(t,e){var i,n;Oe(this),e||(e=Ae._defaultTemplate);const r=await this.containsTask(e);if(await ft(r),r.includes("dlr")&&!(null===(i=ct.dlr)||void 0===i?void 0:i.bLoadConfusableCharsData)){const t=O(gt.engineResourcePaths);await(null===(n=ct.dlr)||void 0===n?void 0:n.loadRecognitionData("ConfusableChars",t.dlr))}let s;if($t(this,be,!1),y(t))s=await this._captureDsimage(t,e);else if("string"==typeof t)s="data:image/"==t.substring(0,11)?await this._captureBase64(t,e):await this._captureUrl(t,e);else if(t instanceof Blob)s=await this._captureBlob(t,e);else if(t instanceof HTMLImageElement)s=await this._captureImage(t,e);else if(t instanceof HTMLCanvasElement)s=await this._captureCanvas(t,e);else{if(!(t instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");s=await this._captureVideo(t,e)}return s}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await I(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),n=i.length,r=new Uint8Array(n);for(;n--;)r[n]=i.charCodeAt(n);return await this._captureBlob(new Blob([r]),e)}async _captureBlob(t,e){let i=null,n=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(n=await async function(t){return await new Promise(((e,i)=>{let n=URL.createObjectURL(t),r=new Image;r.src=n,r.onload=()=>{URL.revokeObjectURL(r.dbrObjUrl),e(r)},r.onerror=t=>{i(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))}(t));let r=await this._captureImage(i||n,e);return i&&i.close(),r}async _captureImage(t,e){let i,n,r=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,a=Math.max(r,s);a>this.maxImageSideLength?($t(this,Te,this.maxImageSideLength/a),i=Math.round(r*Kt(this,Te,"f")),n=Math.round(s*Kt(this,Te,"f"))):(i=r,n=s),Kt(this,_e,"f")||$t(this,_e,document.createElement("canvas"));const o=Kt(this,_e,"f");o.width===i&&o.height===n||(o.width=i,o.height=n),o.ctx2d||(o.ctx2d=o.getContext("2d",{willReadFrequently:!0}));return o.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(o,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),n={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(n,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,n,r=t.videoWidth,s=t.videoHeight,a=Math.max(r,s);a>this.maxImageSideLength?($t(this,Te,this.maxImageSideLength/a),i=Math.round(r*Kt(this,Te,"f")),n=Math.round(s*Kt(this,Te,"f"))):(i=r,n=s),Kt(this,_e,"f")||$t(this,_e,document.createElement("canvas"));const o=Kt(this,_e,"f");o.width===i&&o.height===n||(o.width=i,o.height=n),o.ctx2d||(o.ctx2d=o.getContext("2d",{willReadFrequently:!0}));return o.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),await this._captureCanvas(o,e)}async _captureInWorker(t,e){const{bytes:i,width:n,height:r,stride:s,format:a}=t;let o=nt();const l=new ee;return rt[o]=async e=>{var i,n;if(!e.success){let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l.reject(t)}{const r=Date.now();Ae._onLog&&(Ae._onLog(`get result time from worker: ${r}`),Ae._onLog("worker to main time consume: "+(r-e.workerReturnMsgTime)));try{const r=e.captureResult;if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,l.reject(t)}t.bytes=e.bytes;for(let e of r.items)0!==Kt(this,Te,"f")&&Re(e,Kt(this,Te,"f")),e.type===mt.CRIT_ORIGINAL_IMAGE?e.imageData=t:e.type===mt.CRIT_NORMALIZED_IMAGE?null===(i=ct.ddn)||void 0===i||i.handleNormalizedImageResultItem(e):e.type===mt.CRIT_PARSED_RESULT&&(null===(n=ct.dcp)||void 0===n||n.handleParsedResultItem(e));if(Kt(this,be,"f"))for(let t of Kt(this,Se,"f"))t.onDecodedBarcodesReceived(r),t.onRecognizedTextLinesReceived(r),t.onDetectedQuadsReceived(r),t.onNormalizedImagesReceived(r);for(let t in ge){const e=t,i=r.items.filter((t=>t.type===ge[e].type));i.length&&(r[t]=i)}if(!this._isPauseScan||!Kt(this,be,"f")){const e=r.intermediateResult;if(e){let i=0;for(let n of Kt(this,ye,"f")._intermediateResultReceiverSet){i++;for(let r of e){if("onTaskResultsReceived"===r.info.callbackName){for(let e of r.intermediateResultUnits)e.originalImageTag=t.tag?t.tag:null;n[r.info.callbackName]&&n[r.info.callbackName]({intermediateResultUnits:r.intermediateResultUnits},r.info)}else n[r.info.callbackName]&&n[r.info.callbackName](r.result,r.info);i===Kt(this,ye,"f")._intermediateResultReceiverSet.size&&delete r.info.callbackName}}}}return r&&r.hasOwnProperty("intermediateResult")&&delete r.intermediateResult,$t(this,Te,0),l.resolve(r)}catch(t){return l.reject(t)}}},Ae._onLog&&Ae._onLog(`send buffer to worker: ${Date.now()}`),et.postMessage({type:"cvr_capture",id:o,instanceID:this._instanceID,body:{bytes:i,width:n,height:r,stride:s,format:a,templateName:e||"",isScanner:Kt(this,be,"f")}},[i.buffer]),l}async initSettings(t){return Oe(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?t.trimStart().startsWith("{")||(t=await I(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise(((e,i)=>{let n=nt();rt[n]=async n=>{if(n.success){const r=JSON.parse(n.response);if(0!==r.errorCode){let t=new Error(r.errorString?r.errorString:"Init Settings Failed.");return t.errorCode=r.errorCode,i(t)}const s=JSON.parse(t);this._currentSettings=s;let a=[],o=s.CaptureVisionTemplates;for(let t=0;t{let n=nt();rt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,i(t)}return e(JSON.parse(n.data))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_outputSettings",id:n,instanceID:this._instanceID,body:{templateName:t||"*"}})}))}async outputSettingsToFile(t,e,i){const n=await this.outputSettings(t),r=new Blob([JSON.stringify(n,null,2,(function(t,e){return e instanceof Array?JSON.stringify(e):e}),2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(r),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout((()=>{URL.revokeObjectURL(t.href)}),500)},t.click()}return r}async getTemplateNames(){return Oe(this),await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,e(t)}return t(JSON.parse(n.data))}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})}))}async getSimplifiedSettings(t){Oe(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const e=await this.containsTask(t);return await ft(e),await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,i(t)}const r=JSON.parse(n.data,((t,e)=>"barcodeFormatIds"===t?BigInt(e):e));return r.minImageCaptureInterval=this._minImageCaptureInterval,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_getSimplifiedSettings",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async updateSettings(t,e){Oe(this);const i=await this.containsTask(t);return await ft(i),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success){const r=JSON.parse(t.response);if(e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==r.errorCode){let t=new Error(r.errorString?r.errorString:"Update Settings Failed.");return t.errorCode=r.errorCode,n(t)}return this._currentSettings=await this.outputSettings("*"),i(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},et.postMessage({type:"cvr_updateSettings",id:r,instanceID:this._instanceID,body:{settings:e,templateName:t}})}))}async resetSettings(){return Oe(this),await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Reset Settings Failed.");return t.errorCode=n.errorCode,e(t)}return this._currentSettings=await this.outputSettings("*"),t(n)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})}))}getBufferedItemsManager(){return Kt(this,we,"f")||$t(this,we,new ie(this)),Kt(this,we,"f")}getIntermediateResultManager(){if(Oe(this),!Kt(this,xe,"f")&&0!==gt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return Kt(this,ye,"f")||$t(this,ye,new se(this)),Kt(this,ye,"f")}async parseRequiredResources(t){return Oe(this),await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success)return e(JSON.parse(t.resources));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_parseRequiredResources",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async dispose(){Oe(this),Kt(this,ve,"f")&&this.stopCapturing(),$t(this,pe,null),Kt(this,Ee,"f").clear(),Kt(this,Ce,"f").clear(),Kt(this,Se,"f").clear(),Kt(this,ye,"f")._intermediateResultReceiverSet.clear(),$t(this,Ie,!0);let t=nt();rt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},et.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:Kt(this,pe,"f"),promiseStartScan:Kt(this,ve,"f"),intermediateResultManager:Kt(this,ye,"f"),bufferdItemsManager:Kt(this,we,"f"),resultReceiverSet:Kt(this,Ee,"f"),isaStateListenerSet:Kt(this,Ce,"f"),resultFilterSet:Kt(this,Se,"f"),compressRate:Kt(this,Te,"f"),canvas:Kt(this,_e,"f"),isScanner:Kt(this,be,"f"),innerUseTag:Kt(this,xe,"f"),isDestroyed:Kt(this,Ie,"f")}}async _getWasmFilterState(){return await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})}))}}async function Le(t,e){return Oe(t),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},et.postMessage({type:"cvr_enableResultCrossVerification",id:r,instanceID:t._instanceID,body:{verificationEnabled:e}})}))}async function Me(t,e){return Oe(t),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},et.postMessage({type:"cvr_enableResultDeduplication",id:r,instanceID:t._instanceID,body:{duplicateFilterEnabled:e}})}))}async function Fe(t,e){return Oe(t),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},et.postMessage({type:"cvr_setDuplicateForgetTime",id:r,instanceID:t._instanceID,body:{duplicateForgetTime:e}})}))}pe=new WeakMap,_e=new WeakMap,ve=new WeakMap,ye=new WeakMap,we=new WeakMap,Ee=new WeakMap,Ce=new WeakMap,Se=new WeakMap,Te=new WeakMap,be=new WeakMap,xe=new WeakMap,Ie=new WeakMap,Ae._defaultTemplate="Default";class Pe{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}}var ke;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadBarcodes_Balanced",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(ke||(ke={}));var Ne=Object.freeze({__proto__:null,CaptureVisionRouter:Ae,CaptureVisionRouterModule:fe,CapturedResultReceiver:Pe,get EnumImageSourceState(){return me},get EnumPresetTemplate(){return ke},IntermediateResultReceiver:class{constructor(){this._observedResultUnitTypes=Tt.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledDownColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}});const Be="undefined"==typeof self,je="function"==typeof importScripts,Ve=(()=>{if(!je){if(!Be&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})();gt.engineResourcePaths.dce={version:"4.1.1",path:Ve,isInternal:!0},ut.dce={wasm:!1,js:!1},ct.dce={};let Ue,Ge,We,Ye,ze;function He(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Xe(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(Ue=navigator,Ge=Ue.userAgent,We=Ue.platform,Ye=Ue.mediaDevices),function(){if(!Be){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Ue.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:We,search:"Win"},Mac:{str:We},Linux:{str:We}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Ge,a=r.search||e,o=r.verStr||Ge,l=r.verSearch||e;if(l instanceof Array||(l=[l]),-1!=s.indexOf(a)){i=e;for(let t of l){let e=o.indexOf(t);if(-1!=e){n=parseFloat(o.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Ge,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Ge.indexOf("Windows NT")&&(r="HarmonyOS"),ze={browser:i,version:n,OS:r}}Be&&(ze={browser:"ssr",version:0,OS:"ssr"})}();const Ze="undefined"!=typeof WebAssembly&&Ge&&!(/Safari/.test(Ge)&&!/Chrome/.test(Ge)&&/\(.+\s11_2_([2-6]).*\)/.test(Ge)),qe=!("undefined"==typeof Worker),Je=!(!Ye||!Ye.getUserMedia),Ke=async()=>{let t=!1;if(Je)try{(await Ye.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===ze.browser&&ze.version>66||"Safari"===ze.browser&&ze.version>13||"OPR"===ze.browser&&ze.version>43||"Edge"===ze.browser&&ze.version;var $e={653:(t,e,i)=>{var n,r,s,a,o,l,h,c,u,d,f,g,m,p,_,v,y,w,E,C,S,T=T||{version:"5.2.1"};if(e.fabric=T,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?T.document=document:T.document=document.implementation.createHTMLDocument(""),T.window=window;else{var b=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;T.document=b.document,T.jsdomImplForWrapper=i(898).implForWrapper,T.nodeCanvas=i(245).Canvas,T.window=b,DOMParser=T.window.DOMParser}function x(t,e){var i=t.canvas,n=e.targetCanvas,r=n.getContext("2d");r.translate(0,n.height),r.scale(1,-1);var s=i.height-n.height;r.drawImage(i,0,s,n.width,n.height,0,0,n.width,n.height)}function I(t,e){var i=e.targetCanvas.getContext("2d"),n=e.destinationWidth,r=e.destinationHeight,s=n*r*4,a=new Uint8Array(this.imageBuffer,0,s),o=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,a);var l=new ImageData(o,n,r);i.putImageData(l,0,0)}T.isTouchSupported="ontouchstart"in T.window||"ontouchstart"in T.document||T.window&&T.window.navigator&&T.window.navigator.maxTouchPoints>0,T.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,T.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],T.DPI=96,T.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",T.commaWsp="(?:\\s+,?\\s*|,\\s*)",T.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,T.reNonWord=/[ \n\.,;!\?\-]/,T.fontPaths={},T.iMatrix=[1,0,0,1,0,0],T.svgNS="http://www.w3.org/2000/svg",T.perfLimitSizeTotal=2097152,T.maxCacheSideLimit=4096,T.minCacheSideLimit=256,T.charWidthsCache={},T.textureSize=2048,T.disableStyleCopyPaste=!1,T.enableGLFiltering=!0,T.devicePixelRatio=T.window.devicePixelRatio||T.window.webkitDevicePixelRatio||T.window.mozDevicePixelRatio||1,T.browserShadowBlurConstant=1,T.arcToSegmentsCache={},T.boundsOfCurveCache={},T.cachesBoundsOfCurve=!0,T.forceGLPutImageData=!1,T.initFilterBackend=function(){return T.enableGLFiltering&&T.isWebglSupported&&T.isWebglSupported(T.textureSize)?(console.log("max texture size: "+T.maxTextureSize),new T.WebglFilterBackend({tileSize:T.textureSize})):T.Canvas2dFilterBackend?new T.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=T),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:T.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}T.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var n=0,r=i.length;n-1||!!e&&this._objects.some((function(e){return"function"==typeof e.contains&&e.contains(t,!0)}))},complexity:function(){return this._objects.reduce((function(t,e){return t+(e.complexity?e.complexity():0)}),0)}},T.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof T.Gradient||this.set(e,new T.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof T.Pattern?i&&i():this.set(e,new T.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},n=e,r=Math.sqrt,s=Math.atan2,a=Math.pow,o=Math.PI/180,l=Math.PI/2,T.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/l){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/l){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*o},radiansToDegrees:function(t){return t/o},rotatePoint:function(t,e,i){var n=new T.Point(t.x-e.x,t.y-e.y),r=T.util.rotateVector(n,i);return new T.Point(r.x,r.y).addEquals(e)},rotateVector:function(t,e){var i=T.util.sin(e),n=T.util.cos(e);return{x:t.x*n-t.y*i,y:t.x*i+t.y*n}},createVector:function(t,e){return new T.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new T.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var n=T.util.createVector(t,e),r=T.util.createVector(t,i),s=T.util.calcAngleBetweenVectors(n,r),a=s*(0===T.util.calcAngleBetweenVectors(T.util.rotateVector(n,s),r)?1:-1)/2;return{vector:T.util.getHatVector(T.util.rotateVector(n,a)),angle:s}},projectStrokeOnPoints:function(t,e,i){var n=[],r=e.strokeWidth/2,s=e.strokeUniform?new T.Point(1/e.scaleX,1/e.scaleY):new T.Point(1,1),a=function(t){var e=r/Math.hypot(t.x,t.y);return new T.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach((function(o,l){var h,c,u=new T.Point(o.x,o.y);0===l?(c=t[l+1],h=i?a(T.util.createVector(c,u)).addEquals(u):t[t.length-1]):l===t.length-1?(h=t[l-1],c=i?a(T.util.createVector(h,u)).addEquals(u):t[0]):(h=t[l-1],c=t[l+1]);var d,f,g=T.util.getBisector(u,h,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-r/Math.sin(p/2),f=new T.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/r<=e.strokeMiterLimit))return n.push(u.add(f)),void n.push(u.subtract(f));d=-r*Math.SQRT2,f=new T.Point(m.x*d*s.x,m.y*d*s.y),n.push(u.add(f)),n.push(u.subtract(f))})),n},transformPoint:function(t,e,i){return i?new T.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new T.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>n?e-=n:e=0,i>n?i-=n:i=0);var r,s=!0,a=t.getImageData(e,i,2*n||1,2*n||1),o=a.data.length;for(r=3;r=r?s-r:2*Math.PI-(r-s)}function s(t,e,i){for(var s=i[1],a=i[2],o=i[3],l=i[4],h=i[5],c=function(t,e,i,s,a,o,l){var h=Math.PI,c=l*h/180,u=T.util.sin(c),d=T.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,E=_*v-_*y-v*w,C=0;if(E<0){var S=Math.sqrt(1-E/(_*v));i*=S,s*=S}else C=(a===o?-1:1)*Math.sqrt(E/(_*y+v*w));var b=C*i*p/s,x=-C*s*m/i,I=d*b-u*x+.5*t,R=u*b+d*x+.5*e,O=r(1,0,(m-b)/i,(p-x)/s),D=r((m-b)/i,(p-x)/s,(-m-b)/i,(-p-x)/s);0===o&&D>0?D-=2*h:1===o&&D<0&&(D+=2*h);for(var A=Math.ceil(Math.abs(D/h*2)),L=[],M=D/A,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=O+M,k=0;kC)for(var b=1,x=m.length;b2;for(e=e||0,h&&(o=t[2].xt[i-2].x?1:r.x===t[i-2].x?0:-1,l=r.y>t[i-2].y?1:r.y===t[i-2].y?0:-1),n.push(["L",r.x+o*e,r.y+l*e]),n},T.util.getPathSegmentsInfo=d,T.util.getBoundsOfCurve=function(e,i,n,r,s,a,o,l){var h;if(T.cachesBoundsOfCurve&&(h=t.call(arguments),T.boundsOfCurveCache[h]))return T.boundsOfCurveCache[h];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,E=Math.abs,C=[],S=[[],[]];u=6*e-12*n+6*s,c=-3*e+9*n-9*s+3*o,d=3*n-3*e;for(var b=0;b<2;++b)if(b>0&&(u=6*i-12*r+6*a,c=-3*i+9*r-9*a+3*l,d=3*r-3*i),E(c)<1e-12){if(E(u)<1e-12)continue;0<(f=-d/u)&&f<1&&C.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&C.push(g),0<(m=(-u-_)/(2*c))&&m<1&&C.push(m));for(var x,I,R,O=C.length,D=O;O--;)x=(R=1-(f=C[O]))*R*R*e+3*R*R*f*n+3*R*f*f*s+f*f*f*o,S[0][O]=x,I=R*R*R*i+3*R*R*f*r+3*R*f*f*a+f*f*f*l,S[1][O]=I;S[0][D]=e,S[1][D]=i,S[0][D+1]=o,S[1][D+1]=l;var A=[{x:y.apply(null,S[0]),y:y.apply(null,S[1])},{x:w.apply(null,S[0]),y:w.apply(null,S[1])}];return T.cachesBoundsOfCurve&&(T.boundsOfCurveCache[h]=A),A},T.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var n=0;e-i[n].length>0&&n1e-4;)i=l(s),r=s,(n=a(h.x,h.y,i.x,i.y))+o>e?(s-=c,c/=2):(h=i,s+=c,o+=n);return i.angle=u(r),i}(s,e)}},T.util.transformPath=function(t,e,i){return i&&(e=T.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map((function(t){for(var i=t.slice(0),n={},r=1;r=e}))}}}(),function(){function t(e,i,n){if(n)if(!T.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var r=0,s=i.length;r57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var n=t.charCodeAt(e+1);if(56320>n||n>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var r=t.charCodeAt(e-1);if(55296>r||r>56319)throw"Low surrogate without preceding high surrogate";return!1}T.util.string={camelize:function(t){return t.replace(/-+(.)?/g,(function(t,e){return e?e.toUpperCase():""}))},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,n=0,r=[];for(n=0;n-1?t.prototype[r]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=n;var r=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return r}}(r):t.prototype[r]=e[r],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function r(){}function s(e){for(var i=null,n=this;n.constructor.superclass;){var r=n.constructor.superclass.prototype[e];if(n[e]!==r){i=r;break}n=n.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}T.util.createClass=function(){var i=null,a=t.call(arguments,0);function o(){this.initialize.apply(this,arguments)}"function"==typeof a[0]&&(i=a.shift()),o.superclass=i,o.subclasses=[],i&&(r.prototype=i.prototype,o.prototype=new r,i.subclasses.push(o));for(var l=0,h=a.length;l-1||"touch"===t.pointerType},d="string"==typeof(u=T.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),T.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var n in e)"opacity"===n?m(t,e[n]):i["float"===n||"cssFloat"===n?void 0===i.styleFloat?"cssFloat":"styleFloat":n]=e[n];return t},function(){var t,e,i,n,r=Array.prototype.slice,s=function(t){return r.call(t,0)};try{t=s(T.document.childNodes)instanceof Array}catch(t){}function a(t,e){var i=T.document.createElement(t);for(var n in e)"class"===n?i.className=e[n]:"for"===n?i.htmlFor=e[n]:i.setAttribute(n,e[n]);return i}function o(t){for(var e=0,i=0,n=T.document.documentElement,r=T.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===T.document?(e=r.scrollLeft||n.scrollLeft||0,i=r.scrollTop||n.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=T.document.defaultView&&T.document.defaultView.getComputedStyle?function(t,e){var i=T.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=T.document.documentElement.style,n="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",T.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=T.util.falseFunction),n?t.style[n]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},T.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),n?t.style[n]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},T.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},T.util.getById=function(t){return"string"==typeof t?T.document.getElementById(t):t},T.util.toArray=s,T.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},T.util.makeElement=a,T.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=a(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},T.util.getScrollLeftTop=o,T.util.getElementOffset=function(t){var i,n,r=t&&t.ownerDocument,s={left:0,top:0},a={left:0,top:0},l={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!r)return a;for(var h in l)a[l[h]]+=parseInt(e(t,h),10)||0;return i=r.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),n=o(t),{left:s.left+n.left-(i.clientLeft||0)+a.left,top:s.top+n.top-(i.clientTop||0)+a.top}},T.util.getNodeCanvas=function(t){var e=T.jsdomImplForWrapper(t);return e._canvas||e._image},T.util.cleanUpJsdomNode=function(t){if(T.isLikelyNode){var e=T.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}T.util.request=function(e,i){i||(i={});var n=i.method?i.method.toUpperCase():"GET",r=i.onComplete||function(){},s=new T.window.XMLHttpRequest,a=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(r(s),s.onreadystatechange=t)},"GET"===n&&(a=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(n,e,!0),"POST"!==n&&"PUT"!==n||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(a),s}}(),T.log=console.log,T.warn=console.warn,function(){var t=T.util.object.extend,e=T.util.object.clone,i=[];function n(){return!1}function r(t,e,i,n){return-i*Math.cos(t/n*(Math.PI/2))+i+e}T.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach((function(t){t.cancel()})),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter((function(e){return"object"==typeof e.target&&e.target.canvas===t}));return e.forEach((function(t){t.cancel()})),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach((function(t){t.cancel()})),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find((function(e){return e.cancel===t}))},findAnimationsByTarget:function(t){return t?this.filter((function(e){return e.target===t})):[]}});var s=T.window.requestAnimationFrame||T.window.webkitRequestAnimationFrame||T.window.mozRequestAnimationFrame||T.window.oRequestAnimationFrame||T.window.msRequestAnimationFrame||function(t){return T.window.setTimeout(t,1e3/60)},a=T.window.cancelAnimationFrame||T.window.clearTimeout;function o(){return s.apply(T.window,arguments)}T.util.animate=function(i){i||(i={});var s,a=!1,l=function(){var t=T.runningAnimations.indexOf(s);return t>-1&&T.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return a=!0,l()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),T.runningAnimations.push(s),o((function(t){var e,h=t||+new Date,c=i.duration||500,u=h+c,d=i.onChange||n,f=i.abort||n,g=i.onComplete||n,m=i.easing||r,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map((function(t,e){return v[e]-_[e]})):v-_);i.onStart&&i.onStart(),function t(i){var n=(e=i||+new Date)>u?c:e-h,r=n/c,w=p?_.map((function(t,e){return m(n,_[e],y[e],c)})):m(n,_,y,c),E=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=E,s.durationRate=r,!a){if(!f(w,E,r))return e>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void l()):(d(w,E,r),void o(t));l()}}(h)})),s.cancel},T.util.requestAnimFrame=o,T.util.cancelAnimFrame=function(){return a.apply(T.window,arguments)},T.runningAnimations=i}(),function(){function t(t,e,i){var n="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(n+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}T.util.animateColor=function(e,i,n,r){var s=new T.Color(e).getSource(),a=new T.Color(i).getSource(),o=r.onComplete,l=r.onChange;return r=r||{},T.util.animate(T.util.object.extend(r,{duration:n||500,startValue:s,endValue:a,byValue:a,easing:function(e,i,n,s){return t(i,n,r.colorEasing?r.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,n){if(o)return o(t(a,a,0),i,n)},onChange:function(e,i,n){if(l){if(Array.isArray(e))return l(t(e,e,0),i,n);l(e,i,n)}}}))}}(),function(){function t(t,e,i,n){return t-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===t||"xlink:href"===t||"font"===t)return i;if("imageSmoothing"===t)return"optimizeQuality"===i;o=l?i.map(s):s(i,r)}}else i="";return!l&&isNaN(o)?i:o}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,n,r,s,a=[];for(r=0,s=e.length;r1;)l.shift(),h=e.util.multiplyTransformMatrices(h,l[0]);return h}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,n,r,a,o,l,h=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!h||!(h=h.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,E={},C="",S=0,T=0;if(E.width=0,E.height=0,E.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(m)+") ",o=(t.getAttribute("transform")||"")+C,t.setAttribute("transform",o),t.removeAttribute("x"),t.removeAttribute("y")),w)return E;if(_)return E.width=s(d),E.height=s(f),E;if(i=-parseFloat(h[1]),n=-parseFloat(h[2]),r=parseFloat(h[3]),a=parseFloat(h[4]),E.minX=i,E.minY=n,E.viewBoxWidth=r,E.viewBoxHeight=a,y?(E.width=r,E.height=a):(E.width=s(d),E.height=s(f),c=E.width/r,u=E.height/a),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),S=E.width-r*c,T=E.height-a*c,"Mid"===p.alignX&&(S/=2),"Mid"===p.alignY&&(T/=2),"Min"===p.alignX&&(S=0),"Min"===p.alignY&&(T=0)),1===c&&1===u&&0===i&&0===n&&0===g&&0===m)return E;if((g||m)&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(m)+") "),o=C+" matrix("+c+" 0 0 "+u+" "+(i*c+S)+" "+(n*u+T)+") ","svg"===t.nodeName){for(l=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)l.appendChild(t.firstChild);t.appendChild(l)}else(l=t).removeAttribute("x"),l.removeAttribute("y"),o=l.getAttribute("transform")+o;return l.setAttribute("transform",o),E}function w(t,e){var i="xlink:href",n=_(t,e.getAttribute(i).slice(1));if(n&&n.getAttribute(i)&&w(t,n),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(t){n&&!e.hasAttribute(t)&&n.hasAttribute(t)&&e.setAttribute(t,n.getAttribute(t))})),!e.children.length)for(var r=n.cloneNode(!0);r.firstChild;)e.appendChild(r.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,r,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),n=0;i.length&&nt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,n,r,s){var a,o=(s.x-r.x)*(t.y-r.y)-(s.y-r.y)*(t.x-r.x),l=(n.x-t.x)*(t.y-r.y)-(n.y-t.y)*(t.x-r.x),h=(s.y-r.y)*(n.x-t.x)-(s.x-r.x)*(n.y-t.y);if(0!==h){var c=o/h,u=l/h;0<=c&&c<=1&&0<=u&&u<=1?(a=new i("Intersection")).appendPoint(new e.Point(t.x+c*(n.x-t.x),t.y+c*(n.y-t.y))):a=new i}else a=new i(0===o||0===l?"Coincident":"Parallel");return a},e.Intersection.intersectLinePolygon=function(t,e,n){var r,s,a,o,l=new i,h=n.length;for(o=0;o0&&(l.status="Intersection"),l},e.Intersection.intersectPolygonPolygon=function(t,e){var n,r=new i,s=t.length;for(n=0;n0&&(r.status="Intersection"),r},e.Intersection.intersectPolygonRectangle=function(t,n,r){var s=n.min(r),a=n.max(r),o=new e.Point(a.x,s.y),l=new e.Point(s.x,a.y),h=i.intersectLinePolygon(s,o,t),c=i.intersectLinePolygon(o,a,t),u=i.intersectLinePolygon(a,l,t),d=i.intersectLinePolygon(l,s,t),f=new i;return f.appendPoints(h.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function n(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,n){t/=255,i/=255,n/=255;var r,s,a,o=e.util.array.max([t,i,n]),l=e.util.array.min([t,i,n]);if(a=(o+l)/2,o===l)r=s=0;else{var h=o-l;switch(s=a>.5?h/(2-o-l):h/(o+l),o){case t:r=(i-n)/h+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var n=i.transform.target,r=n.canvas,s=e.util.object.clone(i);s.target=n,r&&r.fire("object:"+t,s),n.fire(t,i)}function m(t,e){var i=e.canvas,n=t[i.uniScaleKey];return i.uniformScaling&&!n||!i.uniformScaling&&n}function p(t){return t.originX===h&&t.originY===h}function _(t,e,i){var n=t.lockScalingX,r=t.lockScalingY;return!((!n||!r)&&(e||!n&&!r||!i)&&(!n||"x"!==e)&&(!r||"y"!==e))}function v(t,e,i,n){return{e:t,transform:e,pointer:{x:i,y:n}}}function y(t){return function(e,i,n,r){var s=i.target,a=s.getCenterPoint(),o=s.translateToOriginPoint(a,i.originX,i.originY),l=t(e,i,n,r);return s.setPositionByOrigin(o,i.originX,i.originY),l}}function w(t,e){return function(i,n,r,s){var a=e(i,n,r,s);return a&&g(t,v(i,n,r,s)),a}}function E(t,i,n,r,s){var a=t.target,o=a.controls[t.corner],l=a.canvas.getZoom(),h=a.padding/l,c=a.toLocalPoint(new e.Point(r,s),i,n);return c.x>=h&&(c.x-=h),c.x<=-h&&(c.x+=h),c.y>=h&&(c.y-=h),c.y<=h&&(c.y+=h),c.x-=o.offsetX,c.y-=o.offsetY,c}function C(t){return t.flipX!==t.flipY}function S(t,e,i,n,r){if(0!==t[e]){var s=r/t._getTransformedDimensions()[n]*t[i];t.set(i,s)}}function T(t,e,i,n){var r,h=e.target,c=h._getTransformedDimensions(0,h.skewY),d=E(e,e.originX,e.originY,i,n),f=Math.abs(2*d.x)-c.x,g=h.skewX;f<2?r=0:(r=u(Math.atan2(f/h.scaleX,c.y/h.scaleY)),e.originX===s&&e.originY===l&&(r=-r),e.originX===o&&e.originY===a&&(r=-r),C(h)&&(r=-r));var m=g!==r;if(m){var p=h._getTransformedDimensions().y;h.set("skewX",r),S(h,"skewY","scaleY","y",p)}return m}function b(t,e,i,n){var r,h=e.target,c=h._getTransformedDimensions(h.skewX,0),d=E(e,e.originX,e.originY,i,n),f=Math.abs(2*d.y)-c.y,g=h.skewY;f<2?r=0:(r=u(Math.atan2(f/h.scaleY,c.x/h.scaleX)),e.originX===s&&e.originY===l&&(r=-r),e.originX===o&&e.originY===a&&(r=-r),C(h)&&(r=-r));var m=g!==r;if(m){var p=h._getTransformedDimensions().x;h.set("skewY",r),S(h,"skewX","scaleX","x",p)}return m}function x(t,e,i,n,r){r=r||{};var s,a,o,l,h,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=r.by,w=m(t,f),C=_(f,y,w),S=e.gestureScale;if(C)return!1;if(S)a=e.scaleX*S,o=e.scaleY*S;else{if(s=E(e,e.originX,e.originY,i,n),h="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=h),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==h||e.signY!==u))return!1;if(l=f._getTransformedDimensions(),w&&!y){var T=Math.abs(s.x)+Math.abs(s.y),b=e.original,x=T/(Math.abs(l.x*b.scaleX/f.scaleX)+Math.abs(l.y*b.scaleY/f.scaleY));a=b.scaleX*x,o=b.scaleY*x}else a=Math.abs(s.x*f.scaleX/l.x),o=Math.abs(s.y*f.scaleY/l.y);p(e)&&(a*=2,o*=2),e.signX!==h&&"y"!==y&&(e.originX=c[e.originX],a*=-1,e.signX=h),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],o*=-1,e.signY=u)}var I=f.scaleX,R=f.scaleY;return y?("x"===y&&f.set("scaleX",a),"y"===y&&f.set("scaleY",o)):(!g&&f.set("scaleX",a),!v&&f.set("scaleY",o)),I!==f.scaleX||R!==f.scaleY}r.scaleCursorStyleHandler=function(t,e,n){var r=m(t,n),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(n,s,r))return"not-allowed";var a=f(n,e);return i[a]+"-resize"},r.skewCursorStyleHandler=function(t,e,i){var r="not-allowed";if(0!==e.x&&i.lockSkewingY)return r;if(0!==e.y&&i.lockSkewingX)return r;var s=f(i,e)%4;return n[s]+"-resize"},r.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?r.skewCursorStyleHandler(t,e,i):r.scaleCursorStyleHandler(t,e,i)},r.rotationWithSnapping=w("rotating",y((function(t,e,i,n){var r=e,s=r.target,a=s.translateToOriginPoint(s.getCenterPoint(),r.originX,r.originY);if(s.lockRotation)return!1;var o,l=Math.atan2(r.ey-a.y,r.ex-a.x),h=Math.atan2(n-a.y,i-a.x),c=u(h-l+r.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:o:(c>0&&(r=u===a?s:o),c<0&&(r=u===a?o:s),C(l)&&(r=r===s?o:s)),e.originX=r,w("skewing",y(T))(t,e,i,n))},r.skewHandlerY=function(t,e,i,n){var r,o=e.target,c=o.skewY,u=e.originX;return!o.lockSkewingY&&(0===c?r=E(e,h,h,i,n).y>0?a:l:(c>0&&(r=u===s?a:l),c<0&&(r=u===s?l:a),C(o)&&(r=r===a?l:a)),e.originY=r,w("skewing",y(b))(t,e,i,n))},r.dragHandler=function(t,e,i,n){var r=e.target,s=i-e.offsetX,a=n-e.offsetY,o=!r.get("lockMovementX")&&r.left!==s,l=!r.get("lockMovementY")&&r.top!==a;return o&&r.set("left",s),l&&r.set("top",a),(o||l)&&g("moving",v(t,e,i,n)),o||l},r.scaleOrSkewActionName=function(t,e,i){var n=t[i.canvas.altActionKey];return 0===e.x?n?"skewX":"scaleY":0===e.y?n?"skewY":"scaleX":void 0},r.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},r.fireEvent=g,r.wrapWithFixedAnchor=y,r.wrapWithFireEvent=w,r.getLocalPoint=E,e.controlsUtils=r}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,n=e.controlsUtils;n.renderCircleControl=function(t,e,i,n,r){n=n||{};var s,a=this.sizeX||n.cornerSize||r.cornerSize,o=this.sizeY||n.cornerSize||r.cornerSize,l=void 0!==n.transparentCorners?n.transparentCorners:r.transparentCorners,h=l?"stroke":"fill",c=!l&&(n.cornerStrokeColor||r.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=n.cornerColor||r.cornerColor,t.strokeStyle=n.cornerStrokeColor||r.cornerStrokeColor,a>o?(s=a,t.scale(1,o/a),d=i*a/o):o>a?(s=o,t.scale(a/o,1),u=e*o/a):s=a,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[h](),c&&t.stroke(),t.restore()},n.renderSquareControl=function(t,e,n,r,s){r=r||{};var a=this.sizeX||r.cornerSize||s.cornerSize,o=this.sizeY||r.cornerSize||s.cornerSize,l=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,h=l?"stroke":"fill",c=!l&&(r.cornerStrokeColor||s.cornerStrokeColor),u=a/2,d=o/2;t.save(),t.fillStyle=r.cornerColor||s.cornerColor,t.strokeStyle=r.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,n),t.rotate(i(s.angle)),t[h+"Rect"](-u,-d,a,o),c&&t.strokeRect(-u,-d,a,o),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,n,r,s){var a,o,l,h,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),m=Math.PI/2-d-e.util.degreesToRadians(t);a=f*e.util.cos(g),o=f*e.util.sin(g),l=f*e.util.cos(m),h=f*e.util.sin(m)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),a=l=f*e.util.cos(g),o=h=f*e.util.sin(g);return{tl:{x:n-h,y:r-l},tr:{x:n+a,y:r-o},bl:{x:n-a,y:r+o},br:{x:n+h,y:r+l}}},render:function(t,i,n,r,s){"circle"===((r=r||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,n,r,s):e.controlsUtils.renderSquareControl.call(this,t,i,n,r,s)}}}(e),function(){function t(t,e){var i,n,r,s,a=t.getAttribute("style"),o=t.getAttribute("offset")||0;if(o=(o=parseFloat(o)/(/%$/.test(o)?100:1))<0?0:o>1?1:o,a){var l=a.split(/\s*;\s*/);for(""===l[l.length-1]&&l.pop(),s=l.length;s--;){var h=l[s].split(/\s*:\s*/),c=h[0].trim(),u=h[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(r=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),r||(r=t.getAttribute("stop-opacity")),n=(i=new T.Color(i)).getAlpha(),r=isNaN(parseFloat(r))?1:parseFloat(r),r*=n*e,{offset:o,color:i.toRgb(),opacity:r}}var e=T.util.object.clone;T.Gradient=T.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach((function(e){i[e]=t[e]})),this.id?this.id+="_"+T.Object.__uid++:this.id=T.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new T.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return T.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var n,r,s,a,o=e(this.coords,!0),l=(i=i||{},e(this.colorStops,!0)),h=o.r1>o.r2,c=this.gradientTransform?this.gradientTransform.concat():T.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(l.sort((function(t,e){return t.offset-e.offset})),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,a='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',a+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+T.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(h)for((l=l.concat()).reverse(),n=0,r=l.length;n0){var p=m/Math.max(o.r1,o.r2);for(n=0,r=l.length;n\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,n,r=T.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(r.x1,r.y1,r.x2,r.y2):"radial"===this.type&&(e=t.createRadialGradient(r.x1,r.y1,r.r1,r.x2,r.y2,r.r2)),i=0,n=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var a,o,l,h,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,m=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(a="linear",o=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(a="radial",o=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),l=c.length;l--;)f.push(t(c[l],s));return h=T.parseTransformAttribute(d),function(t,e,i,n){var r,s;Object.keys(e).forEach((function(t){"Infinity"===(r=e[t])?s=1:"-Infinity"===r?s=0:(s=parseFloat(e[t],10),"string"==typeof r&&/^(\d+\.\d+)%|(\d+)%$/.test(r)&&(s*=.01,"pixels"===n&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s}))}(0,o,r,u),"pixels"===u&&(g=-i.left,m=-i.top),new T.Gradient({id:e.getAttribute("id"),type:a,coords:o,colorStops:f,gradientUnits:u,gradientTransform:h,offsetX:g,offsetY:m})}})}(),_=T.util.toFixed,T.Pattern=T.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=T.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=T.util.createImage(),T.util.loadImage(t.source,(function(t,n){i.source=t,e&&e(i,n)}),null,this.crossOrigin)}},toObject:function(t){var e,i,n=T.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:_(this.offsetX,n),offsetY:_(this.offsetY,n),patternTransform:this.patternTransform?this.patternTransform.concat():null},T.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,n=e.height/t.height,r=this.offsetX/t.width,s=this.offsetY/t.height,a="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(n=1,s&&(n+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,r&&(i+=Math.abs(r))),e.src?a=e.src:e.toDataURL&&(a=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),n=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(n[1],10)||0,offsetY:parseFloat(n[2],10)||0,blur:parseFloat(n[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var n=40,r=40,s=e.Object.NUM_FRACTION_DIGITS,a=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),o=new e.Color(this.color);return t.width&&t.height&&(n=100*i((Math.abs(a.x)+this.blur)/t.width,s)+20,r=100*i((Math.abs(a.y)+this.blur)/t.height,s)+20),t.flipX&&(a.x*=-1),t.flipY&&(a.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(e){this[e]!==i[e]&&(t[e]=this[e])}),this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(T.StaticCanvas)T.warn("fabric.StaticCanvas is already defined.");else{var t=T.util.object.extend,e=T.util.getElementOffset,i=T.util.removeFromArray,n=T.util.toFixed,r=T.util.transformPoint,s=T.util.invertTransform,a=T.util.getNodeCanvas,o=T.util.createCanvasElement,l=new Error("Could not initialize `canvas` element");T.StaticCanvas=T.util.createClass(T.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:T.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return T.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,T.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=T.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,n){return"string"==typeof e?T.util.loadImage(e,(function(e,r){if(e){var s=new T.Image(e,n);this[t]=s,s.canvas=this}i&&i(e,r)}),this,n&&n.crossOrigin):(n&&e.setOptions(n),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=o();if(!t)throw l;if(t.style||(t.style={}),void 0===t.getContext)throw l;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=T.util.getById(t)||this._createCanvasElement(),T.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var n in e=e||{},t)i=t[n],e.cssOnly||(this._setBackstoreDimension(n,t[n]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(n,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,n,r=this._activeObject,s=this.backgroundImage,a=this.overlayImage;for(this.viewportTransform=t,i=0,n=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,r=e.width||this.width,s=e.height||this.height,a='viewBox="0 0 '+this.width+" "+this.height+'" ',o=T.Object.NUM_FRACTION_DIGITS;e.viewBox?a='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,a='viewBox="'+n(-i[4]/i[0],o)+" "+n(-i[5]/i[3],o)+" "+n(this.width/i[0],o)+" "+n(this.height/i[3],o)+'" '),t.push("\n',"Created with Fabric.js ",T.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+T.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map((function(e){var i=t[e+"Color"];if(i&&i.toLive){var n=t[e+"Vpt"],r=t.viewportTransform,s={width:t.width/(n?r[0]:1),height:t.height/(n?r[3]:1)};return i.toSVG(s,{additionalTransform:n?T.util.matrixToSVG(r):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,n,r,s,a,o,l="",h={},c=T.fontPaths,u=[];for(this._objects.forEach((function t(e){u.push(e),e._objects&&e._objects.forEach(t)})),a=0,o=u.length;a',"\n",l,"","\n"].join("")),l},_setSVGObjects:function(t,e){var i,n,r,s=this._objects;for(n=0,r=s.length;n\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(r=s._objects).length;e--;)n=r[e],i(this._objects,n),this._objects.unshift(n);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(r=s._objects,e=0;e0+h&&(a=s-1,i(this._objects,r),this._objects.splice(a,0,r)),h++;else 0!==(s=this._objects.indexOf(t))&&(a=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(a,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var n,r;if(i){for(n=e,r=e-1;r>=0;--r)if(t.intersectsWithObject(this._objects[r])||t.isContainedWithinObject(this._objects[r])||this._objects[r].isContainedWithinObject(t)){n=r;break}}else n=e-1;return n},bringForward:function(t,e){if(!t)return this;var n,r,s,a,o,l=this._activeObject,h=0;if(t===l&&"activeSelection"===t.type)for(n=(o=l._objects).length;n--;)r=o[n],(s=this._objects.indexOf(r))"}}),t(T.StaticCanvas.prototype,T.Observable),t(T.StaticCanvas.prototype,T.Collection),t(T.StaticCanvas.prototype,T.DataURLExporter),t(T.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=o();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),T.StaticCanvas.prototype.toJSON=T.StaticCanvas.prototype.toObject,T.isLikelyNode&&(T.StaticCanvas.prototype.createPNGStream=function(){var t=a(this.lowerCanvasEl);return t&&t.createPNGStream()},T.StaticCanvas.prototype.createJPEGStream=function(t){var e=a(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),T.BaseBrush=T.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,n=t.getZoom();t&&t._isRetinaScaling()&&(n*=T.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*n,i.shadowOffsetX=e.offsetX*n,i.shadowOffsetY=e.offsetY*n}},needsFullRender:function(){return new T.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),T.PencilBrush=T.util.createClass(T.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var n=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,n.x,n.y),n},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,n=i.length,r=this.canvas.contextTop;this._saveAndTransform(r),this.oldEnd&&(r.beginPath(),r.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(r,i[n-2],i[n-1],!0),r.stroke(),r.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new T.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new T.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,n=this._points[0],r=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&n.x===r.x&&n.y===r.y){var s=this.width/1e3;n=new T.Point(n.x,n.y),r=new T.Point(r.x,r.y),n.x-=s,r.x+=s}for(t.moveTo(n.x,n.y),e=1,i=this._points.length;e=r&&(a=t[i],o.push(a));return o.push(t[s]),o},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),T.CircleBrush=T.util.createClass(T.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,n=this.points;for(this._saveAndTransform(i),t=0,e=n.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var r=0,s=this._objects.length;r1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),n=T.util.invertTransform(i),r=this.restorePointerVpt(e);return T.util.transformPoint(r,n)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var n=this._normalizePointer(t,{x:e,y:i}),r=Math.max(t.cacheTranslationX+n.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+n.y*t.zoomY,0);return T.util.isTransparent(t._cacheContext,Math.round(r),Math.round(s),this.targetFindTolerance)}var a=this.contextCache,o=t.selectionBackgroundColor,l=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(a),a.save(),a.transform(l[0],l[1],l[2],l[3],l[4],l[5]),t.render(a),a.restore(),t.selectionBackgroundColor=o,T.util.isTransparent(a,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(e){return!0===t[e]})):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),n=this._activeObject;return!e||e&&n&&i.length>1&&-1===i.indexOf(e)&&n!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&n&&n!==e},_shouldCenterTransform:function(t,e,i){var n;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?n=this.centeredScaling||t.centeredScaling:"rotate"===e&&(n=this.centeredRotation||t.centeredRotation),n?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,n){if(!e||!t)return"drag";var r=n.controls[e];return r.getActionName(i,r,n)},_setupCurrentTransform:function(t,i,n){if(i){var r=this.getPointer(t),s=i.__corner,a=i.controls[s],o=n&&s?a.getActionHandler(t,i,a):T.controlsUtils.dragHandler,l=this._getActionFromCorner(n,s,t,i),h=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:l,actionHandler:o,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:r.x-i.left,offsetY:r.y-i.top,originX:h.x,originY:h.y,ex:r.x,ey:r.y,lastX:r.x,lastY:r.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:T.util.saveObjectTransform(i)};this._shouldCenterTransform(i,l,c)&&(u.originX="center",u.originY="center"),u.original.originX=h.x,u.original.originY=h.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new T.Point(e.ex,e.ey),n=T.util.transformPoint(i,this.viewportTransform),r=new T.Point(e.ex+e.left,e.ey+e.top),s=T.util.transformPoint(r,this.viewportTransform),a=Math.min(n.x,s.x),o=Math.min(n.y,s.y),l=Math.max(n.x,s.x),h=Math.max(n.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(a,o,l-a,h-o)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,a+=c,o+=c,l-=c,h-=c,T.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(a,o,l-a,h-o))},findTarget:function(t,e){if(!this.skipTargetFind){var n,r,s=this.getPointer(t,!0),a=this._activeObject,o=this.getActiveObjects(),l=i(t),h=o.length>1&&!e||1===o.length;if(this.targets=[],h&&a._findTargetCorner(s,l))return a;if(o.length>1&&!e&&a===this._searchPossibleTargets([a],s))return a;if(1===o.length&&a===this._searchPossibleTargets([a],s)){if(!this.preserveObjectStacking)return a;n=a,r=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&n&&c!==n&&(c=n,this.targets=r),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,n,r=t.length;r--;){var s=t[r],a=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(a,s,e)){(i=t[r]).subTargetCheck&&i instanceof T.Group&&(n=this._searchPossibleTargets(i._objects,e))&&this.targets.push(n);break}}return i},restorePointerVpt:function(t){return T.util.transformPoint(t,T.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var n,r=t(e),s=this.upperCanvasEl,a=s.getBoundingClientRect(),o=a.width||0,l=a.height||0;o&&l||("top"in a&&"bottom"in a&&(l=Math.abs(a.top-a.bottom)),"right"in a&&"left"in a&&(o=Math.abs(a.right-a.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,i||(r=this.restorePointerVpt(r));var h=this.getRetinaScaling();return 1!==h&&(r.x/=h,r.y/=h),n=0===o||0===l?{width:1,height:1}:{width:s.width/o,height:s.height/l},{x:r.x*n.width,y:r.y*n.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),T.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=T.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),T.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),T.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;T.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,T.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,n=this.getActiveObjects(),r=[],s=[];t.forEach((function(t){-1===n.indexOf(t)&&(i=!0,t.fire("deselected",{e:e,target:t}),s.push(t))})),n.forEach((function(n){-1===t.indexOf(n)&&(i=!0,n.fire("selected",{e:e,target:n}),r.push(n))})),t.length>0&&n.length>0?i&&this.fire("selection:updated",{e:e,selected:r,deselected:s}):n.length>0?this.fire("selection:created",{e:e,selected:r}):t.length>0&&this.fire("selection:cleared",{e:e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e:e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){T.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,T.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(t),r=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,n),r},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){e[i]=t[i]})),T.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,n)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),T.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),T.StaticCanvas)"prototype"!==n&&(T.Canvas[n]=T.StaticCanvas[n])}(),function(){var t=T.util.addListener,e=T.util.removeListener,i={passive:!1};function n(t,e){return t.button&&t.button===e-1}T.util.object.extend(T.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var n=this.upperCanvasEl,r=this._getEventPrefix();t(T.window,"resize",this._onResize),t(n,r+"down",this._onMouseDown),t(n,r+"move",this._onMouseMove,i),t(n,r+"out",this._onMouseOut),t(n,r+"enter",this._onMouseEnter),t(n,"wheel",this._onMouseWheel),t(n,"contextmenu",this._onContextMenu),t(n,"dblclick",this._onDoubleClick),t(n,"dragover",this._onDragOver),t(n,"dragenter",this._onDragEnter),t(n,"dragleave",this._onDragLeave),t(n,"drop",this._onDrop),this.enablePointerEvents||t(n,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](n,"gesture",this._onGesture),eventjs[e](n,"drag",this._onDrag),eventjs[e](n,"orientation",this._onOrientationChange),eventjs[e](n,"shake",this._onShake),eventjs[e](n,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(T.document,t+"up",this._onMouseUp),e(T.document,"touchend",this._onTouchEnd,i),e(T.document,t+"move",this._onMouseMove,i),e(T.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach((function(n){i.fire("mouse:out",{target:e,e:t}),n&&e.fire("mouseout",{e:t})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(t){t.isEditing&&t.hiddenTextarea.focus()}))},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(n){n.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(n)),this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();t(T.document,"touchend",this._onTouchEnd,i),t(T.document,"touchmove",this._onMouseMove,i),e(r,s+"down",this._onMouseDown)},_onMouseDown:function(n){this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();e(r,s+"move",this._onMouseMove,i),t(T.document,s+"up",this._onMouseUp),t(T.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(n){if(!(n.touches.length>0)){this.__onMouseUp(n),this._resetTransformEventData(),this.mainTouchId=null;var r=this._getEventPrefix();e(T.document,"touchend",this._onTouchEnd,i),e(T.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){t(s.upperCanvasEl,r+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(n){this.__onMouseUp(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(n)&&(e(T.document,s+"up",this._onMouseUp),e(T.document,s+"move",this._onMouseMove,i),t(r,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,r=this._groupSelector,s=!1,a=!r||0===r.left&&0===r.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),n(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,a);else{if(n(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,a),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!a){var o=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!o&&e===this._activeObject)}var l,h;if(e){if(l=e._findTargetCorner(this.getPointer(t,!0),T.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[l],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(h=this.getPointer(t)).x,h.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==l)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);h=h||this.getPointer(t),f&&f(t,i,h.x,h.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,a),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():a||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),n=this.targets,r={e:e,target:i,subTargets:n};if(this.fire(t,r),i&&i.fire(t,r),!n)return i;for(var s=0;s1&&(e=new T.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],n=this._groupSelector.ex,r=this._groupSelector.ey,s=n+this._groupSelector.left,a=r+this._groupSelector.top,o=new T.Point(v(n,s),v(r,a)),l=new T.Point(y(n,s),y(r,a)),h=!this.selectionFullyContained,c=n===s&&r===a,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(h&&e.intersectsWithRect(o,l,!0)||e.isContainedWithinRect(o,l,!0)||h&&e.containsPoint(o,null,!0)||h&&e.containsPoint(l,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter((function(e){return!e.onSelect({e:t})}))),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),T.util.object.extend(T.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,n=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),r=this.toCanvasElement(n,t);return T.util.toDataURL(r,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,n=(e.height||this.height)*t,r=this.getZoom(),s=this.width,a=this.height,o=r*t,l=this.viewportTransform,h=(l[4]-(e.left||0))*t,c=(l[5]-(e.top||0))*t,u=this.interactive,d=[o,0,0,o,h,c],f=this.enableRetinaScaling,g=T.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=n,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=n,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=l,this.width=s,this.height=a,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=m,g}}),T.util.object.extend(T.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var n="string"==typeof t?JSON.parse(t):T.util.object.clone(t),r=this,s=n.clipPath,a=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete n.clipPath,this._enlivenObjects(n.objects,(function(t){r.clear(),r._setBgOverlay(n,(function(){s?r._enlivenObjects([s],(function(i){r.clipPath=i[0],r.__setupCanvas.call(r,n,t,a,e)})):r.__setupCanvas.call(r,n,t,a,e)}))}),i),this}},__setupCanvas:function(t,e,i,n){var r=this;e.forEach((function(t,e){r.insertAt(t,e)})),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),n&&n()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var n=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,n),this.__setBgOverlay("overlayImage",t.overlayImage,i,n),this.__setBgOverlay("backgroundColor",t.background,i,n),this.__setBgOverlay("overlayColor",t.overlay,i,n)}else e&&e()},__setBgOverlay:function(t,e,i,n){var r=this;if(!e)return i[t]=!0,void(n&&n());"backgroundImage"===t||"overlayImage"===t?T.util.enlivenObjects([e],(function(e){r[t]=e[0],i[t]=!0,n&&n()})):this["set"+T.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,n&&n()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?T.util.enlivenObjects(t,(function(t){e&&e(t)}),null,i):e&&e([])},_toDataURL:function(t,e){this.clone((function(i){e(i.toDataURL(t))}))},_toDataURLWithMultiplier:function(t,e,i){this.clone((function(n){i(n.toDataURLWithMultiplier(t,e))}))},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData((function(e){e.loadFromJSON(i,(function(){t&&t(e)}))}))},cloneWithoutData:function(t){var e=T.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new T.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),t&&t(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r=e.util.toFixed,s=e.util.string.capitalize,a=e.util.degreesToRadians,o=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:o,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,n=t.width,r=t.height,s=e.maxCacheSideLimit,a=e.minCacheSideLimit;if(n<=s&&r<=s&&n*r<=i)return nc&&(t.zoomX/=n/c,t.width=c,t.capped=!0),r>u&&(t.zoomY/=r/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,n=e.y*t.scaleY/this.scaleY;return{width:i+2,height:n+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:n}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,n=t._currentTransform.action;if(this===i&&n.slice&&"scale"===n.slice(0,5))return!1}var r,s,a=this._cacheCanvas,o=this._limitCacheSize(this._getCacheCanvasDimensions()),l=e.minCacheSideLimit,h=o.width,c=o.height,u=o.zoomX,d=o.zoomY,f=h!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,E=h>y||c>w;v=E||(h<.9*y||c<.9*w)&&y>l&&w>l,E&&!o.capped&&(h>l||c>l)&&(p=.1*h,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(a.width=Math.ceil(h+p),a.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,a.width,a.height)),r=o.x/2,s=o.y/2,this.cacheTranslationX=Math.round(a.width/2-r)+r,this.cacheTranslationY=Math.round(a.height/2-s)+s,this.cacheWidth=h,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,n={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:r(this.left,i),top:r(this.top,i),width:r(this.width,i),height:r(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:r(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:r(this.strokeMiterLimit,i),scaleX:r(this.scaleX,i),scaleY:r(this.scaleY,i),angle:r(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:r(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:r(this.skewX,i),skewY:r(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(n.clipPath=this.clipPath.toObject(t),n.clipPath.inverted=this.clipPath.inverted,n.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,n,t),this.includeDefaultValues||(n=this._removeDefaultValues(n)),n},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach((function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])})),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var n=this.canvas.getZoom(),r=this.canvas.getRetinaScaling();e*=n*r,i*=n*r}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var n="scaleX"===t||"scaleY"===t,r=this[t]!==i,s=!1;return n&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,r&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var n=e.util.invertTransform(this.calcTransformMatrix());t.transform(n[0],n[1],n[2],n[3],n[4],n[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=n},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var n,r,s,o=this.getViewportTransform(),l=this.calcTransformMatrix();r=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,l=e.util.multiplyTransformMatrices(o,l),n=e.util.qrDecompose(l),t.save(),t.translate(n.translateX,n.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(n.angle-=180),t.rotate(a(this.group?n.angle:this.angle)),i.forActiveSelection||this.group?r&&this.drawBordersInGroup(t,n,i):r&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,n=this.shadow,r=this.canvas,s=r&&r.viewportTransform[0]||1,a=r&&r.viewportTransform[3]||1;i=n.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),r&&r._isRetinaScaling()&&(s*=e.devicePixelRatio,a*=e.devicePixelRatio),t.shadowColor=n.color,t.shadowBlur=n.blur*e.browserShadowBlurConstant*(s+a)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=n.offsetX*s*i.scaleX,t.shadowOffsetY=n.offsetY*a*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,n=-this.width/2+e.offsetX||0,r=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,n,r):t.transform(1,0,0,1,n,r),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:n,offsetY:r}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var n,r=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),a=this.canvas.getRetinaScaling(),o=r.x/this.scaleX/a,l=r.y/this.scaleY/a;s.width=o,s.height=l,(n=s.getContext("2d")).beginPath(),n.moveTo(0,0),n.lineTo(o,0),n.lineTo(o,l),n.lineTo(0,l),n.closePath(),n.translate(o/2,l/2),n.scale(r.zoomX/this.scaleX/a,r.zoomY/this.scaleY/a),this._applyPatternGradientTransform(n,i),n.fillStyle=i.toLive(t),n.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(a*this.scaleX/r.zoomX,a*this.scaleY/r.zoomY),t.strokeStyle=n.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var n=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(n,t):e.Object._fromObject("Object",n,t)},cloneAsImage:function(t,i){var n=this.toCanvasElement(i);return t&&t(new e.Image(n)),this},toCanvasElement:function(t){t||(t={});var i=e.util,n=i.saveObjectTransform(this),r=this.group,s=this.shadow,a=Math.abs,o=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var l,h,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(h=g.blur,l=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(a(g.offsetX)+h)*a(l.scaleX),m.y=2*Math.round(a(g.offsetY)+h)*a(l.scaleY)),c=f.width+m.x,u=f.height+m.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var _=this.canvas;p.add(this);var v=p.toCanvasElement(o||1,t);return this.shadow=s,this.set("canvas",_),r&&(this.group=r),this.set(n).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var n=new e.Point(i.x,i.y),r=this._getLeftTopCoords();return this.angle&&(n=e.util.rotatePoint(n,r,a(-this.angle))),{x:n.x-r.x,y:n.y-r.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,r,s){var a=e[t];i=n(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],(function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,(function(){var t=s?new a(i[s],i):new a(i);r&&r(t)}))}))},e.Object.__uid=0)}(e),w=T.util.degreesToRadians,E={left:-.5,center:0,right:.5},C={top:-.5,center:0,bottom:.5},T.util.object.extend(T.Object.prototype,{translateToGivenOrigin:function(t,e,i,n,r){var s,a,o,l=t.x,h=t.y;return"string"==typeof e?e=E[e]:e-=.5,"string"==typeof n?n=E[n]:n-=.5,"string"==typeof i?i=C[i]:i-=.5,"string"==typeof r?r=C[r]:r-=.5,a=r-i,((s=n-e)||a)&&(o=this._getTransformedDimensions(),l=t.x+s*o.x,h=t.y+a*o.y),new T.Point(l,h)},translateToCenterPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?T.util.rotatePoint(n,t,w(this.angle)):n},translateToOriginPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?T.util.rotatePoint(n,t,w(this.angle)):n},getCenterPoint:function(){var t=new T.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var n,r,s=this.getCenterPoint();return n=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new T.Point(this.left,this.top),r=new T.Point(t.x,t.y),this.angle&&(r=T.util.rotatePoint(r,s,-w(this.angle))),r.subtractEquals(n)},setPositionByOrigin:function(t,e,i){var n=this.translateToCenterPoint(t,e,i),r=this.translateToOriginPoint(n,this.originX,this.originY);this.set("left",r.x),this.set("top",r.y)},adjustPosition:function(t){var e,i,n=w(this.angle),r=this.getScaledWidth(),s=T.util.cos(n)*r,a=T.util.sin(n)*r;e="string"==typeof this.originX?E[this.originX]:this.originX-.5,i="string"==typeof t?E[t]:t-.5,this.left+=s*(i-e),this.top+=a*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=T.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,n=t.transformPoint;t.object.extend(T.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new T.Point(i.tl.x,i.tl.y),new T.Point(i.tr.x,i.tr.y),new T.Point(i.br.x,i.br.y),new T.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,n){var r=this.getCoords(i,n);return"Intersection"===T.Intersection.intersectPolygonRectangle(r,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===T.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var n=this.getCoords(e,i),r=e?t.aCoords:t.lineCoords,s=0,a=t._getImageLines(r);s<4;s++)if(!t.containsPoint(n[s],a))return!1;return!0},isContainedWithinRect:function(t,e,i,n){var r=this.getBoundingRect(i,n);return r.left>=t.x&&r.left+r.width<=e.x&&r.top>=t.y&&r.top+r.height<=e.y},containsPoint:function(t,e,i,n){var r=this._getCoords(i,n),s=(e=e||this._getImageLines(r),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some((function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y}))||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var n={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(n,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every((function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)}))&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,n,r,s=0;for(var a in e)if(!((r=e[a]).o.y=t.y&&r.d.y>=t.y||(r.o.x===r.d.x&&r.o.x>=t.x?n=r.o.x:(i=(r.d.y-r.o.y)/(r.d.x-r.o.x),n=-(t.y-0*t.x-(r.o.y-i*r.o.x))/(0-i)),n>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var n=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(n)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,n=e.additionalTransform||"",r=[this.getSvgTransform(!0,n),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=r,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,n,r=(e=e||{}).noStyle,s=e.reviver,a=r?"":'style="'+this.getSvgStyles()+'" ',o=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",l=this.clipPath,h=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=l&&l.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return l&&(l.clipPathId="CLIPPATH_"+T.Object.__uid++,n='\n'+l.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[a,h,r?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),l&&g.push(n),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=T.util.object.extend,e="stateProperties";function i(e,i,n){var r={};n.forEach((function(t){r[t]=e[t]})),t(e[i],r,!0)}function n(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var r=0,s=t.length;r=0;l--)if(r=o[l],this.isControlVisible(r)&&(n=this._getImageLines(e?this.oCoords[r].touchCorner:this.oCoords[r].corner),0!==(i=this._findCrossPoints({x:s,y:a},n))&&i%2==1))return this.__corner=r,r;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),n=this._calculateCurrentDimensions(),r=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/r[0],1/r[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-n.x/2,-n.y/2,n.x,n.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),n=this.borderScaleFactor,r=i.x+n,s=i.y+n,a=void 0!==e.hasControls?e.hasControls:this.hasControls,o=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-r/2,-s/2,r,s),a&&(t.beginPath(),this.forEachControl((function(e,i,n){e.withConnection&&e.getVisibility(n,i)&&(o=!0,t.moveTo(e.x*r,e.y*s),t.lineTo(e.x*r+e.offsetX,e.y*s+e.offsetY))})),o&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var n=T.util.sizeAfterTransform(this.width,this.height,e),r=this.strokeWidth,s=this.strokeUniform,a=this.borderScaleFactor,o=n.x+r*(s?this.canvas.getZoom():e.scaleX)+a,l=n.y+r*(s?this.canvas.getZoom():e.scaleY)+a;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-o/2,-l/2,o,l),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,n,r=this.canvas.getRetinaScaling();return t.setTransform(r,0,0,r,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(r,s,a){n=a.oCoords[s],r.getVisibility(a,s)&&(i&&(n=T.util.transformPoint(n,i)),r.render(t,n.x,n.y,e,a))})),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),T.util.object.extend(T.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxCenterObjectV:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxRemove:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),r()},onComplete:function(){s.remove(t),n()}})}}),T.util.object.extend(T.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],n=[];for(t in arguments[0])i.push(t);for(var r=0,s=i.length;r-1||r&&s.colorProperties.indexOf(r[1])>-1,o=r?this.get(r[0])[r[1]]:this.get(t);"from"in i||(i.from=o),a||(e=~e.indexOf("=")?o+parseFloat(e.replace("=","")):parseFloat(e));var l={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,n){return i.abort.call(s,t,e,n)},onChange:function(e,a,o){r?s[r[0]][r[1]]=e:s.set(t,e),n||i.onChange&&i.onChange(e,a,o)},onComplete:function(t,e,r){n||(s.setCoords(),i.onComplete&&i.onComplete(t,e,r))}};return a?T.util.animateColor(l.startValue,l.endValue,l.duration,l):T.util.animate(l)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,n=t.axis1,r=t.axis2,s=t.dimension,a=e.nearest,o=e.center,l=e.farthest;return function(){switch(this.get(i)){case a:return Math.min(this.get(n),this.get(r));case o:return Math.min(this.get(n),this.get(r))+.5*this.get(s);case l:return Math.max(this.get(n),this.get(r))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==r[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,n=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:n,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,n,r){r=r||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),a=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];n(new e.Line(a,i(s,r)))},e.Line.fromObject=function(t,i){var r=n(t,!0);r.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",r,(function(t){delete t.points,i&&i(t)}),"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,n=(this.endAngle-this.startAngle)%360;if(0===n)t=["\n'];else{var r=i(this.startAngle),s=i(this.endAngle),a=this.radius;t=['180?"1":"0")+" 1"," "+e.util.cos(s)*a+" "+e.util.sin(s)*a,'" ',"COMMON_PARTS"," />\n"]}return t},_render:function(t){t.beginPath(),t.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(t)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(t){return this.radius=t,this.set("width",2*t).set("height",2*t)}}),e.Circle.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),e.Circle.fromElement=function(t,i){var n,r=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(n=r)&&n.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");r.left=(r.left||0)-r.radius,r.top=(r.top||0)-r.radius,i(new e.Circle(r))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var n=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);n.left=(n.left||0)-n.rx,n.top=(n.top||0)-n.ry,i(new e.Ellipse(n))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,n=this.width,r=this.height,s=-this.width/2,a=-this.height/2,o=0!==e||0!==i,l=.4477152502;t.beginPath(),t.moveTo(s+e,a),t.lineTo(s+n-e,a),o&&t.bezierCurveTo(s+n-l*e,a,s+n,a+l*i,s+n,a+i),t.lineTo(s+n,a+r-i),o&&t.bezierCurveTo(s+n,a+r-l*i,s+n-l*e,a+r,s+n-e,a+r),t.lineTo(s+e,a+r),o&&t.bezierCurveTo(s+l*e,a+r,s,a+r-l*i,s,a+r-i),t.lineTo(s,a+i),o&&t.bezierCurveTo(s,a+l*i,s+l*e,a,s+e,a),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,n,r){if(!t)return n(null);r=r||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var a=new e.Rect(i(r?e.util.object.clone(r):{},s));a.visible=a.visible&&a.width>0&&a.height>0,n(a)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.array.min,r=e.util.array.max,s=e.util.toFixed,a=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return a(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),n=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-n,this.height=i.height-n,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+n/2,y:i.top-this.strokeWidth/2+n/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+n/2,y:i.top+this.height/2+n/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=n(t,"x")||0,i=n(t,"y")||0;return{left:e,top:i,width:(r(t,"x")||0)-e,height:(r(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,n=this.pathOffset.y,r=e.Object.NUM_FRACTION_DIGITS,a=0,o=this.points.length;a\n']},commonRender:function(t){var e,i=this.points.length,n=this.pathOffset.x,r=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-n,this.points[0].y-r);for(var s=0;s"},toObject:function(t){return r(this.callSuper("toObject",t),{path:this.path.map((function(t){return t.slice()}))})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+a(-this.pathOffset.x,t)+", "+a(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,r,s=[],a=[],o=0,l=0,h=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var n=this._objects.length;if(this.useSetOnGroup)for(;n--;)this._objects[n].setOnGroup(t,i);if("canvas"===t)for(;n--;)this._objects[n]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,n=this._objects.filter((function(t){return!t.excludeFromExport})).map((function(e){var n=e.includeDefaultValues;e.includeDefaultValues=i;var r=e.toObject(t);return e.includeDefaultValues=n,r})),r=e.Object.prototype.toObject.call(this,t);return r.objects=n,r},toDatalessObject:function(t){var i,n=this.sourcePath;if(n)i=n;else{var r=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=r;var n=e.toDatalessObject(t);return e.includeDefaultValues=i,n}))}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,n=this._objects.length;i\n"],i=0,n=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,n=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var n=0,r=this._objects.length;n\n','\t\n',"\n"),a=' clip-path="url(#imageCrop_'+l+')" '}if(this.imageSmoothing||(o='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var h=this.fill;this.fill=null,t=["\t\n'],this.fill=h}return"fill"!==this.paintFirst?e.concat(t,i):e.concat(i,t)},getSrc:function(t){var e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src"):e.src:this.src||""},setSrc:function(t,e,i){return T.util.loadImage(t,(function(t,n){this.setElement(t,i),this._setWidthHeight(),e&&e(this,n)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),n=i.scaleX,r=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||n>e&&r>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=n,void(this._lastScaleY=r);T.filterBackend||(T.filterBackend=T.initFilterBackend());var a=T.util.createCanvasElement(),o=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,l=s.width,h=s.height;a.width=l,a.height=h,this._element=a,this._lastScaleX=t.scaleX=n,this._lastScaleY=t.scaleY=r,T.filterBackend.applyFilters([t],s,l,h,this._element,o),this._filterScalingX=a.width/this._originalElement.width,this._filterScalingY=a.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter((function(t){return t&&!t.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,n=e.naturalHeight||e.height;if(this._element===this._originalElement){var r=T.util.createCanvasElement();r.width=i,r.height=n,this._element=r,this._filteredEl=r}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,n),this._lastScaleX=1,this._lastScaleY=1;return T.filterBackend||(T.filterBackend=T.initFilterBackend()),T.filterBackend.applyFilters(t,this._originalElement,i,n,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){T.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){T.util.setImageSmoothing(t,this.imageSmoothing),T.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,n=this._filterScalingY,r=this.width,s=this.height,a=Math.min,o=Math.max,l=o(this.cropX,0),h=o(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=l*i,f=h*n,g=a(r*i,c-d),m=a(s*n,u-f),p=-r/2,_=-s/2,v=a(r,c/i-l),y=a(s,u/n-h);e&&t.drawImage(e,d,f,g,m,p,_,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(T.util.getById(t),e),T.util.addClass(this.getElement(),T.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?T.util.enlivenObjects(t,(function(t){e&&e(t)}),"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=T.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,n=this._element.height,r=1,s=1,a=0,o=0,l=0,h=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(r=c/i,s=u/n):("meet"===e.meetOrSlice&&(t=(c-i*(r=s=T.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(a=-t),"Max"===e.alignX&&(a=t),t=(u-n*s)/2,"Min"===e.alignY&&(o=-t),"Max"===e.alignY&&(o=t)),"slice"===e.meetOrSlice&&(t=i-c/(r=s=T.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(l=t/2),"Max"===e.alignX&&(l=t),t=n-u/s,"Mid"===e.alignY&&(h=t/2),"Max"===e.alignY&&(h=t),i=c/r,n=u/s)),{width:i,height:n,scaleX:r,scaleY:s,offsetLeft:a,offsetTop:o,cropX:l,cropY:h}}}),T.Image.CSS_CANVAS="canvas-img",T.Image.prototype.getSvgSrc=T.Image.prototype.getSrc,T.Image.fromObject=function(t,e){var i=T.util.object.clone(t);T.util.loadImage(i.src,(function(t,n){n?e&&e(null,!0):T.Image.prototype._initFilters.call(i,i.filters,(function(n){i.filters=n||[],T.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(n){i.resizeFilter=n[0],T.util.enlivenObjectEnlivables(i,i,(function(){var n=new T.Image(t,i);e(n,!1)}))}))}))}),null,i.crossOrigin)},T.Image.fromURL=function(t,e,i){T.util.loadImage(t,(function(t,n){e&&e(new T.Image(t,i),n)}),null,i&&i.crossOrigin)},T.Image.ATTRIBUTE_NAMES=T.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),T.Image.fromElement=function(t,i,n){var r=T.parseAttributes(t,T.Image.ATTRIBUTE_NAMES);T.Image.fromURL(r["xlink:href"],i,e(n?T.util.object.clone(n):{},r))})}(e),T.util.object.extend(T.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,n=t.onChange||e,r=this;return T.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){r.rotate(t),n()},onComplete:function(){r.setCoords(),i()}})}}),T.util.object.extend(T.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",n=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(n,i),t.compileShader(n),!!t.getShaderParameter(n,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}T.isWebglSupported=function(e){if(T.isLikelyNode)return!1;e=e||T.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),n=i.getContext("webgl")||i.getContext("experimental-webgl"),r=!1;if(n){T.maxTextureSize=n.getParameter(n.MAX_TEXTURE_SIZE),r=T.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],a=0;a<3;a++)if(t(n,s[a])){T.webGlPrecision=s[a];break}}return this.isSupported=r,r},T.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,n=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var r="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(n&&i&&r&&s){var a=T.util.createCanvasElement(),o=new ArrayBuffer(t*e*4);if(T.forceGLPutImageData)return this.imageBuffer=o,void(this.copyGLTo2D=I);var l,h,c={imageBuffer:o,destinationWidth:t,destinationHeight:e,targetCanvas:a};a.width=t,a.height=e,l=window.performance.now(),x.call(c,this.gl,c),h=window.performance.now()-l,l=window.performance.now(),I.call(c,this.gl,c),h>window.performance.now()-l?(this.imageBuffer=o,this.copyGLTo2D=I):this.copyGLTo2D=x}},createWebGLCanvas:function(t,e){var i=T.util.createCanvasElement();i.width=t,i.height=e;var n={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},r=i.getContext("webgl",n);r||(r=i.getContext("experimental-webgl",n)),r&&(r.clearColor(0,0,0,0),this.canvas=i,this.gl=r)},applyFilters:function(t,e,i,n,r,s){var a,o=this.gl;s&&(a=this.getCachedTexture(s,e));var l={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:n,destinationWidth:i,destinationHeight:n,context:o,sourceTexture:this.createTexture(o,i,n,!a&&e),targetTexture:this.createTexture(o,i,n),originalTexture:a||this.createTexture(o,i,n,!a&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:r},h=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,h),t.forEach((function(t){t&&t.applyTo(l)})),function(t){var e=t.targetCanvas,i=e.width,n=e.height,r=t.destinationWidth,s=t.destinationHeight;i===r&&n===s||(e.width=r,e.height=s)}(l),this.copyGLTo2D(o,l),o.bindTexture(o.TEXTURE_2D,null),o.deleteTexture(l.sourceTexture),o.deleteTexture(l.targetTexture),o.deleteFramebuffer(h),r.getContext("2d").setTransform(1,0,0,1,0,0),l},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,n){var r=t.createTexture();return t.bindTexture(t.TEXTURE_2D,r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),n?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,n):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),r},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:x,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var n=t.getParameter(i.UNMASKED_RENDERER_WEBGL),r=t.getParameter(i.UNMASKED_VENDOR_WEBGL);n&&(e.renderer=n.toLowerCase()),r&&(e.vendor=r.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}T.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,n,r){var s=r.getContext("2d");s.drawImage(e,0,0,i,n);var a={sourceWidth:i,sourceHeight:n,imageData:s.getImageData(0,0,i,n),originalEl:e,originalImageData:s.getImageData(0,0,i,n),canvasEl:r,ctx:s,filterBackend:this};return t.forEach((function(t){t.applyTo(a)})),a.imageData.width===i&&a.imageData.height===n||(r.width=a.imageData.width,r.height=a.imageData.height),s.putImageData(a.imageData,0,0),a}}}(),T.Image=T.Image||{},T.Image.filters=T.Image.filters||{},T.Image.filters.BaseFilter=T.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==T.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+T.webGlPrecision+" float"));var n=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var r=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var s=t.createProgram();if(t.attachShader(s,n),t.attachShader(s,r),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var a=this.getAttributeLocations(t,s),o=this.getUniformLocations(t,s)||{};return o.uStepW=t.getUniformLocation(s,"uStepW"),o.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:a,uniformLocations:o}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var n=e.aPosition,r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,n=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(n.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(n,e,i)),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t.targetTexture,0)):(n.bindFramebuffer(n.FRAMEBUFFER,null),n.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=T.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),T.Image.filters.BaseFilter.fromObject=function(t,e){var i=new T.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.ColorMatrix=n(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,n,r,s,a=t.imageData.data,o=a.length,l=this.matrix,h=this.colorsOnly;for(s=0;s=w||a<0||a>=y||(l=4*(o*y+a),h=p[f*_+d],e+=m[l]*h,i+=m[l+1]*h,n+=m[l+2]*h,S||(r+=m[l+3]*h));C[s]=e,C[s+1]=i,C[s+2]=n,C[s+3]=S?m[s+3]:r}t.imageData=E},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Grayscale=n(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,n=t.imageData.data,r=n.length,s=this.mode;for(e=0;eh[0]&&r>h[1]&&s>h[2]&&n 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,n,r,s,a,o,l,h=t.imageData.data,c=h.length,u=1-this.alpha;i=(l=new e.Color(this.color).getSource())[0]*this.alpha,n=l[1]*this.alpha,r=l[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return o(e)/e*o(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,n=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/n;var r,s=e.width,o=e.height,l=a(s*i),h=a(o*n);"sliceHack"===this.resizeType?r=this.sliceByTwo(t,s,o,l,h):"hermite"===this.resizeType?r=this.hermiteFastResize(t,s,o,l,h):"bilinear"===this.resizeType?r=this.bilinearFiltering(t,s,o,l,h):"lanczos"===this.resizeType&&(r=this.lanczosResize(t,s,o,l,h)),t.imageData=r},sliceByTwo:function(t,i,r,s,a){var o,l,h=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=r*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((o=m.sliceByTwo).width<1.5*i||o.height=e)){L=n(1e3*s(T-E.x)),w[L]||(w[L]={});for(var F=C.y-y;F<=C.y+y;F++)F<0||F>=a||(M=n(1e3*s(F-E.y)),w[L][M]||(w[L][M]=f(r(i(L*p,2)+i(M*_,2))/1e3)),(b=w[L][M])>0&&(I+=b,R+=b*c[x=4*(F*e+T)],O+=b*c[x+1],D+=b*c[x+2],A+=b*c[x+3]))}d[x=4*(S*o+l)]=R/I,d[x+1]=O/I,d[x+2]=D/I,d[x+3]=A/I}return++l1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(b+=y*f[3+(L=4*(A+I*e))],E+=y,f[L+3]<255&&(y=y*f[L+3]/250),C+=y*f[L],S+=y*f[L+1],T+=y*f[L+2],w+=y)}m[v]=C/w,m[v+1]=S/w,m[v+2]=T/w,m[v+3]=b/E}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Contrast=n(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,n=i.length,r=Math.floor(255*this.contrast),s=259*(r+255)/(255*(259-r));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Gamma=n(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,n=this.gamma,r=i.length,s=1/n[0],a=1/n[1],o=1/n[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,r=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=n)}return t},_renderTextLine:function(t,e,i,n,r,s){this._renderChars(t,e,i,n,r,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,n,r,s,a,o,l=t.fillStyle,h=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,m=this._textLines.length;g=0:io?u%=o:u<0&&(u+=o),this._setGraphemeOnPath(u,s,a),u+=s.kernedWidth}return{width:l,numOfSpaces:0}},_setGraphemeOnPath:function(t,i,n){var r=t+i.kernedWidth/2,s=this.path,a=e.util.getPointOnPath(s.path,r,s.segmentsInfo);i.renderLeft=a.x-n.x,i.renderTop=a.y-n.y,i.angle=a.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,n,r){var s,a=this.getCompleteStyleDeclaration(e,i),o=n?this.getCompleteStyleDeclaration(e,i-1):{},l=this._measureChar(t,a,n,o),h=l.kernedWidth,c=l.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),h+=s);var u={width:c,left:0,height:a.fontSize,kernedWidth:h,deltaY:a.deltaY};if(i>0&&!r){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+l.kernedWidth-l.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),n=1,r=e.length;n0){var I=v+s+u;"rtl"===this.direction&&(I=this.width-I-d),h&&_&&(t.fillStyle=_,t.fillRect(I,c+C*n+a,d,this.fontSize/15)),u=f.left,d=f.width,h=g,_=p,n=r,a=o}else d+=f.kernedWidth;I=v+s+u,"rtl"===this.direction&&(I=this.width-I-d),t.fillStyle=p,g&&p&&t.fillRect(I,c+C*n+a,d-E,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var n=t||this,r=this.fontFamily,s=e.Text.genericFonts.indexOf(r.toLowerCase())>-1,a=void 0===r||r.indexOf("'")>-1||r.indexOf(",")>-1||r.indexOf('"')>-1||s?n.fontFamily:'"'+n.fontFamily+'"';return[e.isLikelyNode?n.fontWeight:n.fontStyle,e.isLikelyNode?n.fontStyle:n.fontWeight,i?this.CACHE_FONT_SIZE+"px":n.fontSize+"px",a].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),n=new Array(i.length),r=["\n"],s=[],a=0;a-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}T.IText=T.util.createClass(T.Text,T.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:n.left,topOffset:n.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,n,r,s=0,a=0,o=this.get2DCursorLocation(t);n=o.charIndex,i=o.lineIndex;for(var l=0;l0?a:0)},"rtl"===this.direction&&(r.left*=-1),this.cursorOffsetCache=r,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),n=i.lineIndex,r=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(n,r,"fontSize"),a=this.scaleX*this.canvas.getZoom(),o=this.cursorWidth/a,l=t.topOffset,h=this.getValueOfPropertyAt(n,r,"deltaY");l+=(1-this._fontSizeFraction)*this.getHeightOfLine(n)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(n,r,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-o/2,l+t.top+h,o,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,n=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,r=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),a=this.get2DCursorLocation(n),o=s.lineIndex,l=a.lineIndex,h=s.charIndex<0?0:s.charIndex,c=a.charIndex<0?0:a.charIndex,u=o;u<=l;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),m=0,p=0;if(u===o&&(m=this.__charBounds[o][h].left),u>=o&&u1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,E=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,E=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+E,y,w),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),T.IText.fromObject=function(e,i){if(t(e),e.styles)for(var n in e.styles)for(var r in e.styles[n])t(e.styles[n][r]);T.Object._fromObject("IText",e,i,"text")}}(),S=T.util.object.clone,T.util.object.extend(T.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",(function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))}))},initRemovedHandler:function(){var t=this;this.on("removed",(function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],T.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))}))},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach((function(t){t.__isMousedown=!1}))},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,n){var r;return r={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){r.isAborted||t[n]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return r.isAborted}}),r},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){e._tick()}),i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&nthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var n=i.slice(0,t),r=T.util.string.graphemeSplit(n).length;if(t===e)return{selectionStart:r,selectionEnd:r};var s=i.slice(t,e);return{selectionStart:r,selectionEnd:r+T.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var n=i.slice(0,t).join("").length;return t===e?{selectionStart:n,selectionEnd:n}:{selectionStart:n,selectionEnd:n+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),n=i.lineIndex,r=i.charIndex,s=this.getValueOfPropertyAt(n,r,"fontSize")*this.lineHeight,a=e.leftOffset,o=this.calcTransformMatrix(),l={x:e.left+a,y:e.top+e.topOffset+s},h=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/h,d=c.height/h,f=u-s,g=d-s,m=c.clientWidth/u,p=c.clientHeight/d;return l=T.util.transformPoint(l,o),(l=T.util.transformPoint(l,this.canvas.viewportTransform)).x*=m,l.y*=p,l.x<0&&(l.x=0),l.x>f&&(l.x=f),l.y<0&&(l.y=0),l.y>g&&(l.y=g),l.x+=this.canvas._offset.left,l.y+=this.canvas._offset.top,{left:l.x+"px",top:l.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,n,r=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),a=r.lineIndex,o=r.charIndex,l=s.lineIndex,h=s.charIndex;if(a!==l){if(this.styles[a])for(i=o;i=h&&(n[c-d]=n[u],delete n[u])}},shiftLineStyles:function(t,e){var i=S(this.styles);for(var n in this.styles){var r=parseInt(n,10);r>t&&(this.styles[r+e]=i[r],i[r-e]||delete this.styles[r])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,n){var r,s={},a=!1,o=this._unwrappedTextLines[t].length===e;for(var l in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(r=this.styles[t][0===e?e:e-1]),this.styles[t]){var h=parseInt(l,10);h>=e&&(a=!0,s[h-e]=this.styles[t][l],o&&0===e||delete this.styles[t][l])}var c=!1;for(a&&!o&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)n&&n[i-1]?this.styles[t+i]={0:S(n[i-1])}:r?this.styles[t+i]={0:S(r)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,n){this.styles||(this.styles={});var r=this.styles[t],s=r?S(r):{};for(var a in i||(i=1),s){var o=parseInt(a,10);o>=e&&(r[o+i]=s[o],s[o-i]||delete r[o])}if(this._forceClearCache=!0,n)for(;i--;)Object.keys(n[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=S(n[i]));else if(r)for(var l=r[e?e-1:1];l&&i--;)this.styles[t][e+i]=S(l)},insertNewStyleBlock:function(t,e,i){for(var n=this.get2DCursorLocation(e,!0),r=[0],s=0,a=0;a0&&(this.insertCharStyleObject(n.lineIndex,n.charIndex,r[0],i),i=i&&i.slice(r[0]+1)),s&&this.insertNewlineStyleObject(n.lineIndex,n.charIndex+r[0],s),a=1;a0?this.insertCharStyleObject(n.lineIndex+a,0,r[a],i):i&&this.styles[n.lineIndex+a]&&i[0]&&(this.styles[n.lineIndex+a][0]=i[0]),i=i&&i.slice(r[a]+1);r[a]>0&&this.insertCharStyleObject(n.lineIndex+a,0,r[a],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),T.util.object.extend(T.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,n=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,n,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),n=0,r=0,s=0,a=0,o=0,l=0,h=this._textLines.length;l0&&(a+=this._textLines[l-1].length+this.missingNewlineOffset(l-1));r=this._getLineLeftOffset(o)*this.scaleX,e=this._textLines[o],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+r);for(var c=0,u=e.length;cs||a<0?0:1);return this.flipX&&(o=r-o),o>this._text.length&&(o=this._text.length),o}}),T.util.object.extend(T.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=T.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):T.document.body.appendChild(this.hiddenTextarea),T.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),T.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),T.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),T.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(T.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,n,r,s,a,o=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,l=this._text.length,h=o.length,c=h-l,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):h0&&(n+=(i=this.__charBounds[t][e-1]).left+i.width),n},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(r===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=n.charIndex,a=this._getWidthBeforeCursor(r,s),o=this._getIndexOnLine(r+1,a);return this._textLines[r].slice(s).length+o+1+this.missingNewlineOffset(r)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(0===r||t.metaKey||33===t.keyCode)return-i;var s=n.charIndex,a=this._getWidthBeforeCursor(r,s),o=this._getIndexOnLine(r-1,a),l=this._textLines[r].slice(0,s),h=this.missingNewlineOffset(r-1);return-this._textLines[r-1].length+o-l.length+(1-h)},_getIndexOnLine:function(t,e){for(var i,n,r=this._textLines[t],s=this._getLineLeftOffset(t),a=0,o=0,l=r.length;oe){n=!0;var h=s-i,c=s,u=Math.abs(h-e);a=Math.abs(c-e)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)},moveCursorUp:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)},_moveCursorUpOrDown:function(t,e){var i=this["get"+t+"CursorOffset"](e,"right"===this._selectionDirection);e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(t){var e="left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t},moveCursorWithoutShift:function(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t},moveCursorLeft:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)},_move:function(t,e,i){var n;if(t.altKey)n=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;n=this["findLineBoundary"+i](this[e])}if(void 0!==typeof n&&this[e]!==n)return this[e]=n,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,n){void 0===n&&(n=i),n>i&&this.removeStyleFromTo(i,n);var r=T.util.string.graphemeSplit(t);this.insertNewStyleBlock(r,i,e),this._text=[].concat(this._text.slice(0,i),r,this._text.slice(n)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=T.util.toFixed,e=/ +/g;T.util.object.extend(T.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,n=[],r=[],s=t;this._setSVGBg(r);for(var a=0,o=this._textLines.length;a",T.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,n){var r,s,a,o,l,h=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];n+=h*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)l=g===m||this.charSpacing,u+=f[g],a=this.__charBounds[e][g],0===d?(i+=a.kernedWidth-a.width,d+=a.width):d+=a.kernedWidth,c&&!l&&this._reSpaceAndTab.test(f[g])&&(l=!0),l||(r=r||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),l=this._hasStyleChangedForSvg(r,s)),l&&(o=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,o,i,n)),u="",r=s,i+=d,d=0)},_pushTextBgRect:function(e,i,n,r,s,a){var o=T.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,n){for(var r,s,a=this._textLines[e],o=this.getHeightOfLine(e)/this.lineHeight,l=0,h=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=a.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,n=0,r={},s=0;s0?(i=0,n++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[n])&&s>0&&(i++,n++),r[s]={line:e,offset:i},n+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return r},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var n=this._styleMap[i];n&&(i=n.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,n=0,r=!1,s=this._styleMap[t],a=this._styleMap[t+1];for(var o in s&&(t=s.line,n=s.offset),a&&(r=a.line===t,e=a.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var l in i[o])if(l>=n&&(!r||ln&&!p?(o.push(l),l=[],s=f,p=!0):s+=_,p||a||l.push(d),l=l.concat(c),g=a?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&o.push(l),m+r>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+r),o},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),n=this._wrapText(i.lines,this.width),r=new Array(n.length),s=0;s{},898:()=>{},245:()=>{}},Qe={};function ti(t){var e=Qe[t];if(void 0!==e)return e.exports;var i=Qe[t]={exports:{}};return $e[t](i,i.exports,ti),i.exports}ti.d=(t,e)=>{for(var i in e)ti.o(e,i)&&!ti.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},ti.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var ei={};(()=>{let t;ti.d(ei,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?ti(653).fabric:{version:"5.2.1"}})();var ii,ni,ri,si,ai=ei.R;!function(t){t[t.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",t[t.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",t[t.DIMT_TEXT=4]="DIMT_TEXT",t[t.DIMT_ARC=8]="DIMT_ARC",t[t.DIMT_IMAGE=16]="DIMT_IMAGE",t[t.DIMT_POLYGON=32]="DIMT_POLYGON",t[t.DIMT_LINE=64]="DIMT_LINE",t[t.DIMT_GROUP=128]="DIMT_GROUP"}(ii||(ii={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(ni||(ni={})),function(t){t[t.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",t[t.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",t[t.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS"}(ri||(ri={})),function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(si||(si={}));const oi=t=>"number"==typeof t&&!Number.isNaN(t),li=t=>"string"==typeof t;var hi,ci,ui,di,fi,gi,mi,pi,_i,vi,yi;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(fi||(fi={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(gi||(gi={}));class wi{get mediaType(){return new Map([["rect",ii.DIMT_RECTANGLE],["quad",ii.DIMT_QUADRILATERAL],["text",ii.DIMT_TEXT],["arc",ii.DIMT_ARC],["image",ii.DIMT_IMAGE],["polygon",ii.DIMT_POLYGON],["line",ii.DIMT_LINE],["group",ii.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(He(this,ci,"f")){case ni.DIS_DEFAULT:return"default";case ni.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===He(this,ui,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===He(this,ui,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),Xe(this,ui,t)}get coordinateBase(){return He(this,ui,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(hi.add(this),ci.set(this,void 0),ui.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=e&&!oi(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(ni.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.setState(ni.DIS_SELECTED)})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(ni.DIS_SELECTED):this.setState(ni.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){Xe(this,ci,t)}getState(){return He(this,ci,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),n=this.mapEvent_Callbacks.get(i);if(!n)throw new Error(`Event '${t}' does not exist.`);let r=n.get(e);r||(r=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const n={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,r,s;const a=i.target.getBoundingClientRect();t=a.left,e=a.top,r=t+window.scrollX,s=e+window.scrollY;const{width:o,height:l}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),h=this._drawingLayer.width,c=this._drawingLayer.height,u=o/l,d=h/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)u0?i-1:n,Ti),actionName:"modifyPolygon",pointIndex:i}),t}),{}),Xe(this,pi,JSON.parse(JSON.stringify(t))),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,n){return t["p"+n]=new ai.Control({positionHandler:Ci,actionHandler:bi(n>0?n-1:i,Ti),actionName:"modifyPolygon",pointIndex:n}),t}),{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let n=i.x-e.pathOffset.x,r=i.y-e.pathOffset.y;const s=ai.util.transformPoint({x:n,y:r},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){He(this,pi,"f")&&this.setPolygon(He(this,pi,"f"))}setPolygon(t){if(!T(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Xe(this,pi,JSON.parse(JSON.stringify(t)))}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return He(this,pi,"f")?JSON.parse(JSON.stringify(He(this,pi,"f"))):null}}pi=new WeakMap;_i=new WeakMap,vi=new WeakMap;const Ii=t=>{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let n=0;ni&&(i=r.length)}if(-1===i)break;for(let n=0;n=t[n].length-1)continue;let r=" ".repeat(i+2-t[n][e].length);t[n][e]=t[n][e].concat(r)}}})(e),(t=>{let e="";for(let i=0;i({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Xe(this,Di,JSON.parse(JSON.stringify(t)))}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return He(this,Di,"f")?JSON.parse(JSON.stringify(He(this,Di,"f"))):null}}Di=new WeakMap;class Li extends wi{constructor(t){super(new ai.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.setState(ni.DIS_SELECTED);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.setState(ni.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}setChildDrawingItems(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}}const Mi=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),Fi=t=>!!li(t)&&""!==t,Pi=t=>!(!Mi(t)||"id"in t&&!oi(t.id)||"lineWidth"in t&&!oi(t.lineWidth)||"fillStyle"in t&&!Fi(t.fillStyle)||"strokeStyle"in t&&!Fi(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!Fi(t.fontFamily)||"fontSize"in t&&!oi(t.fontSize));class ki{static convert(t,e,i){const n={x:0,y:0,width:e,height:i};if(!t)return n;if(x(t))t.isMeasuredInPercentage?(n.x=t.x/100*e,n.y=t.y/100*i,n.width=t.width/100*e,n.height=t.height/100*i):(n.x=t.x,n.y=t.y,n.width=t.width,n.height=t.height);else{if(!w(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?(n.x=t.left/100*e,n.y=t.top/100*i,n.width=(t.right-t.left)/100*e,n.height=(t.bottom-t.top)/100*i):(n.x=t.left,n.y=t.top,n.width=t.right-t.left,n.height=t.bottom-t.top)}return n.x=Math.round(n.x),n.y=Math.round(n.y),n.width=Math.round(n.width),n.height=Math.round(n.height),n}}var Ni,Bi;class ji{constructor(){Ni.set(this,new Map),Bi.set(this,!1)}get disposed(){return He(this,Bi,"f")}on(t,e){t=t.toLowerCase();const i=He(this,Ni,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else He(this,Ni,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=He(this,Ni,"f").get(t);if(!i)return;const n=i.indexOf(e);-1!==n&&i.splice(n,1)}offAll(t){t=t.toLowerCase();const e=He(this,Ni,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const n=He(this,Ni,"f").get(t);if(n&&n.length){i=Object.assign({async:!1,copy:!0},i);for(let r of n){if(!r)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let a=!1;if(i.async)setTimeout((()=>{this.disposed||n.includes(r)&&r.apply(i.target,s)}),0);else try{a=r.apply(i.target,s)}catch(t){}if(!0===a)break}}}dispose(){Xe(this,Bi,!0)}}function Vi(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function Ui(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function Gi(t,e,i,n){let r=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(n[1]-e[1])+e[0]*(t[1]-n[1])+n[0]*(e[1]-t[1]);return!((r^s)>=0&&0!==r&&0!==s||(r=i[0]*(t[1]-n[1])+n[0]*(i[1]-t[1])+t[0]*(n[1]-i[1]),s=i[0]*(e[1]-n[1])+n[0]*(i[1]-e[1])+e[0]*(n[1]-i[1]),(r^s)>=0&&0!==r&&0!==s))}Ni=new WeakMap,Bi=new WeakMap;const Wi=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const n=document.createElement("div");if(n.insertAdjacentHTML("beforeend",i),1===n.childElementCount&&n.firstChild instanceof HTMLTemplateElement)return n.firstChild.content;const r=new DocumentFragment;for(let t of n.children)r.append(t);return r};var Yi,zi,Hi,Xi,Zi,qi,Ji,Ki,$i,Qi,tn,en,nn,rn,sn,an,on,ln,hn,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,En,Cn,Sn,Tn;class bn{static createDrawingStyle(t){if(!Pi(t))throw new Error("Invalid style definition.");let e,i=bn.USER_START_STYLE_ID;for(;He(bn,Yi,"f",zi).has(i);)i++;e=i;const n=JSON.parse(JSON.stringify(t));n.id=e;for(let t in He(bn,Yi,"f",Hi))n.hasOwnProperty(t)||(n[t]=He(bn,Yi,"f",Hi)[t]);return He(bn,Yi,"f",zi).set(e,n),n.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=He(bn,Yi,"f",zi).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(He(bn,Yi,"f",zi).values())))}static _updateDrawingStyle(t,e){if(!Pi(e))throw new Error("Invalid style definition.");const i=He(bn,Yi,"f",zi).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}Yi=bn,bn.STYLE_BLUE_STROKE=1,bn.STYLE_GREEN_STROKE=2,bn.STYLE_ORANGE_STROKE=3,bn.STYLE_YELLOW_STROKE=4,bn.STYLE_BLUE_STROKE_FILL=5,bn.STYLE_GREEN_STROKE_FILL=6,bn.STYLE_ORANGE_STROKE_FILL=7,bn.STYLE_YELLOW_STROKE_FILL=8,bn.STYLE_BLUE_STROKE_TRANSPARENT=9,bn.STYLE_GREEN_STROKE_TRANSPARENT=10,bn.STYLE_ORANGE_STROKE_TRANSPARENT=11,bn.USER_START_STYLE_ID=1024,zi={value:new Map([[bn.STYLE_BLUE_STROKE,{id:bn.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[bn.STYLE_GREEN_STROKE,{id:bn.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[bn.STYLE_ORANGE_STROKE,{id:bn.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[bn.STYLE_YELLOW_STROKE,{id:bn.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[bn.STYLE_BLUE_STROKE_FILL,{id:bn.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[bn.STYLE_GREEN_STROKE_FILL,{id:bn.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[bn.STYLE_ORANGE_STROKE_FILL,{id:bn.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[bn.STYLE_YELLOW_STROKE_FILL,{id:bn.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[bn.STYLE_BLUE_STROKE_TRANSPARENT,{id:bn.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[bn.STYLE_GREEN_STROKE_TRANSPARENT,{id:bn.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[bn.STYLE_ORANGE_STROKE_TRANSPARENT,{id:bn.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},Hi={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(ai.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(ai.util.cancelAnimFrame(this.isRendering),this.isRendering=0),this.forEachObject((function(t){t.dispose&&t.dispose()})),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose&&this.backgroundImage.dispose(),this.backgroundImage=null,this.overlayImage&&this.overlayImage.dispose&&this.overlayImage.dispose(),this.overlayImage=null,this._iTextInstances=null,this.contextContainer=null,this.lowerCanvasEl.classList.remove("lower-canvas"),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),ai.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},ai.Object.prototype.transparentCorners=!1,ai.Object.prototype.cornerSize=20,ai.Object.prototype.touchCornerSize=100,ai.Object.prototype.cornerColor="rgb(254,142,20)",ai.Object.prototype.cornerStyle="circle",ai.Object.prototype.strokeUniform=!0,ai.Object.prototype.hasBorders=!1,ai.Canvas.prototype.containerClass="",ai.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i,n=this.upperCanvasEl,r=ai.util.getPointer(t,n),s=n.getBoundingClientRect(),a=s.width||0,o=s.height||0;a&&o||("top"in s&&"bottom"in s&&(o=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(a=Math.abs(s.right-s.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,e||(r=this.restorePointerVpt(r));var l=this.getRetinaScaling();if(1!==l&&(r.x/=l,r.y/=l),0!==a&&0!==o){var h=window.getComputedStyle(n).objectFit,c=n.width,u=n.height,d=a,f=o;i={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===h?p>_?(g=d,m=d/p,{x:r.x*i.width,y:(r.y-(f-m)/2)*i.width}):(g=f*p,m=f,{x:(r.x-(d-g)/2)*i.height,y:r.y*i.height}):"cover"===h?p>_?{x:(c-i.height*d)/2+r.x*i.height,y:r.y*i.height}:{x:r.x*i.width,y:(u-i.width*f)/2+r.y*i.width}:{x:r.x*i.width,y:r.y*i.height}}return i={width:1,height:1},{x:r.x*i.width,y:r.y*i.height}},ai.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,n=this._getEventPrefix();ai.util.addListener(ai.document,"touchend",this._onTouchEnd,{passive:!1}),ai.util.addListener(ai.document,"touchmove",this._onMouseMove,{passive:!1}),ai.util.removeListener(i,n+"down",this._onMouseDown)},ai.Textbox.prototype._wrapLine=function(t,e,i,n){const r=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!r||!r.length);var a=0,o=this.splitByGrapheme||s,l=[],h=[],c=o?ai.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=o?"":" ",g=0,m=0,p=0,_=!0,v=this._getWidthOfCharSpacing();n=n||0,0===c.length&&c.push([]),i-=n;for(var y=0;yi&&!_?(l.push(h),h=[],a=g,_=!0):a+=v,_||o||h.push(f),h=h.concat(u),m=o?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&l.push(h),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+n),l});class xn{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){if(this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas"))this.fabricCanvas=t.getFabricCanvas();else{let e=this.fabricCanvas=new ai.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.on("selection:created",(function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])}),0)}})),e.on("before:selection:cleared",(function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{const e=[];for(let n of i)t.hasDrawingItem(n)&&e.push(n);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)}),0)}})),e.on("selection:updated",(function(t){const e=t.selected,i=t.deselected,n=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of n){const n=[],r=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&n.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&r.push(i)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(n,r)}),0)}})),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let n,r;switch(this.id=e,e){case xn.DDN_LAYER_ID:n=bn.getDrawingStyle(bn.STYLE_BLUE_STROKE),r=bn.getDrawingStyle(bn.STYLE_BLUE_STROKE_FILL);break;case xn.DBR_LAYER_ID:n=bn.getDrawingStyle(bn.STYLE_ORANGE_STROKE),r=bn.getDrawingStyle(bn.STYLE_ORANGE_STROKE_FILL);break;case xn.DLR_LAYER_ID:n=bn.getDrawingStyle(bn.STYLE_GREEN_STROKE),r=bn.getDrawingStyle(bn.STYLE_GREEN_STROKE_FILL);break;default:n=bn.getDrawingStyle(bn.STYLE_YELLOW_STROKE),r=bn.getDrawingStyle(bn.STYLE_YELLOW_STROKE_FILL)}for(let t of wi.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:n.id,selected:r.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return bn.getDrawingStyle(t.styleId);return bn.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,n){const r=this.getDrawingItems((e=>e._mediaType===t));for(let t of r)t.styleSelector===e&&this._changeItemStyle(t,i,!0);n||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const n=t._getFabricObject();"number"==typeof t.styleId&&(e=bn.getDrawingStyle(t.styleId)),n.strokeWidth=e.lineWidth,"fill"===e.paintMode?(n.fill=e.fillStyle,n.stroke=e.fillStyle):"stroke"===e.paintMode?(n.fill="transparent",n.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(n.fill=e.fillStyle,n.stroke=e.strokeStyle),n.fontFamily&&(n.fontFamily=e.fontFamily),n.fontSize&&(n.fontSize=e.fontSize),n.group||(n.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const n=t.getChildDrawingItems();if("add"===i){if(n.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=bn.getDrawingStyle(e.styleId);else{const n=this.mapType_StateAndStyleId.get(e._mediaType);i=bn.getDrawingStyle(n[t.styleSelector]);const r=()=>{this._changeItemStyle(e,bn.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,bn.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",r),e._on("deselected",s),e._funcChangeStyleToSelected=r,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!n.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof wi))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const n=this.fabricCanvas.getObjects();let r,s;if(n.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){r=t.getChildDrawingItems();for(let t of r)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(r){for(let t of r){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of wi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=bn.getDrawingStyle(t.styleId);else{s=bn.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,bn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},n=()=>{this._changeItemStyle(t,bn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of wi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=bn.getDrawingStyle(t.styleId);else{s=bn.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,bn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},n=()=>{this._changeItemStyle(t,bn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const a=this._arrFabricObject.length;let o=n.length;if(a)o=n.indexOf(this._arrFabricObject[a-1])+1;else for(let e=0;et.toLowerCase())):e=wi.arrMediaTypes,i?i.forEach((t=>t.toLowerCase())):i=wi.arrStyleSelectors;const n=bn.getDrawingStyle(t);if(!n)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let r;for(let s of e)if(r=this.mapType_StateAndStyleId.get(s),r)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,n,!0),r[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const n=[];i&ii.DIMT_RECTANGLE&&n.push("rect"),i&ii.DIMT_QUADRILATERAL&&n.push("quad"),i&ii.DIMT_TEXT&&n.push("text"),i&ii.DIMT_ARC&&n.push("arc"),i&ii.DIMT_IMAGE&&n.push("image"),i&ii.DIMT_POLYGON&&n.push("polygon"),i&ii.DIMT_LINE&&n.push("line");const r=[];e&ni.DIS_DEFAULT&&r.push("default"),e&ni.DIS_SELECTED&&r.push("selected"),this._setDefaultStyle(t,n.length?n:null,r.length?r:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}xn.DDN_LAYER_ID=1,xn.DBR_LAYER_ID=2,xn.DLR_LAYER_ID=3,xn.USER_DEFINED_LAYER_BASE_ID=100,xn.TIP_LAYER_ID=999;class In{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new xn(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(t){const e=this.getDrawingLayer(t);if(!e)return;const i=this._arrDrawingLayer;e.dispose(),i.splice(i.indexOf(e),1),this._switchPointerEvent()}clearDrawingLayers(){for(let t of this._arrDrawingLayer)t.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(t){for(let e of this._arrDrawingLayer)if(e.getId()===t)return e;return null}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().getActiveObjects(),e=[];for(let i of t)e.push(i.getDrawingItem());return e}setDimensions(t,e){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(t,e)}setObjectFit(t){for(let e of this._arrDrawingLayer)e&&e._setObjectFit(t)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(t){if(!this._arrDrawingLayer.length)return;this._getFabricCanvas().wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class Rn extends Ri{constructor(t,e,i,n,r){super(t,{x:e,y:i,width:n,height:0},r),Xi.set(this,void 0),Zi.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&Xe(this,Zi,setTimeout((()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()}),He(this,Xi,"f")))}getDuration(){return He(this,Xi,"f")}}Xi=new WeakMap,Zi=new WeakMap;class On{constructor(){qi.add(this),Ji.set(this,void 0),Ki.set(this,void 0),$i.set(this,void 0),Qi.set(this,!0),this._drawingLayerManager=new In}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const n=document.createElement("canvas");return n.width==t&&n.height==e||(n.width=t,n.height=e),n.style.objectFit=i,n}_createDrawingLayer(t,e,i,n){if(!this._layerBaseCvs){let r;try{r=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==r?void 0:r.width)||1280),i||(i=(null==r?void 0:r.height)||720),n||(n=(null==r?void 0:r.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,n)}const r=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(r,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",r.parentElement),s}createDrawingLayer(){let t;for(let e=xn.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==xn.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(tt.getId()>=0&&t.getId()!==xn.TIP_LAYER_ID))}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(Mi(e=t)&&S(e.topLeftPoint)&&oi(e.width))||e.width<=0||!oi(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;Xe(this,Ji,JSON.parse(JSON.stringify(t))),He(this,Ji,"f").coordinateBase||(He(this,Ji,"f").coordinateBase="view"),Xe(this,$i,t.duration),He(this,qi,"m",rn).call(this)}getTipConfig(){return He(this,Ji,"f")?He(this,Ji,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),Xe(this,Qi,t)}isTipVisible(){return He(this,Qi,"f")}updateTipMessage(t){if(!He(this,Ji,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=bn.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(xn.TIP_LAYER_ID)||this._createDrawingLayer(xn.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=He(this,qi,"m",tn).call(this,t,He(this,Ji,"f").topLeftPoint.x,He(this,Ji,"f").topLeftPoint.y,He(this,Ji,"f").width,He(this,Ji,"f").coordinateBase,this._tipStyleId),He(this,qi,"m",en).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",He(this,Qi,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),He(this,Ki,"f")&&clearTimeout(He(this,Ki,"f")),He(this,$i,"f")>=0&&Xe(this,Ki,setTimeout((()=>{He(this,qi,"m",nn).call(this)}),He(this,$i,"f")))}}Ji=new WeakMap,Ki=new WeakMap,$i=new WeakMap,Qi=new WeakMap,qi=new WeakSet,tn=function(t,e,i,n,r,s){const a=new Rn(t,e,i,n,s);return a.coordinateBase=r,a},en=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},nn=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},rn=function(){if(!this._tip)return;const t=He(this,Ji,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class Dn extends HTMLElement{constructor(){super(),sn.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),Xe(this,sn,e);const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const n=document.createElement("slot");n.setAttribute("name","content"),e.append(n);const r=document.createElement("slot");r.setAttribute("name","drawing-layer"),e.append(r);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return He(this,sn,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach((t=>t.remove()))}}sn=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",Dn);class An extends On{static get engineResourcePath(){return O(gt.engineResourcePaths).dce}static set defaultUIElementURL(t){An._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=An._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",An.engineResourcePath)}static async createInstance(t){const e=new An;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",An.engineResourcePath)),await e.setUIElement(t||An.defaultUIElementURL),e}static _transformCoordinates(t,e,i,n,r,s,a){const o=s/n,l=a/r;t.x=Math.round(t.x/o+e),t.y=Math.round(t.y/l+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==He(this,mn,"f")){if(Xe(this,mn,t),He(this,an,"m",vn).call(this))Xe(this,cn,null),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!He(this,cn,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(ze.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Xe(this,cn,t);const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}He(this,an,"m",vn).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return He(this,mn,"f")}get disposed(){return He(this,_n,"f")}constructor(){super(),an.add(this),on.set(this,void 0),ln.set(this,void 0),hn.set(this,void 0),this.containerClassName="dce-video-container",cn.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,un.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,dn.set(this,!1),fn.set(this,!1),gn.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{He(this,an,"m",Sn).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout((()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&He(this,an,"m",Cn).call(this))}),this._updateLayersTimeout)},this._windowResizeListener=()=>{An._onLog&&An._onLog("window resize event triggered."),He(this,gn,"f").width===document.documentElement.clientWidth&&He(this,gn,"f").height===document.documentElement.clientHeight||(He(this,gn,"f").width=document.documentElement.clientWidth,He(this,gn,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},mn.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!He(this,an,"m",vn).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise(((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i},i=(t,e,i,n)=>{t.width==i&&t.height==n||(t.width=i,t.height=n);const r=t.getContext("2d");r.clearRect(0,0,t.width,t.height),r.drawImage(e,0,0)},n=await t(e),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let a=this._cvsSingleFrameMode;const o=null==a?void 0:a.width,l=null==a?void 0:a.height;a||(a=document.createElement("canvas"),this._cvsSingleFrameMode=a),i(a,n,r,s),this._innerComponent.setElement("content",a),o===a.width&&l===a.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout((()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)}),0)})),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},pn.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,n,r,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const a=t.originalImageTag;if(!a)return;const o=t.items;if(!(null==o?void 0:o.length))return;const l=(null===(i=a.cropRegion)||void 0===i?void 0:i.left)||0,h=(null===(n=a.cropRegion)||void 0===n?void 0:n.top)||0,c=(null===(r=a.cropRegion)||void 0===r?void 0:r.right)?a.cropRegion.right-l:a.originalWidth,u=(null===(s=a.cropRegion)||void 0===s?void 0:s.bottom)?a.cropRegion.bottom-h:a.originalHeight,d=a.currentWidth,f=a.currentHeight,g=(t,e,i,n,r,s,a,o,l=[],h)=>{e.forEach((t=>An._transformCoordinates(t,i,n,r,s,a,o)));const c=new Ai({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},h);for(let t of l)c.addNote(t);t.addDrawingItems([c]),He(this,pn,"f").push(c)};let m,p;for(let t of o)switch(t.type){case mt.CRIT_ORIGINAL_IMAGE:break;case mt.CRIT_BARCODE:m=this.getDrawingLayer(xn.DBR_LAYER_ID),p=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?g(m,t.location.points,l,h,c,u,d,f,p):g(m,t.location.points,l,h,c,u,d,f,p,bn.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,l,h,c,u,d,f,p);break;case mt.CRIT_TEXT_LINE:m=this.getDrawingLayer(xn.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,l,h,c,u,d,f,p):g(m,t.location.points,l,h,c,u,d,f,p,bn.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,l,h,c,u,d,f,p);break;case mt.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(xn.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===St.CVS_PASSED?g(m,t.location.points,l,h,c,u,d,f,[]):g(m,t.location.points,l,h,c,u,d,f,[],bn.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,l,h,c,u,d,f,[]);break;case mt.CRIT_NORMALIZED_IMAGE:m=this.getDrawingLayer(xn.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===St.CVS_PASSED?g(m,t.location.points,l,h,c,u,d,f,[]):g(m,t.location.points,l,h,c,u,d,f,[],bn.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,l,h,c,u,d,f,[]);break;case mt.CRIT_PARSED_RESULT:break;default:throw new Error("Illegal item type.")}}},_n.set(this,!1),this.eventHandler=new ji,this.eventHandler.on("content:updated",(()=>{He(this,on,"f")&&clearTimeout(He(this,on,"f")),Xe(this,on,setTimeout((()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)}),0))})),this.eventHandler.on("videoEl:resized",(()=>{He(this,ln,"f")&&clearTimeout(He(this,ln,"f")),Xe(this,ln,setTimeout((()=>{this.disposed||this._updateVideoContainer()}),0))}))}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Wi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let n=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!n)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=document.createElement("dce-component"),n.appendChild(this._innerComponent),He(this,an,"m",vn).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(ze.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Xe(this,cn,t);const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._selRsl&&(this._hideDefaultSelection||He(this,an,"m",vn).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||He(this,an,"m",vn).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||He(this,an,"m",Sn).call(this),He(this,an,"m",vn).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),He(this,an,"m",vn).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{var e;An._onLog&&An._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()})));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}He(this,gn,"f").width=document.documentElement.clientWidth,He(this,gn,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,n;He(this,an,"m",vn).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),He(this,an,"m",Sn).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,Xe(this,cn,null),null===(n=this._videoContainer)||void 0===n||n.remove(),this._videoContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let n of e){const e=document.createElement("option");e.value=n.deviceId,e.innerText=n.label,this._selCam.append(e),n.deviceId&&t&&t.deviceId==n.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),n=Math.min(t.width,t.height);e=n<=1080?n+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return He(this,cn,"f")}isVideoLoaded(){return!(!He(this,cn,"f")||!this.cameraEnhancer)&&this.cameraEnhancer.isOpen()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!He(this,cn,"f"))return;if(He(this,cn,"f").style.objectFit=t,He(this,an,"m",vn).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}He(this,an,"m",Tn).call(this,e,this.getConvertedRegion()),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,n;let r,s,a;if(He(this,an,"m",vn).call(this)?(r=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(n=this._cvsSingleFrameMode)||void 0===n?void 0:n.height,a="contain"):(r=null===(t=He(this,cn,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=He(this,cn,"f"))||void 0===e?void 0:e.videoHeight,a=this.getVideoFit()),!r||!s)throw new Error("Invalid content dimensions.");return{width:r,height:s,objectFit:a}}updateConvertedRegion(t){const e=ki.convert(this.scanRegion,t.width,t.height);Xe(this,un,e),He(this,hn,"f")&&clearTimeout(He(this,hn,"f")),Xe(this,hn,setTimeout((()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}He(this,an,"m",yn).call(this,t,e),He(this,an,"m",Tn).call(this,t,e)}),0))}getConvertedRegion(){return He(this,un,"f")}setScanRegion(t){if(null!=t&&!w(t)&&!x(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=He(this,cn,"f").videoWidth,i=He(this,cn,"f").videoHeight,n=this.getVideoFit(),{width:r,height:s}=this._innerComponent.getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");let a;const o={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===n&&(r/s1){const t=He(this,cn,"f").videoWidth,e=He(this,cn,"f").videoHeight,{width:n,height:r}=this._innerComponent.getBoundingClientRect(),s=t/e;if(n/rt.remove())),He(this,pn,"f").length=0}dispose(){this._unbindUI(),Xe(this,_n,!0)}}function Ln(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Mn(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,i),i}on=new WeakMap,ln=new WeakMap,hn=new WeakMap,cn=new WeakMap,un=new WeakMap,dn=new WeakMap,fn=new WeakMap,gn=new WeakMap,mn=new WeakMap,pn=new WeakMap,_n=new WeakMap,an=new WeakSet,vn=function(){return"disabled"!==this._singleFrameMode},yn=function(t,e){!e||0===e.x&&0===e.y&&e.width===t.width&&e.height===t.height?this.clearScanRegionMask():this.setScanRegionMask(e.x,e.y,e.width,e.height)},wn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},En=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},Cn=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},Sn=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Tn=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:n,objectFit:r}=t;e||(e={x:0,y:0,width:i,height:n});const{width:s,height:a}=this._innerComponent.getBoundingClientRect();if(s<=0||a<=0)return;const o=s/a,l=i/n;let h,c,u,d,f=1;if("contain"===r)o66||"Safari"===jn.browser&&jn.version>13||"OPR"===jn.browser&&jn.version>43||"Edge"===jn.browser&&jn.version,"function"==typeof SuppressedError&&SuppressedError;class Gn{static multiply(t,e){const i=[];for(let n=0;n<3;n++){const r=e.slice(3*n,3*n+3);for(let e=0;e<3;e++){const n=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*r[i]),0);i.push(n)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return Gn.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),n=Math.sin(e);return Gn.multiply(t,[i,-n,0,n,i,0,0,0,1])}static scale(t,e,i){return Gn.multiply(t,[e,0,0,0,i,0,0,0,1])}}var Wn,Yn,zn,Hn,Xn,Zn,qn,Jn,Kn,$n,Qn,tr,er,ir,nr,rr,sr,ar,or,lr,hr,cr,ur,dr,fr,gr,mr,pr,_r,vr,yr,wr,Er,Cr,Sr,Tr,br,xr,Ir,Rr,Or,Dr,Ar,Lr,Mr,Fr,Pr,kr,Nr,Br;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(Wn||(Wn={}));class jr{static get version(){return"1.1.3"}static get webGLSupported(){return void 0===jr._webGLSupported&&(jr._webGLSupported=!!document.createElement("canvas").getContext("webgl")),jr._webGLSupported}get disposed(){return Vn(this,qn,"f")}constructor(){Yn.set(this,Wn.RGBA),zn.set(this,null),Hn.set(this,null),Xn.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,Zn.set(this,null),qn.set(this,!1)}drawImage(t,e,i,n,r,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!n)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if((null==s?void 0:s.bUseWebGL)&&!jr.webGLSupported)throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let a;jr._onLog&&(a=Date.now(),jr._onLog("drawImage(), START: "+a));let o=0,l=0,h=i,c=n,u=0,d=0,f=i,g=n;r&&(r.sx&&(o=Math.round(r.sx)),r.sy&&(l=Math.round(r.sy)),r.sWidth&&(h=Math.round(r.sWidth)),r.sHeight&&(c=Math.round(r.sHeight)),r.dx&&(u=Math.round(r.dx)),r.dy&&(d=Math.round(r.dy)),r.dWidth&&(f=Math.round(r.dWidth)),r.dHeight&&(g=Math.round(r.dHeight)));let m,p=Wn.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!jr.webGLSupported||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){jr._onLog&&jr._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},n=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},r=(t,e,i)=>{const n=t.createShader(e);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(n)}.`);throw e.name="WebGLError",e}return n},s="\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\n\nuniform mat3 u_matrix;\nuniform mat3 u_textureMatrix;\n\nvarying vec2 v_texCoord;\nvoid main(void) {\ngl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\nv_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n}";let a="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(a=p.slice(0,3));const o=`\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_image;\nuniform float uColorFactor;\n\nvoid main() {\nvec4 sample = texture2D(u_image, v_texCoord);\nfloat grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\ngl_FragColor = vec4(sample.${a} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n}`,l=n(t,[r(t,t.VERTEX_SHADER,s),r(t,t.FRAGMENT_SHADER,o)]);Un(this,Hn,{program:l,attribLocations:{vertexPosition:t.getAttribLocation(l,"a_position"),texPosition:t.getAttribLocation(l,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(l,"u_image"),uColorFactor:t.getUniformLocation(l,"uColorFactor"),uMatrix:t.getUniformLocation(l,"u_matrix"),uTextureMatrix:t.getUniformLocation(l,"u_textureMatrix")}}),Un(this,Xn,e(t)),Un(this,zn,i(t)),Un(this,Yn,p)}const r=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const n=t.RGBA,r=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,n,r,s,i)},v=(t,e,s,a)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),r(t,s.positions,e.attribLocations.vertexPosition),r(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,a),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[Wn.GREY,Wn.GREY32].includes(p)?1:0);let m,_,v=Gn.translate(Gn.identity(),-1,-1);v=Gn.scale(v,2,2),v=Gn.scale(v,1/t.canvas.width,1/t.canvas.height),m=Gn.translate(v,u,d),m=Gn.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=Gn.translate(Gn.identity(),o/i,l/n),_=Gn.scale(_,h/i,c/n),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,Vn(this,zn,"f"),e),v(t,Vn(this,Hn,"f"),Vn(this,Xn,"f"),Vn(this,zn,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){jr._onLog&&jr._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return jr._onLog&&jr._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-a)),{context:t,pixelFormat:p===Wn.GREY?Wn.GREY32:p,bUseWebGL:!0}}catch(a){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return jr._onLog&&jr._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,n,r,Object.assign({},s,{bUseWebGL:!1}));throw a.name="WebGLError",a}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let n,r=0,s=0,a=t.canvas.width,o=t.canvas.height;if(e&&(e.x&&(r=e.x),e.y&&(s=e.y),e.width&&(a=e.width),e.height&&(o=e.height)),(null==i?void 0:i.length)<4*a*o)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(r,s,a,o,e.RGBA,e.UNSIGNED_BYTE,i),n=new Uint8Array(i.buffer,0,4*a*o)):(n=new Uint8Array(4*a*o),e.readPixels(r,s,a,o,e.RGBA,e.UNSIGNED_BYTE,n))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(r,s,a,o),n=new Uint8Array(e.data.buffer),null==i||i.set(n)}return n}transformPixelFormat(t,e,i,n){let r,s;if(jr._onLog&&(r=Date.now(),jr._onLog("transformPixelFormat(), START: "+r)),e===i)return jr._onLog&&jr._onLog("transformPixelFormat() end. Costs: "+(Date.now()-r)),n?new Uint8Array(t):t;const a=[Wn.RGBA,Wn.RBGA,Wn.GRBA,Wn.GBRA,Wn.BRGA,Wn.BGRA];if(a.includes(e))if(i===Wn.GREY){s=new Uint8Array(t.length/4);for(let e=0;el||e.sy+e.sHeight>h)throw new Error("Invalid position.");null===(n=jr._onLog)||void 0===n||n.call(jr,"getImageData(), START: "+(c=Date.now()));const d=Math.round(e.sx),f=Math.round(e.sy),g=Math.round(e.sWidth),m=Math.round(e.sHeight),p=Math.round(e.dWidth),_=Math.round(e.dHeight);let v,y=(null==i?void 0:i.pixelFormat)||Wn.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(Wn.GREY===y&&w.length{this.disposed||n.includes(r)&&r.apply(i.target,s)}),0);else try{a=r.apply(i.target,s)}catch(t){}if(!0===a)break}}}dispose(){Mn(this,Kn,!0)}}Jn=new WeakMap,Kn=new WeakMap;const Ur=(t,e,i,n)=>{if(!i)return t;let r=e+Math.round((t-e)/i)*i;return n&&(r=Math.min(r,n)),r};class Gr{static get version(){return"2.0.18"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],n=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],r=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!r.length)return null;const s=r.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const a=r.find((t=>{const e=t.label.toLowerCase();return n.some((t=>e.includes(t)))}));return a?a.deviceId:r[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(jn.OS))return Gr.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(jn.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(n,r)=>{let s;const a=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let o=!1;const l=()=>{o=!0,s&&clearTimeout(s),a(),n(t)},h=t=>{s&&clearTimeout(s),a(),r(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",h(t)},d=()=>{l()},f=()=>{h(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!o){i&&(s=setTimeout((()=>{a(),r(new Error("Failed to play video. Timeout."))}),i)),await m;try{await t.play(),l()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!o)try{await t.play(),l()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),h(t)}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let n;try{n=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==n||n.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!Ln(this,ur,"f"))return"closed";if("pending"===Ln(this,ur,"f"))return"opening";if("fulfilled"===Ln(this,ur,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Gr.isStorageAvailable("localStorage")?Mn(this,or,!0):(Mn(this,or,!1),console.warn("Local storage is unavailable")):Mn(this,or,!1)}get ifSaveLastUsedCamera(){return Ln(this,or,"f")}get isVideoPlaying(){return!(!Ln(this,tr,"f")||Ln(this,tr,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,n;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=Ln(this,_r,"f"))||void 0===e||e.removeEventListener("click",Ln(this,pr,"f")),null===(i=Ln(this,_r,"f"))||void 0===i||i.removeEventListener("touchend",Ln(this,pr,"f")),null===(n=Ln(this,_r,"f"))||void 0===n||n.removeEventListener("touchmove",Ln(this,mr,"f")),Mn(this,_r,t),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(jn.OS)?(t.addEventListener("touchend",Ln(this,pr,"f")),t.addEventListener("touchmove",Ln(this,mr,"f"))):t.addEventListener("click",Ln(this,pr,"f")))}get tapFocusEventBoundEl(){return Ln(this,_r,"f")}get disposed(){return Ln(this,xr,"f")}constructor(t){var e,i;Qn.add(this),tr.set(this,null),er.set(this,void 0),ir.set(this,(()=>{"opened"===this.state&&Ln(this,Er,"f").fire("resumed",null,{target:this,async:!1})})),nr.set(this,(()=>{Ln(this,Er,"f").fire("paused",null,{target:this,async:!1})})),rr.set(this,void 0),sr.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],ar.set(this,void 0),or.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,lr.set(this,void 0),hr.set(this,!0),cr.set(this,void 0),ur.set(this,void 0),dr.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},fr.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const r=window.getComputedStyle(Ln(this,tr,"f")).objectFit,s=this.getResolution(),a=Ln(this,tr,"f").getBoundingClientRect(),o=a.left,l=a.top,{width:h,height:c}=Ln(this,tr,"f").getBoundingClientRect();if(h<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=h/c,d=s.width/s.height;let f=1;if("contain"===r)d>u?(f=h/s.width,i=(t-o)/f,n=(e-l-(c-h/d)/2)/f):(f=c/s.height,n=(e-l)/f,i=(t-o-(h-c*d)/2)/f);else{if("cover"!==r)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,n=(e-l)/f,i=(t-o+(c*d-h)/2)/f):(f=h/s.width,i=(t-o)/f,n=(e-l+(h/d-c)/2)/f)}return{x:i,y:n}},gr.set(this,!1),mr.set(this,(()=>{Mn(this,gr,!0)})),pr.set(this,(async t=>{var e;if(Ln(this,gr,"f"))return void Mn(this,gr,!1);if(!Ln(this,fr,"f"))return;if(!this.isVideoPlaying)return;if(!Ln(this,er,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,n=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,n=t.changedTouches[0].clientY}const r=this.getResolution(),s=2*Math.round(Math.min(r.width,r.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let a;try{a=this.calculateCoordInVideo(i,n)}catch(t){}if(a.x<0||a.x>r.width||a.y<0||a.y>r.height)return;const o={x:a.x+"px",y:a.y+"px"},l=s+"px",h=l;let c;Gr._onLog&&(c=Date.now());try{await Ln(this,Qn,"m",kr).call(this,o,l,h,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Gr._onLog)throw Gr._onLog(t),t}Gr._onLog&&Gr._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;Gr._onLog&&Gr._onLog("Back to continuous focus."),null===(t=Ln(this,er,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),Ln(this,Er,"f").fire("tapfocus",null,{target:this,async:!1})})),_r.set(this,null),vr.set(this,1),yr.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!Ln(this,tr,"f"))return;const t=Ln(this,vr,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)Ln(this,tr,"f").style.transform="";else{const e=window.getComputedStyle(Ln(this,tr,"f")).objectFit,i=Ln(this,tr,"f").videoWidth,n=Ln(this,tr,"f").videoHeight,{width:r,height:s}=Ln(this,tr,"f").getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const a=r/s,o=i/n;let l=1;"contain"===e?l=aa?s/(i/t):r/(n/t));const h=l*(1-1/t)*(i/2-Ln(this,yr,"f").x),c=l*(1-1/t)*(n/2-Ln(this,yr,"f").y);Ln(this,tr,"f").style.transform=`translate(${h}px, ${c}px) scale(${t})`}},wr.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===Wn.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(Gr._onLog&&Gr._onLog("document visible. video paused: "+(null===(t=Ln(this,tr,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Gr._onLog&&Gr._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Gr._onLog&&Gr._onLog("document visible. 1st resume video failed, try open instead.")}e||await Ln(this,Qn,"m",Ar).call(this)}if(await new Promise((t=>setTimeout(t,300))),!this.isVideoPlaying){Gr._onLog&&Gr._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Gr._onLog&&Gr._onLog("document visible. 2rd resume video failed, try open instead.")}e||await Ln(this,Qn,"m",Ar).call(this)}}}else"hidden"===document.visibilityState&&(Gr._onLog&&Gr._onLog("document hidden. video paused: "+(null===(e=Ln(this,tr,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())})),xr.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{Gr.onWarning&&Gr.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),Mn(this,Er,new Vr),this.imageDataGetter=new jr,document.addEventListener("visibilitychange",Ln(this,br,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",Ln(this,ir,"f")),t.addEventListener("pause",Ln(this,nr,"f")),Mn(this,tr,t)}getVideoEl(){return Ln(this,tr,"f")}releaseVideoEl(){var t,e;null===(t=Ln(this,tr,"f"))||void 0===t||t.removeEventListener("play",Ln(this,ir,"f")),null===(e=Ln(this,tr,"f"))||void 0===e||e.removeEventListener("pause",Ln(this,nr,"f")),Mn(this,tr,null)}isVideoLoaded(){return!!Ln(this,tr,"f")&&4==Ln(this,tr,"f").readyState}async open(){if(Ln(this,cr,"f")&&!Ln(this,hr,"f")){if("pending"===Ln(this,ur,"f"))return Ln(this,cr,"f");if("fulfilled"===Ln(this,ur,"f"))return}Ln(this,Er,"f").fire("before:open",null,{target:this}),await Ln(this,Qn,"m",Ar).call(this),Ln(this,Er,"f").fire("played",null,{target:this,async:!1}),Ln(this,Er,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;Ln(this,Er,"f").fire("before:close",null,{target:this});const t=Ln(this,cr,"f");if(Ln(this,Qn,"m",Mr).call(this),t&&"pending"===Ln(this,ur,"f")){try{await t}catch(t){}if(!1===Ln(this,hr,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}Mn(this,cr,null),Mn(this,ur,null),Ln(this,Er,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");Ln(this,tr,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await Ln(this,tr,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof Ln(this,rr,"f").video&&(Ln(this,rr,"f").video={}),delete Ln(this,rr,"f").video.facingMode,Ln(this,rr,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&Ln(this,hr,"f"))){Ln(this,Er,"f").fire("before:camera:change",[],{target:this,async:!1}),await Ln(this,Qn,"m",Lr).call(this);try{this.resetSoftwareScale()}catch(t){}return Ln(this,sr,"f")}}async switchToFrontCamera(t){if("object"!=typeof Ln(this,rr,"f").video&&(Ln(this,rr,"f").video={}),(null==t?void 0:t.resolution)&&(Ln(this,rr,"f").video.width={ideal:t.resolution.width},Ln(this,rr,"f").video.height={ideal:t.resolution.height}),delete Ln(this,rr,"f").video.deviceId,Ln(this,rr,"f").video.facingMode={exact:"user"},Mn(this,ar,null),!("closed"===this.state||this.videoSrc||"opening"===this.state&&Ln(this,hr,"f"))){Ln(this,Er,"f").fire("before:camera:change",[],{target:this,async:!1}),Ln(this,Qn,"m",Lr).call(this);try{this.resetSoftwareScale()}catch(t){}return Ln(this,sr,"f")}}getCamera(){var t;if(Ln(this,sr,"f"))return Ln(this,sr,"f");{let e=(null===(t=Ln(this,rr,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else n=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const r=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof Ln(this,rr,"f").video&&(Ln(this,rr,"f").video={}),i?(Ln(this,rr,"f").video.width={exact:t},Ln(this,rr,"f").video.height={exact:e}):(Ln(this,rr,"f").video.width={ideal:t},Ln(this,rr,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&Ln(this,hr,"f"))return null;Ln(this,Er,"f").fire("before:resolution:change",[],{target:this,async:!1}),await Ln(this,Qn,"m",Lr).call(this);try{this.resetSoftwareScale()}catch(t){}const n=this.getResolution();return{width:n.width,height:n.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&Ln(this,tr,"f"))return{width:Ln(this,tr,"f").videoWidth,height:Ln(this,tr,"f").videoHeight};if(Ln(this,er,"f")){const t=Ln(this,er,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:Ln(this,tr,"f").videoWidth,height:Ln(this,tr,"f").videoHeight};{const t={width:0,height:0};let e=Ln(this,rr,"f").video.width||0,i=Ln(this,rr,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,n,r,s,a,o,l,h,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=Ln(this,Sr,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){d=null===(u=Ln(this,sr,"f"))||void 0===u?void 0:u.deviceId;let e=Ln(this,Sr,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],Ln(this,Sr,"f").set(d,e),Mn(this,dr,!0);try{for(let t of this.detectedResolutions){await Ln(this,er,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),Ln(this,Qn,"m",Rr).call(this);const i=Ln(this,er,"f").getSettings(),n={width:i.width,height:i.height};f(d,n)||e.push({width:n.width,height:n.height})}}catch(t){throw Ln(this,Qn,"m",Mr).call(this),Mn(this,dr,!1),t}try{await Ln(this,Qn,"m",Ar).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{Mn(this,dr,!1)}return e}{const e=async(t,e,i)=>{const n={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let r=null;try{r=await navigator.mediaDevices.getUserMedia(n)}catch(t){return null}if(!r)return null;const s=r.getVideoTracks();let a=null;try{const t=s[0].getSettings();a={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=r,a={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach((t=>{t.stop()})),a};let i=(null===(s=null===(r=null===(n=Ln(this,rr,"f"))||void 0===n?void 0:n.video)||void 0===r?void 0:r.deviceId)||void 0===s?void 0:s.exact)||(null===(l=null===(o=null===(a=Ln(this,rr,"f"))||void 0===a?void 0:a.video)||void 0===o?void 0:o.deviceId)||void 0===l?void 0:l.ideal)||(null===(c=null===(h=Ln(this,rr,"f"))||void 0===h?void 0:h.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=Ln(this,Sr,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],Ln(this,Sr,"f").set(i,u);for(let t of this.detectedResolutions){const n=await e(i,t.width,t.height);n&&!f(i,n)&&u.push({width:n.width,height:n.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");Mn(this,rr,JSON.parse(JSON.stringify(t))),Mn(this,ar,null),e&&Ln(this,Qn,"m",Lr).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(Ln(this,rr,"f")))}resetMediaStreamConstraints(){Mn(this,rr,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null)}getCameraCapabilities(){if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Ln(this,er,"f").getCapabilities?Ln(this,er,"f").getCapabilities():{}}getCameraSettings(){if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Ln(this,er,"f").getSettings()}async turnOnTorch(){if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Ln(this,er,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Ln(this,er,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ur(t,n.min,n.step,n.max)),await Ln(this,er,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ur(t,n.min,n.step,n.max)),await Ln(this,er,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!n)throw Error("Not supported.");e&&(tn.max&&(t=n.max));const r=this.getResolution();return await Ln(this,er,"f").applyConstraints({width:{ideal:Math.max(r.width,r.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),n=null==i?void 0:i.focusMode,r=null==i?void 0:i.focusDistance;if(!n)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!n.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!r)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(ir.max&&(i=r.max),i=Ur(i,r.min,r.step,r.max)),this._focusParameters.focusArea=null,await Ln(this,er,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,n=t.area.height;if(!i||!n){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),n||(n=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:n},await Ln(this,Qn,"m",kr).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await Ln(this,er,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){Mn(this,fr,!0)}disableTapToFocus(){Mn(this,fr,!1)}isTapToFocusEnabled(){return Ln(this,fr,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?Ln(this,Qn,"m",Nr).call(this,t.centerPoint):this.resetScaleCenter();try{if(Ln(this,Qn,"m",Br).call(this,Ln(this,yr,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*Ln(this,vr,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ur(t,n.min,n.step,n.max)),await Ln(this,er,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&Ln(this,Qn,"m",Nr).call(this,e),Mn(this,vr,t),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return Ln(this,vr,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();Mn(this,yr,{x:t.width/2,y:t.height/2})}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(Ln(this,dr,"f"))return null;const e=Date.now();Gr._onLog&&Gr._onLog("getFrameData() START: "+e);const i=Ln(this,tr,"f").videoWidth,n=Ln(this,tr,"f").videoHeight;let r={sx:0,sy:0,sWidth:i,sHeight:n,dWidth:i,dHeight:n};(null==t?void 0:t.position)&&(r=JSON.parse(JSON.stringify(t.position)));let s=Wn.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let a=Ln(this,vr,"f");(null==t?void 0:t.scale)&&(a=t.scale);let o=Ln(this,yr,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,r=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))r=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.scaleCenter.y)/100*n}if(isNaN(e)||isNaN(r))throw new Error("Invalid scale center.");o.x=Math.round(e),o.y=Math.round(r)}let l=null;if((null==t?void 0:t.bufferContainer)&&(l=t.bufferContainer),0==i||0==n)return null;1!==a&&(r.sWidth=Math.round(r.sWidth/a),r.sHeight=Math.round(r.sHeight/a),r.sx=Math.round((1-1/a)*o.x+r.sx/a),r.sy=Math.round((1-1/a)*o.y+r.sy/a));const h=this.imageDataGetter.getImageData(Ln(this,tr,"f"),r,{pixelFormat:s,bufferContainer:l});if(!h)return null;const c=Date.now();return Gr._onLog&&Gr._onLog("getFrameData() END: "+c),{data:h.data,width:h.width,height:h.height,pixelFormat:h.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:Ln(this,wr,"f")}}on(t,e){if(!Ln(this,Cr,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);Ln(this,Er,"f").on(t,e)}off(t,e){Ln(this,Er,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),Ln(this,Er,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",Ln(this,br,"f")),Mn(this,xr,!0)}}var Wr,Yr,zr,Hr,Xr,Zr,qr,Jr,Kr,$r,Qr,ts,es,is,ns,rs,ss,as,os,ls,hs,cs,us,ds,fs,gs,ms,ps,_s,vs,ys,ws,Es,Cs,Ss;tr=new WeakMap,er=new WeakMap,ir=new WeakMap,nr=new WeakMap,rr=new WeakMap,sr=new WeakMap,ar=new WeakMap,or=new WeakMap,lr=new WeakMap,hr=new WeakMap,cr=new WeakMap,ur=new WeakMap,dr=new WeakMap,fr=new WeakMap,gr=new WeakMap,mr=new WeakMap,pr=new WeakMap,_r=new WeakMap,vr=new WeakMap,yr=new WeakMap,wr=new WeakMap,Er=new WeakMap,Cr=new WeakMap,Sr=new WeakMap,Tr=new WeakMap,br=new WeakMap,xr=new WeakMap,Qn=new WeakSet,Ir=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(Ln(this,ar,"f"))delete t.video.facingMode,t.video.deviceId={exact:Ln(this,ar,"f")};else if(this.ifSaveLastUsedCamera&&Gr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(jn.OS)?(await this._getCameras(!1),Ln(this,Qn,"m",Rr).call(this),e=Gr.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(jn.OS)||(await this._getCameras(!1),Ln(this,Qn,"m",Rr).call(this),e=Gr.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const n=await e(i);n&&(delete t.video.facingMode,t.video.deviceId={exact:n})}return t},Rr=function(){if(Ln(this,hr,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},Or=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;try{Gr._onLog&&Gr._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const r=async t=>{for(let r of e){r&&(await new Promise((t=>setTimeout(t,r))),Ln(this,Qn,"m",Rr).call(this));try{Gr._onLog&&Gr._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),Ln(this,Qn,"m",Rr).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Gr._onLog&&Gr._onLog(t.message||t)}}};if(await r(t),n||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await r(t)),!n&&t.video.facingMode&&(delete t.video.facingMode,await r(t)),n||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await r(t))),!n)throw i;return n}catch(t){throw null==n||n.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},Dr=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),Mn(this,er,null)},Ar=async function(){Mn(this,hr,!1);const t=Mn(this,lr,Symbol());if(Ln(this,cr,"f")&&"pending"===Ln(this,ur,"f")){try{await Ln(this,cr,"f")}catch(t){}Ln(this,Qn,"m",Rr).call(this)}if(t!==Ln(this,lr,"f"))return;const e=Mn(this,cr,(async()=>{Mn(this,ur,"pending");try{if(this.videoSrc){if(!Ln(this,tr,"f"))throw new Error("'videoEl' should be set.");await Gr.playVideo(Ln(this,tr,"f"),this.videoSrc,this.cameraOpenTimeout),Ln(this,Qn,"m",Rr).call(this)}else{let t=await Ln(this,Qn,"m",Ir).call(this);Ln(this,Qn,"m",Dr).call(this);let e=await Ln(this,Qn,"m",Or).call(this,t);await this._getCameras(!1),Ln(this,Qn,"m",Rr).call(this);const i=()=>{const t=e.getVideoTracks();let i,n;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,n=e;break}}return n},n=Ln(this,rr,"f");if("object"==typeof n.video){let r=n.video.facingMode;if(r instanceof Array&&r.length&&(r=r[0]),"object"==typeof r&&(r=r.exact||r.ideal),!(Ln(this,ar,"f")||this.ifSaveLastUsedCamera&&Gr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),s=Gr.findBestCamera(this._arrCameras,r,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==n?void 0:n.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await Ln(this,Qn,"m",Or).call(this,t),Ln(this,Qn,"m",Rr).call(this))}}const r=i();(null==r?void 0:r.deviceId)&&(Mn(this,ar,r&&r.deviceId),this.ifSaveLastUsedCamera&&Gr.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",Ln(this,ar,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),Ln(this,tr,"f")&&(await Gr.playVideo(Ln(this,tr,"f"),e,this.cameraOpenTimeout),Ln(this,Qn,"m",Rr).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&Mn(this,er,s[0]),Mn(this,sr,r)}}catch(t){throw Ln(this,Qn,"m",Mr).call(this),Mn(this,ur,null),t}Mn(this,ur,"fulfilled")})());return e},Lr=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=Ln(this,sr,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await Ln(this,Qn,"m",Ar).call(this);const n=this.getResolution();e&&e!==Ln(this,sr,"f").deviceId&&Ln(this,Er,"f").fire("camera:changed",[Ln(this,sr,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||Ln(this,Er,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),Ln(this,Er,"f").fire("played",null,{target:this,async:!1})},Mr=function(){Ln(this,Qn,"m",Dr).call(this),Mn(this,sr,null),Ln(this,tr,"f")&&(Ln(this,tr,"f").srcObject=null,this.videoSrc&&(Ln(this,tr,"f").pause(),Ln(this,tr,"f").currentTime=0)),Mn(this,hr,!0);try{this.resetSoftwareScale()}catch(t){}},Fr=async function t(e,i){const n=t=>{if(!Ln(this,er,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){Ln(this,er,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;i=Ur(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await Ln(this,er,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),n(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,r)})),n(e);let s=e.focusL-e.focusW/2,a=e.focusT-e.focusH/2,o=e.focusW,l=e.focusH;const h=this.getResolution();s=Math.round(s),a=Math.round(a),o=Math.round(o),l=Math.round(l),o>h.width&&(o=h.width),l>h.height&&(l=h.height),s<0?s=0:s+o>h.width&&(s=h.width-o),a<0?a=0:a+l>h.height&&(a=h.height-l);const c=4*h.width*h.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*o*l;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(Ln(this,tr,"f"),{sx:s,sy:a,sWidth:o,sHeight:l,dWidth:o,dHeight:l},{pixelFormat:Wn.RGBA,bufferContainer:d}))return Ln(this,Qn,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;to&&ou)return await Ln(this,Qn,"m",t).call(this,e,a,o,r,s,c,u)}else{let l=await Ln(this,Qn,"m",Fr).call(this,e,c);if(o>l)return await Ln(this,Qn,"m",t).call(this,e,a,o,r,s,c,l);if(o==l)return await Ln(this,Qn,"m",t).call(this,e,a,o,c,l);let u=await Ln(this,Qn,"m",Fr).call(this,e,h);if(u>o&&oa.width||l<0||l>a.height)throw new Error("Invalid 'centerPoint'.");let h=0;if(e.endsWith("px"))h=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");h=parseFloat(e)/100*a.width}if(isNaN(h)||h<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*a.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==Ln(this,vr,"f")){const t=Ln(this,vr,"f"),e=Ln(this,yr,"f");h/=t,c/=t,o=(1-1/t)*e.x+o/t,l=(1-1/t)*e.y+l/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const u={focusL:o,focusT:l,focusW:h,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let n=Ur(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=Ur(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Ur(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),a=await Ln(this,Qn,"m",Fr).call(this,t,s),o=await Ln(this,Qn,"m",Fr).call(this,t,r),l=await Ln(this,Qn,"m",Fr).call(this,t,n);if(o>l&&la&&o>a){let e=await Ln(this,Qn,"m",Fr).call(this,t,i);const r=await Ln(this,Qn,"m",Pr).call(this,t,n,l,i,e,s,a);return this._focusParameters.isDoingFocus=0,r}if(o==l&&ll){const e=await Ln(this,Qn,"m",Pr).call(this,t,n,l,s,a);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,n,r)},Nr=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,n=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))n=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(n))throw new Error("Invalid scale center.");Mn(this,yr,{x:i,y:n})},Br=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},Gr.browserInfo=jn,Gr.onWarning=null===($n=null===window||void 0===window?void 0:window.console)||void 0===$n?void 0:$n.warn;class Ts{constructor(t){Wr.add(this),Yr.set(this,void 0),zr.set(this,0),Hr.set(this,void 0),Xr.set(this,0),Zr.set(this,!1),Xe(this,Yr,t)}startCharging(){He(this,Zr,"f")||(Ts._onLog&&Ts._onLog("start charging."),He(this,Wr,"m",Jr).call(this),Xe(this,Zr,!0))}stopCharging(){He(this,Hr,"f")&&clearTimeout(He(this,Hr,"f")),He(this,Zr,"f")&&(Ts._onLog&&Ts._onLog("stop charging."),Xe(this,zr,Date.now()-He(this,Xr,"f")),Xe(this,Zr,!1))}}Yr=new WeakMap,zr=new WeakMap,Hr=new WeakMap,Xr=new WeakMap,Zr=new WeakMap,Wr=new WeakSet,qr=function(){gt.cfd(1),Ts._onLog&&Ts._onLog("charge 1.")},Jr=function t(){0==He(this,zr,"f")&&He(this,Wr,"m",qr).call(this),Xe(this,Xr,Date.now()),He(this,Hr,"f")&&clearTimeout(He(this,Hr,"f")),Xe(this,Hr,setTimeout((()=>{Xe(this,zr,0),He(this,Wr,"m",t).call(this)}),He(this,Yr,"f")-He(this,zr,"f")))};class bs{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-He(this,Kr,"f",ts)<100)){if(Xe(this,Kr,e,0,ts),He(this,Kr,"f",$r).size&&(t=He(this,Kr,"f",$r).values().next().value,this.beepSoundSource==t.src?(He(this,Kr,"f",$r).delete(t),t.play()):t=null),!t)if(He(this,Kr,"f",Qr).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{He(this,Kr,"f",Qr).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,He(this,Kr,"f",Qr).delete(t),He(this,Kr,"f",$r).add(t)}))}else He(this,Kr,"f",es)||(Xe(this,Kr,!0,0,es),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&He(this,Kr,"f",Qr).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(bs.vibrateDuration)}}}Kr=bs,$r={value:new Set},Qr={value:new Set},ts={value:0},es={value:!1},bs.allowBeep=!0,bs.beepSoundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",bs.allowVibrate=!0,bs.vibrateDuration=300;const xs=new Map([[Wn.GREY,l.IPF_GRAYSCALED],[Wn.RGBA,l.IPF_ABGR_8888]]),Is="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class Rs extends X{static set _onLog(t){Xe(Rs,ns,t,0,rs),Gr._onLog=t,Ts._onLog=t}static get _onLog(){return He(Rs,ns,"f",rs)}static async detectEnvironment(){return await(async()=>({wasm:Ze,worker:qe,getUserMedia:Je,camera:await Ke(),browser:ze.browser,version:ze.version,OS:ze.OS}))()}static async testCameraAccess(){const t=await Gr.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var e,i;if(t&&!(t instanceof An))throw new TypeError("Invalid view.");if(null===(e=ct.license)||void 0===e?void 0:e.LicenseManager){if(!(null===(i=ct.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await gt.loadWasm(["license"]),await ct.license.dynamsoft()}const n=new Rs(t);return Rs.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{Rs.onWarning&&Rs.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{Rs.onWarning&&Rs.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),n}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");Xe(this,os,t)}get singleFrameMode(){return He(this,os,"f")}get _isFetchingStarted(){return He(this,fs,"f")}get disposed(){return He(this,vs,"f")}constructor(t){if(super(),is.add(this),ss.set(this,"closed"),as.set(this,void 0),this.isTorchOn=void 0,os.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},ls.set(this,((t,e,i,n)=>{const r=Date.now(),s={sx:n.x,sy:n.y,sWidth:n.width,sHeight:n.height,dWidth:n.width,dHeight:n.height},a=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&a>this.canvasSizeLimit){const t=this.canvasSizeLimit/a;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const o=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===l.IPF_GRAYSCALED?Wn.GREY:Wn.RGBA});let h=null;if(o){const t=Date.now();let a;a=o.pixelFormat===Wn.GREY?o.width:4*o.width;let l=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(l=!1),h={bytes:o.data,width:o.width,height:o.height,stride:a,format:xs.get(o.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:wt.ITT_FILE_IMAGE,isCropped:l,cropRegion:{left:n.x,top:n.y,right:n.x+n.width,bottom:n.y+n.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:o.width,currentHeight:o.height,timeSpent:t-r,timeStamp:t},toCanvas:He(this,hs,"f"),isDCEFrame:!0}}return h})),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():ki.convert(He(this,us,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=He(this,ls,"f").call(this,t,t.width,t.height,e);He(this,as,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},hs.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===l.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(ze.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",(()=>{He(this,_s,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{He(this,_s,"f").stopCharging();const t=this.cameraView;t&&t.disposed})),this._on("resumed",(()=>{const t=this.cameraView;t&&t.disposed})),this._on("tapfocus",(()=>{He(this,ms,"f").tapToFocus&&He(this,_s,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,n,r,s;if(He(this,is,"m",ys).call(this)||!this.isOpen()||this.isPaused())return;const a=t.intermediateResultUnits;Rs._onLog&&(Rs._onLog("intermediateResultUnits:"),Rs._onLog(a));let o=!1,l=!1;for(let t of a){if(t.unitType===Tt.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){o=!0;break}t.unitType===Tt.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(l=!0)}if(Rs._onLog&&(Rs._onLog("hasLocalizedBarcodes:"),Rs._onLog(l)),He(this,ms,"f").autoZoom||He(this,ms,"f").enhancedFocus)if(o)He(this,ps,"f").autoZoomInFrameArray.length=0,He(this,ps,"f").autoZoomOutFrameCount=0,He(this,ps,"f").frameArrayInIdealZoom.length=0,He(this,ps,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),He(this,ms,"f").autoZoom&&He(this,_s,"f").startCharging()},o=async t=>{await this.setFocus(t),He(this,ms,"f").enhancedFocus&&He(this,_s,"f").startCharging()};if(l){const l=a[0].originalImageTag,h=(null===(i=l.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(n=l.cropRegion)||void 0===n?void 0:n.top)||0,u=(null===(r=l.cropRegion)||void 0===r?void 0:r.right)?l.cropRegion.right-h:l.originalWidth,d=(null===(s=l.cropRegion)||void 0===s?void 0:s.bottom)?l.cropRegion.bottom-c:l.originalHeight,f=l.currentWidth,g=l.currentHeight;let m;{let t,e,i,n,r;{const t=this.video.videoWidth*(1-He(this,ps,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+He(this,ps,"f").autoZoomDetectionArea)/2,i=e,n=t,s=this.video.videoHeight*(1-He(this,ps,"f").autoZoomDetectionArea)/2,a=s,o=this.video.videoHeight*(1+He(this,ps,"f").autoZoomDetectionArea)/2;r=[{x:t,y:s},{x:e,y:a},{x:i,y:o},{x:n,y:o}]}Rs._onLog&&(Rs._onLog("detectionArea:"),Rs._onLog(r));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let n=!1;const r=t.length;if(r<=2)return!1;for(let s=0;s0!=Ui(o.y-i)>0&&Ui(e-(i-a.y)*(a.x-o.x)/(a.y-o.y)-a.x)<0&&(n=!n)}return n}(e,t.x,t.y)},n=(t,e)=>!!(Gi([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||Gi([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||Gi([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||Gi([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(n([e[0].x,e[0].y,e[1].x,e[1].y],t)||n([e[1].x,e[1].y,e[2].x,e[2].y],t)||n([e[2].x,e[2].y,e[3].x,e[3].y],t)||n([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of a)if(e.unitType===Tt.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach((t=>{An._transformCoordinates(t,h,c,u,d,f,g)})),t(r,e)&&s.push(i)}if(Rs._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=bn.createDrawingStyle({strokeStyle:"red"}));for(let i of a)if(i.unitType===Tt.IRUT_LOCALIZED_BARCODES)for(let n of i.localizedBarcodes){if(!n)continue;const i=n.location.points,r=new xi({points:i},e);t.addDrawingItems([r])}}}if(Rs._onLog&&(Rs._onLog("intersectedResults:"),Rs._onLog(s)),!s.length)return;let o;if(s.length){let t=s.filter((t=>t.possibleFormats==Is.BF_QR_CODE||t.possibleFormats==Is.BF_DATAMATRIX));if(t.length||(t=s.filter((t=>t.possibleFormats==Is.BF_ONED)),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,n=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(n-g/2)*(n-g/2)};o=t[0];let i=e(o);if(1!=t.length)for(let n=1;n1.1*o.confidence||t[n].confidence>.9*o.confidence&&ri&&s>i&&a>i&&l>i&&m.result.moduleSize{})),He(this,ps,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=He(this,ps,"f").autoZoomInFrameLimit[1]){He(this,ps,"f").autoZoomInFrameArray.length=0;const i=[(.5-n)/(.5-r),(.5-n)/(.5-s),(.5-n)/(.5-a),(.5-n)/(.5-l)].filter((t=>t>0)),o=Math.min(...i,He(this,ps,"f").autoZoomInIdealModuleSize/m.result.moduleSize),h=this.getZoomSettings().factor;let c=Math.max(Math.pow(h*o,1/He(this,ps,"f").autoZoomInMaxTimes),He(this,ps,"f").autoZoomInMinStep);c=Math.min(c,o);let u=h*c;u=Math.max(He(this,ps,"f").minValue,u),u=Math.min(He(this,ps,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(He(this,ps,"f").autoZoomInFrameArray.length=0,He(this,ps,"f").frameArrayInIdealZoom.push(!0),He(this,ps,"f").frameArrayInIdealZoom.splice(0,He(this,ps,"f").frameArrayInIdealZoom.length-He(this,ps,"f").frameLimitInIdealZoom[0]),He(this,ps,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=He(this,ps,"f").frameLimitInIdealZoom[1]&&(He(this,ps,"f").frameArrayInIdealZoom.length=0,He(this,ms,"f").enhancedFocus)){const e=m.points;try{await o({mode:"manual",area:{centerPoint:{x:(e[0].x+e[2].x)/2+"px",y:(e[0].y+e[2].y)/2+"px"},width:e[2].x-e[0].x+"px",height:e[2].y-e[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!He(this,ms,"f").autoZoom&&He(this,ms,"f").enhancedFocus&&(He(this,ps,"f").autoFocusFrameArray.push(!0),He(this,ps,"f").autoFocusFrameArray.splice(0,He(this,ps,"f").autoFocusFrameArray.length-He(this,ps,"f").autoFocusFrameLimit[0]),He(this,ps,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=He(this,ps,"f").autoFocusFrameLimit[1])){He(this,ps,"f").autoFocusFrameArray.length=0;try{const t=m.points;await o({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(He(this,ms,"f").autoZoom){if(He(this,ps,"f").autoZoomInFrameArray.push(!1),He(this,ps,"f").autoZoomInFrameArray.splice(0,He(this,ps,"f").autoZoomInFrameArray.length-He(this,ps,"f").autoZoomInFrameLimit[0]),He(this,ps,"f").autoZoomOutFrameCount++,He(this,ps,"f").frameArrayInIdealZoom.push(!1),He(this,ps,"f").frameArrayInIdealZoom.splice(0,He(this,ps,"f").frameArrayInIdealZoom.length-He(this,ps,"f").frameLimitInIdealZoom[0]),He(this,ps,"f").autoZoomOutFrameCount>=He(this,ps,"f").autoZoomOutFrameLimit){He(this,ps,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let n=i-Math.max((i-1)*He(this,ps,"f").autoZoomOutStepRate,He(this,ps,"f").autoZoomOutMinStep);n=Math.max(He(this,ps,"f").minValue,n),n=Math.min(He(this,ps,"f").maxValue,n);try{await e({factor:n})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}He(this,ms,"f").enhancedFocus&&o({mode:"continuous"}).catch((()=>{}))}!He(this,ms,"f").autoZoom&&He(this,ms,"f").enhancedFocus&&(He(this,ps,"f").autoFocusFrameArray.length=0,o({mode:"continuous"}).catch((()=>{})))}}},Xe(this,_s,new Ts(1e4))}setCameraView(t){if(!(t instanceof An))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),He(this,is,"m",ys).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;He(this,is,"m",ys).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return He(this,is,"m",ys).call(this)?He(this,ss,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=this.cameraView;if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,He(this,is,"m",ys).call(this)?t._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(He(this,is,"m",ys).call(this));else{try{await this.cameraManager.open()}catch(e){throw t&&t._stopLoading(),"NotFoundError"===e.name?new Error(`No camera devices were detected. Please ensure a camera is connected and recognized by your system. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):"NotAllowedError"===e.name?new Error(`Camera access is blocked. Please check your browser settings or grant permission to use the camera. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):e}let i,n=t.getUIElement();if(n=n.shadowRoot||n,i=n.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=n.elTorchAuto=n.querySelector(".dce-mn-torch-auto"),e=n.elTorchOn=n.querySelector(".dce-mn-torch-on"),r=n.elTorchOff=n.querySelector(".dce-mn-torch-off");t&&(e.style.display=null==this.isTorchOn?"":"none"),e&&(e.style.display=1==this.isTorchOn?"":"none"),r&&(r.style.display=0==this.isTorchOn?"":"none");let s=n.elBeepOn=n.querySelector(".dce-mn-beep-on"),a=n.elBeepOff=n.querySelector(".dce-mn-beep-off");s&&(s.style.display=bs.allowBeep?"":"none"),a&&(a.style.display=bs.allowBeep?"none":"");let o=n.elVibrateOn=n.querySelector(".dce-mn-vibrate-on"),l=n.elVibrateOff=n.querySelector(".dce-mn-vibrate-off");o&&(o.style.display=bs.allowVibrate?"":"none"),l&&(l.style.display=bs.allowVibrate?"none":""),n.elResolutionBox=n.querySelector(".dce-mn-resolution-box");let h,c=n.elZoom=n.querySelector(".dce-mn-zoom");c&&(c.style.display="none",h=n.elZoomSpan=c.querySelector("span"));let u=n.elToast=n.querySelector(".dce-mn-toast"),d=n.elCameraClose=n.querySelector(".dce-mn-camera-close"),f=n.elTakePhoto=n.querySelector(".dce-mn-take-photo"),g=n.elCameraSwitch=n.querySelector(".dce-mn-camera-switch"),m=n.elCameraAndResolutionSettings=n.querySelector(".dce-mn-camera-and-resolution-settings");m&&(m.style.display="none");const p=n.dceMnFs={},_=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",_);const v=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",v);const y=()=>{this.turnAutoTorch()};null==r||r.addEventListener("pointerdown",y);const w=()=>{bs.allowBeep=!bs.allowBeep,s&&(s.style.display=bs.allowBeep?"":"none"),a&&(a.style.display=bs.allowBeep?"none":"")};for(let t of[a,s])null==t||t.addEventListener("pointerdown",w);const E=()=>{bs.allowVibrate=!bs.allowVibrate,o&&(o.style.display=bs.allowVibrate?"":"none"),l&&(l.style.display=bs.allowVibrate?"none":"")};for(let t of[l,o])null==t||t.addEventListener("pointerdown",E);const C=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),n=parseInt(e.getAttribute("data-height")),r=await this.setResolution({width:i,height:n});{let e=Math.max(r.width,r.height),i=Math.min(r.width,r.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&b(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?m&&(m.style.display=m.style.display?"":"none"):m&&""===m.style.display&&(m.style.display="none"))};n.addEventListener("click",C);let S=null;p.funcInfoZoomChange=(t,e=3e3)=>{c&&h&&(h.textContent=t.toFixed(1),c.style.display="",null!=S&&(clearTimeout(S),S=null),S=setTimeout((()=>{c.style.display="none",S=null}),e))};let T=null,b=p.funcShowToast=(t,e=3e3)=>{u&&(u.textContent=t,u.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout((()=>{u.style.display="none",T=null}),e))};const x=()=>{this.close()};null==d||d.addEventListener("click",x);const I=()=>{};null==f||f.addEventListener("pointerdown",I);const R=()=>{var t,e;let i,n=this.getVideoSettings(),r=n.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),a=null==s?void 0:s.indexOf("front");-1===a&&(a=null==s?void 0:s.indexOf("前"));let o=null==s?void 0:s.indexOf("back");-1===o&&(o=null==s?void 0:s.indexOf("后")),"number"==typeof a&&-1!==a?i=!0:"number"==typeof o&&-1!==o&&(i=!1),void 0===i&&(i="user"===((null==r?void 0:r.ideal)||(null==r?void 0:r.exact)||r)),n.video.facingMode={ideal:i?"environment":"user"},delete n.video.deviceId,this.updateVideoSettings(n)};null==g||g.addEventListener("pointerdown",R);let O=-1/0,D=1;const A=t=>{let e=Date.now();e-O>1e3&&(D=this.getZoomSettings().factor),D-=t.deltaY/200,D>20&&(D=20),D<1&&(D=1),this.setZoom({factor:D}),O=e};i.addEventListener("wheel",A);const L=new Map;let M=!1;const F=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],n=t.touches[1],r=L.get(i.identifier),s=L.get(n.identifier);if(!r||!s)break;let a=Math.pow(Math.pow(r.x-s.x,2)+Math.pow(r.y-s.y,2),.5),o=Math.pow(Math.pow(i.clientX-n.clientX,2)+Math.pow(i.clientY-n.clientY,2),.5),l=Date.now();if(M||l-O<100)return;l-O>1e3&&(D=this.getZoomSettings().factor),D*=o/a,D>20&&(D=20),D<1&&(D=1);let h=!1;"safari"==(null===(e=null==ze?void 0:ze.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(o/a>1&&D<2?(D=2,h=!0):o/a<1&&D<2&&(D=1,h=!0)),M=!0,h&&b("zooming..."),await this.setZoom({factor:D}),h&&(u.textContent=""),M=!1,O=Date.now();break}L.clear();for(let e of t.touches)L.set(e.identifier,{x:e.clientX,y:e.clientY})};n.addEventListener("touchstart",F),n.addEventListener("touchmove",F),n.addEventListener("touchend",F),n.addEventListener("touchcancel",F),p.unbind=()=>{null==t||t.removeEventListener("pointerdown",_),null==e||e.removeEventListener("pointerdown",v),null==r||r.removeEventListener("pointerdown",y);for(let t of[a,s])null==t||t.removeEventListener("pointerdown",w);for(let t of[l,o])null==t||t.removeEventListener("pointerdown",E);n.removeEventListener("click",C),null==d||d.removeEventListener("click",x),null==f||f.removeEventListener("pointerdown",I),null==g||g.removeEventListener("pointerdown",R),i.removeEventListener("wheel",A),n.removeEventListener("touchstart",F),n.removeEventListener("touchmove",F),n.removeEventListener("touchend",F),n.removeEventListener("touchcancel",F),delete n.dceMnFs,i.style.display="none"},i.style.display="",t&&null==this.isTorchOn&&setTimeout((()=>{this.turnAutoTorch(1e3)}),0)}this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const r=this.getResolution();e.width=r.width,e.height=r.height,e.deviceId=this.getSelectedCamera().deviceId}return Xe(this,ss,"open"),t&&(t._innerComponent.style.display="",He(this,is,"m",ys).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!1}),t.eventHandler.fire("videoEl:resized",null,{async:!1}))),He(this,as,"f").fire("opened",null,{target:this,async:!1}),e}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),He(this,is,"m",ys).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}Xe(this,ss,"closed"),He(this,_s,"f").stopCharging(),e&&(e._innerComponent.style.display="none",He(this,is,"m",ys).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),He(this,as,"f").fire("closed",null,{target:this,async:!1})}pause(){if(He(this,is,"m",ys).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!He(this,is,"m",ys).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(He(this,is,"m",ys).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(e),this.isTorchOn=!1;const i=this.getResolution(),n=this.cameraView;return n&&!n.disposed&&(n._stopLoading(),n._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),n._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?He(this,as,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?He(this,as,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._on(n,e)}off(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._off(n,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(He(this,is,"m",ys).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(He(this,is,"m",ys).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){if(null!=this._taskid4AutoTorch){if(!(t{var t,r,s;if(this.disposed||e||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++n>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let a;try{a=this.fetchImage()}catch(t){}if(!a||!a.width||!a.height)return;let o=0;if(l.IPF_GRAYSCALED===a.format){for(let t=0;t=this.maxDarkCount4AutoTroch){null===(t=Rs._onLog)||void 0===t||t.call(Rs,`darkCount ${i}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(r=null==t?void 0:t.dceMnFs)||void 0===r||r.funcShowToast("Torch Auto On")}catch(t){console.warn(t),e=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,null===(s=null==i?void 0:i.dceMnFs)||void 0===s||s.funcShowToast("Torch Not Supported")}}}else i=0};this._taskid4AutoTorch=setInterval(r,t),this.isTorchOn=void 0,r();let s=this.cameraView.getUIElement();s=s.shadowRoot||s,s.elTorchAuto&&(s.elTorchAuto.style.display=""),s.elTorchOn&&(s.elTorchOn.style.display="none"),s.elTorchOff&&(s.elTorchOff.style.display="none")}async setColorTemperature(t){if(He(this,is,"m",ys).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(He(this,is,"m",ys).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,n;if(He(this,is,"m",ys).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(n=null==e?void 0:e.dceMnFs)||void 0===n||n.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(He(this,is,"m",ys).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(He(this,is,"m",ys).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(He(this,is,"m",ys).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){He(this,ps,"f").minValue=t.min,He(this,ps,"f").maxValue=t.max}getAutoZoomRange(){return{min:He(this,ps,"f").minValue,max:He(this,ps,"f").maxValue}}async enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=ct.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==gt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&ri.EF_ENHANCED_FOCUS&&(He(this,ms,"f").enhancedFocus=!0),t&ri.EF_AUTO_ZOOM&&(He(this,ms,"f").autoZoom=!0),t&ri.EF_TAP_TO_FOCUS&&(He(this,ms,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&ri.EF_ENHANCED_FOCUS&&(He(this,ms,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),t&ri.EF_AUTO_ZOOM&&(He(this,ms,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),t&ri.EF_TAP_TO_FOCUS&&(He(this,ms,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),He(this,is,"m",Es).call(this)&&He(this,is,"m",ws).call(this)||He(this,_s,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!w(t)&&!x(t))throw TypeError("Invalid 'region'.");Xe(this,us,t?JSON.parse(JSON.stringify(t)):null),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(He(this,us,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");Xe(this,cs,t)}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||He(this,is,"m",ys).call(this))}startFetching(){if(He(this,is,"m",ys).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");He(this,fs,"f")||(Xe(this,fs,!0),He(this,is,"m",Cs).call(this))}stopFetching(){He(this,fs,"f")&&(Rs._onLog&&Rs._onLog("DCE: stop fetching loop: "+Date.now()),He(this,gs,"f")&&clearTimeout(He(this,gs,"f")),Xe(this,fs,!1))}fetchImage(){if(He(this,is,"m",ys).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let e;if(e=ki.convert(He(this,us,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height}),e.x>t.width||e.y>t.height)throw new Error("Invalid scan region.");e.x+e.width>t.width&&(e.width=t.width-e.x),e.y+e.height>t.height&&(e.height=t.height-e.y);const i={sx:e.x,sy:e.y,sWidth:e.width,sHeight:e.height,dWidth:e.width,dHeight:e.height},n=Math.max(i.dWidth,i.dHeight);if(this.canvasSizeLimit&&n>this.canvasSizeLimit){const t=this.canvasSizeLimit/n;i.dWidth>i.dHeight?(i.dWidth=this.canvasSizeLimit,i.dHeight=Math.round(i.dHeight*t)):(i.dWidth=Math.round(i.dWidth*t),i.dHeight=this.canvasSizeLimit)}const r=this.cameraManager.getFrameData({position:i,pixelFormat:this.getPixelFormat()===l.IPF_GRAYSCALED?Wn.GREY:Wn.RGBA});if(!r)return null;let s;s=r.pixelFormat===Wn.GREY?r.width:4*r.width;let a=!0;return 0===i.sx&&0===i.sy&&i.sWidth===t.width&&i.sHeight===t.height&&(a=!1),{bytes:r.data,width:r.width,height:r.height,stride:s,format:xs.get(r.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:wt.ITT_VIDEO_FRAME,isCropped:a,cropRegion:{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:r.width,currentHeight:r.height,timeSpent:r.timeSpent,timeStamp:r.timeStamp},toCanvas:He(this,hs,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,He(this,fs,"f")&&(He(this,gs,"f")&&clearTimeout(He(this,gs,"f")),Xe(this,gs,setTimeout((()=>{this.disposed||He(this,is,"m",Cs).call(this)}),t)))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){Xe(this,ds,t)}getPixelFormat(){return He(this,ds,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(He(this,is,"m",ys).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],n=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise(((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let a=ki.convert(He(this,us,"f"),r,s);a||(a={x:0,y:0,width:r,height:s});const o=He(this,ls,"f").call(this,n,r,s,a);t&&t(o)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=He(this,is,"m",Ss).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=He(this,is,"m",Ss).call(this,t);return{x:e.clientX,y:e.clientY}}convertToScanRegionCoordinates(t){if(!He(this,us,"f"))return JSON.parse(JSON.stringify(t));let e,i,n=He(this,us,"f").left||He(this,us,"f").x||0,r=He(this,us,"f").top||He(this,us,"f").y||0;if(!He(this,us,"f").isMeasuredInPercentage)return{x:t.x-n,y:t.y-r};if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!He(this,is,"m",ys).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(He(this,is,"m",ys).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(He(this,is,"m",ys).call(this)){const t=this.cameraView._innerComponent.getElement("content");e=t.width,i=t.height}else{const t=this.getVideoEl();e=t.videoWidth,i=t.videoHeight}return{x:t.x-Math.round(n*e/100),y:t.y-Math.round(r*i/100)}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),Xe(this,vs,!0)}}var Os,Ds,As,Ls,Ms,Fs,Ps,ks;ns=Rs,ss=new WeakMap,as=new WeakMap,os=new WeakMap,ls=new WeakMap,hs=new WeakMap,cs=new WeakMap,us=new WeakMap,ds=new WeakMap,fs=new WeakMap,gs=new WeakMap,ms=new WeakMap,ps=new WeakMap,_s=new WeakMap,vs=new WeakMap,is=new WeakSet,ys=function(){return"disabled"!==this.singleFrameMode},ws=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},Es=function(){for(let t in He(this,ms,"f"))if(1==He(this,ms,"f")[t])return!0;return!1},Cs=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!He(this,fs,"f"))return He(this,gs,"f")&&clearTimeout(He(this,gs,"f")),void Xe(this,gs,setTimeout((()=>{this.disposed||He(this,is,"m",t).call(this)}),this.fetchInterval));const e=()=>{var t;let e;Rs._onLog&&Rs._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=He(this,cs,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=He(this,cs,"f"))||void 0===t||t.onErrorReceived(_t.EC_IMAGE_READ_FAILED,i)}),0);console.warn(e)}e?(this.addImageToBuffer(e),Rs._onLog&&Rs._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),He(this,as,"f").fire("frameAddedToBuffer",null,{async:!1})):Rs._onLog&&Rs._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case a.BOPM_BLOCK:break;case a.BOPM_UPDATE:e()}else e();He(this,gs,"f")&&clearTimeout(He(this,gs,"f")),Xe(this,gs,setTimeout((()=>{this.disposed||He(this,is,"m",t).call(this)}),this.fetchInterval))},Ss=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!He(this,is,"m",ys).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(He(this,is,"m",ys).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,n=e.top,r=i+window.scrollX,s=n+window.scrollY,{width:a,height:o}=this.cameraView._innerComponent.getBoundingClientRect();if(a<=0||o<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let l,h,c;if(He(this,is,"m",ys).call(this)){const t=this.cameraView._innerComponent.getElement("content");l=t.width,h=t.height,c="contain"}else{const t=this.getVideoEl();l=t.videoWidth,h=t.videoHeight,c=this.cameraView.getVideoFit()}const u=a/o,d=l/h;let f,g,m,p,_=1;if("contain"===c)u{var e;if(!this.isUseMagnifier)return;if(He(this,Ls,"f")||Xe(this,Ls,new Ns),!He(this,Ls,"f").magnifierCanvas)return;document.body.contains(He(this,Ls,"f").magnifierCanvas)||(He(this,Ls,"f").magnifierCanvas.style.position="fixed",He(this,Ls,"f").magnifierCanvas.style.boxSizing="content-box",He(this,Ls,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(He(this,Ls,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void He(this,Fs,"f").call(this);const n=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!n)return;const r=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*r,a=[{image:i,width:i.width,height:i.height},{image:n,width:n.width,height:n.height}];He(this,Ls,"f").update(s,t.pointer,r,a);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(He(this,Ls,"f").magnifierCanvas.style.left="auto",He(this,Ls,"f").magnifierCanvas.style.top="0",He(this,Ls,"f").magnifierCanvas.style.right="0"):(He(this,Ls,"f").magnifierCanvas.style.left="0",He(this,Ls,"f").magnifierCanvas.style.top="0",He(this,Ls,"f").magnifierCanvas.style.right="auto")}He(this,Ls,"f").show()})),Fs.set(this,(()=>{He(this,Ls,"f")&&He(this,Ls,"f").hide()})),Ps.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Wi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=document.createElement("dce-component"),e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let n=this._innerComponent.getElement("content");n||(n=document.createElement("canvas"),n.style.objectFit="contain",this._innerComponent.setElement("content",n)),n.width===e&&n.height===i||(n.width=e,n.height=i);const r=n.getContext("2d");r.clearRect(0,0,n.width,n.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),r.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&r.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(y(t)){Xe(this,As,t);const{width:e,height:i,bytes:n,format:r}=Object.assign({},t);let s;if(r===l.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const n=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new ai.Control({positionHandler:Ci,actionHandler:bi(i>0?i-1:n,Ti),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let n=t.x-i.pathOffset.x,r=t.y-i.pathOffset.y;const s=ai.util.transformPoint({x:n,y:r},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){He(this,Oi,"f")&&this.setLine(He(this,Oi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!C(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else Xe(this,Oi,JSON.parse(JSON.stringify(t)))}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return He(this,Oi,"f")?JSON.parse(JSON.stringify(He(this,Oi,"f"))):null}},QuadDrawingItem:Ai,RectDrawingItem:Ei,TextDrawingItem:Ri});function Gs(t){delete t.moduleId;const e=JSON.parse(t.jsonString).ResultInfo,i=t.fullCodeString;t.getFieldValue=t=>"fullcodestring"===t.toLowerCase()?i:Ws(e,t,"map"),t.getFieldRawValue=t=>Ws(e,t,"raw"),t.getFieldMappingStatus=t=>Ys(e,t),t.getFieldValidationStatus=t=>zs(e,t),delete t.fullCodeString}function Ws(t,e,i){for(let n of t){if(n.FieldName===e)return"raw"===i&&n.RawValue?n.RawValue:n.Value;if(n.ChildFields&&n.ChildFields.length>0){let t;for(let r of n.ChildFields)t=Ws(r,e,i);if(void 0!==t)return t}}}function Ys(t,e){for(let i of t){if(i.FieldName===e)return i.MappingStatus?Number(js[i.MappingStatus]):js.MS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=Ys(n,e);if(void 0!==t)return t}}}function zs(t,e){for(let i of t){if(i.FieldName===e&&i.ValidationStatus)return i.ValidationStatus?Number(Vs[i.ValidationStatus]):Vs.VS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=zs(n,e);if(void 0!==t)return t}}}function Hs(t){if(t.disposed)throw new Error('"CodeParser" instance has been disposed')}!function(t){t[t.MS_NONE=0]="MS_NONE",t[t.MS_SUCCEEDED=1]="MS_SUCCEEDED",t[t.MS_FAILED=2]="MS_FAILED"}(js||(js={})),function(t){t[t.VS_NONE=0]="VS_NONE",t[t.VS_SUCCEEDED=1]="VS_SUCCEEDED",t[t.VS_FAILED=2]="VS_FAILED"}(Vs||(Vs={}));const Xs=t=>t&&"object"==typeof t&&"function"==typeof t.then,Zs=(async()=>{})().constructor;let qs=class extends Zs{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Xs(t)?e=t:"function"==typeof t&&(e=new Zs(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(Xs(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Js="undefined"==typeof self,Ks="function"==typeof importScripts,$s=(()=>{if(!Ks){if(!Js&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})();gt.engineResourcePaths.dcp={version:"2.4.32",path:$s,isInternal:!0},ut.dcp={js:!0,wasm:!0,deps:["license"]},ct.dcp={handleParsedResultItem:Gs};const Qs="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&R(gt.engineResourcePaths.std.version,Qs)<0&&(gt.engineResourcePaths.std={version:Qs,path:(t=>{if(null==t&&(t="./"),Js||Ks);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})($s+`../../dynamsoft-capture-vision-std@${Qs}/dist/`),isInternal:!0});let ta=class{static getVersion(){const t=ht.dcp&&ht.dcp.wasm;return`2.4.32(Worker: ${ht.dcp&&ht.dcp.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadSpec(t,e){return await ft("dcp"),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success)return i();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},e&&!e.endsWith("/")&&(e+="/");const s=t instanceof Array?t:[t],a=O(gt.engineResourcePaths);et.postMessage({type:"dcp_appendResourceBuffer",id:r,body:{specificationPath:e||a.dcp+"specification/",specificationNames:s}})}))}};var ea=Object.freeze({__proto__:null,CodeParser:class t{constructor(){this._instanceID=void 0,this.bDestroyed=!1}static async createInstance(){if(!ct.license)throw Error("Module `license` is not existed.");await ct.license.dynamsoft(),await ft("dcp");const e=new t,i=new qs;let n=nt();return rt[n]=async t=>{if(t.success)e._instanceID=t.instanceID,i.resolve(e);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),i.reject(e)}},et.postMessage({type:"dcp_createInstance",id:n}),i}async dispose(){Hs(this);let t=nt();this.bDestroyed=!0,rt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},et.postMessage({type:"dcp_dispose",id:t,instanceID:this._instanceID})}get disposed(){return this.bDestroyed}async initSettings(t){return Hs(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?t.trimStart().startsWith("{")||(t=await I(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Init Settings Failed.");return t.errorCode=n.errorCode,i(t)}return e(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"dcp_initSettings",id:n,instanceID:this._instanceID,body:{settings:t}})}))):console.error("Invalid settings.")}async resetSettings(){return Hs(this),await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"dcp_resetSettings",id:i,instanceID:this._instanceID})}))}async parse(t,e=""){if(Hs(this),!t||!(t instanceof Array||t instanceof Uint8Array||"string"==typeof t))throw new Error("`parse` must pass in an Array or Uint8Array or string");return await new Promise(((i,n)=>{let r=nt();t instanceof Array&&(t=Uint8Array.from(t)),"string"==typeof t&&(t=Uint8Array.from(function(t){let e=[];for(let i=0;i{if(t.success){let e=JSON.parse(t.parseResponse);return e.errorCode?n(new Error(e.errorString)):(Gs(e),i(e))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},et.postMessage({type:"dcp_parse",id:r,instanceID:this._instanceID,body:{source:t,taskSettingName:e}})}))}},CodeParserModule:ta,get EnumMappingStatus(){return js},get EnumValidationStatus(){return Vs}});const ia="undefined"==typeof self,na="function"==typeof importScripts,ra=(()=>{if(!na){if(!ia&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),sa=t=>{if(null==t&&(t="./"),ia||na);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};gt.engineResourcePaths.dlr={version:"3.4.32",path:ra,isInternal:!0},null==gt.engineResourcePaths.dlrData&&(gt.engineResourcePaths.dlrData={version:"1.0.11",path:sa(ra+"../../dynamsoft-label-recognizer-data@1.0.11/dist/"),isInternal:!0}),ut.dlr={js:!0,wasm:!0,deps:["license","dip","dnn"]},ut.dnn={wasm:!0,deps:["dip"]};const aa="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&R(gt.engineResourcePaths.std.version,aa)<0&&(gt.engineResourcePaths.std={version:aa,path:sa(ra+`../../dynamsoft-capture-vision-std@${aa}/dist/`),isInternal:!0});const oa="2.4.31";(!gt.engineResourcePaths.dip||"string"!=typeof gt.engineResourcePaths.dip&&R(gt.engineResourcePaths.dip.version,oa)<0)&&(gt.engineResourcePaths.dip={version:oa,path:sa(ra+`../../dynamsoft-image-processing@${oa}/dist/`),isInternal:!0});const la="1.0.20";(!gt.engineResourcePaths.dnn||"string"!=typeof gt.engineResourcePaths.dnn&&R(gt.engineResourcePaths.dnn.version,la)<0)&&(gt.engineResourcePaths.dnn={version:la,path:sa(ra+`../../dynamsoft-capture-vision-dnn@${la}/dist/`),isInternal:!0});let ha=!1,ca=class{static getVersion(){const t=ht.dlr&&ht.dlr.wasm;return`3.4.32(Worker: ${ht.dlr&&ht.dlr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadRecognitionData(t,e){return await ft("dlr"),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success){const e=t.result;if(0!==e.errorCode){let t=new Error(e.errorString);return t.errorCode=e.errorCode,n(t)}return e.isModel||(ha=!0),i(e)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},e&&!e.endsWith("/")&&(e+="/");const s=O(gt.engineResourcePaths);e||"ConfusableChars"!==t||(e=s.dlr),et.postMessage({type:"dlr_loadData",id:r,body:{dataName:t,dataPath:e||s.dlrData}})}))}};ct.dlr={loadRecognitionData:ca.loadRecognitionData,get bLoadConfusableCharsData(){return ha}};const ua={filterVINResult:function(t){let e="";if(18===t.characterResults.length){let e=t.characterResults[9].location.points[0].x-t.characterResults[8].location.points[1].x;e<2&&(e=2);let i=t.characterResults[1].location.points[0].x-t.characterResults[0].location.points[1].x,n=t.characterResults[17].location.points[0].x-t.characterResults[16].location.points[1].x,r=2===e?3:e;i-e>=r&&n-e=r&&i-et.characterResults[17].characterHConfidence?t.characterResults.pop():t.characterResults.shift()}else if(19===t.characterResults.length){let e=t.characterResults[10].location.points[0].x-t.characterResults[9].location.points[1].x;e<2&&(e=2);let i,n,r,s=t.characterResults[1].location.points[0].x-t.characterResults[0].location.points[1].x,a=t.characterResults[18].location.points[0].x-t.characterResults[17].location.points[1].x,o=t.characterResults[2].location.points[0].x-t.characterResults[1].location.points[1].x,l=t.characterResults[17].location.points[0].x-t.characterResults[16].location.points[1].x,h=2===e?3:e;if("1"===t.characterResults[1].characterH||"1"===t.characterResults[2].characterH||"1"===t.characterResults[16].characterH||"1"===t.characterResults[17].characterH){for(let e=9;e=(i||h)&&l-e<(n||h))t.characterResults.splice(0,2);else if(l-e>=(n||h)&&o-e<(i||h))t.characterResults.splice(17,2);else if(s>e&&a>e)t.characterResults.pop(),t.characterResults.shift();else{let e=t.characterResults[0].characterHConfidence+t.characterResults[1].characterHConfidence,i=t.characterResults[17].characterHConfidence+t.characterResults[18].characterHConfidence,n=t.characterResults[0].characterHConfidence+t.characterResults[18].characterHConfidence,r=Math.min(e,i,n);r===e?t.characterResults.splice(0,2):r===i?t.characterResults.splice(17,2):r===n&&(t.characterResults.pop(),t.characterResults.shift())}}for(let i of t.characterResults)e+=i.characterH;return e},checkValidVIN:function(t){return!(!t||17!=t.length)&&(t=>{const e=new Map([["A",1],["B",2],["C",3],["D",4],["E",5],["F",6],["G",7],["H",8],["J",1],["K",2],["L",3],["M",4],["N",5],["P",7],["R",9],["S",2],["T",3],["U",4],["V",5],["W",6],["X",7],["Y",8],["Z",9],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9]]),i=[8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2];let n=0;for(let r=0;r{const n=new Map([["<",0],["0",0],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9],["A",10],["B",11],["C",12],["D",13],["E",14],["F",15],["G",16],["H",17],["I",18],["J",19],["K",20],["L",21],["M",22],["N",23],["O",24],["P",25],["Q",26],["R",27],["S",28],["T",29],["U",30],["V",31],["W",32],["X",33],["Y",34],["Z",35]]),r=[7,3,1];let s=0;for(let a=e,o=0;a<=i;a++){let e=n.get(t[a]);e&&(s+=e*r[o%3]),o++}return s%10},i=t.slice(0,10)+t.slice(13,20)+t.slice(21,43),n=e(t,0,8).toString(),r=e(t,13,18).toString(),s=e(t,21,26).toString(),a=e(t,28,41).toString(),o=e(i,0,i.length).toString();return n===t[9]&&r===t[19]&&s===t[27]&&a===t[42]&&o===t[43]},checkValidMRV:function(t){if(!t||44!=t.length&&36!=t.length)return!1;const e=(t,e,i)=>{const n=new Map([["<",0],["0",0],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9],["A",10],["B",11],["C",12],["D",13],["E",14],["F",15],["G",16],["H",17],["I",18],["J",19],["K",20],["L",21],["M",22],["N",23],["O",24],["P",25],["Q",26],["R",27],["S",28],["T",29],["U",30],["V",31],["W",32],["X",33],["Y",34],["Z",35]]),r=[7,3,1];let s=0;for(let a=e,o=0;a<=i;a++){let e=n.get(t[a]);e&&(s+=e*r[o%3]),o++}return s%10},i=e(t,0,8).toString(),n=e(t,13,18).toString(),r=e(t,21,26).toString();return i===t[9]&&n===t[19]&&r===t[27]},checkValidIDCard:function(t,e){if(!t||30!=t.length&&36!=t.length)return!1;const i=(t,e,i)=>{const n=new Map([["<",0],["0",0],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9],["A",10],["B",11],["C",12],["D",13],["E",14],["F",15],["G",16],["H",17],["I",18],["J",19],["K",20],["L",21],["M",22],["N",23],["O",24],["P",25],["Q",26],["R",27],["S",28],["T",29],["U",30],["V",31],["W",32],["X",33],["Y",34],["Z",35]]),r=[7,3,1];let s=0;for(let a=e,o=0;a<=i;a++){let e=n.get(t[a]);e&&(s+=e*r[o%3]),o++}return s%10};if(30===t.length){if(e&&t===e)return i(t,5,13).toString()===t[14];if(e&&t!==e){const n=`${e.substring(5,30)}${t.substring(0,7)}${t.substring(8,15)}${t.substring(18,29)}`;return i(n,0,n.length-1).toString()===t[29]}}else if(36===t.length){const e=i(t,0,8).toString(),n=i(t,13,18).toString(),r=i(t,21,26).toString(),s=`${t.substring(0,10)}${t.substring(13,20)}${t.substring(21,28)}`,a=i(s,0,s.length-1).toString();return e===t[9]&&n===t[19]&&r===t[27]&&a===t[35]}}};var da;!function(t){t[t.RTLS_LOCALIZED=0]="RTLS_LOCALIZED",t[t.RTLS_RECOGNITION_FAILED=1]="RTLS_RECOGNITION_FAILED",t[t.RTLS_RECOGNITION_SUCCEEDED=2]="RTLS_RECOGNITION_SUCCEEDED"}(da||(da={})),rt[-1]=async t=>{ca.onDataLoadProgressChanged&&ca.onDataLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};var fa=Object.freeze({__proto__:null,get EnumRawTextLineStatus(){return da},LabelRecognizerModule:ca,utilsFuncs:ua});const ga=async t=>{let e;await new Promise(((i,n)=>{e=new Image,e.onload=()=>i(e),e.onerror=n,e.src=URL.createObjectURL(t)}));const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e.width,i.height=e.height,n.drawImage(e,0,0),{bytes:Uint8Array.from(n.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:10}};const ma="undefined"==typeof self,pa="function"==typeof importScripts,_a=(()=>{if(!pa){if(!ma&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),va=t=>{if(null==t&&(t="./"),ma||pa);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};gt.engineResourcePaths.utility={version:"1.4.32",path:_a,isInternal:!0},ut.utility={js:!0,wasm:!0};const ya="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&R(gt.engineResourcePaths.std.version,ya)<0&&(gt.engineResourcePaths.std={version:ya,path:va(_a+`../../dynamsoft-capture-vision-std@${ya}/dist/`),isInternal:!0});const wa="2.4.31";(!gt.engineResourcePaths.dip||"string"!=typeof gt.engineResourcePaths.dip&&R(gt.engineResourcePaths.dip.version,wa)<0)&&(gt.engineResourcePaths.dip={version:wa,path:va(_a+`../../dynamsoft-image-processing@${wa}/dist/`),isInternal:!0});function Ea(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}var Ca,Sa,Ta,ba,xa;function Ia(t,e){let i=!0;for(let a=0;a1)return Math.sqrt((l-a)**2+(h-o)**2);{const t=r+u*(a-r),e=s+u*(o-s);return Math.sqrt((l-t)**2+(h-e)**2)}}function Da(t){const e=[];for(let i=0;i=0&&l<=1&&h>=0&&h<=1?{x:t.x+h*r,y:t.y+h*s}:null}function Ma(t){let e=0;for(let i=0;i0}function Pa(t,e){for(let i=0;i<4;i++)if(!Fa(t.points[i],t.points[(i+1)%4],e))return!1;return!0}"function"==typeof SuppressedError&&SuppressedError;function ka(t,e,i,n){const r=t.points,s=e.points;let a=8*i;a=Math.max(a,5);const o=Da(r)[3],l=Da(r)[1],h=Da(s)[3],c=Da(s)[1];let u,d=0;if(u=Math.max(Math.abs(Oa(o,e.points[0])),Math.abs(Oa(o,e.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Oa(l,e.points[1])),Math.abs(Oa(l,e.points[2]))),u>d&&(d=u),u=Math.max(Math.abs(Oa(h,t.points[0])),Math.abs(Oa(h,t.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Oa(c,t.points[1])),Math.abs(Oa(c,t.points[2]))),u>d&&(d=u),d>a)return!1;const f=Aa(Da(r)[0]),g=Aa(Da(r)[2]),m=Aa(Da(s)[0]),p=Aa(Da(s)[2]),_=Ra(f,p),v=Ra(m,g),y=_>v,w=Math.min(_,v),E=Ra(f,g),C=Ra(m,p);let S=12*i;return S=Math.max(S,5),S=Math.min(S,E),S=Math.min(S,C),!!(w{e.x+=t,e.y+=i})),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,n=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-n.area)>.4*i.area)return!1;let r=new Array(4).fill(0),s=new Array(4).fill(0),a=0,o=0;for(let t=0;t<4;++t)r[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,a+=r[t],s[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,o+=s[t];a/=4,o/=4;for(let t=0;t<4;++t){if(Math.abs(r[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1;if(Math.abs(s[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1}return e.x=a,e.y=o,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(Pa(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(Pa(this.location,e))return!0}else{for(let e=0;e<4;e++)if(Pa(t,this.location.points[e]))return!0;if(Pa(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const n=[this.location.points[0],this.location.points[3]],r=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?n:r;if(Math.abs(Oa(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const n=t.location.points[i],r=this.location.points[i];if(!(Math.abs(r.x+e.x-n.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const n=Object.assign({},t.location);for(let t=0;t<4;t++)n.points[t].x-=e.x,n.points[t].y-=e.y;if(!this.isLocationOverlap(n,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let n=0;n<4;n++)for(let r=0;r<4;r++){const s=La(t[n],t[(n+1)%4],e[r],e[(r+1)%4]);s&&i.push(s)}return t.forEach((t=>{Ia(e,t)&&i.push(t)})),e.forEach((e=>{Ia(t,e)&&i.push(e)})),Ma(function(t){if(t.length<=1)return t;t.sort(((t,e)=>t.x-e.x||t.y-e.y));const e=t.shift();return t.sort(((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x))),[e,...t]}(i))}([...this.location.points],n.points)>this.locationArea*t}return!0}}const Ba={BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096)},ja={barcode:2,text_line:4,detected_quad:8,normalized_image:16},Va=t=>Object.values(ja).includes(t)||ja.hasOwnProperty(t),Ua=(t,e)=>"string"==typeof t?e[ja[t]]:e[t],Ga=(t,e,i)=>{"string"==typeof t?e[ja[t]]=i:e[t]=i},Wa=(t,e,i)=>{const n=[8,16].includes(i);if(!n&&t.isResultCrossVerificationEnabled(i))for(let t=0;t{Ga(e,this.verificationEnabled,t)})),Ea(this,Sa,"f").forEach(((t,e)=>{Ga(e,this.duplicateFilterEnabled,t)})),Ea(this,Ta,"f").forEach(((t,e)=>{Ga(e,this.duplicateForgetTime,t)})),Ea(this,ba,"f").forEach(((t,e)=>{Ga(e,this.latestOverlappingEnabled,t)})),Ea(this,xa,"f").forEach(((t,e)=>{Ga(e,this.maxOverlappingFrames,t)}))}enableResultCrossVerification(t,e){Va(t)&&Ea(this,Ca,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!Va(t)&&Ua(t,this.verificationEnabled)}enableResultDeduplication(t,e){Va(t)&&(e&&this.enableLatestOverlapping(t,!1),Ea(this,Sa,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!Va(t)&&Ua(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){Va(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),Ea(this,Ta,"f").set(t,e))}getDuplicateForgetTime(t){return Va(t)?Ua(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){Va(t)&&Ea(this,xa,"f").set(t,e)}getMaxOverlappingFrames(t){return Va(t)?Ua(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){Va(t)&&(e&&this.enableResultDeduplication(t,!1),Ea(this,ba,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!Va(t)&&Ua(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[mt.CRIT_BARCODE,mt.CRIT_TEXT_LINE,mt.CRIT_DETECTED_QUAD,mt.CRIT_NORMALIZED_IMAGE];for(let i=0;i{if(1!==t.type){const e=(BigInt(t.format)&BigInt(Ba.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Ba.BF_GS1_DATABAR))!=BigInt(0);return new Na(l,e?1:2,e,t)}})).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(h).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t)).length;r>p&&(p=r,m=n,g.x=i.x,g.y=i.y)}}if(0===p){for(let e=0;e-1!=t)).length}let i=this.overlapSet.length<=3?p>=1:p>=2;if(!i&&s&&u>0){let t=0;for(let e=0;e=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach(((t,e)=>{if(1!==t.type){const i=Object.assign({},t),n=(BigInt(t.format)&BigInt(Ba.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Ba.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0)))}f.sort(((t,e)=>e-t)).forEach(((e,i)=>{t.items.splice(e,1)})),d.forEach((e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))}))}}onDecodedBarcodesReceived(t){this.latestOverlappingFilter(t),Wa(this,t.items,mt.CRIT_BARCODE)}onRecognizedTextLinesReceived(t){Wa(this,t.items,mt.CRIT_TEXT_LINE)}onDetectedQuadsReceived(t){Wa(this,t.items,mt.CRIT_DETECTED_QUAD)}onNormalizedImagesReceived(t){Wa(this,t.items,mt.CRIT_NORMALIZED_IMAGE)}}Ca=new WeakMap,Sa=new WeakMap,Ta=new WeakMap,ba=new WeakMap,xa=new WeakMap;var za,Ha,Xa,Za=Object.freeze({__proto__:null,ImageManager:class{async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const n=M(t);return D(n,e,i)}async drawOnImage(t,e,i,n=4294901760,r=1,s){let a;if(t instanceof Blob)a=await ga(t);else if("string"==typeof t){let e=await I(t,"blob");a=await ga(e)}return await new Promise(((t,o)=>{let l=nt();rt[l]=async e=>{if(e.success)return s&&this.saveToFile(e.image,"test.png",s),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,o(t)}},et.postMessage({type:"utility_drawOnImage",id:l,body:{dsImage:a,drawingItem:e instanceof Array?e:[e],color:n,thickness:r,type:i}})}))}},MultiFrameResultCrossFilter:Ya,UtilityModule:class{static getVersion(){return`1.4.32(Worker: ${ht.utility&&ht.utility.worker||"Not Loaded"}, Wasm: ${ht.utility&&ht.utility.wasm||"Not Loaded"})`}}});t.EnumMRZScanMode=void 0,(za=t.EnumMRZScanMode||(t.EnumMRZScanMode={})).Passport="passport",za.TD1="td1",za.TD2="td2",za.PassportAndTD1="passportAndTd1",za.PassportAndTD2="passportAndTd2",za.TD1AndTD2="td1AndTd2",za.All="all",t.EnumMRZDocumentType=void 0,(Ha=t.EnumMRZDocumentType||(t.EnumMRZDocumentType={})).Passport="passport",Ha.TD1="td1",Ha.TD2="td2",t.EnumMRZScannerViews=void 0,(Xa=t.EnumMRZScannerViews||(t.EnumMRZScannerViews={})).Scanner="scanner",Xa.Result="scan-result";const qa={[t.EnumMRZScanMode.Passport]:"ReadPassport",[t.EnumMRZScanMode.TD1]:"ReadId-TD1",[t.EnumMRZScanMode.TD2]:"ReadId-TD2",[t.EnumMRZScanMode.PassportAndTD1]:"ReadPassportAndId-TD1",[t.EnumMRZScanMode.PassportAndTD2]:"ReadPassportAndId-TD2",[t.EnumMRZScanMode.TD1AndTD2]:"ReadId",[t.EnumMRZScanMode.All]:"ReadPassportAndId"};var Ja;function Ka(t){if("string"==typeof t){const e=document.querySelector(t);if(!e)throw new Error("Element not found");return e}return t instanceof HTMLElement?t:null}t.EnumResultStatus=void 0,(Ja=t.EnumResultStatus||(t.EnumResultStatus={}))[Ja.RS_SUCCESS=0]="RS_SUCCESS",Ja[Ja.RS_CANCELLED=1]="RS_CANCELLED",Ja[Ja.RS_FAILED=2]="RS_FAILED";function $a(t,e){if(!document.getElementById(t)){const i=document.createElement("style");i.id=t,i.textContent=e,document.head.appendChild(i)}}const Qa=t=>!t||0===Object.keys(t).length;function to(t){return t?t.charAt(0).toUpperCase()+t.slice(1):""}const eo={"4k":{width:3840,height:2160},"2k":{width:2560,height:1440},"1080p":{width:1920,height:1080},"720p":{width:1280,height:720},"480p":{width:640,height:480}};function io(t,e={}){const{message:i,spinnerSize:n=32}=e,r=document.createElement("div");r.className="dynamsoft-mrz-loading-screen";const s=document.createElement("div");s.className="dynamsoft-mrz-loading";const a=document.createElement("div");a.className="dynamsoft-mrz-loading-content";const o=`\n \n \n \n `;if(a.innerHTML=o,i){const t=document.createElement("div");t.className="dynamsoft-mrz-loading-message",t.textContent=i,a.appendChild(t)}return s.appendChild(a),r.appendChild(s),t.appendChild(r),{element:r,updateMessage:t=>{let e=s.querySelector(".dynamsoft-mrz-loading-message");null!==t?e?e.textContent=t:(e=document.createElement("div"),e.className="dynamsoft-mrz-loading-message",e.textContent=t,a.appendChild(e)):null==e||e.remove()},hide:()=>{r&&r.parentNode&&(r.classList.add("fade-out"),setTimeout((()=>{var t;null===(t=r.parentNode)||void 0===t||t.removeChild(r)}),200))}}}const no='\n .dynamsoft-mrz-loading-screen {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: #323234;\n z-index: 998;\n opacity: 1;\n transition: opacity 0.2s ease-out;\n }\n\n .dynamsoft-mrz-loading-screen.fade-out {\n opacity: 0;\n }\n\n .dynamsoft-mrz-loading {\n position: absolute;\n left: 50%;\n top: 50%;\n color: white;\n z-index: 999;\n transform: translate(-50%, -50%);\n }\n\n .dynamsoft-mrz-loading-content {\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 16px;\n }\n\n .dynamsoft-mrz-loading svg {\n animation: spin 1s linear infinite;\n }\n\n .dynamsoft-mrz-loading-message {\n color: white;\n font-family: "Verdana";\n font-size: 14px;\n text-align: center;\n max-width: 200px;\n line-height: 1.4;\n opacity: 0.9;\n }\n\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n';var ro;t.EnumMRZData=void 0,(ro=t.EnumMRZData||(t.EnumMRZData={})).InvalidFields="invalidFields",ro.DocumentType="documentType",ro.DocumentNumber="documentNumber",ro.MRZText="mrzText",ro.FirstName="firstName",ro.LastName="lastName",ro.Age="age",ro.Sex="sex",ro.IssuingState="issuingState",ro.Nationality="nationality",ro.DateOfBirth="dateOfBirth",ro.DateOfExpiry="dateOfExpiry";const so={[t.EnumMRZData.InvalidFields]:"Invalid Fields",[t.EnumMRZData.DocumentType]:"Document Type",[t.EnumMRZData.DocumentNumber]:"Document Number",[t.EnumMRZData.MRZText]:"MRZ Text",[t.EnumMRZData.FirstName]:"Given Name(s)",[t.EnumMRZData.LastName]:"Surname",[t.EnumMRZData.Age]:"Age",[t.EnumMRZData.Sex]:"Sex",[t.EnumMRZData.IssuingState]:"Issuing State",[t.EnumMRZData.Nationality]:"Nationality",[t.EnumMRZData.DateOfBirth]:"Date Of Birth (YYYY-MM-DD)",[t.EnumMRZData.DateOfExpiry]:"Date Of Expiry (YYYY-MM-DD)"};function ao(t,e,i,n=!1){const r=parseInt(t,10);let s;if(n)s=r>=60?1900+r:2e3+r;else{s=r>(new Date).getFullYear()%100?1900+r:2e3+r}return{year:s,month:parseInt(e,10),day:parseInt(i,10)}}function oo(t){const e=t=>{var e;return 1===(null===(e=`${t}`)||void 0===e?void 0:e.length)?`0${t}`:t};return`${null==t?void 0:t.year}-${e(null==t?void 0:t.month)}${(null==t?void 0:t.day)&&`-${e(null==t?void 0:t.day)}`}`}function lo(e,i){const n=[],r=t=>i.getFieldValidationStatus(t)===Vs.VS_FAILED,s=i.codeType,a=function(e){switch(e){case"MRTD_TD1_ID":return t.EnumMRZDocumentType.TD1;case"MRTD_TD2_ID":case"MRTD_TD2_VISA":case"MRTD_TD2_FRENCH_ID":return t.EnumMRZDocumentType.TD2;case"MRTD_TD3_PASSPORT":case"MRTD_TD3_VISA":return t.EnumMRZDocumentType.Passport;default:throw new Error(`Unknown document type: ${e}`)}}(s),o=function(t){switch(t){case"MRTD_TD1_ID":return"ID (TD1)";case"MRTD_TD2_ID":return"ID (TD2)";case"MRTD_TD2_VISA":return"ID (VISA)";case"MRTD_TD2_FRENCH_ID":return"French ID (TD2)";case"MRTD_TD3_PASSPORT":return"Passport (TD3)";case"MRTD_TD3_VISA":return"Visa (TD3)";default:throw new Error(`Unknown document type: ${t}`)}}(s),l=a===t.EnumMRZDocumentType.Passport&&"MRTD_TD3_PASSPORT"===s?"passportNumber":"documentNumber",h=ao(i.getFieldValue("birthYear"),i.getFieldValue("birthMonth"),i.getFieldValue("birthDay")),c=ao(i.getFieldValue("expiryYear"),i.getFieldValue("expiryMonth"),i.getFieldValue("expiryDay"),!0);["birthYear","birthMonth","birthDay"].forEach((e=>{r(e)&&n.push(t.EnumMRZData.DateOfBirth)})),["expiryYear","expiryMonth","expiryDay"].forEach((e=>{r(e)&&n.push(t.EnumMRZData.DateOfExpiry)}));const u={[t.EnumMRZData.LastName]:i.getFieldValue("primaryIdentifier"),[t.EnumMRZData.FirstName]:i.getFieldValue("secondaryIdentifier"),[t.EnumMRZData.Nationality]:i.getFieldRawValue("nationality"),[t.EnumMRZData.DocumentNumber]:i.getFieldValue(l)||i.getFieldValue("longDocumentNumber"),[t.EnumMRZData.IssuingState]:i.getFieldRawValue("issuingState"),[t.EnumMRZData.Sex]:to(i.getFieldValue("sex"))};Object.keys(u).forEach((e=>{let i=!1;switch(e){case t.EnumMRZData.FirstName:i=r("secondaryIdentifier");break;case t.EnumMRZData.LastName:i=r("primaryIdentifier");break;case t.EnumMRZData.DocumentNumber:i=r(l)||r("longDocumentNumber");break;default:i=r(e)}i&&n.push(e)}));const d=function(t){const e=new Date,i=e.getMonth()+1>t.month||e.getMonth()+1===t.month&&e.getDate()>=t.day;return e.getFullYear()-t.year-(i?0:1)}(h);d<1&&n.push(t.EnumMRZData.Age);return{[t.EnumMRZData.InvalidFields]:n,[t.EnumMRZData.FirstName]:u[t.EnumMRZData.FirstName],[t.EnumMRZData.LastName]:u[t.EnumMRZData.LastName],[t.EnumMRZData.Age]:d,[t.EnumMRZData.DateOfBirth]:h,[t.EnumMRZData.Sex]:u[t.EnumMRZData.Sex],[t.EnumMRZData.Nationality]:u[t.EnumMRZData.Nationality],[t.EnumMRZData.DocumentNumber]:u[t.EnumMRZData.DocumentNumber],[t.EnumMRZData.DateOfExpiry]:c,[t.EnumMRZData.IssuingState]:u[t.EnumMRZData.IssuingState],[t.EnumMRZData.DocumentType]:to(o),[t.EnumMRZData.MRZText]:e}}const ho={[t.EnumMRZDocumentType.TD1]:{width:85.6,height:53.98},[t.EnumMRZDocumentType.TD2]:{width:105,height:74},[t.EnumMRZDocumentType.Passport]:{width:125,height:88}};class co{showScannerLoadingOverlay(t){const e=Ka(this.config.container);this.loadingScreen=io(e,{message:t}),e.style.display="block",e.style.position="relative"}hideScannerLoadingOverlay(t=!1){this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,t&&(Ka(this.config.container).style.display="none"))}constructor(e,i){this.resources=e,this.config=i,this.isSoundFeedbackOn=!1,this.scanModeManager={[t.EnumMRZDocumentType.Passport]:!0,[t.EnumMRZDocumentType.TD1]:!0,[t.EnumMRZDocumentType.TD2]:!0},this.currentScanMode=t.EnumMRZScanMode.All,this.resizeTimer=null,this.capturedResultItems=[],this.originalImageData=null,this.initialized=!1,this.initializedDCE=!1,this.DCE_ELEMENTS={selectCameraBtn:null,uploadImageBtn:null,soundFeedbackBtn:null,closeScannerBtn:null,scanModeSelectContainer:null,passportModeOption:null,td1ModeOption:null,td2ModeOption:null,toast:null},this.loadingScreen=null,this.handleResize=()=>{this.toggleScanGuide(!1),this.resizeTimer&&window.clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout((()=>{this.toggleScanGuide(!0)}),500)}}async initialize(){if(!this.initialized){this.initializeScanModeManager(),this.currentScanMode=this.getScanMode(),$a("dynamsoft-mrz-loading-screen-style",no);try{const{cameraView:t,cameraEnhancer:e,cvRouter:i}=this.resources;if(t.setScanRegionMaskStyle({strokeStyle:"transparent",fillStyle:"transparent",lineWidth:0}),t.setVideoFit("cover"),i.setInput(e),await i.initSettings(this.config.templateFilePath),!0===this.config.enableMultiFrameCrossFilter){const t=new Ya;t.enableResultCrossVerification(mt.CRIT_TEXT_LINE,!0),t.enableResultDeduplication(mt.CRIT_TEXT_LINE,!0),await i.addResultFilter(t)}const n=new Pe;n.onCapturedResultReceived=t=>this.handleMRZResult(t),await i.addResultReceiver(n),this.toggleSoundFeedback(!1),!1===this.config.showScanGuide&&this.toggleScanGuide(!1),this.initialized=!0}catch(e){let i=(null==e?void 0:e.message)||e;console.error(i),alert(i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:"Dynamsoft MRZ Scanner initialize error"}};this.currentScanResolver(n)}}}initializeElements(){const t=Ka(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))throw new Error("Shadow root not found");this.DCE_ELEMENTS={selectCameraBtn:e.shadowRoot.querySelector(".dce-mn-select-camera-icon"),uploadImageBtn:e.shadowRoot.querySelector(".dce-mn-upload-image-icon"),soundFeedbackBtn:e.shadowRoot.querySelector(".dce-mn-sound-feedback"),closeScannerBtn:e.shadowRoot.querySelector(".dce-mn-close"),scanModeSelectContainer:e.shadowRoot.querySelector(".dce-mn-scan-mode-select"),passportModeOption:e.shadowRoot.querySelector(".scan-mode-option-passport"),td1ModeOption:e.shadowRoot.querySelector(".scan-mode-option-td1"),td2ModeOption:e.shadowRoot.querySelector(".scan-mode-option-td2"),toast:e.shadowRoot.querySelector(".dce-mn-toast")},this.setupScanModeSelector(),this.assignDCEClickEvents(),this.DCE_ELEMENTS.toast.style.display="none",!1===this.config.showUploadImage&&(this.DCE_ELEMENTS.uploadImageBtn.style.display="none"),!1===this.config.showSoundToggle&&(this.DCE_ELEMENTS.soundFeedbackBtn.style.display="none"),this.initializedDCE=!0}setupScanModeSelector(){if(!1!==this.config.showFormatSelector)switch(this.currentScanMode){case t.EnumMRZScanMode.PassportAndTD1:this.DCE_ELEMENTS.td2ModeOption.style.display="none";break;case t.EnumMRZScanMode.PassportAndTD2:this.DCE_ELEMENTS.td1ModeOption.style.display="none";break;case t.EnumMRZScanMode.TD1AndTD2:this.DCE_ELEMENTS.passportModeOption.style.display="none";break;case t.EnumMRZScanMode.All:break;default:this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}else this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}assignDCEClickEvents(){if(!Object.values(this.DCE_ELEMENTS).every(Boolean))throw new Error("Camera control elements not found");this.closeCamera=this.closeCamera.bind(this),this.DCE_ELEMENTS.uploadImageBtn.onclick=()=>this.uploadImage(),this.DCE_ELEMENTS.soundFeedbackBtn.onclick=()=>this.toggleSoundFeedback(),this.DCE_ELEMENTS.closeScannerBtn.onclick=()=>this.handleCloseBtn(),this.DCE_ELEMENTS.selectCameraBtn.onclick=t=>{t.stopPropagation(),this.toggleSelectCameraBox()},this.DCE_ELEMENTS.passportModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.passportModeOption.style.display&&await this.toggleScanDocType(t.EnumMRZDocumentType.Passport)},this.DCE_ELEMENTS.td1ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td1ModeOption.style.display&&await this.toggleScanDocType(t.EnumMRZDocumentType.TD1)},this.DCE_ELEMENTS.td2ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td2ModeOption.style.display&&await this.toggleScanDocType(t.EnumMRZDocumentType.TD2)}}handleCloseBtn(){this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:t.EnumResultStatus.RS_CANCELLED,message:"Cancelled"}})}attachOptionClickListeners(){const t=Ka(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))return;const i=e.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings");[...e.shadowRoot.querySelectorAll(".dce-mn-camera-option"),...e.shadowRoot.querySelectorAll(".dce-mn-resolution-option")].forEach((t=>{t.addEventListener("click",(async e=>{const n=t.getAttribute("data-davice-id"),r=t.getAttribute("data-height"),s=t.getAttribute("data-width");n?this.resources.cameraEnhancer.selectCamera(n).then((()=>{this.toggleScanGuide()})):r&&s&&this.resources.cameraEnhancer.setResolution({width:parseInt(s),height:parseInt(r)}).then((()=>{this.toggleScanGuide()})),"none"!==i.style.display&&this.toggleSelectCameraBox()}))}))}highlightCameraAndResolutionOption(){const t=Ka(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))return;const i=e.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings"),n=i.querySelectorAll(".dce-mn-camera-option"),r=i.querySelectorAll(".dce-mn-resolution-option"),s=this.resources.cameraEnhancer.getSelectedCamera(),a=this.resources.cameraEnhancer.getResolution();n.forEach((t=>{const e=t;e.getAttribute("data-davice-id")===(null==s?void 0:s.deviceId)?e.style.border="2px solid #fe814a":e.style.border="none"}));const o={"480p":"480","720p":"720","1080p":"1080","2k":"1440","4k":"2160"},l=function(t){const e=t.width*t.height,i=t.width/t.height;let n="480p",r=Number.MAX_VALUE;for(const[t,s]of Object.entries(eo)){const a=s.width*s.height,o=s.width/s.height,l=.7*Math.abs(a-e)+Math.abs(o-i)*a*.3;l{const e=t,i=e.getAttribute("data-height");e.style.border=i===o[l]?"2px solid #fe814a":"none"}))}toggleSelectCameraBox(){const t=Ka(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))return;const i=e.shadowRoot.querySelector(".dce-mn-resolution-box");this.highlightCameraAndResolutionOption(),this.attachOptionClickListeners(),i.click()}async uploadImage(){var e,i,n;const{cvRouter:r}=this.resources,s=document.createElement("input");s.type="file",s.accept="image/*",s.style.display="none",document.body.appendChild(s);try{this.showScannerLoadingOverlay("Processing image..."),await this.closeCamera(!1);const a=await new Promise(((t,e)=>{s.onchange=i=>{var n;const r=null===(n=i.target.files)||void 0===n?void 0:n[0];(null==r?void 0:r.type.startsWith("image/"))?t(r):e(new Error("Please select an image file"))},s.addEventListener("cancel",(async()=>{this.hideScannerLoadingOverlay(!1),await this.launch()})),s.click()}));if(!a)return this.hideScannerLoadingOverlay(!1),void await this.launch();const o=this.config.utilizedTemplateNames[this.currentScanMode];if(!1!==this.config.showScanGuide){const t=await r.getSimplifiedSettings(o);t.roiMeasuredInPercentage=!0,t.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await r.updateSettings(o,t)}const l=await r.capture(a,o);this.capturedResultItems=l.items;const h=this.capturedResultItems.filter((t=>t.type===mt.CRIT_ORIGINAL_IMAGE))[0].imageData;h.toCanvas=()=>{const t=document.createElement("canvas");t.width=h.width,t.height=h.height;const e=t.getContext("2d");if(!e)throw new Error("Failed to get canvas context");const i=new ImageData(new Uint8ClampedArray(h.bytes.buffer),h.width,h.height);return e.putImageData(i,0,0),t},this.originalImageData=h;const c=null==l?void 0:l.textLineResultItems,u=null==l?void 0:l.parsedResultItems;let d={};if(null==c?void 0:c.length){const t=(null===(e=c[0])||void 0===e?void 0:e.text)||"";d=lo(t,u[0])}const f={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,_imageData:this.originalImageData,data:d};null===(n=(i=this.resources).onResultUpdated)||void 0===n||n.call(i,f),this.currentScanResolver(f),this.hideScannerLoadingOverlay(!0)}catch(e){let i=(null==e?void 0:e.message)||e;console.error(i),alert(i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:"Error processing uploaded image"}};this.currentScanResolver(n)}finally{document.body.removeChild(s)}}toggleSoundFeedback(t){this.isSoundFeedbackOn=void 0!==t?t:!this.isSoundFeedbackOn;const e=Ka(this.config.container),i=e.children[e.children.length-1];if(!(null==i?void 0:i.shadowRoot))return;const n=i.shadowRoot.querySelector(".dce-mn-sound-feedback"),r=n.querySelector(".dce-mn-sound-feedback-on");n.querySelector(".dce-mn-sound-feedback-off").style.display=this.isSoundFeedbackOn?"none":"block",r.style.display=this.isSoundFeedbackOn?"block":"none"}calculateScanRegion(t){const{cameraEnhancer:e,cameraView:i}=this.resources;if(!e||!e.isOpen())return;const n=i.getVisibleRegionOfVideo({inPixels:!0});if(!n)return;const r=i.getVideoElement(),s=r.videoWidth,a=r.videoHeight,o=ho[t];let l;const h=n.height-80;if(n.width>n.height){l=.75*h/o.height;l*o.width>.9*n.width&&(l=.9*n.width/o.width)}else{l=.9*n.width/o.width;l*o.height>.75*h&&(l=.75*h/o.height)}const c=l*o.width,u=l*o.height,d=(n.width-c)/2,f=(h-u)/2,g=d,m=d+c,p=f,_=f+u,v=(n.x+g)/s*100,y=(n.x+m)/s*100,w=(n.y+p)/a*100,E=(n.y+_)/a*100,C={left:Math.round(v),right:Math.round(y),top:Math.round(w),bottom:Math.round(E),isMeasuredInPercentage:!0};null==i||i.setScanRegionMaskVisible(!0),e.setScanRegion(C)}toggleScanGuide(e){const i=Ka(this.config.container),n=i.children[i.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const r=n.shadowRoot.querySelector(".dce-scanguide-passport"),s=n.shadowRoot.querySelector(".dce-scanguide-td1"),a=n.shadowRoot.querySelector(".dce-scanguide-td2");if(!1===e||!1===this.config.showScanGuide)return r.style.display="none",s.style.display="none",void(a.style.display="none");switch(this.currentScanMode){case t.EnumMRZScanMode.All:case t.EnumMRZScanMode.Passport:case t.EnumMRZScanMode.PassportAndTD1:case t.EnumMRZScanMode.PassportAndTD2:r.style.display="block",s.style.display="none",a.style.display="none",this.calculateScanRegion(t.EnumMRZDocumentType.Passport);break;case t.EnumMRZScanMode.TD1:case t.EnumMRZScanMode.TD1AndTD2:r.style.display="none",s.style.display="block",a.style.display="none",this.calculateScanRegion(t.EnumMRZDocumentType.TD1);break;case t.EnumMRZScanMode.TD2:r.style.display="none",s.style.display="none",a.style.display="block",this.calculateScanRegion(t.EnumMRZDocumentType.TD2)}}async openCamera(){try{this.showScannerLoadingOverlay("Initializing camera...");const{cameraEnhancer:t,cameraView:e}=this.resources,i=Ka(this.config.container);if(i.style.display="block",t.isOpen())t.isPaused()&&await t.resume();else{const n=e.getUIElement();n.parentElement||i.append(n),await t.open()}!this.initializedDCE&&t.isOpen()&&await this.initializeElements(),window.addEventListener("resize",this.handleResize);const n=i.children[i.children.length-1];if(!(null==n?void 0:n.shadowRoot))throw new Error("Shadow root not found");n.shadowRoot.querySelector(".dce-mn-torch-off").style.display="none",n.shadowRoot.querySelector(".dce-mn-torch-on").style.display="none"}catch(e){let i=(null==e?void 0:e.message)||e;console.error(i),alert(i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:"MRZ Scanner Open Camera Error"}};this.currentScanResolver(n)}finally{this.hideScannerLoadingOverlay()}}async closeCamera(t=!0){try{window.removeEventListener("resize",this.handleResize),this.resizeTimer&&(window.clearTimeout(this.resizeTimer),this.resizeTimer=null);const{cameraEnhancer:e,cameraView:i}=this.resources,n=Ka(this.config.container);n.style.display=t?"none":"block",(null==i?void 0:i.getUIElement().parentElement)&&n.removeChild(i.getUIElement()),e.close(),this.stopCapturing()}catch(t){let e=(null==t?void 0:t.message)||t;console.error(`Close Camera error: ${e}`)}}pauseCamera(){const{cameraEnhancer:t}=this.resources;t.pause()}stopCapturing(){const{cameraView:t,cvRouter:e}=this.resources;e.stopCapturing(),t.clearAllInnerDrawingItems()}async handleMRZResult(e){var i;if(this.capturedResultItems=e.items,!(e.items.length<=1))try{const{onResultUpdated:n}=this.resources,r=e.items.filter((t=>t.type===mt.CRIT_ORIGINAL_IMAGE));this.originalImageData=r.length&&r[0].imageData;const s=null==e?void 0:e.textLineResultItems,a=null==e?void 0:e.parsedResultItems;if(s){this.isSoundFeedbackOn&&bs.beep();const e=(null===(i=null==s?void 0:s[0])||void 0===i?void 0:i.text)||"",r=lo(e,a[0]);this.closeCamera();const o={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,_imageData:this.originalImageData,data:r};null==n||n(o),this.currentScanResolver(o)}}catch(e){let i=(null==e?void 0:e.message)||e;console.error(i),alert(i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:"Error capturing image"}};this.currentScanResolver(n)}}initializeScanModeManager(){const{mrzFormatType:e}=this.config;if(this.scanModeManager={[t.EnumMRZDocumentType.Passport]:!0,[t.EnumMRZDocumentType.TD1]:!0,[t.EnumMRZDocumentType.TD2]:!0},!e||Array.isArray(e)&&0===e.length)return;Object.keys(this.scanModeManager).forEach((t=>{this.scanModeManager[t]=!1}));(Array.isArray(e)?e:[e]).forEach((t=>{this.scanModeManager[t]=!0}))}getScanMode(){const e=Object.entries(this.scanModeManager).filter((([t,e])=>e)).map((([t])=>t)).sort().join(",");return{[t.EnumMRZDocumentType.Passport]:t.EnumMRZScanMode.Passport,[t.EnumMRZDocumentType.TD1]:t.EnumMRZScanMode.TD1,[t.EnumMRZDocumentType.TD2]:t.EnumMRZScanMode.TD2,[`${t.EnumMRZDocumentType.Passport},${t.EnumMRZDocumentType.TD1}`]:t.EnumMRZScanMode.PassportAndTD1,[`${t.EnumMRZDocumentType.Passport},${t.EnumMRZDocumentType.TD2}`]:t.EnumMRZScanMode.PassportAndTD2,[`${t.EnumMRZDocumentType.TD1},${t.EnumMRZDocumentType.TD2}`]:t.EnumMRZScanMode.TD1AndTD2,[`${t.EnumMRZDocumentType.Passport},${t.EnumMRZDocumentType.TD1},${t.EnumMRZDocumentType.TD2}`]:t.EnumMRZScanMode.All,"":t.EnumMRZScanMode.All}[e]}DCEShowToast(t,e=3e3){this.DCE_ELEMENTS.toast&&(this.DCE_ELEMENTS.toast.textContent=t,this.DCE_ELEMENTS.toast.style.display="",setTimeout((()=>{this.DCE_ELEMENTS.toast.style.display="none"}),e))}async startCapturing(){const{cvRouter:e,cameraEnhancer:i}=this.resources,n=this.config.utilizedTemplateNames[this.currentScanMode];try{if(!1!==this.config.showScanGuide){const t=await e.getSimplifiedSettings(n);t.roiMeasuredInPercentage=!0,t.roi.points=[{x:0,y:50},{x:100,y:50},{x:100,y:100},{x:0,y:100}],await e.updateSettings(n,t)}await e.startCapturing(n),i.setPixelFormat(l.IPF_ABGR_8888)}catch(e){let i=(null==e?void 0:e.message)||e;console.error("Failed to start capturing:",i),this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:t.EnumResultStatus.RS_FAILED,message:"Failed to start capturing"}})}}async toggleScanDocType(e){try{if(this.scanModeManager[e]&&0===Object.entries(this.scanModeManager).filter((([t,i])=>i&&t!==e)).length)return console.warn("MRZ Scanner - At least one mode must be enabled"),void this.DCEShowToast("At least one mode must be enabled");this.scanModeManager[e]=!this.scanModeManager[e],this.currentScanMode=this.getScanMode(),this.stopCapturing(),await this.startCapturing(),this.toggleScanGuide(),this.DCE_ELEMENTS.td1ModeOption.classList.toggle("selected",this.scanModeManager[t.EnumMRZDocumentType.TD1]),this.DCE_ELEMENTS.td2ModeOption.classList.toggle("selected",this.scanModeManager[t.EnumMRZDocumentType.TD2]),this.DCE_ELEMENTS.passportModeOption.classList.toggle("selected",this.scanModeManager[t.EnumMRZDocumentType.Passport])}catch(e){let i=(null==e?void 0:e.message)||e;console.error("MRZ Scanner switch scan mode error: ",i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:"MRZ Scanner switch scan mode error"}};this.currentScanResolver(n)}}async launch(){try{await this.initialize();const{cvRouter:t,cameraEnhancer:e}=this.resources;return new Promise((async t=>{this.currentScanResolver=t,await this.openCamera(),!this.initializedDCE&&e.isOpen()&&await this.initializeElements(),await this.startCapturing(),this.toggleScanGuide()}))}catch(e){let i=(null==e?void 0:e.message)||e;console.error("MRZ Scanner launch error: ",i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:"MRZ Scanner launch error"}};this.currentScanResolver(n)}}}const uo={rescan:'\n\n\n \n\n\n\n\n\n\n\n',complete:'\n\n\n\n \n\n\n\n\n\n\n\n',failed:'\n \n \n \n\n',info:'\n\n \n \n \n\n'};class fo{constructor(t,e,i){this.resources=t,this.config=e,this.scannerView=i,this.editedFields={}}async launch(){try{return Ka(this.config.container).textContent="",await this.initialize(),Ka(this.config.container).style.display="flex",new Promise((t=>{this.currentScanResultViewResolver=t}))}catch(t){let e=(null==t?void 0:t.message)||t;throw console.error(e),e}}async handleRescan(){var e;try{if(!this.scannerView)return void console.error("Scanner View not initialized");this.hideView();const i=await this.scannerView.launch();if((null===(e=null==i?void 0:i.status)||void 0===e?void 0:e.code)===t.EnumResultStatus.RS_FAILED)return void(this.currentScanResultViewResolver&&this.currentScanResultViewResolver(i));this.resources.onResultUpdated&&((null==i?void 0:i.status.code)===t.EnumResultStatus.RS_CANCELLED?this.resources.onResultUpdated(this.resources.result):(null==i?void 0:i.status.code)===t.EnumResultStatus.RS_SUCCESS&&this.resources.onResultUpdated(i)),this.dispose(!0),await this.initialize(),Ka(this.config.container).style.display="flex"}catch(e){throw console.error("Error in rescan handler:",e),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:t.EnumResultStatus.RS_FAILED,message:(null==e?void 0:e.message)||e}}),e}}async handleDone(){var e,i;try{(null===(e=this.resources.result)||void 0===e?void 0:e.data)&&!Qa(this.editedFields)&&(this.resources.result.data=Object.assign(Object.assign({},this.resources.result.data),this.editedFields),this.resources.onResultUpdated&&this.resources.onResultUpdated(this.resources.result)),(null===(i=this.config)||void 0===i?void 0:i.onDone)&&await this.config.onDone(this.resources.result),this.currentScanResultViewResolver&&this.resources.result&&this.currentScanResultViewResolver(this.resources.result),this.hideView(),this.dispose()}catch(e){throw console.error("Error in done handler:",e),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:t.EnumResultStatus.RS_FAILED,message:(null==e?void 0:e.message)||e}}),e}}createControls(){var t,e,i,n,r,s,a,o;const{toolbarButtonsConfig:l}=this.config;return function(t){$a("dynamsoft-mrz-controls-style","\n .dynamsoft-mrz-controls {\n display: flex;\n height: 6rem;\n background-color: #323234;\n align-items: center;\n font-size: 12px;\n font-family: Verdana;\n color: white;\n width: 100%;\n }\n\n .dynamsoft-mrz-control-btn {\n background-color: #323234;\n color: white;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n height: 100%;\n width: 100%;\n gap: 0.5rem;\n text-align: center;\n user-select: none;\n }\n\n .dynamsoft-mrz-control-btn.hide {\n display: none;\n }\n\n .dynamsoft-mrz-control-btn.disabled {\n opacity: 0.4;\n pointer-events: none;\n cursor: default;\n }\n\n .dynamsoft-mrz-control-icon-wrapper {\n flex: 0.75;\n display: flex;\n align-items: flex-end;\n justify-content: center;\n min-height: 40px;\n }\n\n .dynamsoft-mrz-control-icon img,\n .dynamsoft-mrz-control-icon svg {\n width: 32px;\n height: 32px;\n fill: #fe8e14;\n }\n\n .dynamsoft-mrz-control-text {\n flex: 0.5;\n display: flex;\n align-items: flex-start;\n justify-content: center;\n padding-bottom: 0.5rem;\n }\n\n \n @media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-controls {\n flex-direction: column;\n height: 100%;\n width: 5rem;\n }\n\n .dynamsoft-mrz-control-text {\n padding: 0 0.5rem 0.5rem;\n }\n }\n");const e=document.createElement("div");return e.className="dynamsoft-mrz-controls",t.forEach((t=>{const i=document.createElement("div");i.className=`dynamsoft-mrz-control-btn ${null==t?void 0:t.className}`;const n=document.createElement("div");if(n.className="dynamsoft-mrz-control-icon-wrapper",(r=t.icon).trim().startsWith(""))n.innerHTML=t.icon;else{const e=document.createElement("img");e.src=t.icon,e.alt=t.label,e.width=24,e.height=24,n.appendChild(e)}var r;const s=document.createElement("div");s.className="dynamsoft-mrz-control-text",s.textContent=t.label,t.isDisabled&&i.classList.add("disabled"),t.isHidden&&i.classList.add("hide"),i.appendChild(n),i.appendChild(s),t.onClick&&!t.isDisabled&&i.addEventListener("click",t.onClick),e.appendChild(i)})),e}([{id:"dynamsoft-mrz-scanResult-rescan",icon:(null===(t=null==l?void 0:l.rescan)||void 0===t?void 0:t.icon)||uo.rescan,label:(null===(e=null==l?void 0:l.rescan)||void 0===e?void 0:e.label)||"Re-scan",onClick:()=>this.handleRescan(),className:`${(null===(i=null==l?void 0:l.rescan)||void 0===i?void 0:i.className)||""}`,isHidden:(null===(n=null==l?void 0:l.rescan)||void 0===n?void 0:n.isHidden)||!1,isDisabled:!this.scannerView},{id:"dynamsoft-mrz-scanResult-done",icon:(null===(r=null==l?void 0:l.done)||void 0===r?void 0:r.icon)||uo.complete,label:(null===(s=null==l?void 0:l.done)||void 0===s?void 0:s.label)||"Done",className:`${(null===(a=null==l?void 0:l.done)||void 0===a?void 0:a.className)||""}`,isHidden:(null===(o=null==l?void 0:l.done)||void 0===o?void 0:o.isHidden)||!1,onClick:()=>this.handleDone()}])}handleFieldEdit(e,i){if(e===t.EnumMRZData.DateOfBirth||e===t.EnumMRZData.DateOfExpiry)try{const[t,n,r]=i.split(/[\/\-\.]/);r&&n&&t&&(this.editedFields[e]={day:parseInt(r,10),month:parseInt(n,10),year:parseInt(t,10)})}catch(t){console.error("Error parsing date",t)}else this.editedFields[e]=i}createMRZDataDisplay(){var e;const i=(null===(e=this.resources.result)||void 0===e?void 0:e.data)||{},n=!!this.config.allowResultEditing,r=i.invalidFields||[],s=document.createElement("div");if(s.className="dynamsoft-mrz-data-container",Qa(i)){const t=document.createElement("div");return t.className="dynamsoft-mrz-data-row empty",t.innerText="No MRZ detected. Please try again.",s.appendChild(t),s}if(r.length>0){const t=document.createElement("div");t.className="dynamsoft-mrz-error-notification",t.innerHTML=`\n
${uo.failed}
\n
\n ${n?"Some fields require correction. Please review highlighted fields.":"Some fields contain invalid information. Please rescan the document."}\n
\n `,s.appendChild(t)}else if(0===r.length&&n){const t=document.createElement("div");t.className="dynamsoft-mrz-info-notification",t.innerHTML=`\n
${uo.info}
\n
\n Please review all fields to ensure the information is correct.\n
\n `,s.appendChild(t)}return Object.entries(i).forEach((([e,i])=>{var a;if(e===t.EnumMRZData.InvalidFields||!i)return;if(e===t.EnumMRZData.MRZText&&!1===(null===(a=this.config)||void 0===a?void 0:a.showMRZText))return;const o=document.createElement("div");o.className="dynamsoft-mrz-data-row";const l=r.includes(e);l&&o.classList.add("invalid-field");const h=[t.EnumMRZData.MRZText,t.EnumMRZData.DocumentType],c=document.createElement("span");if(c.className="dynamsoft-mrz-data-label",c.innerText=so[e]||e,l){const t=document.createElement("span");if(t.className="dynamsoft-mrz-error-icon",t.innerHTML=uo.failed,c.appendChild(t),n){const t=document.createElement("span");t.className="dynamsoft-mrz-error-hint",t.textContent="Please correct this field",c.appendChild(t)}}const u=document.createElement("div");if(u.className="dynamsoft-mrz-data-value",n&&!h.includes(e)){const n=document.createElement("input");n.className="dynamsoft-mrz-data-input",l&&n.classList.add("invalid"),e===t.EnumMRZData.DateOfBirth||e===t.EnumMRZData.DateOfExpiry?(n.value=oo(i),n.setAttribute("placeholder","YYYY-MM-DD")):n.value=i,n.addEventListener("input",(t=>{if(this.handleFieldEdit(e,t.target.value),l){n.classList.remove("invalid"),o.classList.remove("invalid-field"),this.editedFields.invalidFields||(this.editedFields.invalidFields=[...r]);const t=this.editedFields.invalidFields.indexOf(e);t>-1&&this.editedFields.invalidFields.splice(t,1)}})),u.appendChild(n)}else e===t.EnumMRZData.MRZText?(u.classList.add("code"),u.innerText=i):e===t.EnumMRZData.DateOfBirth||e===t.EnumMRZData.DateOfExpiry?u.innerText=oo(i):u.innerText=i,l&&u.classList.add("invalid-value");o.appendChild(c),o.appendChild(u),s.appendChild(o)})),s}async initialize(){try{if(!this.resources.result)throw Error("Captured image is missing. Please capture an image first!");if(!this.config.container)throw new Error("Please create a Scan Result View Container element");$a("dynamsoft-mrz-result-view-style",go);const t=document.createElement("div");if(t.className="dynamsoft-mrz-result-view-container",!1!==this.config.showOriginalImage){const e=this.resources.result.originalImageResult,i=document.createElement("div");let n;i.className="dynamsoft-mrz-result-view-image-container",(null==e?void 0:e.toCanvas)&&(n=null==e?void 0:e.toCanvas()),Object.assign(n.style,{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}),i.appendChild(n),t.appendChild(i)}const e=this.createMRZDataDisplay();t.appendChild(e);const i=this.createControls();t.appendChild(i),Ka(this.config.container).appendChild(t)}catch(t){let e=(null==t?void 0:t.message)||t;console.error(e),alert(e)}}hideView(){Ka(this.config.container).style.display="none"}dispose(t=!1){Ka(this.config.container).textContent="",t||(this.currentScanResultViewResolver=void 0)}}const go="\n .dynamsoft-mrz-result-view-container {\n display: flex;\n width: 100%;\n height: 100%;\n background-color:#575757;\n font-size: 12px;\n flex-direction: column;\n align-items: center;\n }\n\n .dynamsoft-mrz-result-view-image-container {\n width: 100%;\n height: 200px;\n display: flex;\n justify-content: center;\n align-items: center;\n background-color: #323234;\n }\n\n \n.dynamsoft-mrz-data-container {\n font-size: 16px;\n font-family: Verdana;\n color: white;\n overflow: auto;\n width: 100%;\n height: 100%;\n min-height: 0;\n margin: 1rem 0;\n}\n\n.dynamsoft-mrz-data-row {\n padding: 0.5rem 2rem;\n display: flex;\n flex-direction: column;\n gap: 0.5rem;\n transition: background-color 0.3s ease;\n}\n\n.dynamsoft-mrz-data-row.invalid-field {\n background-color: rgba(231, 76, 60, 0.1);\n border-left: 3px solid #e74c3c;\n padding-left: calc(2rem - 3px);\n}\n\n.dynamsoft-mrz-data-label {\n color: #aaa;\n display: flex;\n gap: 0.5rem;\n align-items: end;\n flex-wrap: wrap;\n}\n\n.dynamsoft-mrz-error-notification,\n.dynamsoft-mrz-info-notification {\n color: white;\n padding: 1rem;\n margin: 0.5rem 2rem;\n border-radius: 4px;\n display: flex;\n align-items: center;\n gap: 1rem;\n text-align: start;\n}\n\n.dynamsoft-mrz-error-notification {\n background-color: rgba(231, 76, 60, 0.2);\n}\n\n.dynamsoft-mrz-info-notification {\n background-color: rgba(196, 231, 60, 0.2);\n}\n\n.dynamsoft-mrz-edit-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #aaa;\n}\n\n.dynamsoft-mrz-error-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-info-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: white;\n}\n\n.dynamsoft-mrz-info-message,\n.dynamsoft-mrz-error-message {\n flex: 1;\n}\n\n.dynamsoft-mrz-error-hint {\n font-size: 0.8rem;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-value {\n word-wrap: break-word;\n text-align: start;\n}\n\n.dynamsoft-mrz-data-value.code {\n font-family: monospace;\n}\n\n.dynamsoft-mrz-data-value.invalid-value {\n color: #e74c3c;\n text-decoration: wavy underline #e74c3c;\n text-decoration-skip-ink: none;\n}\n\n.dynamsoft-mrz-data-input {\n width: 100%;\n padding: 5px;\n background-color: rgba(255, 255, 255, 0.1);\n border: 1px solid rgba(255, 255, 255, 0.3);\n color: white;\n border-radius: 4px;\n font-size: 14px;\n transition: all 0.3s ease;\n}\n\n.dynamsoft-mrz-data-input.invalid {\n background-color: rgba(231, 76, 60, 0.1);\n border-color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-input:focus {\n background-color: rgba(255, 255, 255, 0.2);\n border-color: #fe8e14;\n outline: none;\n}\n\n@media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-result-view-container {\n flex-direction: row;\n }\n\n .dynamsoft-mrz-result-view-image-container{\n flex: 1;\n height: 100%;\n }\n\n .dynamsoft-mrz-data-container{\n flex: 1;\n }\n\n .dynamsoft-mrz-data-row:first-of-type {\n padding-top: 2rem;\n }\n\n .dynamsoft-mrz-data-row:last-of-type {\n padding-bottom: 2rem;\n }\n\n .dynamsoft-mrz-data-row.empty {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n padding-top: 0;\n padding-bottom: 0;\n }\n}\n",mo={rootDirectory:"https://cdn.jsdelivr.net/npm/"};class po{showLoadingOverlay(t){var e,i;const n=Ka(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)||Ka(null===(i=this.config.resultViewConfig)||void 0===i?void 0:i.container);this.loadingScreen=io(n,{message:t}),n.style.display="block",n.style.position="relative"}hideLoadingOverlay(t=!1){var e,i,n;const r=Ka(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)||Ka(null===(i=this.config.resultViewConfig)||void 0===i?void 0:i.container);this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,t&&(r.style.display="none",(null===(n=this.config)||void 0===n?void 0:n.container)&&(Ka(this.config.container).style.display="none")))}constructor(t){this.config=t,this.resources={},this.isInitialized=!1,this.isCapturing=!1,this.loadingScreen=null}async initialize(){if(this.isInitialized)return{resources:this.resources,components:{scannerView:this.scannerView,resultView:this.resultView}};try{if(!this.initializeMRZScannerConfig())return console.error("Failed to initialize mrz scanner config"),{resources:this.resources,components:{}};$a("dynamsoft-mrz-loading-screen-style",no),this.showLoadingOverlay("Loading...");if(!await this.initializeDCVResources())return this.hideLoadingOverlay(!0),console.error("Failed to initialize DCV resources"),{resources:this.resources,components:{}};this.resources.onResultUpdated=t=>{this.resources.result=t};const t={};return this.config.scannerViewConfig&&(this.scannerView=new co(this.resources,this.config.scannerViewConfig),t.scannerView=this.scannerView,await this.scannerView.initialize()),this.config.resultViewConfig&&(this.resultView=new fo(this.resources,this.config.resultViewConfig,this.scannerView),t.resultView=this.resultView),this.isInitialized=!0,{resources:this.resources,components:t}}catch(t){this.isInitialized=!1;const e=`Initialization Failed: ${(null==t?void 0:t.message)||t}`;return alert(e),console.error(e),{resources:this.resources,components:{}}}finally{this.hideLoadingOverlay(!0)}}async initializeDCVResources(){var t,e,i;try{return Zt.initLicense((null===(t=this.config)||void 0===t?void 0:t.license)||"",!0),gt.engineResourcePaths=Qa(null===(e=this.config)||void 0===e?void 0:e.engineResourcePaths)?mo:this.config.engineResourcePaths,gt.loadWasm(["DLR","DCP"]),ta.loadSpec("MRTD_TD3_PASSPORT"),ta.loadSpec("MRTD_TD1_ID"),ta.loadSpec("MRTD_TD2_ID"),ca.loadRecognitionData("MRZ"),this.resources.cameraView=await An.createInstance(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.cameraEnhancerUIPath),this.resources.cameraEnhancer=await Rs.createInstance(this.resources.cameraView),this.resources.cvRouter=await Ae.createInstance(),!0}catch(t){let e=(null==t?void 0:t.message)||t;if(null==e?void 0:e.toLowerCase().includes("license")){const t="The MRZ Scanner license is invalid or has expired. Please contact the site administrator to resolve this issue.";alert(t),console.error(t)}else{const t=`Resource Initialization Failed: ${e}`;alert(t),console.error(t)}return!1}}shouldCreateDefaultContainer(){var t,e;const i=!this.config.container,n=!((null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)||(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container));return i&&n}createDefaultMRZScannerContainer(){const t=document.createElement("div");return t.className="mrz-scanner-main-container",Object.assign(t.style,{height:"100dvh",width:"100%",position:"absolute",left:"0",top:"0",zIndex:"999"}),document.body.append(t),t}checkForTemporaryLicense(t){return!(null==t?void 0:t.length)||(null==t?void 0:t.startsWith("A"))||(null==t?void 0:t.startsWith("L"))||(null==t?void 0:t.startsWith("P"))||(null==t?void 0:t.startsWith("Y"))?"DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9":t}validateViewConfigs(){var t,e,i,n,r,s,a,o;if(!this.config.container){if((null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)&&this.config.showResultView&&!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container)){const t="MRZResultView container is required when showResultView is true";return alert(t),console.error(t),!1}if(!(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.container)&&(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container)&&!this.resources.result){const t="Result is needed to create MRZResultView without a scanner view";return alert(t),console.error(t),!1}}try{if(this.config.container&&!Ka(this.config.container)){const t="Invalid main container reference";return alert(t),console.error(t),!1}if((null===(r=this.config.scannerViewConfig)||void 0===r?void 0:r.container)&&!Ka(null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.container)){const t="Invalid scanner view container reference";return alert(t),console.error(t),!1}if((null===(a=this.config.resultViewConfig)||void 0===a?void 0:a.container)&&!Ka(null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)){const t="Invalid result view container reference";return alert(t),console.error(t),!1}}catch(t){const e=`Error accessing container references: ${t.message}`;return alert(e),console.error(e),!1}return!0}showResultView(){var t,e;return!1!==this.config.showResultView&&(this.config.container?!(void 0!==this.config.showResultView||!(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container)&&!this.config.container)||!!this.config.showResultView:this.config.showResultView&&!!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container))}initializeMRZScannerConfig(){var e,i,n,r,s,a,o;this.config=null!==(e=this.config)&&void 0!==e?e:{};if(!this.validateViewConfigs())return!1;this.shouldCreateDefaultContainer()?this.config.container=this.createDefaultMRZScannerContainer():this.config.container&&(this.config.container=Ka(this.config.container));const l=this.config.container?this.createViewContainers(Ka(this.config.container)):{},h={license:this.checkForTemporaryLicense(this.config.license),utilizedTemplateNames:Object.fromEntries(Object.values(t.EnumMRZScanMode).map((t=>{var e;return[t,(null===(e=this.config.utilizedTemplateNames)||void 0===e?void 0:e[t])||qa[t]]}))),templateFilePath:(null===(i=this.config)||void 0===i?void 0:i.templateFilePath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.0.0/dist/mrz-scanner.template.json"},c=Object.assign(Object.assign({},this.config.scannerViewConfig),{container:l[t.EnumMRZScannerViews.Scanner]||Ka(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)||null,cameraEnhancerUIPath:(null===(r=this.config.scannerViewConfig)||void 0===r?void 0:r.cameraEnhancerUIPath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.0.0/dist/mrz-scanner.ui.html",templateFilePath:h.templateFilePath,utilizedTemplateNames:h.utilizedTemplateNames,enableMultiFrameCrossFilter:null===(a=null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.enableMultiFrameCrossFilter)||void 0===a||a,mrzFormatType:this.config.mrzFormatType}),u=this.showResultView()?Object.assign(Object.assign({},this.config.resultViewConfig),{container:l[t.EnumMRZScannerViews.Result]||Ka(null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)||null}):void 0;return Object.assign(this.config,Object.assign(Object.assign({},h),{scannerViewConfig:c,resultViewConfig:u})),!0}createViewContainers(e){e.textContent="";const i=[t.EnumMRZScannerViews.Scanner];return this.showResultView()&&i.push(t.EnumMRZScannerViews.Result),i.reduce(((t,i)=>{const n=document.createElement("div");return n.className=`mrz-scanner-${i}-view-container`,Object.assign(n.style,{height:"100%",width:"100%",display:"none",position:"relative"}),e.append(n),t[i]=n,t}),{})}dispose(){var t,e;this.resultView&&(this.resultView.dispose(),this.resultView=null),this.scannerView=null,this.resources.cameraEnhancer&&(this.resources.cameraEnhancer.dispose(),this.resources.cameraEnhancer=null),this.resources.cameraView&&(this.resources.cameraView.dispose(),this.resources.cameraView=null),this.resources.cvRouter&&(this.resources.cvRouter.dispose(),this.resources.cvRouter=null),this.resources.result=null,this.resources.onResultUpdated=null;const i=t=>{const e=Ka(t);e&&(e.style.display="none",e.textContent="")};i(this.config.container),i(null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container),i(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container),this.isInitialized=!1}async launch(){if(this.isCapturing)throw new Error("Capture session already in progress");try{this.isCapturing=!0;const{components:e}=await this.initialize();if(Qa(e))throw new Error("MRZ Scanner initialization failed.");if(this.config.container&&(Ka(this.config.container).style.display="block"),!e.scannerView&&this.resources.result&&e.resultView)return await e.resultView.launch();if(!e.scannerView&&!this.resources.result)throw new Error("Scanner view is required when no previous result exists");if(e.scannerView){const i=await e.scannerView.launch();if((null==i?void 0:i.status.code)!==t.EnumResultStatus.RS_SUCCESS)return{status:{code:null==i?void 0:i.status.code,message:(null==i?void 0:i.status.message)||"Failed to capture image"}};if(e.resultView)return await e.resultView.launch()}return this.resources.result}catch(e){return alert((null==e?void 0:e.message)||e),console.error((null==e?void 0:e.message)||e),{status:{code:t.EnumResultStatus.RS_FAILED,message:(null==e?void 0:e.message)||e}}}finally{this.isCapturing=!1,this.dispose()}}}const _o={MRZScanner:po,MRZScannerView:co,MRZResultView:fo};t.CVR=Ne,t.Core=It,t.DCE=Us,t.DCP=ea,t.DEFAULT_TEMPLATE_NAMES=qa,t.DLR=fa,t.DynamsoftMRZScanner=_o,t.License=Jt,t.MRZDataLabel=so,t.MRZResultView=fo,t.MRZScanner=po,t.MRZScannerView=co,t.Utility=Za,t.displayMRZDate=oo})); +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Dynamsoft=t.Dynamsoft||{})}(this,(function(t){"use strict";const e=t=>t&&"object"==typeof t&&"function"==typeof t.then,i=(async()=>{})().constructor;class n extends i{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let n;this._task=t,e(t)?n=t:"function"==typeof t&&(n=new i(t)),n&&(async()=>{try{const e=await n;t===this._task&&this.resolve(e)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let i,n;super(((t,e)=>{i=t,n=e})),this._s="pending",this.resolve=t=>{this.isPending&&(e(t)?this.task=t:(this._s="fulfilled",i(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",n(t))},this.task=t}}function r(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function s(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,i),i}var a,o,l;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(a||(a={})),function(t){t[t.CCUT_AUTO=0]="CCUT_AUTO",t[t.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",t[t.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",t[t.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",t[t.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",t[t.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(o||(o={})),function(t){t[t.IPF_BINARY=0]="IPF_BINARY",t[t.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",t[t.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",t[t.IPF_NV21=3]="IPF_NV21",t[t.IPF_RGB_565=4]="IPF_RGB_565",t[t.IPF_RGB_555=5]="IPF_RGB_555",t[t.IPF_RGB_888=6]="IPF_RGB_888",t[t.IPF_ARGB_8888=7]="IPF_ARGB_8888",t[t.IPF_RGB_161616=8]="IPF_RGB_161616",t[t.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",t[t.IPF_ABGR_8888=10]="IPF_ABGR_8888",t[t.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",t[t.IPF_BGR_888=12]="IPF_BGR_888",t[t.IPF_BINARY_8=13]="IPF_BINARY_8",t[t.IPF_NV12=14]="IPF_NV12",t[t.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(l||(l={}));const h="undefined"==typeof self,c="function"==typeof importScripts,u=(()=>{if(!c){if(!h&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),d=t=>{if(null==t&&(t="./"),h||c);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},f=t=>Object.prototype.toString.call(t),g=t=>Array.isArray?Array.isArray(t):"[object Array]"===f(t),m=t=>"[object Boolean]"===f(t),p=t=>"number"==typeof t&&!Number.isNaN(t),_=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),v=t=>!(!_(t)||!p(t.width)||t.width<=0||!p(t.height)||t.height<=0||!p(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!E(t.tag)),y=t=>!!v(t)&&t.bytes instanceof Uint8Array,w=t=>!(!_(t)||!p(t.left)||t.left<0||!p(t.top)||t.top<0||!p(t.right)||t.right<0||!p(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom||!m(t.isMeasuredInPercentage)),E=t=>null===t||!!_(t)&&!!p(t.imageId)&&"type"in t,C=t=>!(!_(t)||!S(t.startPoint)||!S(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),S=t=>!!_(t)&&!!p(t.x)&&!!p(t.y),T=t=>!!_(t)&&!!g(t.points)&&0!=t.points.length&&!t.points.some((t=>!S(t))),b=t=>!!_(t)&&!!g(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some((t=>!S(t))),I=t=>!(!_(t)||!p(t.x)||!p(t.y)||!p(t.width)||t.width<0||!p(t.height)||t.height<0||"isMeasuredInPercentage"in t&&!m(t.isMeasuredInPercentage)),x=async(t,e)=>await new Promise(((i,n)=>{let r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType=e,r.send(),r.onloadend=async()=>{r.status<200||r.status>=300?n(new Error(t+" "+r.status)):i(r.response)},r.onerror=()=>{n(new Error("Network Error: "+r.statusText))}})),R=(t,e)=>{let i=t.split("."),n=e.split(".");for(let t=0;t{const e={},i={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcpd:"dynamsoft-code-parser",dlrData:"dynamsoft-label-recognizer-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer"};for(let n in t){if("rootDirectory"===n)continue;let r=n,s=t[r],a=s&&"object"==typeof s&&s.path?s.path:s,o=t.rootDirectory;if(o&&!o.endsWith("/")&&(o+="/"),"object"==typeof s&&s.isInternal)o&&(a=t[r].version?`${o}${i[r]}@${t[r].version}/dist/${"ddv"===r?"engine":""}`:`${o}${i[r]}/dist/${"ddv"===r?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof a&&(a=a.replace(i,o||"")),"object"==typeof a&&"dwt"===r){const n=t[r].resourcesPath,s=t[r].serviceInstallerLocation;e[r]={resourcesPath:n.replace(i,o||""),serviceInstallerLocation:s.replace(i,o||"")};continue}}e[r]=d(a)}return e},D=async(t,e,i)=>await new Promise((async(n,r)=>{try{const r=e.split(".");let s=r[r.length-1];const a=await L(`image/${s}`,t);r.length<=1&&(s="png");const o=new File([a],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(o),i=document.createElement("a");i.href=t,i.download=e,i.click()}return n(o)}catch(t){return r()}})),A=t=>{y(t)&&(t=M(t));const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},L=async(t,e)=>{y(e)&&(e=M(e));const i=A(e);return new Promise(((e,n)=>{i.toBlob((t=>e(t)),t)}))},M=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===l.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n=r)break;e[a]=e[a+1]=e[a+2]=(128&n)/128*255,e[a+3]=255,n<<=1}}}else if(Number(t.format)===l.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n=r)break;e[a]=e[a+1]=e[a+2]=128&n?0:255,e[a+3]=255,n<<=1}}}return new ImageData(e,t.width,t.height)};var F,P,k,N,B,V,j,U;let G,W,Y,z,H,X=class t{get _isFetchingStarted(){return r(this,B,"f")}constructor(){F.add(this),P.set(this,[]),k.set(this,1),N.set(this,a.BOPM_BLOCK),B.set(this,!1),V.set(this,void 0),j.set(this,o.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!y(t))throw new TypeError("Invalid 'image'.");if((null===(e=t.tag)||void 0===e?void 0:e.hasOwnProperty("imageId"))&&"number"==typeof t.tag.imageId&&this.hasImage(t.tag.imageId))throw new Error("Existed imageId.");if(r(this,P,"f").length>=r(this,k,"f"))switch(r(this,N,"f")){case a.BOPM_BLOCK:break;case a.BOPM_UPDATE:if(r(this,P,"f").push(t),_(r(this,V,"f"))&&p(r(this,V,"f").imageId)&&1==r(this,V,"f").keepInBuffer)for(;r(this,P,"f").length>r(this,k,"f");){const t=r(this,P,"f").findIndex((t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==r(this,V,"f").imageId}));r(this,P,"f").splice(t,1)}else r(this,P,"f").splice(0,r(this,P,"f").length-r(this,k,"f"))}else r(this,P,"f").push(t)}getImage(){if(0===r(this,P,"f").length)return null;let e;if(r(this,V,"f")&&p(r(this,V,"f").imageId)){const t=r(this,F,"m",U).call(this,r(this,V,"f").imageId);if(t<0)throw new Error(`Image with id ${r(this,V,"f").imageId} doesn't exist.`);e=r(this,P,"f").slice(t,t+1)[0]}else e=r(this,P,"f").pop();if([l.IPF_RGB_565,l.IPF_RGB_555,l.IPF_RGB_888,l.IPF_ARGB_8888,l.IPF_RGB_161616,l.IPF_ARGB_16161616,l.IPF_ABGR_8888,l.IPF_ABGR_16161616,l.IPF_BGR_888].includes(e.format)){if(r(this,j,"f")===o.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t0!==t.length&&t.every((t=>p(t))))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&!m(e))throw new TypeError("Invalid 'keepInBuffer'.");s(this,V,{imageId:t,keepInBuffer:e})}_resetNextReturnedImage(){s(this,V,null)}hasImage(t){return r(this,F,"m",U).call(this,t)>=0}startFetching(){s(this,B,!0)}stopFetching(){s(this,B,!1)}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(s(this,k,t);r(this,P,"f")&&r(this,P,"f").length>t;)r(this,P,"f").shift()}getMaxImageCount(){return r(this,k,"f")}getImageCount(){return r(this,P,"f").length}clearBuffer(){r(this,P,"f").length=0}isBufferEmpty(){return 0===r(this,P,"f").length}setBufferOverflowProtectionMode(t){s(this,N,t)}getBufferOverflowProtectionMode(){return r(this,N,"f")}setColourChannelUsageType(t){s(this,j,t)}getColourChannelUsageType(){return r(this,j,"f")}};P=new WeakMap,k=new WeakMap,N=new WeakMap,B=new WeakMap,V=new WeakMap,j=new WeakMap,F=new WeakSet,U=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return r(this,P,"f").findIndex((e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t}))},"undefined"!=typeof navigator&&(G=navigator,W=G.userAgent,Y=G.platform,z=G.mediaDevices),function(){if(!h){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:G.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Y,search:"Win"},Mac:{str:Y},Linux:{str:Y}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||W,a=r.search||e,o=r.verStr||W,l=r.verSearch||e;if(l instanceof Array||(l=[l]),-1!=s.indexOf(a)){i=e;for(let t of l){let e=o.indexOf(t);if(-1!=e){n=parseFloat(o.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||W,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=W.indexOf("Windows NT")&&(r="HarmonyOS"),H={browser:i,version:n,OS:r}}h&&(H={browser:"ssr",version:0,OS:"ssr"})}();const Z="undefined"!=typeof WebAssembly&&W&&!(/Safari/.test(W)&&!/Chrome/.test(W)&&/\(.+\s11_2_([2-6]).*\)/.test(W)),q=!("undefined"==typeof Worker),J=!(!z||!z.getUserMedia),K=async()=>{let t=!1;if(J)try{(await z.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===H.browser&&H.version>66||"Safari"===H.browser&&H.version>13||"OPR"===H.browser&&H.version>43||"Edge"===H.browser&&H.version;const $={},Q=async t=>{let e="string"==typeof t?[t]:t,i=[];for(let t of e)i.push($[t]=$[t]||new n);await Promise.all(i)},tt=async(t,e)=>{let i,r="string"==typeof t?[t]:t,s=[];for(let t of r){let r;s.push(r=$[t]=$[t]||new n(i=i||e())),r.isEmpty&&(r.task=i=i||e())}await Promise.all(s)};let et,it=0;const nt=()=>it++,rt={};let st;const at=t=>{st=t,et&&et.postMessage({type:"setBLog",body:{value:!!t}})};let ot=!1;const lt=t=>{ot=t,et&&et.postMessage({type:"setBDebug",body:{value:!!t}})},ht={},ct={},ut={dip:{wasm:!0}},dt={std:{version:"1.4.21",path:d(u+"../../dynamsoft-capture-vision-std@1.4.21/dist/"),isInternal:!0},core:{version:"3.4.31",path:u,isInternal:!0}},ft=async t=>{let e;t instanceof Array||(t=t?[t]:[]);let i=$.core;e=!i||i.isEmpty;let r=new Map;const s=t=>{if("std"==(t=t.toLowerCase())||"core"==t)return;if(!ut[t])throw Error("The '"+t+"' module cannot be found.");let e=ut[t].deps;if(null==e?void 0:e.length)for(let t of e)s(t);let i=$[t];r.has(t)||r.set(t,!i||i.isEmpty)};for(let e of t)s(e);let a=[];e&&a.push("core"),a.push(...r.keys());const o=[...r.entries()].filter((t=>!t[1])).map((t=>t[0]));await tt(a,(async()=>{const t=[...r.entries()].filter((t=>t[1])).map((t=>t[0]));await Q(o);const i=O(dt),s={};for(let e of t)s[e]=ut[e];const a={engineResourcePaths:i,autoResources:s,names:t};let l=new n;if(e){a.needLoadCore=!0;let t=i.core+gt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),et=new Worker(t),et.onerror=t=>{let e=new Error(t.message);l.reject(e)},et.addEventListener("message",(t=>{let e=t.data?t.data:t,i=e.type,n=e.id,r=e.body;switch(i){case"log":st&&st(e.message);break;case"task":try{rt[n](r),delete rt[n]}catch(t){throw delete rt[n],t}break;case"event":try{rt[n](r)}catch(t){throw t}break;default:console.log(t)}})),a.bLog=!!st,a.bd=ot,a.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await Q("core");let h=it++;rt[h]=t=>{if(t.success)Object.assign(ht,t.versions),"{}"!==JSON.stringify(t.versions)&&(gt._versions=t.versions),l.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),l.reject(e)}},et.postMessage({type:"loadWasm",body:a,id:h}),await l}))};class gt{static get engineResourcePaths(){return dt}static set engineResourcePaths(t){Object.assign(dt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return st}static set _onLog(t){at(t)}static get _bDebug(){return ot}static set _bDebug(t){lt(t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!$[t]&&$[t].isFulfilled}static async loadWasm(t){return await ft(t)}static async detectEnvironment(){return await(async()=>({wasm:Z,worker:q,getUserMedia:J,camera:await K(),browser:H.browser,version:H.version,OS:H.OS}))()}static async getModuleVersion(){return await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success)return t(i.versions);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"getModuleVersion",id:i})}))}static getVersion(){return`3.4.31(Worker: ${ht.core&&ht.core.worker||"Not Loaded"}, Wasm: ${ht.core&&ht.core.wasm||"Not Loaded"})`}static enableLogging(){X._onLog=console.log,gt._onLog=console.log}static disableLogging(){X._onLog=null,gt._onLog=null}static async cfd(t){return await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cfd",id:n,body:{count:t}})}))}}var mt,pt,_t,vt,yt,wt,Et,Ct,St;gt._bSupportDce4Module=-1,gt._bSupportIRTModule=-1,gt._versions=null,gt._workerName="core.worker.js",gt.browserInfo=H,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT"}(mt||(mt={})),function(t){t[t.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",t[t.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",t[t.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",t[t.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(pt||(pt={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",t[t.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",t[t.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",t[t.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",t[t.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",t[t.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",t[t.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",t[t.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",t[t.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",t[t.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",t[t.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",t[t.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",t[t.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",t[t.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",t[t.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",t[t.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",t[t.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",t[t.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",t[t.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",t[t.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",t[t.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",t[t.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",t[t.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(_t||(_t={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV"}(vt||(vt={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV"}(yt||(yt={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(wt||(wt={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(Et||(Et={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(Ct||(Ct={})),function(t){t[t.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",t[t.CVS_PASSED=1]="CVS_PASSED",t[t.CVS_FAILED=2]="CVS_FAILED"}(St||(St={}));const Tt={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_DOWN_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_UP_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_NORMALIZED_IMAGES:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var bt,It;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_NORMALIZED_IMAGE=6]="ROET_NORMALIZED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI"}(bt||(bt={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_NORMALIZATION=7]="ST_DOCUMENT_NORMALIZATION"}(It||(It={}));var xt=Object.freeze({__proto__:null,CoreModule:gt,get EnumBufferOverflowProtectionMode(){return a},get EnumCapturedResultItemType(){return mt},get EnumColourChannelUsageType(){return o},get EnumCornerType(){return pt},get EnumCrossVerificationStatus(){return St},get EnumErrorCode(){return _t},get EnumGrayscaleEnhancementMode(){return vt},get EnumGrayscaleTransformationMode(){return yt},get EnumImagePixelFormat(){return l},get EnumImageTagType(){return wt},EnumIntermediateResultUnitType:Tt,get EnumPDFReadingMode(){return Et},get EnumRasterDataSource(){return Ct},get EnumRegionObjectElementType(){return bt},get EnumSectionType(){return It},ImageSourceAdapter:X,_getNorImageData:M,_saveToFile:D,_toBlob:L,_toCanvas:A,_toImage:(t,e)=>{y(e)&&(e=M(e));const i=A(e);let n=new Image,r=i.toDataURL(t);return n.src=r,n},get bDebug(){return ot},checkIsLink:t=>/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t),compareVersion:R,doOrWaitAsyncDependency:tt,getNextTaskID:nt,handleEngineResourcePaths:O,innerVersions:ht,isArc:t=>!(!_(t)||!p(t.x)||!p(t.y)||!p(t.radius)||t.radius<0||!p(t.startAngle)||!p(t.endAngle)),isContour:t=>!!_(t)&&!!g(t.points)&&0!=t.points.length&&!t.points.some((t=>!S(t))),isDSImageData:y,isDSRect:w,isImageTag:E,isLineSegment:C,isObject:_,isOriginalDsImageData:t=>!(!v(t)||!p(t.bytes.length)&&!p(t.bytes.ptr)),isPoint:S,isPolygon:T,isQuad:b,isRect:I,loadWasm:ft,mapAsyncDependency:$,mapPackageRegister:ct,mapTaskCallBack:rt,get onLog(){return st},requestResource:x,setBDebug:lt,setOnLog:at,waitAsyncDependency:Q,get worker(){return et},workerAutoResources:ut});const Rt="undefined"==typeof self,Ot=Rt?{}:self,Dt="function"==typeof importScripts,At=(()=>{if(!Dt){if(!Rt&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),Lt=t=>t&&"object"==typeof t&&"function"==typeof t.then,Mt=(async()=>{})().constructor;let Ft=class extends Mt{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Lt(t)?e=t:"function"==typeof t&&(e=new Mt(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(Lt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Pt=" is not allowed to change after `createInstance` or `loadWasm` is called.",kt=!Rt&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",Nt=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Pt);i._license=e}};!Rt&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Bt=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=Bt(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Pt);i._licenseServer=e}},jt=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Pt);i._deviceFriendlyName=e}};let Ut,Gt,Wt,Yt,zt;"undefined"!=typeof navigator&&(Ut=navigator,Gt=Ut.userAgent,Wt=Ut.platform,Yt=Ut.mediaDevices),function(){if(!Rt){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Ut.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Wt,search:"Win"},Mac:{str:Wt},Linux:{str:Wt}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Gt,a=r.search||e,o=r.verStr||Gt,l=r.verSearch||e;if(l instanceof Array||(l=[l]),-1!=s.indexOf(a)){i=e;for(let t of l){let e=o.indexOf(t);if(-1!=e){n=parseFloat(o.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Gt,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Gt.indexOf("Windows NT")&&(r="HarmonyOS"),zt={browser:i,version:n,OS:r}}Rt&&(zt={browser:"ssr",version:0,OS:"ssr"})}(),Yt&&Yt.getUserMedia,"Chrome"===zt.browser&&zt.version>66||"Safari"===zt.browser&&zt.version>13||"OPR"===zt.browser&&zt.version>43||"Edge"===zt.browser&&zt.version;const Ht=()=>(ft("license"),tt("dynamsoft_inited",(async()=>{let{lt:t,l:e,ls:i,sp:n,rmk:r,cv:s}=((t,e=!1)=>{const i=t;if(i._pLoad.isEmpty){let n,r,s,a=i._license||"",o=JSON.parse(JSON.stringify(i._licenseServer)),l=i._sessionPassword,h=0;if(a.startsWith("t")||a.startsWith("f"))h=0;else if(0===a.length||a.startsWith("P")||a.startsWith("L")||a.startsWith("Y")||a.startsWith("A"))h=1;else{h=2;const e=a.indexOf(":");-1!=e&&(a=a.substring(e+1));const i=a.indexOf("?");if(-1!=i&&(r=a.substring(i+1),a=a.substring(0,i)),a.startsWith("DLC2"))h=0;else{if(a.startsWith("DLS2")){let e;try{let t=a.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(a=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof a&&(a=JSON.stringify(a)),0===o.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),o=Bt(t)}!l&&e.sessionPassword&&(l=e.sessionPassword),n=e.remark}a&&"200001"!==a&&!a.startsWith("200001-")||(h=1)}}if(h&&(e||(Ot.crypto||(s="Please upgrade your browser to support online key."),Ot.crypto.subtle||(s="Require https to use online key in this browser."))),s)throw new Error(s);return 1===h&&(a="",console.warn("Applying for a public trial license ...")),{lt:h,l:a,ls:o,sp:l,rmk:n,cv:r}}throw new Error("Can't preprocess license again"+Pt)})(Zt),a=new Ft;Zt._pLoad.task=a,(async()=>{try{await Zt._pLoad}catch(t){}})();let o=nt();rt[o]=e=>{if(e.message&&Zt._onAuthMessage){let t=Zt._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,n=!1;if(1===t&&(n=!0),e.success?(st&&st("init license success"),e.message&&console.warn(e.message),gt._bSupportIRTModule=e.bSupportIRTModule,gt._bSupportDce4Module=e.bSupportDce4Module,Zt.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):a.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),n||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(n=!0)),n){const t=O(gt.engineResourcePaths);(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let n=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!n.ok)throw Error("Get license dialog fail. Network Error: "+n.statusText);let r=await n.text();if(!r.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.innerHTML=r;let a=[];for(let t=0;t{if(t==e.target){o.remove();for(let t of a)t.remove()}}));else if(!h&&t.classList.contains("dls-license-icon-close"))h=t,t.addEventListener("click",(()=>{o.remove();for(let t of a)t.remove()}));else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-icon-warn"))u=t,"warn"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-msg-content")){d=t;let e=i;for(;e;){let i=e.indexOf("["),n=e.indexOf("]",i),r=e.indexOf("(",n),s=e.indexOf(")",r);if(-1==i||-1==n||-1==r||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let a=document.createElement("a"),o=e.substring(i+1,n);a.innerText=o;let l=e.substring(r+1,s);a.setAttribute("href",l),a.setAttribute("target","_blank"),t.appendChild(a),e=e.substring(s+1)}}document.body.appendChild(o)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:Zt._bNeverShowDialog,engineResourcePath:t.license,_onLog:st},e.success?"warn":"error",e.message)}e.success?a.resolve(void 0):a.reject(i)},await Q("core"),et.postMessage({type:"license_dynamsoft",body:{v:"3.4.31",brtk:!!t,bptk:1===t,l:e,os:zt,fn:Zt.deviceFriendlyName,ls:i,sp:n,rmk:r,cv:s},id:o}),Zt.bCallInitLicense=!0,await a})));let Xt;ct.license={},ct.license.dynamsoft=Ht,ct.license.getAR=async()=>{{let t=$.dynamsoft_inited;t&&t.isRejected&&await t}return et?new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success){delete i.success;{let t=Zt.license;t&&(t.startsWith("t")||t.startsWith("f"))&&(i.pk=t)}if(Object.keys(i).length){if(i.lem){let t=Error(i.lem);t.ltsErrorCode=i.lec,delete i.lem,delete i.lec,i.ae=t}t(i)}else t(null)}else{let t=Error(i.message);i.stack&&(t.stack=i.stack),e(t)}},et.postMessage({type:"license_getAR",id:i})})):null};let Zt=class t{static setLicenseServer(e){Vt(t,e)}static get license(){return this._license}static set license(e){Nt(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Vt(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){jt(t,e)}static initLicense(e,i){if(Nt(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return Ht()}static setDeviceFriendlyName(e){jt(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await tt("dynamsoft_uuid",(async()=>{await ft();let t=new Ft,e=nt();rt[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},et.postMessage({type:"license_getDeviceUUID",id:e}),Xt=await t})),Xt))()}};Zt._pLoad=new Ft,Zt.bPassValidation=!1,Zt.bCallInitLicense=!1,Zt._license=kt,Zt._licenseServer=[],Zt._deviceFriendlyName="",gt.engineResourcePaths.license={version:"3.4.31",path:At,isInternal:!0},ut.license={wasm:!0,js:!0},ct.license.LicenseManager=Zt;const qt="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&R(gt.engineResourcePaths.std.version,qt)<0&&(gt.engineResourcePaths.std={version:qt,path:(t=>{if(null==t&&(t="./"),Rt||Dt);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(At+`../../dynamsoft-capture-vision-std@${qt}/dist/`),isInternal:!0});var Jt=Object.freeze({__proto__:null,LicenseManager:Zt,LicenseModule:class{static getVersion(){return`3.4.31(Worker: ${ht.license&&ht.license.worker||"Not Loaded"}, Wasm: ${ht.license&&ht.license.wasm||"Not Loaded"})`}}});function Kt(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function $t(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const Qt=t=>t&&"object"==typeof t&&"function"==typeof t.then,te=(async()=>{})().constructor;class ee extends te{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Qt(t)?e=t:"function"==typeof t&&(e=new te(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(Qt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class ie{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success)return t(i.count);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})}))}async setMaxBufferedItems(t){return await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_setMaxBufferedItems",id:n,instanceID:this._cvr._instanceID,body:{count:t}})}))}async getBufferedCharacterItemSet(){return await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success)return t(i.itemSet);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})}))}}var ne={onTaskResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onColourImageUnitReceived:!1,onScaledDownColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledUpBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesReceived:!1};const re=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};class se{constructor(t){this._irrRegistryState=ne,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),re(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach(((t,e)=>{i[e]=t})),t._observedTaskMap.clear()}return await new Promise(((t,n)=>{let r=nt();rt[r]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},et.postMessage({type:"cvr_setIrrRegistry",id:r,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})}))}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),re(this),await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})}))}getOriginalImage(){return this._cvr._dsImage}}const ae="undefined"==typeof self,oe="function"==typeof importScripts,le=(()=>{if(!oe){if(!ae&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),he=t=>{if(null==t&&(t="./"),ae||oe);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var ce;gt.engineResourcePaths.cvr={version:"2.4.33",path:le,isInternal:!0},ut.cvr={js:!0,wasm:!0,deps:["license","dip"]},ct.cvr={};const ue="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&R(gt.engineResourcePaths.std.version,ue)<0&&(gt.engineResourcePaths.std={version:ue,path:he(le+`../../dynamsoft-capture-vision-std@${ue}/dist/`),isInternal:!0});const de="2.4.31";(!gt.engineResourcePaths.dip||"string"!=typeof gt.engineResourcePaths.dip&&R(gt.engineResourcePaths.dip.version,de)<0)&&(gt.engineResourcePaths.dip={version:de,path:he(le+`../../dynamsoft-image-processing@${de}/dist/`),isInternal:!0});class fe{static getVersion(){return this._version}}fe._version=`2.4.33(Worker: ${null===(ce=ht.cvr)||void 0===ce?void 0:ce.worker}, Wasm: loading...`;const ge={barcodeResultItems:{type:mt.CRIT_BARCODE,reveiver:"onDecodedBarcodesReceived",isNeedFilter:!0},textLineResultItems:{type:mt.CRIT_TEXT_LINE,reveiver:"onRecognizedTextLinesReceived",isNeedFilter:!0},detectedQuadResultItems:{type:mt.CRIT_DETECTED_QUAD,reveiver:"onDetectedQuadsReceived",isNeedFilter:!1},normalizedImageResultItems:{type:mt.CRIT_NORMALIZED_IMAGE,reveiver:"onNormalizedImagesReceived",isNeedFilter:!1},parsedResultItems:{type:mt.CRIT_PARSED_RESULT,reveiver:"onParsedResultsReceived",isNeedFilter:!1}};var me,pe,_e,ve,ye,we,Ee,Ce,Se,Te,be,Ie,xe;function Re(t,e){if(t&&t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;Re(t.referencedItem,e)}}function Oe(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}!function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(me||(me={}));const De={onTaskResultsReceived:()=>{},isFilter:!0};class Ae{constructor(){this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(gt.browserInfo.OS)?2048:4096,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,pe.set(this,null),_e.set(this,null),ve.set(this,null),ye.set(this,null),we.set(this,null),Ee.set(this,new Set),Ce.set(this,new Set),Se.set(this,new Set),Te.set(this,0),be.set(this,!1),Ie.set(this,!1),xe.set(this,!1),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return Kt(this,xe,"f")}static async createInstance(){if(!ct.license)throw Error("Module `license` is not existed.");await ct.license.dynamsoft(),await ft(["cvr"]);const t=new Ae,e=new ee;let i=nt();return rt[i]=async i=>{var n;if(i.success)t._instanceID=i.instanceID,t._currentSettings=JSON.parse(JSON.parse(i.outputSettings).data),fe._version=`2.4.33(Worker: ${null===(n=ht.cvr)||void 0===n?void 0:n.worker}, Wasm: ${i.version})`,$t(t,Ie,!0),$t(t,ye,t.getIntermediateResultManager()),$t(t,Ie,!1),e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},et.postMessage({type:"cvr_createInstance",id:i}),e}async _singleFrameModeCallback(t){for(let e of Kt(this,Ee,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;const n={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of Kt(this,Ee,"f"))if(t.isDce)t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1});else{for(let e in ge){const r=e,s=ge[r];t[s.reveiver]&&i[r]&&t[s.reveiver](Object.assign(Object.assign({},n),{[r]:i[r]}))}t.onCapturedResultReceived&&t.onCapturedResultReceived(i)}}setInput(t){if(Oe(this),t){if($t(this,pe,t),t.isCameraEnhancer){Kt(this,ye,"f")&&(Kt(this,pe,"f")._intermediateResultReceiver.isDce=!0,Kt(this,ye,"f").addResultReceiver(Kt(this,pe,"f")._intermediateResultReceiver));const t=Kt(this,pe,"f").getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,Kt(this,Ee,"f").add(e)}}}else $t(this,pe,null)}getInput(){return Kt(this,pe,"f")}addImageSourceStateListener(t){if(Oe(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&Kt(this,Ce,"f").add(t)}removeImageSourceStateListener(t){return Oe(this),Kt(this,Ce,"f").delete(t)}addResultReceiver(t){if(Oe(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(Kt(this,Ee,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){Oe(this),Kt(this,Ee,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onParsedResultsReceived:!1};for(let e of Kt(this,Ee,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onDetectedQuadsReceived=!!e.onDetectedQuadsReceived,t.onNormalizedImagesReceived=!!e.onNormalizedImagesReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new ee;let i=nt();return rt[i]=async t=>{if(t.success)e.resolve();else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject()}},et.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(Oe(this),!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");Kt(this,Se,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){Oe(this),Kt(this,Se,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(Kt(this,ye,"f").removeResultReceiver(De),0===Kt(this,Se,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[mt.CRIT_BARCODE]:!1,[mt.CRIT_TEXT_LINE]:!1,[mt.CRIT_DETECTED_QUAD]:!1,[mt.CRIT_NORMALIZED_IMAGE]:!1},e={[mt.CRIT_BARCODE]:!1,[mt.CRIT_TEXT_LINE]:!1,[mt.CRIT_DETECTED_QUAD]:!1,[mt.CRIT_NORMALIZED_IMAGE]:!1};return await Le(this,t),void await Me(this,e)}for(let t of Kt(this,Se,"f")){if(this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(mt.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(mt.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(mt.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(mt.CRIT_NORMALIZED_IMAGE),t.isLatestOverlappingEnabled(mt.CRIT_BARCODE)){[...Kt(this,ye,"f")._intermediateResultReceiverSet.values()].find((t=>t.isFilter))||Kt(this,ye,"f").addResultReceiver(De)}await Le(this,t.verificationEnabled),await Me(this,t.duplicateFilterEnabled),await Fe(this,t.duplicateForgetTime)}}async startCapturing(t){var e,i;if(Oe(this),!this._isPauseScan)return;if(!Kt(this,pe,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");t||(t=Ae._defaultTemplate);const n=await this.containsTask(t);await ft(n);for(let t of Kt(this,Se,"f"))await this.addResultFilter(t);if(n.includes("dlr")&&!(null===(e=ct.dlr)||void 0===e?void 0:e.bLoadConfusableCharsData)){const t=O(gt.engineResourcePaths);await(null===(i=ct.dlr)||void 0===i?void 0:i.loadRecognitionData("ConfusableChars",t.dlr))}if(Kt(this,pe,"f").isCameraEnhancer&&(n.includes("ddn")?Kt(this,pe,"f").setPixelFormat(l.IPF_ABGR_8888):Kt(this,pe,"f").setPixelFormat(l.IPF_GRAYSCALED)),void 0!==Kt(this,pe,"f").singleFrameMode&&"disabled"!==Kt(this,pe,"f").singleFrameMode)return this._templateName=t,void Kt(this,pe,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind);return Kt(this,pe,"f").getColourChannelUsageType()===o.CCUT_AUTO&&Kt(this,pe,"f").setColourChannelUsageType(n.includes("ddn")?o.CCUT_FULL_CHANNEL:o.CCUT_Y_CHANNEL_ONLY),Kt(this,ve,"f")&&Kt(this,ve,"f").isPending?Kt(this,ve,"f"):($t(this,ve,new ee(((e,i)=>{if(this.disposed)return;let n=nt();rt[n]=async n=>{if(Kt(this,ve,"f")&&!Kt(this,ve,"f").isFulfilled){if(!n.success){let t=new Error(n.message);return t.stack=n.stack+"\n"+t.stack,i(t)}this._isPauseScan=!1,this._isOutputOriginalImage=n.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((async()=>{-1!==this._minImageCaptureInterval&&Kt(this,pe,"f").startFetching(),this._loopReadVideo(t),e()}),0)}},et.postMessage({type:"cvr_startCapturing",id:n,instanceID:this._instanceID,body:{templateName:t}})}))),await Kt(this,ve,"f"))}stopCapturing(){Oe(this),Kt(this,pe,"f")&&(Kt(this,pe,"f").isCameraEnhancer&&void 0!==Kt(this,pe,"f").singleFrameMode&&"disabled"!==Kt(this,pe,"f").singleFrameMode?Kt(this,pe,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(!async function(t){let e=nt();const i=new ee;rt[e]=async t=>{if(t.success)return i.resolve();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i.reject(e)}},et.postMessage({type:"cvr_clearVerifyList",id:e,instanceID:t._instanceID})}(this),Kt(this,pe,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,$t(this,ve,null),Kt(this,pe,"f").setColourChannelUsageType(o.CCUT_AUTO)))}async containsTask(t){return Oe(this),await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success)return e(JSON.parse(t.tasks));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_containsTask",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async _loopReadVideo(t){if(this.disposed||this._isPauseScan)return;if($t(this,be,!0),Kt(this,pe,"f").isBufferEmpty())if(Kt(this,pe,"f").hasNextImageToFetch())for(let t of Kt(this,Ce,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(me.ISS_BUFFER_EMPTY);else if(!Kt(this,pe,"f").hasNextImageToFetch())for(let t of Kt(this,Ce,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(me.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||Kt(this,pe,"f").isBufferEmpty())try{Kt(this,pe,"f").isBufferEmpty()&&Ae._onLog&&Ae._onLog("buffer is empty so fetch image"),Ae._onLog&&Ae._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=Kt(this,pe,"f").fetchImage(),Ae._onLog&&Ae._onLog(`DCE: finish fetching a frame: ${Date.now()}`),Kt(this,pe,"f").setImageFetchInterval(this._averageTime)}catch(e){return void this._reRunCurrnetFunc(t)}else if(Kt(this,pe,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=Kt(this,pe,"f").getImage(),this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(t);if(!this._dsImage)return void this._reRunCurrnetFunc(t);for(let t of Kt(this,Ee,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const e=Date.now();this._captureDsimage(this._dsImage,t).then((async i=>{if(Ae._onLog&&Ae._onLog("no js handle time: "+(Date.now()-e)),this._isPauseScan)return void this._reRunCurrnetFunc(t);i.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;const n={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of Kt(this,Ee,"f"))if(t.isDce){const e=Date.now();if(t.onCapturedResultReceived(i,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),Ae._onLog){const t=Date.now()-e;t>10&&Ae._onLog(`draw result time: ${t}`)}}else{for(let e in ge){const r=e,s=ge[r];t[s.reveiver],t[s.reveiver]&&i[r]&&t[s.reveiver](Object.assign(Object.assign({},n),{[r]:i[r].filter((t=>!s.isNeedFilter||!t.isFilter))})),i[r]&&(i[r]=i[r].filter((t=>!s.isNeedFilter||!t.isFilter)))}t.onCapturedResultReceived&&(i.items=i.items.filter((t=>[mt.CRIT_DETECTED_QUAD,mt.CRIT_NORMALIZED_IMAGE].includes(t.type)||!t.isFilter)),t.onCapturedResultReceived(i))}const r=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-e),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,Ae._onLog&&(Ae._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),Ae._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),Ae._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),Ae._onLog(`averageTime: ${this._averageTime}`))),Ae._onLog){const t=Date.now()-r;t>10&&Ae._onLog(`fetch image calculate time: ${t}`)}Ae._onLog&&Ae._onLog(`time finish decode: ${Date.now()}`),Ae._onLog&&Ae._onLog("main time: "+(Date.now()-e)),Ae._onLog&&Ae._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,0))})).catch((e=>{Kt(this,pe,"f").stopFetching(),e.errorCode&&0===e.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{Kt(this,pe,"f").startFetching(),this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,1e3))),"platform error"!==e.message&&setTimeout((()=>{throw e}),0)}))}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),0)}async capture(t,e){var i,n;Oe(this),e||(e=Ae._defaultTemplate);const r=await this.containsTask(e);if(await ft(r),r.includes("dlr")&&!(null===(i=ct.dlr)||void 0===i?void 0:i.bLoadConfusableCharsData)){const t=O(gt.engineResourcePaths);await(null===(n=ct.dlr)||void 0===n?void 0:n.loadRecognitionData("ConfusableChars",t.dlr))}let s;if($t(this,be,!1),y(t))s=await this._captureDsimage(t,e);else if("string"==typeof t)s="data:image/"==t.substring(0,11)?await this._captureBase64(t,e):await this._captureUrl(t,e);else if(t instanceof Blob)s=await this._captureBlob(t,e);else if(t instanceof HTMLImageElement)s=await this._captureImage(t,e);else if(t instanceof HTMLCanvasElement)s=await this._captureCanvas(t,e);else{if(!(t instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");s=await this._captureVideo(t,e)}return s}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await x(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),n=i.length,r=new Uint8Array(n);for(;n--;)r[n]=i.charCodeAt(n);return await this._captureBlob(new Blob([r]),e)}async _captureBlob(t,e){let i=null,n=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(n=await async function(t){return await new Promise(((e,i)=>{let n=URL.createObjectURL(t),r=new Image;r.src=n,r.onload=()=>{URL.revokeObjectURL(r.dbrObjUrl),e(r)},r.onerror=t=>{i(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))}(t));let r=await this._captureImage(i||n,e);return i&&i.close(),r}async _captureImage(t,e){let i,n,r=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,a=Math.max(r,s);a>this.maxImageSideLength?($t(this,Te,this.maxImageSideLength/a),i=Math.round(r*Kt(this,Te,"f")),n=Math.round(s*Kt(this,Te,"f"))):(i=r,n=s),Kt(this,_e,"f")||$t(this,_e,document.createElement("canvas"));const o=Kt(this,_e,"f");o.width===i&&o.height===n||(o.width=i,o.height=n),o.ctx2d||(o.ctx2d=o.getContext("2d",{willReadFrequently:!0}));return o.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(o,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),n={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(n,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,n,r=t.videoWidth,s=t.videoHeight,a=Math.max(r,s);a>this.maxImageSideLength?($t(this,Te,this.maxImageSideLength/a),i=Math.round(r*Kt(this,Te,"f")),n=Math.round(s*Kt(this,Te,"f"))):(i=r,n=s),Kt(this,_e,"f")||$t(this,_e,document.createElement("canvas"));const o=Kt(this,_e,"f");o.width===i&&o.height===n||(o.width=i,o.height=n),o.ctx2d||(o.ctx2d=o.getContext("2d",{willReadFrequently:!0}));return o.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),await this._captureCanvas(o,e)}async _captureInWorker(t,e){const{bytes:i,width:n,height:r,stride:s,format:a}=t;let o=nt();const l=new ee;return rt[o]=async e=>{var i,n;if(!e.success){let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l.reject(t)}{const r=Date.now();Ae._onLog&&(Ae._onLog(`get result time from worker: ${r}`),Ae._onLog("worker to main time consume: "+(r-e.workerReturnMsgTime)));try{const r=e.captureResult;if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,l.reject(t)}t.bytes=e.bytes;for(let e of r.items)0!==Kt(this,Te,"f")&&Re(e,Kt(this,Te,"f")),e.type===mt.CRIT_ORIGINAL_IMAGE?e.imageData=t:e.type===mt.CRIT_NORMALIZED_IMAGE?null===(i=ct.ddn)||void 0===i||i.handleNormalizedImageResultItem(e):e.type===mt.CRIT_PARSED_RESULT&&(null===(n=ct.dcp)||void 0===n||n.handleParsedResultItem(e));if(Kt(this,be,"f"))for(let t of Kt(this,Se,"f"))t.onDecodedBarcodesReceived(r),t.onRecognizedTextLinesReceived(r),t.onDetectedQuadsReceived(r),t.onNormalizedImagesReceived(r);for(let t in ge){const e=t,i=r.items.filter((t=>t.type===ge[e].type));i.length&&(r[t]=i)}if(!this._isPauseScan||!Kt(this,be,"f")){const e=r.intermediateResult;if(e){let i=0;for(let n of Kt(this,ye,"f")._intermediateResultReceiverSet){i++;for(let r of e){if("onTaskResultsReceived"===r.info.callbackName){for(let e of r.intermediateResultUnits)e.originalImageTag=t.tag?t.tag:null;n[r.info.callbackName]&&n[r.info.callbackName]({intermediateResultUnits:r.intermediateResultUnits},r.info)}else n[r.info.callbackName]&&n[r.info.callbackName](r.result,r.info);i===Kt(this,ye,"f")._intermediateResultReceiverSet.size&&delete r.info.callbackName}}}}return r&&r.hasOwnProperty("intermediateResult")&&delete r.intermediateResult,$t(this,Te,0),l.resolve(r)}catch(t){return l.reject(t)}}},Ae._onLog&&Ae._onLog(`send buffer to worker: ${Date.now()}`),et.postMessage({type:"cvr_capture",id:o,instanceID:this._instanceID,body:{bytes:i,width:n,height:r,stride:s,format:a,templateName:e||"",isScanner:Kt(this,be,"f")}},[i.buffer]),l}async initSettings(t){return Oe(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?t.trimStart().startsWith("{")||(t=await x(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise(((e,i)=>{let n=nt();rt[n]=async n=>{if(n.success){const r=JSON.parse(n.response);if(0!==r.errorCode){let t=new Error(r.errorString?r.errorString:"Init Settings Failed.");return t.errorCode=r.errorCode,i(t)}const s=JSON.parse(t);this._currentSettings=s;let a=[],o=s.CaptureVisionTemplates;for(let t=0;t{let n=nt();rt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,i(t)}return e(JSON.parse(n.data))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_outputSettings",id:n,instanceID:this._instanceID,body:{templateName:t||"*"}})}))}async outputSettingsToFile(t,e,i){const n=await this.outputSettings(t),r=new Blob([JSON.stringify(n,null,2,(function(t,e){return e instanceof Array?JSON.stringify(e):e}),2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(r),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout((()=>{URL.revokeObjectURL(t.href)}),500)},t.click()}return r}async getTemplateNames(){return Oe(this),await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,e(t)}return t(JSON.parse(n.data))}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})}))}async getSimplifiedSettings(t){Oe(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const e=await this.containsTask(t);return await ft(e),await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,i(t)}const r=JSON.parse(n.data,((t,e)=>"barcodeFormatIds"===t?BigInt(e):e));return r.minImageCaptureInterval=this._minImageCaptureInterval,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_getSimplifiedSettings",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async updateSettings(t,e){Oe(this);const i=await this.containsTask(t);return await ft(i),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success){const r=JSON.parse(t.response);if(e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==r.errorCode){let t=new Error(r.errorString?r.errorString:"Update Settings Failed.");return t.errorCode=r.errorCode,n(t)}return this._currentSettings=await this.outputSettings("*"),i(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},et.postMessage({type:"cvr_updateSettings",id:r,instanceID:this._instanceID,body:{settings:e,templateName:t}})}))}async resetSettings(){return Oe(this),await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Reset Settings Failed.");return t.errorCode=n.errorCode,e(t)}return this._currentSettings=await this.outputSettings("*"),t(n)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})}))}getBufferedItemsManager(){return Kt(this,we,"f")||$t(this,we,new ie(this)),Kt(this,we,"f")}getIntermediateResultManager(){if(Oe(this),!Kt(this,Ie,"f")&&0!==gt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return Kt(this,ye,"f")||$t(this,ye,new se(this)),Kt(this,ye,"f")}async parseRequiredResources(t){return Oe(this),await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success)return e(JSON.parse(t.resources));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"cvr_parseRequiredResources",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async dispose(){Oe(this),Kt(this,ve,"f")&&this.stopCapturing(),$t(this,pe,null),Kt(this,Ee,"f").clear(),Kt(this,Ce,"f").clear(),Kt(this,Se,"f").clear(),Kt(this,ye,"f")._intermediateResultReceiverSet.clear(),$t(this,xe,!0);let t=nt();rt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},et.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:Kt(this,pe,"f"),promiseStartScan:Kt(this,ve,"f"),intermediateResultManager:Kt(this,ye,"f"),bufferdItemsManager:Kt(this,we,"f"),resultReceiverSet:Kt(this,Ee,"f"),isaStateListenerSet:Kt(this,Ce,"f"),resultFilterSet:Kt(this,Se,"f"),compressRate:Kt(this,Te,"f"),canvas:Kt(this,_e,"f"),isScanner:Kt(this,be,"f"),innerUseTag:Kt(this,Ie,"f"),isDestroyed:Kt(this,xe,"f")}}async _getWasmFilterState(){return await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})}))}}async function Le(t,e){return Oe(t),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},et.postMessage({type:"cvr_enableResultCrossVerification",id:r,instanceID:t._instanceID,body:{verificationEnabled:e}})}))}async function Me(t,e){return Oe(t),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},et.postMessage({type:"cvr_enableResultDeduplication",id:r,instanceID:t._instanceID,body:{duplicateFilterEnabled:e}})}))}async function Fe(t,e){return Oe(t),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},et.postMessage({type:"cvr_setDuplicateForgetTime",id:r,instanceID:t._instanceID,body:{duplicateForgetTime:e}})}))}pe=new WeakMap,_e=new WeakMap,ve=new WeakMap,ye=new WeakMap,we=new WeakMap,Ee=new WeakMap,Ce=new WeakMap,Se=new WeakMap,Te=new WeakMap,be=new WeakMap,Ie=new WeakMap,xe=new WeakMap,Ae._defaultTemplate="Default";class Pe{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}}var ke;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadBarcodes_Balanced",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(ke||(ke={}));var Ne=Object.freeze({__proto__:null,CaptureVisionRouter:Ae,CaptureVisionRouterModule:fe,CapturedResultReceiver:Pe,get EnumImageSourceState(){return me},get EnumPresetTemplate(){return ke},IntermediateResultReceiver:class{constructor(){this._observedResultUnitTypes=Tt.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledDownColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}});const Be="undefined"==typeof self,Ve="function"==typeof importScripts,je=(()=>{if(!Ve){if(!Be&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})();gt.engineResourcePaths.dce={version:"4.1.1",path:je,isInternal:!0},ut.dce={wasm:!1,js:!1},ct.dce={};let Ue,Ge,We,Ye,ze;function He(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Xe(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(Ue=navigator,Ge=Ue.userAgent,We=Ue.platform,Ye=Ue.mediaDevices),function(){if(!Be){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Ue.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:We,search:"Win"},Mac:{str:We},Linux:{str:We}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||Ge,a=r.search||e,o=r.verStr||Ge,l=r.verSearch||e;if(l instanceof Array||(l=[l]),-1!=s.indexOf(a)){i=e;for(let t of l){let e=o.indexOf(t);if(-1!=e){n=parseFloat(o.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||Ge,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=Ge.indexOf("Windows NT")&&(r="HarmonyOS"),ze={browser:i,version:n,OS:r}}Be&&(ze={browser:"ssr",version:0,OS:"ssr"})}();const Ze="undefined"!=typeof WebAssembly&&Ge&&!(/Safari/.test(Ge)&&!/Chrome/.test(Ge)&&/\(.+\s11_2_([2-6]).*\)/.test(Ge)),qe=!("undefined"==typeof Worker),Je=!(!Ye||!Ye.getUserMedia),Ke=async()=>{let t=!1;if(Je)try{(await Ye.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===ze.browser&&ze.version>66||"Safari"===ze.browser&&ze.version>13||"OPR"===ze.browser&&ze.version>43||"Edge"===ze.browser&&ze.version;var $e={653:(t,e,i)=>{var n,r,s,a,o,l,h,c,u,d,f,g,m,p,_,v,y,w,E,C,S,T=T||{version:"5.2.1"};if(e.fabric=T,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?T.document=document:T.document=document.implementation.createHTMLDocument(""),T.window=window;else{var b=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;T.document=b.document,T.jsdomImplForWrapper=i(898).implForWrapper,T.nodeCanvas=i(245).Canvas,T.window=b,DOMParser=T.window.DOMParser}function I(t,e){var i=t.canvas,n=e.targetCanvas,r=n.getContext("2d");r.translate(0,n.height),r.scale(1,-1);var s=i.height-n.height;r.drawImage(i,0,s,n.width,n.height,0,0,n.width,n.height)}function x(t,e){var i=e.targetCanvas.getContext("2d"),n=e.destinationWidth,r=e.destinationHeight,s=n*r*4,a=new Uint8Array(this.imageBuffer,0,s),o=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,a);var l=new ImageData(o,n,r);i.putImageData(l,0,0)}T.isTouchSupported="ontouchstart"in T.window||"ontouchstart"in T.document||T.window&&T.window.navigator&&T.window.navigator.maxTouchPoints>0,T.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,T.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],T.DPI=96,T.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",T.commaWsp="(?:\\s+,?\\s*|,\\s*)",T.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,T.reNonWord=/[ \n\.,;!\?\-]/,T.fontPaths={},T.iMatrix=[1,0,0,1,0,0],T.svgNS="http://www.w3.org/2000/svg",T.perfLimitSizeTotal=2097152,T.maxCacheSideLimit=4096,T.minCacheSideLimit=256,T.charWidthsCache={},T.textureSize=2048,T.disableStyleCopyPaste=!1,T.enableGLFiltering=!0,T.devicePixelRatio=T.window.devicePixelRatio||T.window.webkitDevicePixelRatio||T.window.mozDevicePixelRatio||1,T.browserShadowBlurConstant=1,T.arcToSegmentsCache={},T.boundsOfCurveCache={},T.cachesBoundsOfCurve=!0,T.forceGLPutImageData=!1,T.initFilterBackend=function(){return T.enableGLFiltering&&T.isWebglSupported&&T.isWebglSupported(T.textureSize)?(console.log("max texture size: "+T.maxTextureSize),new T.WebglFilterBackend({tileSize:T.textureSize})):T.Canvas2dFilterBackend?new T.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=T),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:T.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}T.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var n=0,r=i.length;n-1||!!e&&this._objects.some((function(e){return"function"==typeof e.contains&&e.contains(t,!0)}))},complexity:function(){return this._objects.reduce((function(t,e){return t+(e.complexity?e.complexity():0)}),0)}},T.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof T.Gradient||this.set(e,new T.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof T.Pattern?i&&i():this.set(e,new T.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},n=e,r=Math.sqrt,s=Math.atan2,a=Math.pow,o=Math.PI/180,l=Math.PI/2,T.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/l){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/l){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*o},radiansToDegrees:function(t){return t/o},rotatePoint:function(t,e,i){var n=new T.Point(t.x-e.x,t.y-e.y),r=T.util.rotateVector(n,i);return new T.Point(r.x,r.y).addEquals(e)},rotateVector:function(t,e){var i=T.util.sin(e),n=T.util.cos(e);return{x:t.x*n-t.y*i,y:t.x*i+t.y*n}},createVector:function(t,e){return new T.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new T.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var n=T.util.createVector(t,e),r=T.util.createVector(t,i),s=T.util.calcAngleBetweenVectors(n,r),a=s*(0===T.util.calcAngleBetweenVectors(T.util.rotateVector(n,s),r)?1:-1)/2;return{vector:T.util.getHatVector(T.util.rotateVector(n,a)),angle:s}},projectStrokeOnPoints:function(t,e,i){var n=[],r=e.strokeWidth/2,s=e.strokeUniform?new T.Point(1/e.scaleX,1/e.scaleY):new T.Point(1,1),a=function(t){var e=r/Math.hypot(t.x,t.y);return new T.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach((function(o,l){var h,c,u=new T.Point(o.x,o.y);0===l?(c=t[l+1],h=i?a(T.util.createVector(c,u)).addEquals(u):t[t.length-1]):l===t.length-1?(h=t[l-1],c=i?a(T.util.createVector(h,u)).addEquals(u):t[0]):(h=t[l-1],c=t[l+1]);var d,f,g=T.util.getBisector(u,h,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(d=-r/Math.sin(p/2),f=new T.Point(m.x*d*s.x,m.y*d*s.y),Math.hypot(f.x,f.y)/r<=e.strokeMiterLimit))return n.push(u.add(f)),void n.push(u.subtract(f));d=-r*Math.SQRT2,f=new T.Point(m.x*d*s.x,m.y*d*s.y),n.push(u.add(f)),n.push(u.subtract(f))})),n},transformPoint:function(t,e,i){return i?new T.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new T.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>n?e-=n:e=0,i>n?i-=n:i=0);var r,s=!0,a=t.getImageData(e,i,2*n||1,2*n||1),o=a.data.length;for(r=3;r=r?s-r:2*Math.PI-(r-s)}function s(t,e,i){for(var s=i[1],a=i[2],o=i[3],l=i[4],h=i[5],c=function(t,e,i,s,a,o,l){var h=Math.PI,c=l*h/180,u=T.util.sin(c),d=T.util.cos(c),f=0,g=0,m=-d*t*.5-u*e*.5,p=-d*e*.5+u*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,E=_*v-_*y-v*w,C=0;if(E<0){var S=Math.sqrt(1-E/(_*v));i*=S,s*=S}else C=(a===o?-1:1)*Math.sqrt(E/(_*y+v*w));var b=C*i*p/s,I=-C*s*m/i,x=d*b-u*I+.5*t,R=u*b+d*I+.5*e,O=r(1,0,(m-b)/i,(p-I)/s),D=r((m-b)/i,(p-I)/s,(-m-b)/i,(-p-I)/s);0===o&&D>0?D-=2*h:1===o&&D<0&&(D+=2*h);for(var A=Math.ceil(Math.abs(D/h*2)),L=[],M=D/A,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=O+M,k=0;kC)for(var b=1,I=m.length;b2;for(e=e||0,h&&(o=t[2].xt[i-2].x?1:r.x===t[i-2].x?0:-1,l=r.y>t[i-2].y?1:r.y===t[i-2].y?0:-1),n.push(["L",r.x+o*e,r.y+l*e]),n},T.util.getPathSegmentsInfo=d,T.util.getBoundsOfCurve=function(e,i,n,r,s,a,o,l){var h;if(T.cachesBoundsOfCurve&&(h=t.call(arguments),T.boundsOfCurveCache[h]))return T.boundsOfCurveCache[h];var c,u,d,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,E=Math.abs,C=[],S=[[],[]];u=6*e-12*n+6*s,c=-3*e+9*n-9*s+3*o,d=3*n-3*e;for(var b=0;b<2;++b)if(b>0&&(u=6*i-12*r+6*a,c=-3*i+9*r-9*a+3*l,d=3*r-3*i),E(c)<1e-12){if(E(u)<1e-12)continue;0<(f=-d/u)&&f<1&&C.push(f)}else(p=u*u-4*d*c)<0||(0<(g=(-u+(_=v(p)))/(2*c))&&g<1&&C.push(g),0<(m=(-u-_)/(2*c))&&m<1&&C.push(m));for(var I,x,R,O=C.length,D=O;O--;)I=(R=1-(f=C[O]))*R*R*e+3*R*R*f*n+3*R*f*f*s+f*f*f*o,S[0][O]=I,x=R*R*R*i+3*R*R*f*r+3*R*f*f*a+f*f*f*l,S[1][O]=x;S[0][D]=e,S[1][D]=i,S[0][D+1]=o,S[1][D+1]=l;var A=[{x:y.apply(null,S[0]),y:y.apply(null,S[1])},{x:w.apply(null,S[0]),y:w.apply(null,S[1])}];return T.cachesBoundsOfCurve&&(T.boundsOfCurveCache[h]=A),A},T.util.getPointOnPath=function(t,e,i){i||(i=d(t));for(var n=0;e-i[n].length>0&&n1e-4;)i=l(s),r=s,(n=a(h.x,h.y,i.x,i.y))+o>e?(s-=c,c/=2):(h=i,s+=c,o+=n);return i.angle=u(r),i}(s,e)}},T.util.transformPath=function(t,e,i){return i&&(e=T.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map((function(t){for(var i=t.slice(0),n={},r=1;r=e}))}}}(),function(){function t(e,i,n){if(n)if(!T.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var r=0,s=i.length;r57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var n=t.charCodeAt(e+1);if(56320>n||n>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var r=t.charCodeAt(e-1);if(55296>r||r>56319)throw"Low surrogate without preceding high surrogate";return!1}T.util.string={camelize:function(t){return t.replace(/-+(.)?/g,(function(t,e){return e?e.toUpperCase():""}))},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,n=0,r=[];for(n=0;n-1?t.prototype[r]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=n;var r=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return r}}(r):t.prototype[r]=e[r],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function r(){}function s(e){for(var i=null,n=this;n.constructor.superclass;){var r=n.constructor.superclass.prototype[e];if(n[e]!==r){i=r;break}n=n.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}T.util.createClass=function(){var i=null,a=t.call(arguments,0);function o(){this.initialize.apply(this,arguments)}"function"==typeof a[0]&&(i=a.shift()),o.superclass=i,o.subclasses=[],i&&(r.prototype=i.prototype,o.prototype=new r,i.subclasses.push(o));for(var l=0,h=a.length;l-1||"touch"===t.pointerType},d="string"==typeof(u=T.document.createElement("div")).style.opacity,f="string"==typeof u.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},d?m=function(t,e){return t.style.opacity=e,t}:f&&(m=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),T.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var n in e)"opacity"===n?m(t,e[n]):i["float"===n||"cssFloat"===n?void 0===i.styleFloat?"cssFloat":"styleFloat":n]=e[n];return t},function(){var t,e,i,n,r=Array.prototype.slice,s=function(t){return r.call(t,0)};try{t=s(T.document.childNodes)instanceof Array}catch(t){}function a(t,e){var i=T.document.createElement(t);for(var n in e)"class"===n?i.className=e[n]:"for"===n?i.htmlFor=e[n]:i.setAttribute(n,e[n]);return i}function o(t){for(var e=0,i=0,n=T.document.documentElement,r=T.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===T.document?(e=r.scrollLeft||n.scrollLeft||0,i=r.scrollTop||n.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=T.document.defaultView&&T.document.defaultView.getComputedStyle?function(t,e){var i=T.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=T.document.documentElement.style,n="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",T.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=T.util.falseFunction),n?t.style[n]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},T.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),n?t.style[n]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},T.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},T.util.getById=function(t){return"string"==typeof t?T.document.getElementById(t):t},T.util.toArray=s,T.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},T.util.makeElement=a,T.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=a(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},T.util.getScrollLeftTop=o,T.util.getElementOffset=function(t){var i,n,r=t&&t.ownerDocument,s={left:0,top:0},a={left:0,top:0},l={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!r)return a;for(var h in l)a[l[h]]+=parseInt(e(t,h),10)||0;return i=r.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),n=o(t),{left:s.left+n.left-(i.clientLeft||0)+a.left,top:s.top+n.top-(i.clientTop||0)+a.top}},T.util.getNodeCanvas=function(t){var e=T.jsdomImplForWrapper(t);return e._canvas||e._image},T.util.cleanUpJsdomNode=function(t){if(T.isLikelyNode){var e=T.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}T.util.request=function(e,i){i||(i={});var n=i.method?i.method.toUpperCase():"GET",r=i.onComplete||function(){},s=new T.window.XMLHttpRequest,a=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(r(s),s.onreadystatechange=t)},"GET"===n&&(a=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(n,e,!0),"POST"!==n&&"PUT"!==n||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(a),s}}(),T.log=console.log,T.warn=console.warn,function(){var t=T.util.object.extend,e=T.util.object.clone,i=[];function n(){return!1}function r(t,e,i,n){return-i*Math.cos(t/n*(Math.PI/2))+i+e}T.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach((function(t){t.cancel()})),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter((function(e){return"object"==typeof e.target&&e.target.canvas===t}));return e.forEach((function(t){t.cancel()})),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach((function(t){t.cancel()})),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find((function(e){return e.cancel===t}))},findAnimationsByTarget:function(t){return t?this.filter((function(e){return e.target===t})):[]}});var s=T.window.requestAnimationFrame||T.window.webkitRequestAnimationFrame||T.window.mozRequestAnimationFrame||T.window.oRequestAnimationFrame||T.window.msRequestAnimationFrame||function(t){return T.window.setTimeout(t,1e3/60)},a=T.window.cancelAnimationFrame||T.window.clearTimeout;function o(){return s.apply(T.window,arguments)}T.util.animate=function(i){i||(i={});var s,a=!1,l=function(){var t=T.runningAnimations.indexOf(s);return t>-1&&T.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return a=!0,l()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),T.runningAnimations.push(s),o((function(t){var e,h=t||+new Date,c=i.duration||500,u=h+c,d=i.onChange||n,f=i.abort||n,g=i.onComplete||n,m=i.easing||r,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map((function(t,e){return v[e]-_[e]})):v-_);i.onStart&&i.onStart(),function t(i){var n=(e=i||+new Date)>u?c:e-h,r=n/c,w=p?_.map((function(t,e){return m(n,_[e],y[e],c)})):m(n,_,y,c),E=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=E,s.durationRate=r,!a){if(!f(w,E,r))return e>u?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,d(p?v.slice():v,1,1),g(v,1,1),void l()):(d(w,E,r),void o(t));l()}}(h)})),s.cancel},T.util.requestAnimFrame=o,T.util.cancelAnimFrame=function(){return a.apply(T.window,arguments)},T.runningAnimations=i}(),function(){function t(t,e,i){var n="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(n+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}T.util.animateColor=function(e,i,n,r){var s=new T.Color(e).getSource(),a=new T.Color(i).getSource(),o=r.onComplete,l=r.onChange;return r=r||{},T.util.animate(T.util.object.extend(r,{duration:n||500,startValue:s,endValue:a,byValue:a,easing:function(e,i,n,s){return t(i,n,r.colorEasing?r.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,n){if(o)return o(t(a,a,0),i,n)},onChange:function(e,i,n){if(l){if(Array.isArray(e))return l(t(e,e,0),i,n);l(e,i,n)}}}))}}(),function(){function t(t,e,i,n){return t-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===t||"xlink:href"===t||"font"===t)return i;if("imageSmoothing"===t)return"optimizeQuality"===i;o=l?i.map(s):s(i,r)}}else i="";return!l&&isNaN(o)?i:o}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,n,r,s,a=[];for(r=0,s=e.length;r1;)l.shift(),h=e.util.multiplyTransformMatrices(h,l[0]);return h}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,n,r,a,o,l,h=t.getAttribute("viewBox"),c=1,u=1,d=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!h||!(h=h.match(v)),y=!d||!f||"100%"===d||"100%"===f,w=_&&y,E={},C="",S=0,T=0;if(E.width=0,E.height=0,E.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(m)+") ",o=(t.getAttribute("transform")||"")+C,t.setAttribute("transform",o),t.removeAttribute("x"),t.removeAttribute("y")),w)return E;if(_)return E.width=s(d),E.height=s(f),E;if(i=-parseFloat(h[1]),n=-parseFloat(h[2]),r=parseFloat(h[3]),a=parseFloat(h[4]),E.minX=i,E.minY=n,E.viewBoxWidth=r,E.viewBoxHeight=a,y?(E.width=r,E.height=a):(E.width=s(d),E.height=s(f),c=E.width/r,u=E.height/a),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(u=c=c>u?u:c),"slice"===p.meetOrSlice&&(u=c=c>u?c:u),S=E.width-r*c,T=E.height-a*c,"Mid"===p.alignX&&(S/=2),"Mid"===p.alignY&&(T/=2),"Min"===p.alignX&&(S=0),"Min"===p.alignY&&(T=0)),1===c&&1===u&&0===i&&0===n&&0===g&&0===m)return E;if((g||m)&&"#document"!==t.parentNode.nodeName&&(C=" translate("+s(g)+" "+s(m)+") "),o=C+" matrix("+c+" 0 0 "+u+" "+(i*c+S)+" "+(n*u+T)+") ","svg"===t.nodeName){for(l=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)l.appendChild(t.firstChild);t.appendChild(l)}else(l=t).removeAttribute("x"),l.removeAttribute("y"),o=l.getAttribute("transform")+o;return l.setAttribute("transform",o),E}function w(t,e){var i="xlink:href",n=_(t,e.getAttribute(i).slice(1));if(n&&n.getAttribute(i)&&w(t,n),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(t){n&&!e.hasAttribute(t)&&n.hasAttribute(t)&&e.setAttribute(t,n.getAttribute(t))})),!e.children.length)for(var r=n.cloneNode(!0);r.firstChild;)e.appendChild(r.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,r,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),n=0;i.length&&nt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,n,r,s){var a,o=(s.x-r.x)*(t.y-r.y)-(s.y-r.y)*(t.x-r.x),l=(n.x-t.x)*(t.y-r.y)-(n.y-t.y)*(t.x-r.x),h=(s.y-r.y)*(n.x-t.x)-(s.x-r.x)*(n.y-t.y);if(0!==h){var c=o/h,u=l/h;0<=c&&c<=1&&0<=u&&u<=1?(a=new i("Intersection")).appendPoint(new e.Point(t.x+c*(n.x-t.x),t.y+c*(n.y-t.y))):a=new i}else a=new i(0===o||0===l?"Coincident":"Parallel");return a},e.Intersection.intersectLinePolygon=function(t,e,n){var r,s,a,o,l=new i,h=n.length;for(o=0;o0&&(l.status="Intersection"),l},e.Intersection.intersectPolygonPolygon=function(t,e){var n,r=new i,s=t.length;for(n=0;n0&&(r.status="Intersection"),r},e.Intersection.intersectPolygonRectangle=function(t,n,r){var s=n.min(r),a=n.max(r),o=new e.Point(a.x,s.y),l=new e.Point(s.x,a.y),h=i.intersectLinePolygon(s,o,t),c=i.intersectLinePolygon(o,a,t),u=i.intersectLinePolygon(a,l,t),d=i.intersectLinePolygon(l,s,t),f=new i;return f.appendPoints(h.points),f.appendPoints(c.points),f.appendPoints(u.points),f.appendPoints(d.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function n(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,n){t/=255,i/=255,n/=255;var r,s,a,o=e.util.array.max([t,i,n]),l=e.util.array.min([t,i,n]);if(a=(o+l)/2,o===l)r=s=0;else{var h=o-l;switch(s=a>.5?h/(2-o-l):h/(o+l),o){case t:r=(i-n)/h+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+u(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var n=i.transform.target,r=n.canvas,s=e.util.object.clone(i);s.target=n,r&&r.fire("object:"+t,s),n.fire(t,i)}function m(t,e){var i=e.canvas,n=t[i.uniScaleKey];return i.uniformScaling&&!n||!i.uniformScaling&&n}function p(t){return t.originX===h&&t.originY===h}function _(t,e,i){var n=t.lockScalingX,r=t.lockScalingY;return!((!n||!r)&&(e||!n&&!r||!i)&&(!n||"x"!==e)&&(!r||"y"!==e))}function v(t,e,i,n){return{e:t,transform:e,pointer:{x:i,y:n}}}function y(t){return function(e,i,n,r){var s=i.target,a=s.getCenterPoint(),o=s.translateToOriginPoint(a,i.originX,i.originY),l=t(e,i,n,r);return s.setPositionByOrigin(o,i.originX,i.originY),l}}function w(t,e){return function(i,n,r,s){var a=e(i,n,r,s);return a&&g(t,v(i,n,r,s)),a}}function E(t,i,n,r,s){var a=t.target,o=a.controls[t.corner],l=a.canvas.getZoom(),h=a.padding/l,c=a.toLocalPoint(new e.Point(r,s),i,n);return c.x>=h&&(c.x-=h),c.x<=-h&&(c.x+=h),c.y>=h&&(c.y-=h),c.y<=h&&(c.y+=h),c.x-=o.offsetX,c.y-=o.offsetY,c}function C(t){return t.flipX!==t.flipY}function S(t,e,i,n,r){if(0!==t[e]){var s=r/t._getTransformedDimensions()[n]*t[i];t.set(i,s)}}function T(t,e,i,n){var r,h=e.target,c=h._getTransformedDimensions(0,h.skewY),d=E(e,e.originX,e.originY,i,n),f=Math.abs(2*d.x)-c.x,g=h.skewX;f<2?r=0:(r=u(Math.atan2(f/h.scaleX,c.y/h.scaleY)),e.originX===s&&e.originY===l&&(r=-r),e.originX===o&&e.originY===a&&(r=-r),C(h)&&(r=-r));var m=g!==r;if(m){var p=h._getTransformedDimensions().y;h.set("skewX",r),S(h,"skewY","scaleY","y",p)}return m}function b(t,e,i,n){var r,h=e.target,c=h._getTransformedDimensions(h.skewX,0),d=E(e,e.originX,e.originY,i,n),f=Math.abs(2*d.y)-c.y,g=h.skewY;f<2?r=0:(r=u(Math.atan2(f/h.scaleY,c.x/h.scaleX)),e.originX===s&&e.originY===l&&(r=-r),e.originX===o&&e.originY===a&&(r=-r),C(h)&&(r=-r));var m=g!==r;if(m){var p=h._getTransformedDimensions().x;h.set("skewY",r),S(h,"skewX","scaleX","x",p)}return m}function I(t,e,i,n,r){r=r||{};var s,a,o,l,h,u,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=r.by,w=m(t,f),C=_(f,y,w),S=e.gestureScale;if(C)return!1;if(S)a=e.scaleX*S,o=e.scaleY*S;else{if(s=E(e,e.originX,e.originY,i,n),h="y"!==y?d(s.x):1,u="x"!==y?d(s.y):1,e.signX||(e.signX=h),e.signY||(e.signY=u),f.lockScalingFlip&&(e.signX!==h||e.signY!==u))return!1;if(l=f._getTransformedDimensions(),w&&!y){var T=Math.abs(s.x)+Math.abs(s.y),b=e.original,I=T/(Math.abs(l.x*b.scaleX/f.scaleX)+Math.abs(l.y*b.scaleY/f.scaleY));a=b.scaleX*I,o=b.scaleY*I}else a=Math.abs(s.x*f.scaleX/l.x),o=Math.abs(s.y*f.scaleY/l.y);p(e)&&(a*=2,o*=2),e.signX!==h&&"y"!==y&&(e.originX=c[e.originX],a*=-1,e.signX=h),e.signY!==u&&"x"!==y&&(e.originY=c[e.originY],o*=-1,e.signY=u)}var x=f.scaleX,R=f.scaleY;return y?("x"===y&&f.set("scaleX",a),"y"===y&&f.set("scaleY",o)):(!g&&f.set("scaleX",a),!v&&f.set("scaleY",o)),x!==f.scaleX||R!==f.scaleY}r.scaleCursorStyleHandler=function(t,e,n){var r=m(t,n),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(n,s,r))return"not-allowed";var a=f(n,e);return i[a]+"-resize"},r.skewCursorStyleHandler=function(t,e,i){var r="not-allowed";if(0!==e.x&&i.lockSkewingY)return r;if(0!==e.y&&i.lockSkewingX)return r;var s=f(i,e)%4;return n[s]+"-resize"},r.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?r.skewCursorStyleHandler(t,e,i):r.scaleCursorStyleHandler(t,e,i)},r.rotationWithSnapping=w("rotating",y((function(t,e,i,n){var r=e,s=r.target,a=s.translateToOriginPoint(s.getCenterPoint(),r.originX,r.originY);if(s.lockRotation)return!1;var o,l=Math.atan2(r.ey-a.y,r.ex-a.x),h=Math.atan2(n-a.y,i-a.x),c=u(h-l+r.theta);if(s.snapAngle>0){var d=s.snapAngle,f=s.snapThreshold||d,g=Math.ceil(c/d)*d,m=Math.floor(c/d)*d;Math.abs(c-m)0?s:o:(c>0&&(r=u===a?s:o),c<0&&(r=u===a?o:s),C(l)&&(r=r===s?o:s)),e.originX=r,w("skewing",y(T))(t,e,i,n))},r.skewHandlerY=function(t,e,i,n){var r,o=e.target,c=o.skewY,u=e.originX;return!o.lockSkewingY&&(0===c?r=E(e,h,h,i,n).y>0?a:l:(c>0&&(r=u===s?a:l),c<0&&(r=u===s?l:a),C(o)&&(r=r===a?l:a)),e.originY=r,w("skewing",y(b))(t,e,i,n))},r.dragHandler=function(t,e,i,n){var r=e.target,s=i-e.offsetX,a=n-e.offsetY,o=!r.get("lockMovementX")&&r.left!==s,l=!r.get("lockMovementY")&&r.top!==a;return o&&r.set("left",s),l&&r.set("top",a),(o||l)&&g("moving",v(t,e,i,n)),o||l},r.scaleOrSkewActionName=function(t,e,i){var n=t[i.canvas.altActionKey];return 0===e.x?n?"skewX":"scaleY":0===e.y?n?"skewY":"scaleX":void 0},r.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},r.fireEvent=g,r.wrapWithFixedAnchor=y,r.wrapWithFireEvent=w,r.getLocalPoint=E,e.controlsUtils=r}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,n=e.controlsUtils;n.renderCircleControl=function(t,e,i,n,r){n=n||{};var s,a=this.sizeX||n.cornerSize||r.cornerSize,o=this.sizeY||n.cornerSize||r.cornerSize,l=void 0!==n.transparentCorners?n.transparentCorners:r.transparentCorners,h=l?"stroke":"fill",c=!l&&(n.cornerStrokeColor||r.cornerStrokeColor),u=e,d=i;t.save(),t.fillStyle=n.cornerColor||r.cornerColor,t.strokeStyle=n.cornerStrokeColor||r.cornerStrokeColor,a>o?(s=a,t.scale(1,o/a),d=i*a/o):o>a?(s=o,t.scale(a/o,1),u=e*o/a):s=a,t.lineWidth=1,t.beginPath(),t.arc(u,d,s/2,0,2*Math.PI,!1),t[h](),c&&t.stroke(),t.restore()},n.renderSquareControl=function(t,e,n,r,s){r=r||{};var a=this.sizeX||r.cornerSize||s.cornerSize,o=this.sizeY||r.cornerSize||s.cornerSize,l=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,h=l?"stroke":"fill",c=!l&&(r.cornerStrokeColor||s.cornerStrokeColor),u=a/2,d=o/2;t.save(),t.fillStyle=r.cornerColor||s.cornerColor,t.strokeStyle=r.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,n),t.rotate(i(s.angle)),t[h+"Rect"](-u,-d,a,o),c&&t.strokeRect(-u,-d,a,o),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,n,r,s){var a,o,l,h,c=s?this.touchSizeX:this.sizeX,u=s?this.touchSizeY:this.sizeY;if(c&&u&&c!==u){var d=Math.atan2(u,c),f=Math.sqrt(c*c+u*u)/2,g=d-e.util.degreesToRadians(t),m=Math.PI/2-d-e.util.degreesToRadians(t);a=f*e.util.cos(g),o=f*e.util.sin(g),l=f*e.util.cos(m),h=f*e.util.sin(m)}else f=.7071067812*(c&&u?c:i),g=e.util.degreesToRadians(45-t),a=l=f*e.util.cos(g),o=h=f*e.util.sin(g);return{tl:{x:n-h,y:r-l},tr:{x:n+a,y:r-o},bl:{x:n-a,y:r+o},br:{x:n+h,y:r+l}}},render:function(t,i,n,r,s){"circle"===((r=r||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,n,r,s):e.controlsUtils.renderSquareControl.call(this,t,i,n,r,s)}}}(e),function(){function t(t,e){var i,n,r,s,a=t.getAttribute("style"),o=t.getAttribute("offset")||0;if(o=(o=parseFloat(o)/(/%$/.test(o)?100:1))<0?0:o>1?1:o,a){var l=a.split(/\s*;\s*/);for(""===l[l.length-1]&&l.pop(),s=l.length;s--;){var h=l[s].split(/\s*:\s*/),c=h[0].trim(),u=h[1].trim();"stop-color"===c?i=u:"stop-opacity"===c&&(r=u)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),r||(r=t.getAttribute("stop-opacity")),n=(i=new T.Color(i)).getAlpha(),r=isNaN(parseFloat(r))?1:parseFloat(r),r*=n*e,{offset:o,color:i.toRgb(),opacity:r}}var e=T.util.object.clone;T.Gradient=T.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach((function(e){i[e]=t[e]})),this.id?this.id+="_"+T.Object.__uid++:this.id=T.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new T.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return T.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var n,r,s,a,o=e(this.coords,!0),l=(i=i||{},e(this.colorStops,!0)),h=o.r1>o.r2,c=this.gradientTransform?this.gradientTransform.concat():T.iMatrix.concat(),u=-this.offsetX,d=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(l.sort((function(t,e){return t.offset-e.offset})),"objectBoundingBox"===g?(u/=t.width,d/=t.height):(u+=t.width/2,d+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(u-=t.pathOffset.x,d-=t.pathOffset.y),c[4]-=u,c[5]-=d,a='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',a+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+T.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(h)for((l=l.concat()).reverse(),n=0,r=l.length;n0){var p=m/Math.max(o.r1,o.r2);for(n=0,r=l.length;n\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,n,r=T.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(r.x1,r.y1,r.x2,r.y2):"radial"===this.type&&(e=t.createRadialGradient(r.x1,r.y1,r.r1,r.x2,r.y2,r.r2)),i=0,n=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var a,o,l,h,c=e.getElementsByTagName("stop"),u="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",d=e.getAttribute("gradientTransform")||"",f=[],g=0,m=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(a="linear",o=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(a="radial",o=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),l=c.length;l--;)f.push(t(c[l],s));return h=T.parseTransformAttribute(d),function(t,e,i,n){var r,s;Object.keys(e).forEach((function(t){"Infinity"===(r=e[t])?s=1:"-Infinity"===r?s=0:(s=parseFloat(e[t],10),"string"==typeof r&&/^(\d+\.\d+)%|(\d+)%$/.test(r)&&(s*=.01,"pixels"===n&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s}))}(0,o,r,u),"pixels"===u&&(g=-i.left,m=-i.top),new T.Gradient({id:e.getAttribute("id"),type:a,coords:o,colorStops:f,gradientUnits:u,gradientTransform:h,offsetX:g,offsetY:m})}})}(),_=T.util.toFixed,T.Pattern=T.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=T.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=T.util.createImage(),T.util.loadImage(t.source,(function(t,n){i.source=t,e&&e(i,n)}),null,this.crossOrigin)}},toObject:function(t){var e,i,n=T.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:_(this.offsetX,n),offsetY:_(this.offsetY,n),patternTransform:this.patternTransform?this.patternTransform.concat():null},T.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,n=e.height/t.height,r=this.offsetX/t.width,s=this.offsetY/t.height,a="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(n=1,s&&(n+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,r&&(i+=Math.abs(r))),e.src?a=e.src:e.toDataURL&&(a=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),n=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(n[1],10)||0,offsetY:parseFloat(n[2],10)||0,blur:parseFloat(n[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var n=40,r=40,s=e.Object.NUM_FRACTION_DIGITS,a=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),o=new e.Color(this.color);return t.width&&t.height&&(n=100*i((Math.abs(a.x)+this.blur)/t.width,s)+20,r=100*i((Math.abs(a.y)+this.blur)/t.height,s)+20),t.flipX&&(a.x*=-1),t.flipY&&(a.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(e){this[e]!==i[e]&&(t[e]=this[e])}),this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(T.StaticCanvas)T.warn("fabric.StaticCanvas is already defined.");else{var t=T.util.object.extend,e=T.util.getElementOffset,i=T.util.removeFromArray,n=T.util.toFixed,r=T.util.transformPoint,s=T.util.invertTransform,a=T.util.getNodeCanvas,o=T.util.createCanvasElement,l=new Error("Could not initialize `canvas` element");T.StaticCanvas=T.util.createClass(T.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:T.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return T.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,T.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=T.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,n){return"string"==typeof e?T.util.loadImage(e,(function(e,r){if(e){var s=new T.Image(e,n);this[t]=s,s.canvas=this}i&&i(e,r)}),this,n&&n.crossOrigin):(n&&e.setOptions(n),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=o();if(!t)throw l;if(t.style||(t.style={}),void 0===t.getContext)throw l;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=T.util.getById(t)||this._createCanvasElement(),T.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var n in e=e||{},t)i=t[n],e.cssOnly||(this._setBackstoreDimension(n,t[n]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(n,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,n,r=this._activeObject,s=this.backgroundImage,a=this.overlayImage;for(this.viewportTransform=t,i=0,n=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,r=e.width||this.width,s=e.height||this.height,a='viewBox="0 0 '+this.width+" "+this.height+'" ',o=T.Object.NUM_FRACTION_DIGITS;e.viewBox?a='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,a='viewBox="'+n(-i[4]/i[0],o)+" "+n(-i[5]/i[3],o)+" "+n(this.width/i[0],o)+" "+n(this.height/i[3],o)+'" '),t.push("\n',"Created with Fabric.js ",T.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+T.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map((function(e){var i=t[e+"Color"];if(i&&i.toLive){var n=t[e+"Vpt"],r=t.viewportTransform,s={width:t.width/(n?r[0]:1),height:t.height/(n?r[3]:1)};return i.toSVG(s,{additionalTransform:n?T.util.matrixToSVG(r):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,n,r,s,a,o,l="",h={},c=T.fontPaths,u=[];for(this._objects.forEach((function t(e){u.push(e),e._objects&&e._objects.forEach(t)})),a=0,o=u.length;a',"\n",l,"","\n"].join("")),l},_setSVGObjects:function(t,e){var i,n,r,s=this._objects;for(n=0,r=s.length;n\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(r=s._objects).length;e--;)n=r[e],i(this._objects,n),this._objects.unshift(n);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(r=s._objects,e=0;e0+h&&(a=s-1,i(this._objects,r),this._objects.splice(a,0,r)),h++;else 0!==(s=this._objects.indexOf(t))&&(a=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(a,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var n,r;if(i){for(n=e,r=e-1;r>=0;--r)if(t.intersectsWithObject(this._objects[r])||t.isContainedWithinObject(this._objects[r])||this._objects[r].isContainedWithinObject(t)){n=r;break}}else n=e-1;return n},bringForward:function(t,e){if(!t)return this;var n,r,s,a,o,l=this._activeObject,h=0;if(t===l&&"activeSelection"===t.type)for(n=(o=l._objects).length;n--;)r=o[n],(s=this._objects.indexOf(r))"}}),t(T.StaticCanvas.prototype,T.Observable),t(T.StaticCanvas.prototype,T.Collection),t(T.StaticCanvas.prototype,T.DataURLExporter),t(T.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=o();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),T.StaticCanvas.prototype.toJSON=T.StaticCanvas.prototype.toObject,T.isLikelyNode&&(T.StaticCanvas.prototype.createPNGStream=function(){var t=a(this.lowerCanvasEl);return t&&t.createPNGStream()},T.StaticCanvas.prototype.createJPEGStream=function(t){var e=a(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),T.BaseBrush=T.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,n=t.getZoom();t&&t._isRetinaScaling()&&(n*=T.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*n,i.shadowOffsetX=e.offsetX*n,i.shadowOffsetY=e.offsetY*n}},needsFullRender:function(){return new T.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),T.PencilBrush=T.util.createClass(T.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var n=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,n.x,n.y),n},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,n=i.length,r=this.canvas.contextTop;this._saveAndTransform(r),this.oldEnd&&(r.beginPath(),r.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(r,i[n-2],i[n-1],!0),r.stroke(),r.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new T.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new T.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,n=this._points[0],r=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&n.x===r.x&&n.y===r.y){var s=this.width/1e3;n=new T.Point(n.x,n.y),r=new T.Point(r.x,r.y),n.x-=s,r.x+=s}for(t.moveTo(n.x,n.y),e=1,i=this._points.length;e=r&&(a=t[i],o.push(a));return o.push(t[s]),o},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),T.CircleBrush=T.util.createClass(T.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,n=this.points;for(this._saveAndTransform(i),t=0,e=n.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var r=0,s=this._objects.length;r1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),n=T.util.invertTransform(i),r=this.restorePointerVpt(e);return T.util.transformPoint(r,n)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var n=this._normalizePointer(t,{x:e,y:i}),r=Math.max(t.cacheTranslationX+n.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+n.y*t.zoomY,0);return T.util.isTransparent(t._cacheContext,Math.round(r),Math.round(s),this.targetFindTolerance)}var a=this.contextCache,o=t.selectionBackgroundColor,l=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(a),a.save(),a.transform(l[0],l[1],l[2],l[3],l[4],l[5]),t.render(a),a.restore(),t.selectionBackgroundColor=o,T.util.isTransparent(a,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(e){return!0===t[e]})):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),n=this._activeObject;return!e||e&&n&&i.length>1&&-1===i.indexOf(e)&&n!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&n&&n!==e},_shouldCenterTransform:function(t,e,i){var n;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?n=this.centeredScaling||t.centeredScaling:"rotate"===e&&(n=this.centeredRotation||t.centeredRotation),n?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,n){if(!e||!t)return"drag";var r=n.controls[e];return r.getActionName(i,r,n)},_setupCurrentTransform:function(t,i,n){if(i){var r=this.getPointer(t),s=i.__corner,a=i.controls[s],o=n&&s?a.getActionHandler(t,i,a):T.controlsUtils.dragHandler,l=this._getActionFromCorner(n,s,t,i),h=this._getOriginFromCorner(i,s),c=t[this.centeredKey],u={target:i,action:l,actionHandler:o,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:r.x-i.left,offsetY:r.y-i.top,originX:h.x,originY:h.y,ex:r.x,ey:r.y,lastX:r.x,lastY:r.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:T.util.saveObjectTransform(i)};this._shouldCenterTransform(i,l,c)&&(u.originX="center",u.originY="center"),u.original.originX=h.x,u.original.originY=h.y,this._currentTransform=u,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new T.Point(e.ex,e.ey),n=T.util.transformPoint(i,this.viewportTransform),r=new T.Point(e.ex+e.left,e.ey+e.top),s=T.util.transformPoint(r,this.viewportTransform),a=Math.min(n.x,s.x),o=Math.min(n.y,s.y),l=Math.max(n.x,s.x),h=Math.max(n.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(a,o,l-a,h-o)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,a+=c,o+=c,l-=c,h-=c,T.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(a,o,l-a,h-o))},findTarget:function(t,e){if(!this.skipTargetFind){var n,r,s=this.getPointer(t,!0),a=this._activeObject,o=this.getActiveObjects(),l=i(t),h=o.length>1&&!e||1===o.length;if(this.targets=[],h&&a._findTargetCorner(s,l))return a;if(o.length>1&&!e&&a===this._searchPossibleTargets([a],s))return a;if(1===o.length&&a===this._searchPossibleTargets([a],s)){if(!this.preserveObjectStacking)return a;n=a,r=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&n&&c!==n&&(c=n,this.targets=r),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,n,r=t.length;r--;){var s=t[r],a=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(a,s,e)){(i=t[r]).subTargetCheck&&i instanceof T.Group&&(n=this._searchPossibleTargets(i._objects,e))&&this.targets.push(n);break}}return i},restorePointerVpt:function(t){return T.util.transformPoint(t,T.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var n,r=t(e),s=this.upperCanvasEl,a=s.getBoundingClientRect(),o=a.width||0,l=a.height||0;o&&l||("top"in a&&"bottom"in a&&(l=Math.abs(a.top-a.bottom)),"right"in a&&"left"in a&&(o=Math.abs(a.right-a.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,i||(r=this.restorePointerVpt(r));var h=this.getRetinaScaling();return 1!==h&&(r.x/=h,r.y/=h),n=0===o||0===l?{width:1,height:1}:{width:s.width/o,height:s.height/l},{x:r.x*n.width,y:r.y*n.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),T.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=T.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),T.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),T.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;T.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,T.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,n=this.getActiveObjects(),r=[],s=[];t.forEach((function(t){-1===n.indexOf(t)&&(i=!0,t.fire("deselected",{e:e,target:t}),s.push(t))})),n.forEach((function(n){-1===t.indexOf(n)&&(i=!0,n.fire("selected",{e:e,target:n}),r.push(n))})),t.length>0&&n.length>0?i&&this.fire("selection:updated",{e:e,selected:r,deselected:s}):n.length>0?this.fire("selection:created",{e:e,selected:r}):t.length>0&&this.fire("selection:cleared",{e:e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e:e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){T.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,T.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(t),r=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,n),r},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){e[i]=t[i]})),T.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,n)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),T.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),T.StaticCanvas)"prototype"!==n&&(T.Canvas[n]=T.StaticCanvas[n])}(),function(){var t=T.util.addListener,e=T.util.removeListener,i={passive:!1};function n(t,e){return t.button&&t.button===e-1}T.util.object.extend(T.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var n=this.upperCanvasEl,r=this._getEventPrefix();t(T.window,"resize",this._onResize),t(n,r+"down",this._onMouseDown),t(n,r+"move",this._onMouseMove,i),t(n,r+"out",this._onMouseOut),t(n,r+"enter",this._onMouseEnter),t(n,"wheel",this._onMouseWheel),t(n,"contextmenu",this._onContextMenu),t(n,"dblclick",this._onDoubleClick),t(n,"dragover",this._onDragOver),t(n,"dragenter",this._onDragEnter),t(n,"dragleave",this._onDragLeave),t(n,"drop",this._onDrop),this.enablePointerEvents||t(n,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](n,"gesture",this._onGesture),eventjs[e](n,"drag",this._onDrag),eventjs[e](n,"orientation",this._onOrientationChange),eventjs[e](n,"shake",this._onShake),eventjs[e](n,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(T.document,t+"up",this._onMouseUp),e(T.document,"touchend",this._onTouchEnd,i),e(T.document,t+"move",this._onMouseMove,i),e(T.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach((function(n){i.fire("mouse:out",{target:e,e:t}),n&&e.fire("mouseout",{e:t})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(t){t.isEditing&&t.hiddenTextarea.focus()}))},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(n){n.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(n)),this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();t(T.document,"touchend",this._onTouchEnd,i),t(T.document,"touchmove",this._onMouseMove,i),e(r,s+"down",this._onMouseDown)},_onMouseDown:function(n){this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();e(r,s+"move",this._onMouseMove,i),t(T.document,s+"up",this._onMouseUp),t(T.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(n){if(!(n.touches.length>0)){this.__onMouseUp(n),this._resetTransformEventData(),this.mainTouchId=null;var r=this._getEventPrefix();e(T.document,"touchend",this._onTouchEnd,i),e(T.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){t(s.upperCanvasEl,r+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(n){this.__onMouseUp(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(n)&&(e(T.document,s+"up",this._onMouseUp),e(T.document,s+"move",this._onMouseMove,i),t(r,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,r=this._groupSelector,s=!1,a=!r||0===r.left&&0===r.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),n(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,a);else{if(n(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,a),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!a){var o=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!o&&e===this._activeObject)}var l,h;if(e){if(l=e._findTargetCorner(this.getPointer(t,!0),T.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[l],u=c&&c.getMouseUpHandler(t,e,c);u&&u(t,i,(h=this.getPointer(t)).x,h.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==l)){var d=i.target&&i.target.controls[i.corner],f=d&&d.getMouseUpHandler(t,e,c);h=h||this.getPointer(t),f&&f(t,i,h.x,h.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,a),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():a||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),n=this.targets,r={e:e,target:i,subTargets:n};if(this.fire(t,r),i&&i.fire(t,r),!n)return i;for(var s=0;s1&&(e=new T.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],n=this._groupSelector.ex,r=this._groupSelector.ey,s=n+this._groupSelector.left,a=r+this._groupSelector.top,o=new T.Point(v(n,s),v(r,a)),l=new T.Point(y(n,s),y(r,a)),h=!this.selectionFullyContained,c=n===s&&r===a,u=this._objects.length;u--&&!((e=this._objects[u])&&e.selectable&&e.visible&&(h&&e.intersectsWithRect(o,l,!0)||e.isContainedWithinRect(o,l,!0)||h&&e.containsPoint(o,null,!0)||h&&e.containsPoint(l,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter((function(e){return!e.onSelect({e:t})}))),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),T.util.object.extend(T.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,n=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),r=this.toCanvasElement(n,t);return T.util.toDataURL(r,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,n=(e.height||this.height)*t,r=this.getZoom(),s=this.width,a=this.height,o=r*t,l=this.viewportTransform,h=(l[4]-(e.left||0))*t,c=(l[5]-(e.top||0))*t,u=this.interactive,d=[o,0,0,o,h,c],f=this.enableRetinaScaling,g=T.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=n,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=d,this.width=i,this.height=n,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=l,this.width=s,this.height=a,this.calcViewportBoundaries(),this.interactive=u,this.enableRetinaScaling=f,this.contextTop=m,g}}),T.util.object.extend(T.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var n="string"==typeof t?JSON.parse(t):T.util.object.clone(t),r=this,s=n.clipPath,a=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete n.clipPath,this._enlivenObjects(n.objects,(function(t){r.clear(),r._setBgOverlay(n,(function(){s?r._enlivenObjects([s],(function(i){r.clipPath=i[0],r.__setupCanvas.call(r,n,t,a,e)})):r.__setupCanvas.call(r,n,t,a,e)}))}),i),this}},__setupCanvas:function(t,e,i,n){var r=this;e.forEach((function(t,e){r.insertAt(t,e)})),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),n&&n()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var n=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,n),this.__setBgOverlay("overlayImage",t.overlayImage,i,n),this.__setBgOverlay("backgroundColor",t.background,i,n),this.__setBgOverlay("overlayColor",t.overlay,i,n)}else e&&e()},__setBgOverlay:function(t,e,i,n){var r=this;if(!e)return i[t]=!0,void(n&&n());"backgroundImage"===t||"overlayImage"===t?T.util.enlivenObjects([e],(function(e){r[t]=e[0],i[t]=!0,n&&n()})):this["set"+T.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,n&&n()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?T.util.enlivenObjects(t,(function(t){e&&e(t)}),null,i):e&&e([])},_toDataURL:function(t,e){this.clone((function(i){e(i.toDataURL(t))}))},_toDataURLWithMultiplier:function(t,e,i){this.clone((function(n){i(n.toDataURLWithMultiplier(t,e))}))},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData((function(e){e.loadFromJSON(i,(function(){t&&t(e)}))}))},cloneWithoutData:function(t){var e=T.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new T.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),t&&t(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r=e.util.toFixed,s=e.util.string.capitalize,a=e.util.degreesToRadians,o=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:o,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,n=t.width,r=t.height,s=e.maxCacheSideLimit,a=e.minCacheSideLimit;if(n<=s&&r<=s&&n*r<=i)return nc&&(t.zoomX/=n/c,t.width=c,t.capped=!0),r>u&&(t.zoomY/=r/u,t.height=u,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,n=e.y*t.scaleY/this.scaleY;return{width:i+2,height:n+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:n}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,n=t._currentTransform.action;if(this===i&&n.slice&&"scale"===n.slice(0,5))return!1}var r,s,a=this._cacheCanvas,o=this._limitCacheSize(this._getCacheCanvasDimensions()),l=e.minCacheSideLimit,h=o.width,c=o.height,u=o.zoomX,d=o.zoomY,f=h!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==u||this.zoomY!==d,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,E=h>y||c>w;v=E||(h<.9*y||c<.9*w)&&y>l&&w>l,E&&!o.capped&&(h>l||c>l)&&(p=.1*h,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(a.width=Math.ceil(h+p),a.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,a.width,a.height)),r=o.x/2,s=o.y/2,this.cacheTranslationX=Math.round(a.width/2-r)+r,this.cacheTranslationY=Math.round(a.height/2-s)+s,this.cacheWidth=h,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(u,d),this.zoomX=u,this.zoomY=d,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,n={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:r(this.left,i),top:r(this.top,i),width:r(this.width,i),height:r(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:r(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:r(this.strokeMiterLimit,i),scaleX:r(this.scaleX,i),scaleY:r(this.scaleY,i),angle:r(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:r(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:r(this.skewX,i),skewY:r(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(n.clipPath=this.clipPath.toObject(t),n.clipPath.inverted=this.clipPath.inverted,n.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,n,t),this.includeDefaultValues||(n=this._removeDefaultValues(n)),n},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach((function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])})),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var n=this.canvas.getZoom(),r=this.canvas.getRetinaScaling();e*=n*r,i*=n*r}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var n="scaleX"===t||"scaleY"===t,r=this[t]!==i,s=!1;return n&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,r&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var n=e.util.invertTransform(this.calcTransformMatrix());t.transform(n[0],n[1],n[2],n[3],n[4],n[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=n},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var n,r,s,o=this.getViewportTransform(),l=this.calcTransformMatrix();r=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,l=e.util.multiplyTransformMatrices(o,l),n=e.util.qrDecompose(l),t.save(),t.translate(n.translateX,n.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(n.angle-=180),t.rotate(a(this.group?n.angle:this.angle)),i.forActiveSelection||this.group?r&&this.drawBordersInGroup(t,n,i):r&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,n=this.shadow,r=this.canvas,s=r&&r.viewportTransform[0]||1,a=r&&r.viewportTransform[3]||1;i=n.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),r&&r._isRetinaScaling()&&(s*=e.devicePixelRatio,a*=e.devicePixelRatio),t.shadowColor=n.color,t.shadowBlur=n.blur*e.browserShadowBlurConstant*(s+a)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=n.offsetX*s*i.scaleX,t.shadowOffsetY=n.offsetY*a*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,n=-this.width/2+e.offsetX||0,r=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,n,r):t.transform(1,0,0,1,n,r),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:n,offsetY:r}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var n,r=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),a=this.canvas.getRetinaScaling(),o=r.x/this.scaleX/a,l=r.y/this.scaleY/a;s.width=o,s.height=l,(n=s.getContext("2d")).beginPath(),n.moveTo(0,0),n.lineTo(o,0),n.lineTo(o,l),n.lineTo(0,l),n.closePath(),n.translate(o/2,l/2),n.scale(r.zoomX/this.scaleX/a,r.zoomY/this.scaleY/a),this._applyPatternGradientTransform(n,i),n.fillStyle=i.toLive(t),n.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(a*this.scaleX/r.zoomX,a*this.scaleY/r.zoomY),t.strokeStyle=n.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var n=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(n,t):e.Object._fromObject("Object",n,t)},cloneAsImage:function(t,i){var n=this.toCanvasElement(i);return t&&t(new e.Image(n)),this},toCanvasElement:function(t){t||(t={});var i=e.util,n=i.saveObjectTransform(this),r=this.group,s=this.shadow,a=Math.abs,o=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var l,h,c,u,d=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(h=g.blur,l=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(a(g.offsetX)+h)*a(l.scaleX),m.y=2*Math.round(a(g.offsetY)+h)*a(l.scaleY)),c=f.width+m.x,u=f.height+m.y,d.width=Math.ceil(c),d.height=Math.ceil(u);var p=new e.StaticCanvas(d,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var _=this.canvas;p.add(this);var v=p.toCanvasElement(o||1,t);return this.shadow=s,this.set("canvas",_),r&&(this.group=r),this.set(n).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var n=new e.Point(i.x,i.y),r=this._getLeftTopCoords();return this.angle&&(n=e.util.rotatePoint(n,r,a(-this.angle))),{x:n.x-r.x,y:n.y-r.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,r,s){var a=e[t];i=n(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],(function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,(function(){var t=s?new a(i[s],i):new a(i);r&&r(t)}))}))},e.Object.__uid=0)}(e),w=T.util.degreesToRadians,E={left:-.5,center:0,right:.5},C={top:-.5,center:0,bottom:.5},T.util.object.extend(T.Object.prototype,{translateToGivenOrigin:function(t,e,i,n,r){var s,a,o,l=t.x,h=t.y;return"string"==typeof e?e=E[e]:e-=.5,"string"==typeof n?n=E[n]:n-=.5,"string"==typeof i?i=C[i]:i-=.5,"string"==typeof r?r=C[r]:r-=.5,a=r-i,((s=n-e)||a)&&(o=this._getTransformedDimensions(),l=t.x+s*o.x,h=t.y+a*o.y),new T.Point(l,h)},translateToCenterPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?T.util.rotatePoint(n,t,w(this.angle)):n},translateToOriginPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?T.util.rotatePoint(n,t,w(this.angle)):n},getCenterPoint:function(){var t=new T.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var n,r,s=this.getCenterPoint();return n=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new T.Point(this.left,this.top),r=new T.Point(t.x,t.y),this.angle&&(r=T.util.rotatePoint(r,s,-w(this.angle))),r.subtractEquals(n)},setPositionByOrigin:function(t,e,i){var n=this.translateToCenterPoint(t,e,i),r=this.translateToOriginPoint(n,this.originX,this.originY);this.set("left",r.x),this.set("top",r.y)},adjustPosition:function(t){var e,i,n=w(this.angle),r=this.getScaledWidth(),s=T.util.cos(n)*r,a=T.util.sin(n)*r;e="string"==typeof this.originX?E[this.originX]:this.originX-.5,i="string"==typeof t?E[t]:t-.5,this.left+=s*(i-e),this.top+=a*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=T.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,n=t.transformPoint;t.object.extend(T.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new T.Point(i.tl.x,i.tl.y),new T.Point(i.tr.x,i.tr.y),new T.Point(i.br.x,i.br.y),new T.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,n){var r=this.getCoords(i,n);return"Intersection"===T.Intersection.intersectPolygonRectangle(r,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===T.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var n=this.getCoords(e,i),r=e?t.aCoords:t.lineCoords,s=0,a=t._getImageLines(r);s<4;s++)if(!t.containsPoint(n[s],a))return!1;return!0},isContainedWithinRect:function(t,e,i,n){var r=this.getBoundingRect(i,n);return r.left>=t.x&&r.left+r.width<=e.x&&r.top>=t.y&&r.top+r.height<=e.y},containsPoint:function(t,e,i,n){var r=this._getCoords(i,n),s=(e=e||this._getImageLines(r),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some((function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y}))||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var n={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(n,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every((function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)}))&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,n,r,s=0;for(var a in e)if(!((r=e[a]).o.y=t.y&&r.d.y>=t.y||(r.o.x===r.d.x&&r.o.x>=t.x?n=r.o.x:(i=(r.d.y-r.o.y)/(r.d.x-r.o.x),n=-(t.y-0*t.x-(r.o.y-i*r.o.x))/(0-i)),n>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var n=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(n)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,n=e.additionalTransform||"",r=[this.getSvgTransform(!0,n),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=r,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,n,r=(e=e||{}).noStyle,s=e.reviver,a=r?"":'style="'+this.getSvgStyles()+'" ',o=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",l=this.clipPath,h=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=l&&l.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return l&&(l.clipPathId="CLIPPATH_"+T.Object.__uid++,n='\n'+l.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[a,h,r?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=i,d&&d.toLive&&g.push(d.toSVG(this)),u&&u.toLive&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),l&&g.push(n),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=T.util.object.extend,e="stateProperties";function i(e,i,n){var r={};n.forEach((function(t){r[t]=e[t]})),t(e[i],r,!0)}function n(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var r=0,s=t.length;r=0;l--)if(r=o[l],this.isControlVisible(r)&&(n=this._getImageLines(e?this.oCoords[r].touchCorner:this.oCoords[r].corner),0!==(i=this._findCrossPoints({x:s,y:a},n))&&i%2==1))return this.__corner=r,r;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),n=this._calculateCurrentDimensions(),r=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/r[0],1/r[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-n.x/2,-n.y/2,n.x,n.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),n=this.borderScaleFactor,r=i.x+n,s=i.y+n,a=void 0!==e.hasControls?e.hasControls:this.hasControls,o=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-r/2,-s/2,r,s),a&&(t.beginPath(),this.forEachControl((function(e,i,n){e.withConnection&&e.getVisibility(n,i)&&(o=!0,t.moveTo(e.x*r,e.y*s),t.lineTo(e.x*r+e.offsetX,e.y*s+e.offsetY))})),o&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var n=T.util.sizeAfterTransform(this.width,this.height,e),r=this.strokeWidth,s=this.strokeUniform,a=this.borderScaleFactor,o=n.x+r*(s?this.canvas.getZoom():e.scaleX)+a,l=n.y+r*(s?this.canvas.getZoom():e.scaleY)+a;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-o/2,-l/2,o,l),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,n,r=this.canvas.getRetinaScaling();return t.setTransform(r,0,0,r,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(r,s,a){n=a.oCoords[s],r.getVisibility(a,s)&&(i&&(n=T.util.transformPoint(n,i)),r.render(t,n.x,n.y,e,a))})),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),T.util.object.extend(T.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxCenterObjectV:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxRemove:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return T.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),r()},onComplete:function(){s.remove(t),n()}})}}),T.util.object.extend(T.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],n=[];for(t in arguments[0])i.push(t);for(var r=0,s=i.length;r-1||r&&s.colorProperties.indexOf(r[1])>-1,o=r?this.get(r[0])[r[1]]:this.get(t);"from"in i||(i.from=o),a||(e=~e.indexOf("=")?o+parseFloat(e.replace("=","")):parseFloat(e));var l={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,n){return i.abort.call(s,t,e,n)},onChange:function(e,a,o){r?s[r[0]][r[1]]=e:s.set(t,e),n||i.onChange&&i.onChange(e,a,o)},onComplete:function(t,e,r){n||(s.setCoords(),i.onComplete&&i.onComplete(t,e,r))}};return a?T.util.animateColor(l.startValue,l.endValue,l.duration,l):T.util.animate(l)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,n=t.axis1,r=t.axis2,s=t.dimension,a=e.nearest,o=e.center,l=e.farthest;return function(){switch(this.get(i)){case a:return Math.min(this.get(n),this.get(r));case o:return Math.min(this.get(n),this.get(r))+.5*this.get(s);case l:return Math.max(this.get(n),this.get(r))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==r[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,n=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:n,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,n,r){r=r||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),a=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];n(new e.Line(a,i(s,r)))},e.Line.fromObject=function(t,i){var r=n(t,!0);r.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",r,(function(t){delete t.points,i&&i(t)}),"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,n=(this.endAngle-this.startAngle)%360;if(0===n)t=["\n'];else{var r=i(this.startAngle),s=i(this.endAngle),a=this.radius;t=['180?"1":"0")+" 1"," "+e.util.cos(s)*a+" "+e.util.sin(s)*a,'" ',"COMMON_PARTS"," />\n"]}return t},_render:function(t){t.beginPath(),t.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(t)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(t){return this.radius=t,this.set("width",2*t).set("height",2*t)}}),e.Circle.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),e.Circle.fromElement=function(t,i){var n,r=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(n=r)&&n.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");r.left=(r.left||0)-r.radius,r.top=(r.top||0)-r.radius,i(new e.Circle(r))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var n=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);n.left=(n.left||0)-n.rx,n.top=(n.top||0)-n.ry,i(new e.Ellipse(n))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,n=this.width,r=this.height,s=-this.width/2,a=-this.height/2,o=0!==e||0!==i,l=.4477152502;t.beginPath(),t.moveTo(s+e,a),t.lineTo(s+n-e,a),o&&t.bezierCurveTo(s+n-l*e,a,s+n,a+l*i,s+n,a+i),t.lineTo(s+n,a+r-i),o&&t.bezierCurveTo(s+n,a+r-l*i,s+n-l*e,a+r,s+n-e,a+r),t.lineTo(s+e,a+r),o&&t.bezierCurveTo(s+l*e,a+r,s,a+r-l*i,s,a+r-i),t.lineTo(s,a+i),o&&t.bezierCurveTo(s,a+l*i,s+l*e,a,s+e,a),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,n,r){if(!t)return n(null);r=r||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var a=new e.Rect(i(r?e.util.object.clone(r):{},s));a.visible=a.visible&&a.width>0&&a.height>0,n(a)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.array.min,r=e.util.array.max,s=e.util.toFixed,a=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return a(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),n=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-n,this.height=i.height-n,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+n/2,y:i.top-this.strokeWidth/2+n/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+n/2,y:i.top+this.height/2+n/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=n(t,"x")||0,i=n(t,"y")||0;return{left:e,top:i,width:(r(t,"x")||0)-e,height:(r(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,n=this.pathOffset.y,r=e.Object.NUM_FRACTION_DIGITS,a=0,o=this.points.length;a\n']},commonRender:function(t){var e,i=this.points.length,n=this.pathOffset.x,r=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-n,this.points[0].y-r);for(var s=0;s"},toObject:function(t){return r(this.callSuper("toObject",t),{path:this.path.map((function(t){return t.slice()}))})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+a(-this.pathOffset.x,t)+", "+a(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,r,s=[],a=[],o=0,l=0,h=0,c=0,u=0,d=this.path.length;u"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var n=this._objects.length;if(this.useSetOnGroup)for(;n--;)this._objects[n].setOnGroup(t,i);if("canvas"===t)for(;n--;)this._objects[n]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,n=this._objects.filter((function(t){return!t.excludeFromExport})).map((function(e){var n=e.includeDefaultValues;e.includeDefaultValues=i;var r=e.toObject(t);return e.includeDefaultValues=n,r})),r=e.Object.prototype.toObject.call(this,t);return r.objects=n,r},toDatalessObject:function(t){var i,n=this.sourcePath;if(n)i=n;else{var r=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=r;var n=e.toDatalessObject(t);return e.includeDefaultValues=i,n}))}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,n=this._objects.length;i\n"],i=0,n=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,n=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var n=0,r=this._objects.length;n\n','\t\n',"\n"),a=' clip-path="url(#imageCrop_'+l+')" '}if(this.imageSmoothing||(o='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var h=this.fill;this.fill=null,t=["\t\n'],this.fill=h}return"fill"!==this.paintFirst?e.concat(t,i):e.concat(i,t)},getSrc:function(t){var e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src"):e.src:this.src||""},setSrc:function(t,e,i){return T.util.loadImage(t,(function(t,n){this.setElement(t,i),this._setWidthHeight(),e&&e(this,n)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),n=i.scaleX,r=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||n>e&&r>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=n,void(this._lastScaleY=r);T.filterBackend||(T.filterBackend=T.initFilterBackend());var a=T.util.createCanvasElement(),o=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,l=s.width,h=s.height;a.width=l,a.height=h,this._element=a,this._lastScaleX=t.scaleX=n,this._lastScaleY=t.scaleY=r,T.filterBackend.applyFilters([t],s,l,h,this._element,o),this._filterScalingX=a.width/this._originalElement.width,this._filterScalingY=a.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter((function(t){return t&&!t.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,n=e.naturalHeight||e.height;if(this._element===this._originalElement){var r=T.util.createCanvasElement();r.width=i,r.height=n,this._element=r,this._filteredEl=r}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,n),this._lastScaleX=1,this._lastScaleY=1;return T.filterBackend||(T.filterBackend=T.initFilterBackend()),T.filterBackend.applyFilters(t,this._originalElement,i,n,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){T.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){T.util.setImageSmoothing(t,this.imageSmoothing),T.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,n=this._filterScalingY,r=this.width,s=this.height,a=Math.min,o=Math.max,l=o(this.cropX,0),h=o(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=l*i,f=h*n,g=a(r*i,c-d),m=a(s*n,u-f),p=-r/2,_=-s/2,v=a(r,c/i-l),y=a(s,u/n-h);e&&t.drawImage(e,d,f,g,m,p,_,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(T.util.getById(t),e),T.util.addClass(this.getElement(),T.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?T.util.enlivenObjects(t,(function(t){e&&e(t)}),"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=T.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,n=this._element.height,r=1,s=1,a=0,o=0,l=0,h=0,c=this.width,u=this.height,d={width:c,height:u};return!e||"none"===e.alignX&&"none"===e.alignY?(r=c/i,s=u/n):("meet"===e.meetOrSlice&&(t=(c-i*(r=s=T.util.findScaleToFit(this._element,d)))/2,"Min"===e.alignX&&(a=-t),"Max"===e.alignX&&(a=t),t=(u-n*s)/2,"Min"===e.alignY&&(o=-t),"Max"===e.alignY&&(o=t)),"slice"===e.meetOrSlice&&(t=i-c/(r=s=T.util.findScaleToCover(this._element,d)),"Mid"===e.alignX&&(l=t/2),"Max"===e.alignX&&(l=t),t=n-u/s,"Mid"===e.alignY&&(h=t/2),"Max"===e.alignY&&(h=t),i=c/r,n=u/s)),{width:i,height:n,scaleX:r,scaleY:s,offsetLeft:a,offsetTop:o,cropX:l,cropY:h}}}),T.Image.CSS_CANVAS="canvas-img",T.Image.prototype.getSvgSrc=T.Image.prototype.getSrc,T.Image.fromObject=function(t,e){var i=T.util.object.clone(t);T.util.loadImage(i.src,(function(t,n){n?e&&e(null,!0):T.Image.prototype._initFilters.call(i,i.filters,(function(n){i.filters=n||[],T.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(n){i.resizeFilter=n[0],T.util.enlivenObjectEnlivables(i,i,(function(){var n=new T.Image(t,i);e(n,!1)}))}))}))}),null,i.crossOrigin)},T.Image.fromURL=function(t,e,i){T.util.loadImage(t,(function(t,n){e&&e(new T.Image(t,i),n)}),null,i&&i.crossOrigin)},T.Image.ATTRIBUTE_NAMES=T.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),T.Image.fromElement=function(t,i,n){var r=T.parseAttributes(t,T.Image.ATTRIBUTE_NAMES);T.Image.fromURL(r["xlink:href"],i,e(n?T.util.object.clone(n):{},r))})}(e),T.util.object.extend(T.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,n=t.onChange||e,r=this;return T.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){r.rotate(t),n()},onComplete:function(){r.setCoords(),i()}})}}),T.util.object.extend(T.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",n=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(n,i),t.compileShader(n),!!t.getShaderParameter(n,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}T.isWebglSupported=function(e){if(T.isLikelyNode)return!1;e=e||T.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),n=i.getContext("webgl")||i.getContext("experimental-webgl"),r=!1;if(n){T.maxTextureSize=n.getParameter(n.MAX_TEXTURE_SIZE),r=T.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],a=0;a<3;a++)if(t(n,s[a])){T.webGlPrecision=s[a];break}}return this.isSupported=r,r},T.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,n=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var r="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(n&&i&&r&&s){var a=T.util.createCanvasElement(),o=new ArrayBuffer(t*e*4);if(T.forceGLPutImageData)return this.imageBuffer=o,void(this.copyGLTo2D=x);var l,h,c={imageBuffer:o,destinationWidth:t,destinationHeight:e,targetCanvas:a};a.width=t,a.height=e,l=window.performance.now(),I.call(c,this.gl,c),h=window.performance.now()-l,l=window.performance.now(),x.call(c,this.gl,c),h>window.performance.now()-l?(this.imageBuffer=o,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=T.util.createCanvasElement();i.width=t,i.height=e;var n={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},r=i.getContext("webgl",n);r||(r=i.getContext("experimental-webgl",n)),r&&(r.clearColor(0,0,0,0),this.canvas=i,this.gl=r)},applyFilters:function(t,e,i,n,r,s){var a,o=this.gl;s&&(a=this.getCachedTexture(s,e));var l={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:n,destinationWidth:i,destinationHeight:n,context:o,sourceTexture:this.createTexture(o,i,n,!a&&e),targetTexture:this.createTexture(o,i,n),originalTexture:a||this.createTexture(o,i,n,!a&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:r},h=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,h),t.forEach((function(t){t&&t.applyTo(l)})),function(t){var e=t.targetCanvas,i=e.width,n=e.height,r=t.destinationWidth,s=t.destinationHeight;i===r&&n===s||(e.width=r,e.height=s)}(l),this.copyGLTo2D(o,l),o.bindTexture(o.TEXTURE_2D,null),o.deleteTexture(l.sourceTexture),o.deleteTexture(l.targetTexture),o.deleteFramebuffer(h),r.getContext("2d").setTransform(1,0,0,1,0,0),l},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,n){var r=t.createTexture();return t.bindTexture(t.TEXTURE_2D,r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),n?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,n):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),r},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var n=t.getParameter(i.UNMASKED_RENDERER_WEBGL),r=t.getParameter(i.UNMASKED_VENDOR_WEBGL);n&&(e.renderer=n.toLowerCase()),r&&(e.vendor=r.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}T.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,n,r){var s=r.getContext("2d");s.drawImage(e,0,0,i,n);var a={sourceWidth:i,sourceHeight:n,imageData:s.getImageData(0,0,i,n),originalEl:e,originalImageData:s.getImageData(0,0,i,n),canvasEl:r,ctx:s,filterBackend:this};return t.forEach((function(t){t.applyTo(a)})),a.imageData.width===i&&a.imageData.height===n||(r.width=a.imageData.width,r.height=a.imageData.height),s.putImageData(a.imageData,0,0),a}}}(),T.Image=T.Image||{},T.Image.filters=T.Image.filters||{},T.Image.filters.BaseFilter=T.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==T.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+T.webGlPrecision+" float"));var n=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var r=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var s=t.createProgram();if(t.attachShader(s,n),t.attachShader(s,r),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var a=this.getAttributeLocations(t,s),o=this.getUniformLocations(t,s)||{};return o.uStepW=t.getUniformLocation(s,"uStepW"),o.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:a,uniformLocations:o}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var n=e.aPosition,r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,n=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(n.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(n,e,i)),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t.targetTexture,0)):(n.bindFramebuffer(n.FRAMEBUFFER,null),n.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=T.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),T.Image.filters.BaseFilter.fromObject=function(t,e){var i=new T.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.ColorMatrix=n(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,n,r,s,a=t.imageData.data,o=a.length,l=this.matrix,h=this.colorsOnly;for(s=0;s=w||a<0||a>=y||(l=4*(o*y+a),h=p[f*_+d],e+=m[l]*h,i+=m[l+1]*h,n+=m[l+2]*h,S||(r+=m[l+3]*h));C[s]=e,C[s+1]=i,C[s+2]=n,C[s+3]=S?m[s+3]:r}t.imageData=E},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Grayscale=n(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,n=t.imageData.data,r=n.length,s=this.mode;for(e=0;eh[0]&&r>h[1]&&s>h[2]&&n 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,n,r,s,a,o,l,h=t.imageData.data,c=h.length,u=1-this.alpha;i=(l=new e.Color(this.color).getSource())[0]*this.alpha,n=l[1]*this.alpha,r=l[2]*this.alpha;for(var d=0;d=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return o(e)/e*o(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,n=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/n;var r,s=e.width,o=e.height,l=a(s*i),h=a(o*n);"sliceHack"===this.resizeType?r=this.sliceByTwo(t,s,o,l,h):"hermite"===this.resizeType?r=this.hermiteFastResize(t,s,o,l,h):"bilinear"===this.resizeType?r=this.bilinearFiltering(t,s,o,l,h):"lanczos"===this.resizeType&&(r=this.lanczosResize(t,s,o,l,h)),t.imageData=r},sliceByTwo:function(t,i,r,s,a){var o,l,h=t.imageData,c=.5,u=!1,d=!1,f=i*c,g=r*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((o=m.sliceByTwo).width<1.5*i||o.height=e)){L=n(1e3*s(T-E.x)),w[L]||(w[L]={});for(var F=C.y-y;F<=C.y+y;F++)F<0||F>=a||(M=n(1e3*s(F-E.y)),w[L][M]||(w[L][M]=f(r(i(L*p,2)+i(M*_,2))/1e3)),(b=w[L][M])>0&&(x+=b,R+=b*c[I=4*(F*e+T)],O+=b*c[I+1],D+=b*c[I+2],A+=b*c[I+3]))}d[I=4*(S*o+l)]=R/x,d[I+1]=O/x,d[I+2]=D/x,d[I+3]=A/x}return++l1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(b+=y*f[3+(L=4*(A+x*e))],E+=y,f[L+3]<255&&(y=y*f[L+3]/250),C+=y*f[L],S+=y*f[L+1],T+=y*f[L+2],w+=y)}m[v]=C/w,m[v+1]=S/w,m[v+2]=T/w,m[v+3]=b/E}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Contrast=n(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,n=i.length,r=Math.floor(255*this.contrast),s=259*(r+255)/(255*(259-r));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Gamma=n(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,n=this.gamma,r=i.length,s=1/n[0],a=1/n[1],o=1/n[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,r=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=n)}return t},_renderTextLine:function(t,e,i,n,r,s){this._renderChars(t,e,i,n,r,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,n,r,s,a,o,l=t.fillStyle,h=this._getLeftOffset(),c=this._getTopOffset(),u=0,d=0,f=this.path,g=0,m=this._textLines.length;g=0:io?u%=o:u<0&&(u+=o),this._setGraphemeOnPath(u,s,a),u+=s.kernedWidth}return{width:l,numOfSpaces:0}},_setGraphemeOnPath:function(t,i,n){var r=t+i.kernedWidth/2,s=this.path,a=e.util.getPointOnPath(s.path,r,s.segmentsInfo);i.renderLeft=a.x-n.x,i.renderTop=a.y-n.y,i.angle=a.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,n,r){var s,a=this.getCompleteStyleDeclaration(e,i),o=n?this.getCompleteStyleDeclaration(e,i-1):{},l=this._measureChar(t,a,n,o),h=l.kernedWidth,c=l.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),h+=s);var u={width:c,left:0,height:a.fontSize,kernedWidth:h,deltaY:a.deltaY};if(i>0&&!r){var d=this.__charBounds[e][i-1];u.left=d.left+d.width+l.kernedWidth-l.width}return u},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),n=1,r=e.length;n0){var x=v+s+u;"rtl"===this.direction&&(x=this.width-x-d),h&&_&&(t.fillStyle=_,t.fillRect(x,c+C*n+a,d,this.fontSize/15)),u=f.left,d=f.width,h=g,_=p,n=r,a=o}else d+=f.kernedWidth;x=v+s+u,"rtl"===this.direction&&(x=this.width-x-d),t.fillStyle=p,g&&p&&t.fillRect(x,c+C*n+a,d-E,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var n=t||this,r=this.fontFamily,s=e.Text.genericFonts.indexOf(r.toLowerCase())>-1,a=void 0===r||r.indexOf("'")>-1||r.indexOf(",")>-1||r.indexOf('"')>-1||s?n.fontFamily:'"'+n.fontFamily+'"';return[e.isLikelyNode?n.fontWeight:n.fontStyle,e.isLikelyNode?n.fontStyle:n.fontWeight,i?this.CACHE_FONT_SIZE+"px":n.fontSize+"px",a].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),n=new Array(i.length),r=["\n"],s=[],a=0;a-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}T.IText=T.util.createClass(T.Text,T.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:n.left,topOffset:n.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,n,r,s=0,a=0,o=this.get2DCursorLocation(t);n=o.charIndex,i=o.lineIndex;for(var l=0;l0?a:0)},"rtl"===this.direction&&(r.left*=-1),this.cursorOffsetCache=r,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),n=i.lineIndex,r=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(n,r,"fontSize"),a=this.scaleX*this.canvas.getZoom(),o=this.cursorWidth/a,l=t.topOffset,h=this.getValueOfPropertyAt(n,r,"deltaY");l+=(1-this._fontSizeFraction)*this.getHeightOfLine(n)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(n,r,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-o/2,l+t.top+h,o,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,n=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,r=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),a=this.get2DCursorLocation(n),o=s.lineIndex,l=a.lineIndex,h=s.charIndex<0?0:s.charIndex,c=a.charIndex<0?0:a.charIndex,u=o;u<=l;u++){var d,f=this._getLineLeftOffset(u)||0,g=this.getHeightOfLine(u),m=0,p=0;if(u===o&&(m=this.__charBounds[o][h].left),u>=o&&u1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,E=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,E=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+E,y,w),t.topOffset+=d}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),T.IText.fromObject=function(e,i){if(t(e),e.styles)for(var n in e.styles)for(var r in e.styles[n])t(e.styles[n][r]);T.Object._fromObject("IText",e,i,"text")}}(),S=T.util.object.clone,T.util.object.extend(T.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",(function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))}))},initRemovedHandler:function(){var t=this;this.on("removed",(function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],T.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))}))},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach((function(t){t.__isMousedown=!1}))},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,n){var r;return r={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){r.isAborted||t[n]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return r.isAborted}}),r},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){e._tick()}),i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&nthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var n=i.slice(0,t),r=T.util.string.graphemeSplit(n).length;if(t===e)return{selectionStart:r,selectionEnd:r};var s=i.slice(t,e);return{selectionStart:r,selectionEnd:r+T.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var n=i.slice(0,t).join("").length;return t===e?{selectionStart:n,selectionEnd:n}:{selectionStart:n,selectionEnd:n+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),n=i.lineIndex,r=i.charIndex,s=this.getValueOfPropertyAt(n,r,"fontSize")*this.lineHeight,a=e.leftOffset,o=this.calcTransformMatrix(),l={x:e.left+a,y:e.top+e.topOffset+s},h=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/h,d=c.height/h,f=u-s,g=d-s,m=c.clientWidth/u,p=c.clientHeight/d;return l=T.util.transformPoint(l,o),(l=T.util.transformPoint(l,this.canvas.viewportTransform)).x*=m,l.y*=p,l.x<0&&(l.x=0),l.x>f&&(l.x=f),l.y<0&&(l.y=0),l.y>g&&(l.y=g),l.x+=this.canvas._offset.left,l.y+=this.canvas._offset.top,{left:l.x+"px",top:l.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,n,r=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),a=r.lineIndex,o=r.charIndex,l=s.lineIndex,h=s.charIndex;if(a!==l){if(this.styles[a])for(i=o;i=h&&(n[c-d]=n[u],delete n[u])}},shiftLineStyles:function(t,e){var i=S(this.styles);for(var n in this.styles){var r=parseInt(n,10);r>t&&(this.styles[r+e]=i[r],i[r-e]||delete this.styles[r])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,n){var r,s={},a=!1,o=this._unwrappedTextLines[t].length===e;for(var l in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(r=this.styles[t][0===e?e:e-1]),this.styles[t]){var h=parseInt(l,10);h>=e&&(a=!0,s[h-e]=this.styles[t][l],o&&0===e||delete this.styles[t][l])}var c=!1;for(a&&!o&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)n&&n[i-1]?this.styles[t+i]={0:S(n[i-1])}:r?this.styles[t+i]={0:S(r)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,n){this.styles||(this.styles={});var r=this.styles[t],s=r?S(r):{};for(var a in i||(i=1),s){var o=parseInt(a,10);o>=e&&(r[o+i]=s[o],s[o-i]||delete r[o])}if(this._forceClearCache=!0,n)for(;i--;)Object.keys(n[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=S(n[i]));else if(r)for(var l=r[e?e-1:1];l&&i--;)this.styles[t][e+i]=S(l)},insertNewStyleBlock:function(t,e,i){for(var n=this.get2DCursorLocation(e,!0),r=[0],s=0,a=0;a0&&(this.insertCharStyleObject(n.lineIndex,n.charIndex,r[0],i),i=i&&i.slice(r[0]+1)),s&&this.insertNewlineStyleObject(n.lineIndex,n.charIndex+r[0],s),a=1;a0?this.insertCharStyleObject(n.lineIndex+a,0,r[a],i):i&&this.styles[n.lineIndex+a]&&i[0]&&(this.styles[n.lineIndex+a][0]=i[0]),i=i&&i.slice(r[a]+1);r[a]>0&&this.insertCharStyleObject(n.lineIndex+a,0,r[a],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),T.util.object.extend(T.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,n=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,n,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),n=0,r=0,s=0,a=0,o=0,l=0,h=this._textLines.length;l0&&(a+=this._textLines[l-1].length+this.missingNewlineOffset(l-1));r=this._getLineLeftOffset(o)*this.scaleX,e=this._textLines[o],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+r);for(var c=0,u=e.length;cs||a<0?0:1);return this.flipX&&(o=r-o),o>this._text.length&&(o=this._text.length),o}}),T.util.object.extend(T.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=T.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):T.document.body.appendChild(this.hiddenTextarea),T.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),T.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),T.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),T.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),T.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),T.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(T.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,n,r,s,a,o=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,l=this._text.length,h=o.length,c=h-l,u=this.selectionStart,d=this.selectionEnd,f=u!==d;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=u>g.selectionStart;f?(i=this._text.slice(u,d),c+=d-u):h0&&(n+=(i=this.__charBounds[t][e-1]).left+i.width),n},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(r===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=n.charIndex,a=this._getWidthBeforeCursor(r,s),o=this._getIndexOnLine(r+1,a);return this._textLines[r].slice(s).length+o+1+this.missingNewlineOffset(r)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(0===r||t.metaKey||33===t.keyCode)return-i;var s=n.charIndex,a=this._getWidthBeforeCursor(r,s),o=this._getIndexOnLine(r-1,a),l=this._textLines[r].slice(0,s),h=this.missingNewlineOffset(r-1);return-this._textLines[r-1].length+o-l.length+(1-h)},_getIndexOnLine:function(t,e){for(var i,n,r=this._textLines[t],s=this._getLineLeftOffset(t),a=0,o=0,l=r.length;oe){n=!0;var h=s-i,c=s,u=Math.abs(h-e);a=Math.abs(c-e)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)},moveCursorUp:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)},_moveCursorUpOrDown:function(t,e){var i=this["get"+t+"CursorOffset"](e,"right"===this._selectionDirection);e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(t){var e="left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t},moveCursorWithoutShift:function(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t},moveCursorLeft:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)},_move:function(t,e,i){var n;if(t.altKey)n=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;n=this["findLineBoundary"+i](this[e])}if(void 0!==typeof n&&this[e]!==n)return this[e]=n,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,n){void 0===n&&(n=i),n>i&&this.removeStyleFromTo(i,n);var r=T.util.string.graphemeSplit(t);this.insertNewStyleBlock(r,i,e),this._text=[].concat(this._text.slice(0,i),r,this._text.slice(n)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=T.util.toFixed,e=/ +/g;T.util.object.extend(T.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,n=[],r=[],s=t;this._setSVGBg(r);for(var a=0,o=this._textLines.length;a",T.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,n){var r,s,a,o,l,h=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),u="",d=0,f=this._textLines[e];n+=h*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)l=g===m||this.charSpacing,u+=f[g],a=this.__charBounds[e][g],0===d?(i+=a.kernedWidth-a.width,d+=a.width):d+=a.kernedWidth,c&&!l&&this._reSpaceAndTab.test(f[g])&&(l=!0),l||(r=r||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),l=this._hasStyleChangedForSvg(r,s)),l&&(o=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(u,o,i,n)),u="",r=s,i+=d,d=0)},_pushTextBgRect:function(e,i,n,r,s,a){var o=T.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,n){for(var r,s,a=this._textLines[e],o=this.getHeightOfLine(e)/this.lineHeight,l=0,h=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),u=0,d=a.length;uthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,n=0,r={},s=0;s0?(i=0,n++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[n])&&s>0&&(i++,n++),r[s]={line:e,offset:i},n+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return r},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var n=this._styleMap[i];n&&(i=n.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,n=0,r=!1,s=this._styleMap[t],a=this._styleMap[t+1];for(var o in s&&(t=s.line,n=s.offset),a&&(r=a.line===t,e=a.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var l in i[o])if(l>=n&&(!r||ln&&!p?(o.push(l),l=[],s=f,p=!0):s+=_,p||a||l.push(d),l=l.concat(c),g=a?0:this._measureWord([d],i,u),u++,p=!1,f>m&&(m=f);return v&&o.push(l),m+r>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+r),o},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),n=this._wrapText(i.lines,this.width),r=new Array(n.length),s=0;s{},898:()=>{},245:()=>{}},Qe={};function ti(t){var e=Qe[t];if(void 0!==e)return e.exports;var i=Qe[t]={exports:{}};return $e[t](i,i.exports,ti),i.exports}ti.d=(t,e)=>{for(var i in e)ti.o(e,i)&&!ti.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},ti.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var ei={};(()=>{let t;ti.d(ei,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?ti(653).fabric:{version:"5.2.1"}})();var ii,ni,ri,si,ai=ei.R;!function(t){t[t.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",t[t.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",t[t.DIMT_TEXT=4]="DIMT_TEXT",t[t.DIMT_ARC=8]="DIMT_ARC",t[t.DIMT_IMAGE=16]="DIMT_IMAGE",t[t.DIMT_POLYGON=32]="DIMT_POLYGON",t[t.DIMT_LINE=64]="DIMT_LINE",t[t.DIMT_GROUP=128]="DIMT_GROUP"}(ii||(ii={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(ni||(ni={})),function(t){t[t.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",t[t.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",t[t.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS"}(ri||(ri={})),function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(si||(si={}));const oi=t=>"number"==typeof t&&!Number.isNaN(t),li=t=>"string"==typeof t;var hi,ci,ui,di,fi,gi,mi,pi,_i,vi,yi;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(fi||(fi={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(gi||(gi={}));class wi{get mediaType(){return new Map([["rect",ii.DIMT_RECTANGLE],["quad",ii.DIMT_QUADRILATERAL],["text",ii.DIMT_TEXT],["arc",ii.DIMT_ARC],["image",ii.DIMT_IMAGE],["polygon",ii.DIMT_POLYGON],["line",ii.DIMT_LINE],["group",ii.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(He(this,ci,"f")){case ni.DIS_DEFAULT:return"default";case ni.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===He(this,ui,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===He(this,ui,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),Xe(this,ui,t)}get coordinateBase(){return He(this,ui,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(hi.add(this),ci.set(this,void 0),ui.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=e&&!oi(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(ni.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.setState(ni.DIS_SELECTED)})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(ni.DIS_SELECTED):this.setState(ni.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){Xe(this,ci,t)}getState(){return He(this,ci,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),n=this.mapEvent_Callbacks.get(i);if(!n)throw new Error(`Event '${t}' does not exist.`);let r=n.get(e);r||(r=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const n={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,r,s;const a=i.target.getBoundingClientRect();t=a.left,e=a.top,r=t+window.scrollX,s=e+window.scrollY;const{width:o,height:l}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),h=this._drawingLayer.width,c=this._drawingLayer.height,u=o/l,d=h/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)u0?i-1:n,Ti),actionName:"modifyPolygon",pointIndex:i}),t}),{}),Xe(this,pi,JSON.parse(JSON.stringify(t))),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,n){return t["p"+n]=new ai.Control({positionHandler:Ci,actionHandler:bi(n>0?n-1:i,Ti),actionName:"modifyPolygon",pointIndex:n}),t}),{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let n=i.x-e.pathOffset.x,r=i.y-e.pathOffset.y;const s=ai.util.transformPoint({x:n,y:r},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){He(this,pi,"f")&&this.setPolygon(He(this,pi,"f"))}setPolygon(t){if(!T(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Xe(this,pi,JSON.parse(JSON.stringify(t)))}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return He(this,pi,"f")?JSON.parse(JSON.stringify(He(this,pi,"f"))):null}}pi=new WeakMap;_i=new WeakMap,vi=new WeakMap;const xi=t=>{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let n=0;ni&&(i=r.length)}if(-1===i)break;for(let n=0;n=t[n].length-1)continue;let r=" ".repeat(i+2-t[n][e].length);t[n][e]=t[n][e].concat(r)}}})(e),(t=>{let e="";for(let i=0;i({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Xe(this,Di,JSON.parse(JSON.stringify(t)))}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return He(this,Di,"f")?JSON.parse(JSON.stringify(He(this,Di,"f"))):null}}Di=new WeakMap;class Li extends wi{constructor(t){super(new ai.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.setState(ni.DIS_SELECTED);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.setState(ni.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}setChildDrawingItems(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}}const Mi=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),Fi=t=>!!li(t)&&""!==t,Pi=t=>!(!Mi(t)||"id"in t&&!oi(t.id)||"lineWidth"in t&&!oi(t.lineWidth)||"fillStyle"in t&&!Fi(t.fillStyle)||"strokeStyle"in t&&!Fi(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!Fi(t.fontFamily)||"fontSize"in t&&!oi(t.fontSize));class ki{static convert(t,e,i){const n={x:0,y:0,width:e,height:i};if(!t)return n;if(I(t))t.isMeasuredInPercentage?(n.x=t.x/100*e,n.y=t.y/100*i,n.width=t.width/100*e,n.height=t.height/100*i):(n.x=t.x,n.y=t.y,n.width=t.width,n.height=t.height);else{if(!w(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?(n.x=t.left/100*e,n.y=t.top/100*i,n.width=(t.right-t.left)/100*e,n.height=(t.bottom-t.top)/100*i):(n.x=t.left,n.y=t.top,n.width=t.right-t.left,n.height=t.bottom-t.top)}return n.x=Math.round(n.x),n.y=Math.round(n.y),n.width=Math.round(n.width),n.height=Math.round(n.height),n}}var Ni,Bi;class Vi{constructor(){Ni.set(this,new Map),Bi.set(this,!1)}get disposed(){return He(this,Bi,"f")}on(t,e){t=t.toLowerCase();const i=He(this,Ni,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else He(this,Ni,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=He(this,Ni,"f").get(t);if(!i)return;const n=i.indexOf(e);-1!==n&&i.splice(n,1)}offAll(t){t=t.toLowerCase();const e=He(this,Ni,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const n=He(this,Ni,"f").get(t);if(n&&n.length){i=Object.assign({async:!1,copy:!0},i);for(let r of n){if(!r)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let a=!1;if(i.async)setTimeout((()=>{this.disposed||n.includes(r)&&r.apply(i.target,s)}),0);else try{a=r.apply(i.target,s)}catch(t){}if(!0===a)break}}}dispose(){Xe(this,Bi,!0)}}function ji(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function Ui(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function Gi(t,e,i,n){let r=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(n[1]-e[1])+e[0]*(t[1]-n[1])+n[0]*(e[1]-t[1]);return!((r^s)>=0&&0!==r&&0!==s||(r=i[0]*(t[1]-n[1])+n[0]*(i[1]-t[1])+t[0]*(n[1]-i[1]),s=i[0]*(e[1]-n[1])+n[0]*(i[1]-e[1])+e[0]*(n[1]-i[1]),(r^s)>=0&&0!==r&&0!==s))}Ni=new WeakMap,Bi=new WeakMap;const Wi=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const n=document.createElement("div");if(n.insertAdjacentHTML("beforeend",i),1===n.childElementCount&&n.firstChild instanceof HTMLTemplateElement)return n.firstChild.content;const r=new DocumentFragment;for(let t of n.children)r.append(t);return r};var Yi,zi,Hi,Xi,Zi,qi,Ji,Ki,$i,Qi,tn,en,nn,rn,sn,an,on,ln,hn,cn,un,dn,fn,gn,mn,pn,_n,vn,yn,wn,En,Cn,Sn,Tn;class bn{static createDrawingStyle(t){if(!Pi(t))throw new Error("Invalid style definition.");let e,i=bn.USER_START_STYLE_ID;for(;He(bn,Yi,"f",zi).has(i);)i++;e=i;const n=JSON.parse(JSON.stringify(t));n.id=e;for(let t in He(bn,Yi,"f",Hi))n.hasOwnProperty(t)||(n[t]=He(bn,Yi,"f",Hi)[t]);return He(bn,Yi,"f",zi).set(e,n),n.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=He(bn,Yi,"f",zi).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(He(bn,Yi,"f",zi).values())))}static _updateDrawingStyle(t,e){if(!Pi(e))throw new Error("Invalid style definition.");const i=He(bn,Yi,"f",zi).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}Yi=bn,bn.STYLE_BLUE_STROKE=1,bn.STYLE_GREEN_STROKE=2,bn.STYLE_ORANGE_STROKE=3,bn.STYLE_YELLOW_STROKE=4,bn.STYLE_BLUE_STROKE_FILL=5,bn.STYLE_GREEN_STROKE_FILL=6,bn.STYLE_ORANGE_STROKE_FILL=7,bn.STYLE_YELLOW_STROKE_FILL=8,bn.STYLE_BLUE_STROKE_TRANSPARENT=9,bn.STYLE_GREEN_STROKE_TRANSPARENT=10,bn.STYLE_ORANGE_STROKE_TRANSPARENT=11,bn.USER_START_STYLE_ID=1024,zi={value:new Map([[bn.STYLE_BLUE_STROKE,{id:bn.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[bn.STYLE_GREEN_STROKE,{id:bn.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[bn.STYLE_ORANGE_STROKE,{id:bn.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[bn.STYLE_YELLOW_STROKE,{id:bn.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[bn.STYLE_BLUE_STROKE_FILL,{id:bn.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[bn.STYLE_GREEN_STROKE_FILL,{id:bn.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[bn.STYLE_ORANGE_STROKE_FILL,{id:bn.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[bn.STYLE_YELLOW_STROKE_FILL,{id:bn.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[bn.STYLE_BLUE_STROKE_TRANSPARENT,{id:bn.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[bn.STYLE_GREEN_STROKE_TRANSPARENT,{id:bn.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[bn.STYLE_ORANGE_STROKE_TRANSPARENT,{id:bn.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},Hi={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(ai.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(ai.util.cancelAnimFrame(this.isRendering),this.isRendering=0),this.forEachObject((function(t){t.dispose&&t.dispose()})),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose&&this.backgroundImage.dispose(),this.backgroundImage=null,this.overlayImage&&this.overlayImage.dispose&&this.overlayImage.dispose(),this.overlayImage=null,this._iTextInstances=null,this.contextContainer=null,this.lowerCanvasEl.classList.remove("lower-canvas"),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),ai.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},ai.Object.prototype.transparentCorners=!1,ai.Object.prototype.cornerSize=20,ai.Object.prototype.touchCornerSize=100,ai.Object.prototype.cornerColor="rgb(254,142,20)",ai.Object.prototype.cornerStyle="circle",ai.Object.prototype.strokeUniform=!0,ai.Object.prototype.hasBorders=!1,ai.Canvas.prototype.containerClass="",ai.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i,n=this.upperCanvasEl,r=ai.util.getPointer(t,n),s=n.getBoundingClientRect(),a=s.width||0,o=s.height||0;a&&o||("top"in s&&"bottom"in s&&(o=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(a=Math.abs(s.right-s.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,e||(r=this.restorePointerVpt(r));var l=this.getRetinaScaling();if(1!==l&&(r.x/=l,r.y/=l),0!==a&&0!==o){var h=window.getComputedStyle(n).objectFit,c=n.width,u=n.height,d=a,f=o;i={width:c/d,height:u/f};var g,m,p=c/u,_=d/f;return"contain"===h?p>_?(g=d,m=d/p,{x:r.x*i.width,y:(r.y-(f-m)/2)*i.width}):(g=f*p,m=f,{x:(r.x-(d-g)/2)*i.height,y:r.y*i.height}):"cover"===h?p>_?{x:(c-i.height*d)/2+r.x*i.height,y:r.y*i.height}:{x:r.x*i.width,y:(u-i.width*f)/2+r.y*i.width}:{x:r.x*i.width,y:r.y*i.height}}return i={width:1,height:1},{x:r.x*i.width,y:r.y*i.height}},ai.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,n=this._getEventPrefix();ai.util.addListener(ai.document,"touchend",this._onTouchEnd,{passive:!1}),ai.util.addListener(ai.document,"touchmove",this._onMouseMove,{passive:!1}),ai.util.removeListener(i,n+"down",this._onMouseDown)},ai.Textbox.prototype._wrapLine=function(t,e,i,n){const r=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!r||!r.length);var a=0,o=this.splitByGrapheme||s,l=[],h=[],c=o?ai.util.string.graphemeSplit(t):t.split(this._wordJoiners),u="",d=0,f=o?"":" ",g=0,m=0,p=0,_=!0,v=this._getWidthOfCharSpacing();n=n||0,0===c.length&&c.push([]),i-=n;for(var y=0;yi&&!_?(l.push(h),h=[],a=g,_=!0):a+=v,_||o||h.push(f),h=h.concat(u),m=o?0:this._measureWord([f],e,d),d++,_=!1,g>p&&(p=g);return y&&l.push(h),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+n),l});class In{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){if(this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas"))this.fabricCanvas=t.getFabricCanvas();else{let e=this.fabricCanvas=new ai.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.on("selection:created",(function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])}),0)}})),e.on("before:selection:cleared",(function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{const e=[];for(let n of i)t.hasDrawingItem(n)&&e.push(n);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)}),0)}})),e.on("selection:updated",(function(t){const e=t.selected,i=t.deselected,n=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of n){const n=[],r=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&n.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&r.push(i)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(n,r)}),0)}})),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let n,r;switch(this.id=e,e){case In.DDN_LAYER_ID:n=bn.getDrawingStyle(bn.STYLE_BLUE_STROKE),r=bn.getDrawingStyle(bn.STYLE_BLUE_STROKE_FILL);break;case In.DBR_LAYER_ID:n=bn.getDrawingStyle(bn.STYLE_ORANGE_STROKE),r=bn.getDrawingStyle(bn.STYLE_ORANGE_STROKE_FILL);break;case In.DLR_LAYER_ID:n=bn.getDrawingStyle(bn.STYLE_GREEN_STROKE),r=bn.getDrawingStyle(bn.STYLE_GREEN_STROKE_FILL);break;default:n=bn.getDrawingStyle(bn.STYLE_YELLOW_STROKE),r=bn.getDrawingStyle(bn.STYLE_YELLOW_STROKE_FILL)}for(let t of wi.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:n.id,selected:r.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return bn.getDrawingStyle(t.styleId);return bn.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,n){const r=this.getDrawingItems((e=>e._mediaType===t));for(let t of r)t.styleSelector===e&&this._changeItemStyle(t,i,!0);n||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const n=t._getFabricObject();"number"==typeof t.styleId&&(e=bn.getDrawingStyle(t.styleId)),n.strokeWidth=e.lineWidth,"fill"===e.paintMode?(n.fill=e.fillStyle,n.stroke=e.fillStyle):"stroke"===e.paintMode?(n.fill="transparent",n.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(n.fill=e.fillStyle,n.stroke=e.strokeStyle),n.fontFamily&&(n.fontFamily=e.fontFamily),n.fontSize&&(n.fontSize=e.fontSize),n.group||(n.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const n=t.getChildDrawingItems();if("add"===i){if(n.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=bn.getDrawingStyle(e.styleId);else{const n=this.mapType_StateAndStyleId.get(e._mediaType);i=bn.getDrawingStyle(n[t.styleSelector]);const r=()=>{this._changeItemStyle(e,bn.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,bn.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",r),e._on("deselected",s),e._funcChangeStyleToSelected=r,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!n.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof wi))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const n=this.fabricCanvas.getObjects();let r,s;if(n.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){r=t.getChildDrawingItems();for(let t of r)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(r){for(let t of r){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of wi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=bn.getDrawingStyle(t.styleId);else{s=bn.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,bn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},n=()=>{this._changeItemStyle(t,bn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of wi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=bn.getDrawingStyle(t.styleId);else{s=bn.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,bn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},n=()=>{this._changeItemStyle(t,bn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const a=this._arrFabricObject.length;let o=n.length;if(a)o=n.indexOf(this._arrFabricObject[a-1])+1;else for(let e=0;et.toLowerCase())):e=wi.arrMediaTypes,i?i.forEach((t=>t.toLowerCase())):i=wi.arrStyleSelectors;const n=bn.getDrawingStyle(t);if(!n)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let r;for(let s of e)if(r=this.mapType_StateAndStyleId.get(s),r)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,n,!0),r[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const n=[];i&ii.DIMT_RECTANGLE&&n.push("rect"),i&ii.DIMT_QUADRILATERAL&&n.push("quad"),i&ii.DIMT_TEXT&&n.push("text"),i&ii.DIMT_ARC&&n.push("arc"),i&ii.DIMT_IMAGE&&n.push("image"),i&ii.DIMT_POLYGON&&n.push("polygon"),i&ii.DIMT_LINE&&n.push("line");const r=[];e&ni.DIS_DEFAULT&&r.push("default"),e&ni.DIS_SELECTED&&r.push("selected"),this._setDefaultStyle(t,n.length?n:null,r.length?r:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}In.DDN_LAYER_ID=1,In.DBR_LAYER_ID=2,In.DLR_LAYER_ID=3,In.USER_DEFINED_LAYER_BASE_ID=100,In.TIP_LAYER_ID=999;class xn{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new In(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(t){const e=this.getDrawingLayer(t);if(!e)return;const i=this._arrDrawingLayer;e.dispose(),i.splice(i.indexOf(e),1),this._switchPointerEvent()}clearDrawingLayers(){for(let t of this._arrDrawingLayer)t.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(t){for(let e of this._arrDrawingLayer)if(e.getId()===t)return e;return null}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().getActiveObjects(),e=[];for(let i of t)e.push(i.getDrawingItem());return e}setDimensions(t,e){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(t,e)}setObjectFit(t){for(let e of this._arrDrawingLayer)e&&e._setObjectFit(t)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(t){if(!this._arrDrawingLayer.length)return;this._getFabricCanvas().wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class Rn extends Ri{constructor(t,e,i,n,r){super(t,{x:e,y:i,width:n,height:0},r),Xi.set(this,void 0),Zi.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&Xe(this,Zi,setTimeout((()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()}),He(this,Xi,"f")))}getDuration(){return He(this,Xi,"f")}}Xi=new WeakMap,Zi=new WeakMap;class On{constructor(){qi.add(this),Ji.set(this,void 0),Ki.set(this,void 0),$i.set(this,void 0),Qi.set(this,!0),this._drawingLayerManager=new xn}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const n=document.createElement("canvas");return n.width==t&&n.height==e||(n.width=t,n.height=e),n.style.objectFit=i,n}_createDrawingLayer(t,e,i,n){if(!this._layerBaseCvs){let r;try{r=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==r?void 0:r.width)||1280),i||(i=(null==r?void 0:r.height)||720),n||(n=(null==r?void 0:r.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,n)}const r=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(r,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",r.parentElement),s}createDrawingLayer(){let t;for(let e=In.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==In.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(tt.getId()>=0&&t.getId()!==In.TIP_LAYER_ID))}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(Mi(e=t)&&S(e.topLeftPoint)&&oi(e.width))||e.width<=0||!oi(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;Xe(this,Ji,JSON.parse(JSON.stringify(t))),He(this,Ji,"f").coordinateBase||(He(this,Ji,"f").coordinateBase="view"),Xe(this,$i,t.duration),He(this,qi,"m",rn).call(this)}getTipConfig(){return He(this,Ji,"f")?He(this,Ji,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),Xe(this,Qi,t)}isTipVisible(){return He(this,Qi,"f")}updateTipMessage(t){if(!He(this,Ji,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=bn.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(In.TIP_LAYER_ID)||this._createDrawingLayer(In.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=He(this,qi,"m",tn).call(this,t,He(this,Ji,"f").topLeftPoint.x,He(this,Ji,"f").topLeftPoint.y,He(this,Ji,"f").width,He(this,Ji,"f").coordinateBase,this._tipStyleId),He(this,qi,"m",en).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",He(this,Qi,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),He(this,Ki,"f")&&clearTimeout(He(this,Ki,"f")),He(this,$i,"f")>=0&&Xe(this,Ki,setTimeout((()=>{He(this,qi,"m",nn).call(this)}),He(this,$i,"f")))}}Ji=new WeakMap,Ki=new WeakMap,$i=new WeakMap,Qi=new WeakMap,qi=new WeakSet,tn=function(t,e,i,n,r,s){const a=new Rn(t,e,i,n,s);return a.coordinateBase=r,a},en=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},nn=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},rn=function(){if(!this._tip)return;const t=He(this,Ji,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class Dn extends HTMLElement{constructor(){super(),sn.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),Xe(this,sn,e);const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const n=document.createElement("slot");n.setAttribute("name","content"),e.append(n);const r=document.createElement("slot");r.setAttribute("name","drawing-layer"),e.append(r);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return He(this,sn,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach((t=>t.remove()))}}sn=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",Dn);class An extends On{static get engineResourcePath(){return O(gt.engineResourcePaths).dce}static set defaultUIElementURL(t){An._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=An._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",An.engineResourcePath)}static async createInstance(t){const e=new An;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",An.engineResourcePath)),await e.setUIElement(t||An.defaultUIElementURL),e}static _transformCoordinates(t,e,i,n,r,s,a){const o=s/n,l=a/r;t.x=Math.round(t.x/o+e),t.y=Math.round(t.y/l+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==He(this,mn,"f")){if(Xe(this,mn,t),He(this,an,"m",vn).call(this))Xe(this,cn,null),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!He(this,cn,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(ze.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Xe(this,cn,t);const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}He(this,an,"m",vn).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return He(this,mn,"f")}get disposed(){return He(this,_n,"f")}constructor(){super(),an.add(this),on.set(this,void 0),ln.set(this,void 0),hn.set(this,void 0),this.containerClassName="dce-video-container",cn.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,un.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,dn.set(this,!1),fn.set(this,!1),gn.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{He(this,an,"m",Sn).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout((()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&He(this,an,"m",Cn).call(this))}),this._updateLayersTimeout)},this._windowResizeListener=()=>{An._onLog&&An._onLog("window resize event triggered."),He(this,gn,"f").width===document.documentElement.clientWidth&&He(this,gn,"f").height===document.documentElement.clientHeight||(He(this,gn,"f").width=document.documentElement.clientWidth,He(this,gn,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},mn.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!He(this,an,"m",vn).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise(((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i},i=(t,e,i,n)=>{t.width==i&&t.height==n||(t.width=i,t.height=n);const r=t.getContext("2d");r.clearRect(0,0,t.width,t.height),r.drawImage(e,0,0)},n=await t(e),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let a=this._cvsSingleFrameMode;const o=null==a?void 0:a.width,l=null==a?void 0:a.height;a||(a=document.createElement("canvas"),this._cvsSingleFrameMode=a),i(a,n,r,s),this._innerComponent.setElement("content",a),o===a.width&&l===a.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout((()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)}),0)})),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},pn.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,n,r,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const a=t.originalImageTag;if(!a)return;const o=t.items;if(!(null==o?void 0:o.length))return;const l=(null===(i=a.cropRegion)||void 0===i?void 0:i.left)||0,h=(null===(n=a.cropRegion)||void 0===n?void 0:n.top)||0,c=(null===(r=a.cropRegion)||void 0===r?void 0:r.right)?a.cropRegion.right-l:a.originalWidth,u=(null===(s=a.cropRegion)||void 0===s?void 0:s.bottom)?a.cropRegion.bottom-h:a.originalHeight,d=a.currentWidth,f=a.currentHeight,g=(t,e,i,n,r,s,a,o,l=[],h)=>{e.forEach((t=>An._transformCoordinates(t,i,n,r,s,a,o)));const c=new Ai({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},h);for(let t of l)c.addNote(t);t.addDrawingItems([c]),He(this,pn,"f").push(c)};let m,p;for(let t of o)switch(t.type){case mt.CRIT_ORIGINAL_IMAGE:break;case mt.CRIT_BARCODE:m=this.getDrawingLayer(In.DBR_LAYER_ID),p=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?g(m,t.location.points,l,h,c,u,d,f,p):g(m,t.location.points,l,h,c,u,d,f,p,bn.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,l,h,c,u,d,f,p);break;case mt.CRIT_TEXT_LINE:m=this.getDrawingLayer(In.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,l,h,c,u,d,f,p):g(m,t.location.points,l,h,c,u,d,f,p,bn.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,l,h,c,u,d,f,p);break;case mt.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(In.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===St.CVS_PASSED?g(m,t.location.points,l,h,c,u,d,f,[]):g(m,t.location.points,l,h,c,u,d,f,[],bn.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,l,h,c,u,d,f,[]);break;case mt.CRIT_NORMALIZED_IMAGE:m=this.getDrawingLayer(In.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===St.CVS_PASSED?g(m,t.location.points,l,h,c,u,d,f,[]):g(m,t.location.points,l,h,c,u,d,f,[],bn.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,l,h,c,u,d,f,[]);break;case mt.CRIT_PARSED_RESULT:break;default:throw new Error("Illegal item type.")}}},_n.set(this,!1),this.eventHandler=new Vi,this.eventHandler.on("content:updated",(()=>{He(this,on,"f")&&clearTimeout(He(this,on,"f")),Xe(this,on,setTimeout((()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)}),0))})),this.eventHandler.on("videoEl:resized",(()=>{He(this,ln,"f")&&clearTimeout(He(this,ln,"f")),Xe(this,ln,setTimeout((()=>{this.disposed||this._updateVideoContainer()}),0))}))}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Wi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let n=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!n)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=document.createElement("dce-component"),n.appendChild(this._innerComponent),He(this,an,"m",vn).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(ze.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Xe(this,cn,t);const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._selRsl&&(this._hideDefaultSelection||He(this,an,"m",vn).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||He(this,an,"m",vn).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||He(this,an,"m",Sn).call(this),He(this,an,"m",vn).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),He(this,an,"m",vn).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{var e;An._onLog&&An._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()})));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}He(this,gn,"f").width=document.documentElement.clientWidth,He(this,gn,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,n;He(this,an,"m",vn).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),He(this,an,"m",Sn).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,Xe(this,cn,null),null===(n=this._videoContainer)||void 0===n||n.remove(),this._videoContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let n of e){const e=document.createElement("option");e.value=n.deviceId,e.innerText=n.label,this._selCam.append(e),n.deviceId&&t&&t.deviceId==n.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),n=Math.min(t.width,t.height);e=n<=1080?n+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return He(this,cn,"f")}isVideoLoaded(){return!(!He(this,cn,"f")||!this.cameraEnhancer)&&this.cameraEnhancer.isOpen()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!He(this,cn,"f"))return;if(He(this,cn,"f").style.objectFit=t,He(this,an,"m",vn).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}He(this,an,"m",Tn).call(this,e,this.getConvertedRegion()),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,n;let r,s,a;if(He(this,an,"m",vn).call(this)?(r=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(n=this._cvsSingleFrameMode)||void 0===n?void 0:n.height,a="contain"):(r=null===(t=He(this,cn,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=He(this,cn,"f"))||void 0===e?void 0:e.videoHeight,a=this.getVideoFit()),!r||!s)throw new Error("Invalid content dimensions.");return{width:r,height:s,objectFit:a}}updateConvertedRegion(t){const e=ki.convert(this.scanRegion,t.width,t.height);Xe(this,un,e),He(this,hn,"f")&&clearTimeout(He(this,hn,"f")),Xe(this,hn,setTimeout((()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}He(this,an,"m",yn).call(this,t,e),He(this,an,"m",Tn).call(this,t,e)}),0))}getConvertedRegion(){return He(this,un,"f")}setScanRegion(t){if(null!=t&&!w(t)&&!I(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=He(this,cn,"f").videoWidth,i=He(this,cn,"f").videoHeight,n=this.getVideoFit(),{width:r,height:s}=this._innerComponent.getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");let a;const o={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===n&&(r/s1){const t=He(this,cn,"f").videoWidth,e=He(this,cn,"f").videoHeight,{width:n,height:r}=this._innerComponent.getBoundingClientRect(),s=t/e;if(n/rt.remove())),He(this,pn,"f").length=0}dispose(){this._unbindUI(),Xe(this,_n,!0)}}function Ln(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Mn(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,i),i}on=new WeakMap,ln=new WeakMap,hn=new WeakMap,cn=new WeakMap,un=new WeakMap,dn=new WeakMap,fn=new WeakMap,gn=new WeakMap,mn=new WeakMap,pn=new WeakMap,_n=new WeakMap,an=new WeakSet,vn=function(){return"disabled"!==this._singleFrameMode},yn=function(t,e){!e||0===e.x&&0===e.y&&e.width===t.width&&e.height===t.height?this.clearScanRegionMask():this.setScanRegionMask(e.x,e.y,e.width,e.height)},wn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},En=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},Cn=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},Sn=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Tn=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:n,objectFit:r}=t;e||(e={x:0,y:0,width:i,height:n});const{width:s,height:a}=this._innerComponent.getBoundingClientRect();if(s<=0||a<=0)return;const o=s/a,l=i/n;let h,c,u,d,f=1;if("contain"===r)o66||"Safari"===Vn.browser&&Vn.version>13||"OPR"===Vn.browser&&Vn.version>43||"Edge"===Vn.browser&&Vn.version,"function"==typeof SuppressedError&&SuppressedError;class Gn{static multiply(t,e){const i=[];for(let n=0;n<3;n++){const r=e.slice(3*n,3*n+3);for(let e=0;e<3;e++){const n=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*r[i]),0);i.push(n)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return Gn.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),n=Math.sin(e);return Gn.multiply(t,[i,-n,0,n,i,0,0,0,1])}static scale(t,e,i){return Gn.multiply(t,[e,0,0,0,i,0,0,0,1])}}var Wn,Yn,zn,Hn,Xn,Zn,qn,Jn,Kn,$n,Qn,tr,er,ir,nr,rr,sr,ar,or,lr,hr,cr,ur,dr,fr,gr,mr,pr,_r,vr,yr,wr,Er,Cr,Sr,Tr,br,Ir,xr,Rr,Or,Dr,Ar,Lr,Mr,Fr,Pr,kr,Nr,Br;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(Wn||(Wn={}));class Vr{static get version(){return"1.1.3"}static get webGLSupported(){return void 0===Vr._webGLSupported&&(Vr._webGLSupported=!!document.createElement("canvas").getContext("webgl")),Vr._webGLSupported}get disposed(){return jn(this,qn,"f")}constructor(){Yn.set(this,Wn.RGBA),zn.set(this,null),Hn.set(this,null),Xn.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,Zn.set(this,null),qn.set(this,!1)}drawImage(t,e,i,n,r,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!n)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if((null==s?void 0:s.bUseWebGL)&&!Vr.webGLSupported)throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let a;Vr._onLog&&(a=Date.now(),Vr._onLog("drawImage(), START: "+a));let o=0,l=0,h=i,c=n,u=0,d=0,f=i,g=n;r&&(r.sx&&(o=Math.round(r.sx)),r.sy&&(l=Math.round(r.sy)),r.sWidth&&(h=Math.round(r.sWidth)),r.sHeight&&(c=Math.round(r.sHeight)),r.dx&&(u=Math.round(r.dx)),r.dy&&(d=Math.round(r.dy)),r.dWidth&&(f=Math.round(r.dWidth)),r.dHeight&&(g=Math.round(r.dHeight)));let m,p=Wn.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!Vr.webGLSupported||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){Vr._onLog&&Vr._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},n=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},r=(t,e,i)=>{const n=t.createShader(e);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(n)}.`);throw e.name="WebGLError",e}return n},s="\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\n\nuniform mat3 u_matrix;\nuniform mat3 u_textureMatrix;\n\nvarying vec2 v_texCoord;\nvoid main(void) {\ngl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\nv_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n}";let a="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(a=p.slice(0,3));const o=`\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_image;\nuniform float uColorFactor;\n\nvoid main() {\nvec4 sample = texture2D(u_image, v_texCoord);\nfloat grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\ngl_FragColor = vec4(sample.${a} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n}`,l=n(t,[r(t,t.VERTEX_SHADER,s),r(t,t.FRAGMENT_SHADER,o)]);Un(this,Hn,{program:l,attribLocations:{vertexPosition:t.getAttribLocation(l,"a_position"),texPosition:t.getAttribLocation(l,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(l,"u_image"),uColorFactor:t.getUniformLocation(l,"uColorFactor"),uMatrix:t.getUniformLocation(l,"u_matrix"),uTextureMatrix:t.getUniformLocation(l,"u_textureMatrix")}}),Un(this,Xn,e(t)),Un(this,zn,i(t)),Un(this,Yn,p)}const r=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const n=t.RGBA,r=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,n,r,s,i)},v=(t,e,s,a)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),r(t,s.positions,e.attribLocations.vertexPosition),r(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,a),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[Wn.GREY,Wn.GREY32].includes(p)?1:0);let m,_,v=Gn.translate(Gn.identity(),-1,-1);v=Gn.scale(v,2,2),v=Gn.scale(v,1/t.canvas.width,1/t.canvas.height),m=Gn.translate(v,u,d),m=Gn.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=Gn.translate(Gn.identity(),o/i,l/n),_=Gn.scale(_,h/i,c/n),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,jn(this,zn,"f"),e),v(t,jn(this,Hn,"f"),jn(this,Xn,"f"),jn(this,zn,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(u,d,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){Vr._onLog&&Vr._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return Vr._onLog&&Vr._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-a)),{context:t,pixelFormat:p===Wn.GREY?Wn.GREY32:p,bUseWebGL:!0}}catch(a){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return Vr._onLog&&Vr._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,n,r,Object.assign({},s,{bUseWebGL:!1}));throw a.name="WebGLError",a}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let n,r=0,s=0,a=t.canvas.width,o=t.canvas.height;if(e&&(e.x&&(r=e.x),e.y&&(s=e.y),e.width&&(a=e.width),e.height&&(o=e.height)),(null==i?void 0:i.length)<4*a*o)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(r,s,a,o,e.RGBA,e.UNSIGNED_BYTE,i),n=new Uint8Array(i.buffer,0,4*a*o)):(n=new Uint8Array(4*a*o),e.readPixels(r,s,a,o,e.RGBA,e.UNSIGNED_BYTE,n))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(r,s,a,o),n=new Uint8Array(e.data.buffer),null==i||i.set(n)}return n}transformPixelFormat(t,e,i,n){let r,s;if(Vr._onLog&&(r=Date.now(),Vr._onLog("transformPixelFormat(), START: "+r)),e===i)return Vr._onLog&&Vr._onLog("transformPixelFormat() end. Costs: "+(Date.now()-r)),n?new Uint8Array(t):t;const a=[Wn.RGBA,Wn.RBGA,Wn.GRBA,Wn.GBRA,Wn.BRGA,Wn.BGRA];if(a.includes(e))if(i===Wn.GREY){s=new Uint8Array(t.length/4);for(let e=0;el||e.sy+e.sHeight>h)throw new Error("Invalid position.");null===(n=Vr._onLog)||void 0===n||n.call(Vr,"getImageData(), START: "+(c=Date.now()));const d=Math.round(e.sx),f=Math.round(e.sy),g=Math.round(e.sWidth),m=Math.round(e.sHeight),p=Math.round(e.dWidth),_=Math.round(e.dHeight);let v,y=(null==i?void 0:i.pixelFormat)||Wn.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(Wn.GREY===y&&w.length{this.disposed||n.includes(r)&&r.apply(i.target,s)}),0);else try{a=r.apply(i.target,s)}catch(t){}if(!0===a)break}}}dispose(){Mn(this,Kn,!0)}}Jn=new WeakMap,Kn=new WeakMap;const Ur=(t,e,i,n)=>{if(!i)return t;let r=e+Math.round((t-e)/i)*i;return n&&(r=Math.min(r,n)),r};class Gr{static get version(){return"2.0.18"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],n=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],r=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!r.length)return null;const s=r.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const a=r.find((t=>{const e=t.label.toLowerCase();return n.some((t=>e.includes(t)))}));return a?a.deviceId:r[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(Vn.OS))return Gr.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(Vn.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(n,r)=>{let s;const a=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",u),t.removeEventListener("play",d),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let o=!1;const l=()=>{o=!0,s&&clearTimeout(s),a(),n(t)},h=t=>{s&&clearTimeout(s),a(),r(t)},c=()=>{t.addEventListener("abort",u,{once:!0})},u=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",h(t)},d=()=>{l()},f=()=>{h(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",d,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!o){i&&(s=setTimeout((()=>{a(),r(new Error("Failed to play video. Timeout."))}),i)),await m;try{await t.play(),l()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!o)try{await t.play(),l()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),h(t)}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let n;try{n=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==n||n.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!Ln(this,ur,"f"))return"closed";if("pending"===Ln(this,ur,"f"))return"opening";if("fulfilled"===Ln(this,ur,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Gr.isStorageAvailable("localStorage")?Mn(this,or,!0):(Mn(this,or,!1),console.warn("Local storage is unavailable")):Mn(this,or,!1)}get ifSaveLastUsedCamera(){return Ln(this,or,"f")}get isVideoPlaying(){return!(!Ln(this,tr,"f")||Ln(this,tr,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,n;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=Ln(this,_r,"f"))||void 0===e||e.removeEventListener("click",Ln(this,pr,"f")),null===(i=Ln(this,_r,"f"))||void 0===i||i.removeEventListener("touchend",Ln(this,pr,"f")),null===(n=Ln(this,_r,"f"))||void 0===n||n.removeEventListener("touchmove",Ln(this,mr,"f")),Mn(this,_r,t),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(Vn.OS)?(t.addEventListener("touchend",Ln(this,pr,"f")),t.addEventListener("touchmove",Ln(this,mr,"f"))):t.addEventListener("click",Ln(this,pr,"f")))}get tapFocusEventBoundEl(){return Ln(this,_r,"f")}get disposed(){return Ln(this,Ir,"f")}constructor(t){var e,i;Qn.add(this),tr.set(this,null),er.set(this,void 0),ir.set(this,(()=>{"opened"===this.state&&Ln(this,Er,"f").fire("resumed",null,{target:this,async:!1})})),nr.set(this,(()=>{Ln(this,Er,"f").fire("paused",null,{target:this,async:!1})})),rr.set(this,void 0),sr.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],ar.set(this,void 0),or.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,lr.set(this,void 0),hr.set(this,!0),cr.set(this,void 0),ur.set(this,void 0),dr.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},fr.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const r=window.getComputedStyle(Ln(this,tr,"f")).objectFit,s=this.getResolution(),a=Ln(this,tr,"f").getBoundingClientRect(),o=a.left,l=a.top,{width:h,height:c}=Ln(this,tr,"f").getBoundingClientRect();if(h<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const u=h/c,d=s.width/s.height;let f=1;if("contain"===r)d>u?(f=h/s.width,i=(t-o)/f,n=(e-l-(c-h/d)/2)/f):(f=c/s.height,n=(e-l)/f,i=(t-o-(h-c*d)/2)/f);else{if("cover"!==r)throw new Error("Unsupported object-fit.");d>u?(f=c/s.height,n=(e-l)/f,i=(t-o+(c*d-h)/2)/f):(f=h/s.width,i=(t-o)/f,n=(e-l+(h/d-c)/2)/f)}return{x:i,y:n}},gr.set(this,!1),mr.set(this,(()=>{Mn(this,gr,!0)})),pr.set(this,(async t=>{var e;if(Ln(this,gr,"f"))return void Mn(this,gr,!1);if(!Ln(this,fr,"f"))return;if(!this.isVideoPlaying)return;if(!Ln(this,er,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,n=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,n=t.changedTouches[0].clientY}const r=this.getResolution(),s=2*Math.round(Math.min(r.width,r.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let a;try{a=this.calculateCoordInVideo(i,n)}catch(t){}if(a.x<0||a.x>r.width||a.y<0||a.y>r.height)return;const o={x:a.x+"px",y:a.y+"px"},l=s+"px",h=l;let c;Gr._onLog&&(c=Date.now());try{await Ln(this,Qn,"m",kr).call(this,o,l,h,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Gr._onLog)throw Gr._onLog(t),t}Gr._onLog&&Gr._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;Gr._onLog&&Gr._onLog("Back to continuous focus."),null===(t=Ln(this,er,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),Ln(this,Er,"f").fire("tapfocus",null,{target:this,async:!1})})),_r.set(this,null),vr.set(this,1),yr.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!Ln(this,tr,"f"))return;const t=Ln(this,vr,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)Ln(this,tr,"f").style.transform="";else{const e=window.getComputedStyle(Ln(this,tr,"f")).objectFit,i=Ln(this,tr,"f").videoWidth,n=Ln(this,tr,"f").videoHeight,{width:r,height:s}=Ln(this,tr,"f").getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const a=r/s,o=i/n;let l=1;"contain"===e?l=aa?s/(i/t):r/(n/t));const h=l*(1-1/t)*(i/2-Ln(this,yr,"f").x),c=l*(1-1/t)*(n/2-Ln(this,yr,"f").y);Ln(this,tr,"f").style.transform=`translate(${h}px, ${c}px) scale(${t})`}},wr.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===Wn.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(Gr._onLog&&Gr._onLog("document visible. video paused: "+(null===(t=Ln(this,tr,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Gr._onLog&&Gr._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Gr._onLog&&Gr._onLog("document visible. 1st resume video failed, try open instead.")}e||await Ln(this,Qn,"m",Ar).call(this)}if(await new Promise((t=>setTimeout(t,300))),!this.isVideoPlaying){Gr._onLog&&Gr._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Gr._onLog&&Gr._onLog("document visible. 2rd resume video failed, try open instead.")}e||await Ln(this,Qn,"m",Ar).call(this)}}}else"hidden"===document.visibilityState&&(Gr._onLog&&Gr._onLog("document hidden. video paused: "+(null===(e=Ln(this,tr,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())})),Ir.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{Gr.onWarning&&Gr.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),Mn(this,Er,new jr),this.imageDataGetter=new Vr,document.addEventListener("visibilitychange",Ln(this,br,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",Ln(this,ir,"f")),t.addEventListener("pause",Ln(this,nr,"f")),Mn(this,tr,t)}getVideoEl(){return Ln(this,tr,"f")}releaseVideoEl(){var t,e;null===(t=Ln(this,tr,"f"))||void 0===t||t.removeEventListener("play",Ln(this,ir,"f")),null===(e=Ln(this,tr,"f"))||void 0===e||e.removeEventListener("pause",Ln(this,nr,"f")),Mn(this,tr,null)}isVideoLoaded(){return!!Ln(this,tr,"f")&&4==Ln(this,tr,"f").readyState}async open(){if(Ln(this,cr,"f")&&!Ln(this,hr,"f")){if("pending"===Ln(this,ur,"f"))return Ln(this,cr,"f");if("fulfilled"===Ln(this,ur,"f"))return}Ln(this,Er,"f").fire("before:open",null,{target:this}),await Ln(this,Qn,"m",Ar).call(this),Ln(this,Er,"f").fire("played",null,{target:this,async:!1}),Ln(this,Er,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;Ln(this,Er,"f").fire("before:close",null,{target:this});const t=Ln(this,cr,"f");if(Ln(this,Qn,"m",Mr).call(this),t&&"pending"===Ln(this,ur,"f")){try{await t}catch(t){}if(!1===Ln(this,hr,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}Mn(this,cr,null),Mn(this,ur,null),Ln(this,Er,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");Ln(this,tr,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await Ln(this,tr,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof Ln(this,rr,"f").video&&(Ln(this,rr,"f").video={}),delete Ln(this,rr,"f").video.facingMode,Ln(this,rr,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&Ln(this,hr,"f"))){Ln(this,Er,"f").fire("before:camera:change",[],{target:this,async:!1}),await Ln(this,Qn,"m",Lr).call(this);try{this.resetSoftwareScale()}catch(t){}return Ln(this,sr,"f")}}async switchToFrontCamera(t){if("object"!=typeof Ln(this,rr,"f").video&&(Ln(this,rr,"f").video={}),(null==t?void 0:t.resolution)&&(Ln(this,rr,"f").video.width={ideal:t.resolution.width},Ln(this,rr,"f").video.height={ideal:t.resolution.height}),delete Ln(this,rr,"f").video.deviceId,Ln(this,rr,"f").video.facingMode={exact:"user"},Mn(this,ar,null),!("closed"===this.state||this.videoSrc||"opening"===this.state&&Ln(this,hr,"f"))){Ln(this,Er,"f").fire("before:camera:change",[],{target:this,async:!1}),Ln(this,Qn,"m",Lr).call(this);try{this.resetSoftwareScale()}catch(t){}return Ln(this,sr,"f")}}getCamera(){var t;if(Ln(this,sr,"f"))return Ln(this,sr,"f");{let e=(null===(t=Ln(this,rr,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else n=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const r=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof Ln(this,rr,"f").video&&(Ln(this,rr,"f").video={}),i?(Ln(this,rr,"f").video.width={exact:t},Ln(this,rr,"f").video.height={exact:e}):(Ln(this,rr,"f").video.width={ideal:t},Ln(this,rr,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&Ln(this,hr,"f"))return null;Ln(this,Er,"f").fire("before:resolution:change",[],{target:this,async:!1}),await Ln(this,Qn,"m",Lr).call(this);try{this.resetSoftwareScale()}catch(t){}const n=this.getResolution();return{width:n.width,height:n.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&Ln(this,tr,"f"))return{width:Ln(this,tr,"f").videoWidth,height:Ln(this,tr,"f").videoHeight};if(Ln(this,er,"f")){const t=Ln(this,er,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:Ln(this,tr,"f").videoWidth,height:Ln(this,tr,"f").videoHeight};{const t={width:0,height:0};let e=Ln(this,rr,"f").video.width||0,i=Ln(this,rr,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,n,r,s,a,o,l,h,c,u;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let d="";const f=(t,e)=>{const i=Ln(this,Sr,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){d=null===(u=Ln(this,sr,"f"))||void 0===u?void 0:u.deviceId;let e=Ln(this,Sr,"f").get(d);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],Ln(this,Sr,"f").set(d,e),Mn(this,dr,!0);try{for(let t of this.detectedResolutions){await Ln(this,er,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),Ln(this,Qn,"m",Rr).call(this);const i=Ln(this,er,"f").getSettings(),n={width:i.width,height:i.height};f(d,n)||e.push({width:n.width,height:n.height})}}catch(t){throw Ln(this,Qn,"m",Mr).call(this),Mn(this,dr,!1),t}try{await Ln(this,Qn,"m",Ar).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{Mn(this,dr,!1)}return e}{const e=async(t,e,i)=>{const n={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let r=null;try{r=await navigator.mediaDevices.getUserMedia(n)}catch(t){return null}if(!r)return null;const s=r.getVideoTracks();let a=null;try{const t=s[0].getSettings();a={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=r,a={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach((t=>{t.stop()})),a};let i=(null===(s=null===(r=null===(n=Ln(this,rr,"f"))||void 0===n?void 0:n.video)||void 0===r?void 0:r.deviceId)||void 0===s?void 0:s.exact)||(null===(l=null===(o=null===(a=Ln(this,rr,"f"))||void 0===a?void 0:a.video)||void 0===o?void 0:o.deviceId)||void 0===l?void 0:l.ideal)||(null===(c=null===(h=Ln(this,rr,"f"))||void 0===h?void 0:h.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let u=Ln(this,Sr,"f").get(i);if(u&&!t)return JSON.parse(JSON.stringify(u));u=[],Ln(this,Sr,"f").set(i,u);for(let t of this.detectedResolutions){const n=await e(i,t.width,t.height);n&&!f(i,n)&&u.push({width:n.width,height:n.height})}return u}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");Mn(this,rr,JSON.parse(JSON.stringify(t))),Mn(this,ar,null),e&&Ln(this,Qn,"m",Lr).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(Ln(this,rr,"f")))}resetMediaStreamConstraints(){Mn(this,rr,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null)}getCameraCapabilities(){if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Ln(this,er,"f").getCapabilities?Ln(this,er,"f").getCapabilities():{}}getCameraSettings(){if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Ln(this,er,"f").getSettings()}async turnOnTorch(){if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Ln(this,er,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Ln(this,er,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ur(t,n.min,n.step,n.max)),await Ln(this,er,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ur(t,n.min,n.step,n.max)),await Ln(this,er,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!n)throw Error("Not supported.");e&&(tn.max&&(t=n.max));const r=this.getResolution();return await Ln(this,er,"f").applyConstraints({width:{ideal:Math.max(r.width,r.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),n=null==i?void 0:i.focusMode,r=null==i?void 0:i.focusDistance;if(!n)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!n.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!r)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(ir.max&&(i=r.max),i=Ur(i,r.min,r.step,r.max)),this._focusParameters.focusArea=null,await Ln(this,er,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,n=t.area.height;if(!i||!n){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),n||(n=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:n},await Ln(this,Qn,"m",kr).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await Ln(this,er,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){Mn(this,fr,!0)}disableTapToFocus(){Mn(this,fr,!1)}isTapToFocusEnabled(){return Ln(this,fr,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?Ln(this,Qn,"m",Nr).call(this,t.centerPoint):this.resetScaleCenter();try{if(Ln(this,Qn,"m",Br).call(this,Ln(this,yr,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*Ln(this,vr,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!Ln(this,er,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Ur(t,n.min,n.step,n.max)),await Ln(this,er,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&Ln(this,Qn,"m",Nr).call(this,e),Mn(this,vr,t),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return Ln(this,vr,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();Mn(this,yr,{x:t.width/2,y:t.height/2})}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(Ln(this,dr,"f"))return null;const e=Date.now();Gr._onLog&&Gr._onLog("getFrameData() START: "+e);const i=Ln(this,tr,"f").videoWidth,n=Ln(this,tr,"f").videoHeight;let r={sx:0,sy:0,sWidth:i,sHeight:n,dWidth:i,dHeight:n};(null==t?void 0:t.position)&&(r=JSON.parse(JSON.stringify(t.position)));let s=Wn.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let a=Ln(this,vr,"f");(null==t?void 0:t.scale)&&(a=t.scale);let o=Ln(this,yr,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,r=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))r=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.scaleCenter.y)/100*n}if(isNaN(e)||isNaN(r))throw new Error("Invalid scale center.");o.x=Math.round(e),o.y=Math.round(r)}let l=null;if((null==t?void 0:t.bufferContainer)&&(l=t.bufferContainer),0==i||0==n)return null;1!==a&&(r.sWidth=Math.round(r.sWidth/a),r.sHeight=Math.round(r.sHeight/a),r.sx=Math.round((1-1/a)*o.x+r.sx/a),r.sy=Math.round((1-1/a)*o.y+r.sy/a));const h=this.imageDataGetter.getImageData(Ln(this,tr,"f"),r,{pixelFormat:s,bufferContainer:l});if(!h)return null;const c=Date.now();return Gr._onLog&&Gr._onLog("getFrameData() END: "+c),{data:h.data,width:h.width,height:h.height,pixelFormat:h.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:Ln(this,wr,"f")}}on(t,e){if(!Ln(this,Cr,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);Ln(this,Er,"f").on(t,e)}off(t,e){Ln(this,Er,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),Ln(this,Er,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",Ln(this,br,"f")),Mn(this,Ir,!0)}}var Wr,Yr,zr,Hr,Xr,Zr,qr,Jr,Kr,$r,Qr,ts,es,is,ns,rs,ss,as,os,ls,hs,cs,us,ds,fs,gs,ms,ps,_s,vs,ys,ws,Es,Cs,Ss;tr=new WeakMap,er=new WeakMap,ir=new WeakMap,nr=new WeakMap,rr=new WeakMap,sr=new WeakMap,ar=new WeakMap,or=new WeakMap,lr=new WeakMap,hr=new WeakMap,cr=new WeakMap,ur=new WeakMap,dr=new WeakMap,fr=new WeakMap,gr=new WeakMap,mr=new WeakMap,pr=new WeakMap,_r=new WeakMap,vr=new WeakMap,yr=new WeakMap,wr=new WeakMap,Er=new WeakMap,Cr=new WeakMap,Sr=new WeakMap,Tr=new WeakMap,br=new WeakMap,Ir=new WeakMap,Qn=new WeakSet,xr=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(Ln(this,ar,"f"))delete t.video.facingMode,t.video.deviceId={exact:Ln(this,ar,"f")};else if(this.ifSaveLastUsedCamera&&Gr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(Vn.OS)?(await this._getCameras(!1),Ln(this,Qn,"m",Rr).call(this),e=Gr.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(Vn.OS)||(await this._getCameras(!1),Ln(this,Qn,"m",Rr).call(this),e=Gr.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const n=await e(i);n&&(delete t.video.facingMode,t.video.deviceId={exact:n})}return t},Rr=function(){if(Ln(this,hr,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},Or=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;try{Gr._onLog&&Gr._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const r=async t=>{for(let r of e){r&&(await new Promise((t=>setTimeout(t,r))),Ln(this,Qn,"m",Rr).call(this));try{Gr._onLog&&Gr._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),Ln(this,Qn,"m",Rr).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Gr._onLog&&Gr._onLog(t.message||t)}}};if(await r(t),n||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await r(t)),!n&&t.video.facingMode&&(delete t.video.facingMode,await r(t)),n||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await r(t))),!n)throw i;return n}catch(t){throw null==n||n.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},Dr=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),Mn(this,er,null)},Ar=async function(){Mn(this,hr,!1);const t=Mn(this,lr,Symbol());if(Ln(this,cr,"f")&&"pending"===Ln(this,ur,"f")){try{await Ln(this,cr,"f")}catch(t){}Ln(this,Qn,"m",Rr).call(this)}if(t!==Ln(this,lr,"f"))return;const e=Mn(this,cr,(async()=>{Mn(this,ur,"pending");try{if(this.videoSrc){if(!Ln(this,tr,"f"))throw new Error("'videoEl' should be set.");await Gr.playVideo(Ln(this,tr,"f"),this.videoSrc,this.cameraOpenTimeout),Ln(this,Qn,"m",Rr).call(this)}else{let t=await Ln(this,Qn,"m",xr).call(this);Ln(this,Qn,"m",Dr).call(this);let e=await Ln(this,Qn,"m",Or).call(this,t);await this._getCameras(!1),Ln(this,Qn,"m",Rr).call(this);const i=()=>{const t=e.getVideoTracks();let i,n;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,n=e;break}}return n},n=Ln(this,rr,"f");if("object"==typeof n.video){let r=n.video.facingMode;if(r instanceof Array&&r.length&&(r=r[0]),"object"==typeof r&&(r=r.exact||r.ideal),!(Ln(this,ar,"f")||this.ifSaveLastUsedCamera&&Gr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),s=Gr.findBestCamera(this._arrCameras,r,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==n?void 0:n.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await Ln(this,Qn,"m",Or).call(this,t),Ln(this,Qn,"m",Rr).call(this))}}const r=i();(null==r?void 0:r.deviceId)&&(Mn(this,ar,r&&r.deviceId),this.ifSaveLastUsedCamera&&Gr.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",Ln(this,ar,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),Ln(this,tr,"f")&&(await Gr.playVideo(Ln(this,tr,"f"),e,this.cameraOpenTimeout),Ln(this,Qn,"m",Rr).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&Mn(this,er,s[0]),Mn(this,sr,r)}}catch(t){throw Ln(this,Qn,"m",Mr).call(this),Mn(this,ur,null),t}Mn(this,ur,"fulfilled")})());return e},Lr=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=Ln(this,sr,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await Ln(this,Qn,"m",Ar).call(this);const n=this.getResolution();e&&e!==Ln(this,sr,"f").deviceId&&Ln(this,Er,"f").fire("camera:changed",[Ln(this,sr,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||Ln(this,Er,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),Ln(this,Er,"f").fire("played",null,{target:this,async:!1})},Mr=function(){Ln(this,Qn,"m",Dr).call(this),Mn(this,sr,null),Ln(this,tr,"f")&&(Ln(this,tr,"f").srcObject=null,this.videoSrc&&(Ln(this,tr,"f").pause(),Ln(this,tr,"f").currentTime=0)),Mn(this,hr,!0);try{this.resetSoftwareScale()}catch(t){}},Fr=async function t(e,i){const n=t=>{if(!Ln(this,er,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){Ln(this,er,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;i=Ur(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await Ln(this,er,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),n(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,r)})),n(e);let s=e.focusL-e.focusW/2,a=e.focusT-e.focusH/2,o=e.focusW,l=e.focusH;const h=this.getResolution();s=Math.round(s),a=Math.round(a),o=Math.round(o),l=Math.round(l),o>h.width&&(o=h.width),l>h.height&&(l=h.height),s<0?s=0:s+o>h.width&&(s=h.width-o),a<0?a=0:a+l>h.height&&(a=h.height-l);const c=4*h.width*h.height*this._focusParameters.defaultTempBufferContainerLenRatio,u=4*o*l;let d=this._focusParameters.tempBufferContainer;if(d){const t=d.length;c>t&&c>=u?d=new Uint8Array(c):u>t&&u>=c&&(d=new Uint8Array(u))}else d=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,u));if(!this.imageDataGetter.getImageData(Ln(this,tr,"f"),{sx:s,sy:a,sWidth:o,sHeight:l,dWidth:o,dHeight:l},{pixelFormat:Wn.RGBA,bufferContainer:d}))return Ln(this,Qn,"m",t).call(this,e,i);const f=d;let g=0;for(let t=0,e=u-8;to&&ou)return await Ln(this,Qn,"m",t).call(this,e,a,o,r,s,c,u)}else{let l=await Ln(this,Qn,"m",Fr).call(this,e,c);if(o>l)return await Ln(this,Qn,"m",t).call(this,e,a,o,r,s,c,l);if(o==l)return await Ln(this,Qn,"m",t).call(this,e,a,o,c,l);let u=await Ln(this,Qn,"m",Fr).call(this,e,h);if(u>o&&oa.width||l<0||l>a.height)throw new Error("Invalid 'centerPoint'.");let h=0;if(e.endsWith("px"))h=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");h=parseFloat(e)/100*a.width}if(isNaN(h)||h<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*a.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==Ln(this,vr,"f")){const t=Ln(this,vr,"f"),e=Ln(this,yr,"f");h/=t,c/=t,o=(1-1/t)*e.x+o/t,l=(1-1/t)*e.y+l/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const u={focusL:o,focusT:l,focusW:h,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},d=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let n=Ur(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=Ur(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Ur(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),a=await Ln(this,Qn,"m",Fr).call(this,t,s),o=await Ln(this,Qn,"m",Fr).call(this,t,r),l=await Ln(this,Qn,"m",Fr).call(this,t,n);if(o>l&&la&&o>a){let e=await Ln(this,Qn,"m",Fr).call(this,t,i);const r=await Ln(this,Qn,"m",Pr).call(this,t,n,l,i,e,s,a);return this._focusParameters.isDoingFocus=0,r}if(o==l&&ll){const e=await Ln(this,Qn,"m",Pr).call(this,t,n,l,s,a);return this._focusParameters.isDoingFocus=0,e}return d(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return d(u,n,r)},Nr=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,n=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))n=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(n))throw new Error("Invalid scale center.");Mn(this,yr,{x:i,y:n})},Br=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},Gr.browserInfo=Vn,Gr.onWarning=null===($n=null===window||void 0===window?void 0:window.console)||void 0===$n?void 0:$n.warn;class Ts{constructor(t){Wr.add(this),Yr.set(this,void 0),zr.set(this,0),Hr.set(this,void 0),Xr.set(this,0),Zr.set(this,!1),Xe(this,Yr,t)}startCharging(){He(this,Zr,"f")||(Ts._onLog&&Ts._onLog("start charging."),He(this,Wr,"m",Jr).call(this),Xe(this,Zr,!0))}stopCharging(){He(this,Hr,"f")&&clearTimeout(He(this,Hr,"f")),He(this,Zr,"f")&&(Ts._onLog&&Ts._onLog("stop charging."),Xe(this,zr,Date.now()-He(this,Xr,"f")),Xe(this,Zr,!1))}}Yr=new WeakMap,zr=new WeakMap,Hr=new WeakMap,Xr=new WeakMap,Zr=new WeakMap,Wr=new WeakSet,qr=function(){gt.cfd(1),Ts._onLog&&Ts._onLog("charge 1.")},Jr=function t(){0==He(this,zr,"f")&&He(this,Wr,"m",qr).call(this),Xe(this,Xr,Date.now()),He(this,Hr,"f")&&clearTimeout(He(this,Hr,"f")),Xe(this,Hr,setTimeout((()=>{Xe(this,zr,0),He(this,Wr,"m",t).call(this)}),He(this,Yr,"f")-He(this,zr,"f")))};class bs{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-He(this,Kr,"f",ts)<100)){if(Xe(this,Kr,e,0,ts),He(this,Kr,"f",$r).size&&(t=He(this,Kr,"f",$r).values().next().value,this.beepSoundSource==t.src?(He(this,Kr,"f",$r).delete(t),t.play()):t=null),!t)if(He(this,Kr,"f",Qr).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{He(this,Kr,"f",Qr).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,He(this,Kr,"f",Qr).delete(t),He(this,Kr,"f",$r).add(t)}))}else He(this,Kr,"f",es)||(Xe(this,Kr,!0,0,es),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&He(this,Kr,"f",Qr).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(bs.vibrateDuration)}}}Kr=bs,$r={value:new Set},Qr={value:new Set},ts={value:0},es={value:!1},bs.allowBeep=!0,bs.beepSoundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",bs.allowVibrate=!0,bs.vibrateDuration=300;const Is=new Map([[Wn.GREY,l.IPF_GRAYSCALED],[Wn.RGBA,l.IPF_ABGR_8888]]),xs="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class Rs extends X{static set _onLog(t){Xe(Rs,ns,t,0,rs),Gr._onLog=t,Ts._onLog=t}static get _onLog(){return He(Rs,ns,"f",rs)}static async detectEnvironment(){return await(async()=>({wasm:Ze,worker:qe,getUserMedia:Je,camera:await Ke(),browser:ze.browser,version:ze.version,OS:ze.OS}))()}static async testCameraAccess(){const t=await Gr.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var e,i;if(t&&!(t instanceof An))throw new TypeError("Invalid view.");if(null===(e=ct.license)||void 0===e?void 0:e.LicenseManager){if(!(null===(i=ct.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await gt.loadWasm(["license"]),await ct.license.dynamsoft()}const n=new Rs(t);return Rs.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{Rs.onWarning&&Rs.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{Rs.onWarning&&Rs.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),n}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");Xe(this,os,t)}get singleFrameMode(){return He(this,os,"f")}get _isFetchingStarted(){return He(this,fs,"f")}get disposed(){return He(this,vs,"f")}constructor(t){if(super(),is.add(this),ss.set(this,"closed"),as.set(this,void 0),this.isTorchOn=void 0,os.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},ls.set(this,((t,e,i,n)=>{const r=Date.now(),s={sx:n.x,sy:n.y,sWidth:n.width,sHeight:n.height,dWidth:n.width,dHeight:n.height},a=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&a>this.canvasSizeLimit){const t=this.canvasSizeLimit/a;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const o=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===l.IPF_GRAYSCALED?Wn.GREY:Wn.RGBA});let h=null;if(o){const t=Date.now();let a;a=o.pixelFormat===Wn.GREY?o.width:4*o.width;let l=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(l=!1),h={bytes:o.data,width:o.width,height:o.height,stride:a,format:Is.get(o.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:wt.ITT_FILE_IMAGE,isCropped:l,cropRegion:{left:n.x,top:n.y,right:n.x+n.width,bottom:n.y+n.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:o.width,currentHeight:o.height,timeSpent:t-r,timeStamp:t},toCanvas:He(this,hs,"f"),isDCEFrame:!0}}return h})),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():ki.convert(He(this,us,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=He(this,ls,"f").call(this,t,t.width,t.height,e);He(this,as,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},hs.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===l.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(ze.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",(()=>{He(this,_s,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{He(this,_s,"f").stopCharging();const t=this.cameraView;t&&t.disposed})),this._on("resumed",(()=>{const t=this.cameraView;t&&t.disposed})),this._on("tapfocus",(()=>{He(this,ms,"f").tapToFocus&&He(this,_s,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,n,r,s;if(He(this,is,"m",ys).call(this)||!this.isOpen()||this.isPaused())return;const a=t.intermediateResultUnits;Rs._onLog&&(Rs._onLog("intermediateResultUnits:"),Rs._onLog(a));let o=!1,l=!1;for(let t of a){if(t.unitType===Tt.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){o=!0;break}t.unitType===Tt.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(l=!0)}if(Rs._onLog&&(Rs._onLog("hasLocalizedBarcodes:"),Rs._onLog(l)),He(this,ms,"f").autoZoom||He(this,ms,"f").enhancedFocus)if(o)He(this,ps,"f").autoZoomInFrameArray.length=0,He(this,ps,"f").autoZoomOutFrameCount=0,He(this,ps,"f").frameArrayInIdealZoom.length=0,He(this,ps,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),He(this,ms,"f").autoZoom&&He(this,_s,"f").startCharging()},o=async t=>{await this.setFocus(t),He(this,ms,"f").enhancedFocus&&He(this,_s,"f").startCharging()};if(l){const l=a[0].originalImageTag,h=(null===(i=l.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(n=l.cropRegion)||void 0===n?void 0:n.top)||0,u=(null===(r=l.cropRegion)||void 0===r?void 0:r.right)?l.cropRegion.right-h:l.originalWidth,d=(null===(s=l.cropRegion)||void 0===s?void 0:s.bottom)?l.cropRegion.bottom-c:l.originalHeight,f=l.currentWidth,g=l.currentHeight;let m;{let t,e,i,n,r;{const t=this.video.videoWidth*(1-He(this,ps,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+He(this,ps,"f").autoZoomDetectionArea)/2,i=e,n=t,s=this.video.videoHeight*(1-He(this,ps,"f").autoZoomDetectionArea)/2,a=s,o=this.video.videoHeight*(1+He(this,ps,"f").autoZoomDetectionArea)/2;r=[{x:t,y:s},{x:e,y:a},{x:i,y:o},{x:n,y:o}]}Rs._onLog&&(Rs._onLog("detectionArea:"),Rs._onLog(r));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let n=!1;const r=t.length;if(r<=2)return!1;for(let s=0;s0!=Ui(o.y-i)>0&&Ui(e-(i-a.y)*(a.x-o.x)/(a.y-o.y)-a.x)<0&&(n=!n)}return n}(e,t.x,t.y)},n=(t,e)=>!!(Gi([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||Gi([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||Gi([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||Gi([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(n([e[0].x,e[0].y,e[1].x,e[1].y],t)||n([e[1].x,e[1].y,e[2].x,e[2].y],t)||n([e[2].x,e[2].y,e[3].x,e[3].y],t)||n([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of a)if(e.unitType===Tt.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach((t=>{An._transformCoordinates(t,h,c,u,d,f,g)})),t(r,e)&&s.push(i)}if(Rs._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=bn.createDrawingStyle({strokeStyle:"red"}));for(let i of a)if(i.unitType===Tt.IRUT_LOCALIZED_BARCODES)for(let n of i.localizedBarcodes){if(!n)continue;const i=n.location.points,r=new Ii({points:i},e);t.addDrawingItems([r])}}}if(Rs._onLog&&(Rs._onLog("intersectedResults:"),Rs._onLog(s)),!s.length)return;let o;if(s.length){let t=s.filter((t=>t.possibleFormats==xs.BF_QR_CODE||t.possibleFormats==xs.BF_DATAMATRIX));if(t.length||(t=s.filter((t=>t.possibleFormats==xs.BF_ONED)),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,n=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(n-g/2)*(n-g/2)};o=t[0];let i=e(o);if(1!=t.length)for(let n=1;n1.1*o.confidence||t[n].confidence>.9*o.confidence&&ri&&s>i&&a>i&&l>i&&m.result.moduleSize{})),He(this,ps,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=He(this,ps,"f").autoZoomInFrameLimit[1]){He(this,ps,"f").autoZoomInFrameArray.length=0;const i=[(.5-n)/(.5-r),(.5-n)/(.5-s),(.5-n)/(.5-a),(.5-n)/(.5-l)].filter((t=>t>0)),o=Math.min(...i,He(this,ps,"f").autoZoomInIdealModuleSize/m.result.moduleSize),h=this.getZoomSettings().factor;let c=Math.max(Math.pow(h*o,1/He(this,ps,"f").autoZoomInMaxTimes),He(this,ps,"f").autoZoomInMinStep);c=Math.min(c,o);let u=h*c;u=Math.max(He(this,ps,"f").minValue,u),u=Math.min(He(this,ps,"f").maxValue,u);try{await e({factor:u})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(He(this,ps,"f").autoZoomInFrameArray.length=0,He(this,ps,"f").frameArrayInIdealZoom.push(!0),He(this,ps,"f").frameArrayInIdealZoom.splice(0,He(this,ps,"f").frameArrayInIdealZoom.length-He(this,ps,"f").frameLimitInIdealZoom[0]),He(this,ps,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=He(this,ps,"f").frameLimitInIdealZoom[1]&&(He(this,ps,"f").frameArrayInIdealZoom.length=0,He(this,ms,"f").enhancedFocus)){const e=m.points;try{await o({mode:"manual",area:{centerPoint:{x:(e[0].x+e[2].x)/2+"px",y:(e[0].y+e[2].y)/2+"px"},width:e[2].x-e[0].x+"px",height:e[2].y-e[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!He(this,ms,"f").autoZoom&&He(this,ms,"f").enhancedFocus&&(He(this,ps,"f").autoFocusFrameArray.push(!0),He(this,ps,"f").autoFocusFrameArray.splice(0,He(this,ps,"f").autoFocusFrameArray.length-He(this,ps,"f").autoFocusFrameLimit[0]),He(this,ps,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=He(this,ps,"f").autoFocusFrameLimit[1])){He(this,ps,"f").autoFocusFrameArray.length=0;try{const t=m.points;await o({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(He(this,ms,"f").autoZoom){if(He(this,ps,"f").autoZoomInFrameArray.push(!1),He(this,ps,"f").autoZoomInFrameArray.splice(0,He(this,ps,"f").autoZoomInFrameArray.length-He(this,ps,"f").autoZoomInFrameLimit[0]),He(this,ps,"f").autoZoomOutFrameCount++,He(this,ps,"f").frameArrayInIdealZoom.push(!1),He(this,ps,"f").frameArrayInIdealZoom.splice(0,He(this,ps,"f").frameArrayInIdealZoom.length-He(this,ps,"f").frameLimitInIdealZoom[0]),He(this,ps,"f").autoZoomOutFrameCount>=He(this,ps,"f").autoZoomOutFrameLimit){He(this,ps,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let n=i-Math.max((i-1)*He(this,ps,"f").autoZoomOutStepRate,He(this,ps,"f").autoZoomOutMinStep);n=Math.max(He(this,ps,"f").minValue,n),n=Math.min(He(this,ps,"f").maxValue,n);try{await e({factor:n})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}He(this,ms,"f").enhancedFocus&&o({mode:"continuous"}).catch((()=>{}))}!He(this,ms,"f").autoZoom&&He(this,ms,"f").enhancedFocus&&(He(this,ps,"f").autoFocusFrameArray.length=0,o({mode:"continuous"}).catch((()=>{})))}}},Xe(this,_s,new Ts(1e4))}setCameraView(t){if(!(t instanceof An))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),He(this,is,"m",ys).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;He(this,is,"m",ys).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return He(this,is,"m",ys).call(this)?He(this,ss,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=this.cameraView;if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,He(this,is,"m",ys).call(this)?t._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(He(this,is,"m",ys).call(this));else{try{await this.cameraManager.open()}catch(e){throw t&&t._stopLoading(),"NotFoundError"===e.name?new Error(`No camera devices were detected. Please ensure a camera is connected and recognized by your system. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):"NotAllowedError"===e.name?new Error(`Camera access is blocked. Please check your browser settings or grant permission to use the camera. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):e}let i,n=t.getUIElement();if(n=n.shadowRoot||n,i=n.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=n.elTorchAuto=n.querySelector(".dce-mn-torch-auto"),e=n.elTorchOn=n.querySelector(".dce-mn-torch-on"),r=n.elTorchOff=n.querySelector(".dce-mn-torch-off");t&&(e.style.display=null==this.isTorchOn?"":"none"),e&&(e.style.display=1==this.isTorchOn?"":"none"),r&&(r.style.display=0==this.isTorchOn?"":"none");let s=n.elBeepOn=n.querySelector(".dce-mn-beep-on"),a=n.elBeepOff=n.querySelector(".dce-mn-beep-off");s&&(s.style.display=bs.allowBeep?"":"none"),a&&(a.style.display=bs.allowBeep?"none":"");let o=n.elVibrateOn=n.querySelector(".dce-mn-vibrate-on"),l=n.elVibrateOff=n.querySelector(".dce-mn-vibrate-off");o&&(o.style.display=bs.allowVibrate?"":"none"),l&&(l.style.display=bs.allowVibrate?"none":""),n.elResolutionBox=n.querySelector(".dce-mn-resolution-box");let h,c=n.elZoom=n.querySelector(".dce-mn-zoom");c&&(c.style.display="none",h=n.elZoomSpan=c.querySelector("span"));let u=n.elToast=n.querySelector(".dce-mn-toast"),d=n.elCameraClose=n.querySelector(".dce-mn-camera-close"),f=n.elTakePhoto=n.querySelector(".dce-mn-take-photo"),g=n.elCameraSwitch=n.querySelector(".dce-mn-camera-switch"),m=n.elCameraAndResolutionSettings=n.querySelector(".dce-mn-camera-and-resolution-settings");m&&(m.style.display="none");const p=n.dceMnFs={},_=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",_);const v=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",v);const y=()=>{this.turnAutoTorch()};null==r||r.addEventListener("pointerdown",y);const w=()=>{bs.allowBeep=!bs.allowBeep,s&&(s.style.display=bs.allowBeep?"":"none"),a&&(a.style.display=bs.allowBeep?"none":"")};for(let t of[a,s])null==t||t.addEventListener("pointerdown",w);const E=()=>{bs.allowVibrate=!bs.allowVibrate,o&&(o.style.display=bs.allowVibrate?"":"none"),l&&(l.style.display=bs.allowVibrate?"none":"")};for(let t of[l,o])null==t||t.addEventListener("pointerdown",E);const C=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),n=parseInt(e.getAttribute("data-height")),r=await this.setResolution({width:i,height:n});{let e=Math.max(r.width,r.height),i=Math.min(r.width,r.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&b(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?m&&(m.style.display=m.style.display?"":"none"):m&&""===m.style.display&&(m.style.display="none"))};n.addEventListener("click",C);let S=null;p.funcInfoZoomChange=(t,e=3e3)=>{c&&h&&(h.textContent=t.toFixed(1),c.style.display="",null!=S&&(clearTimeout(S),S=null),S=setTimeout((()=>{c.style.display="none",S=null}),e))};let T=null,b=p.funcShowToast=(t,e=3e3)=>{u&&(u.textContent=t,u.style.display="",null!=T&&(clearTimeout(T),T=null),T=setTimeout((()=>{u.style.display="none",T=null}),e))};const I=()=>{this.close()};null==d||d.addEventListener("click",I);const x=()=>{};null==f||f.addEventListener("pointerdown",x);const R=()=>{var t,e;let i,n=this.getVideoSettings(),r=n.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),a=null==s?void 0:s.indexOf("front");-1===a&&(a=null==s?void 0:s.indexOf("前"));let o=null==s?void 0:s.indexOf("back");-1===o&&(o=null==s?void 0:s.indexOf("后")),"number"==typeof a&&-1!==a?i=!0:"number"==typeof o&&-1!==o&&(i=!1),void 0===i&&(i="user"===((null==r?void 0:r.ideal)||(null==r?void 0:r.exact)||r)),n.video.facingMode={ideal:i?"environment":"user"},delete n.video.deviceId,this.updateVideoSettings(n)};null==g||g.addEventListener("pointerdown",R);let O=-1/0,D=1;const A=t=>{let e=Date.now();e-O>1e3&&(D=this.getZoomSettings().factor),D-=t.deltaY/200,D>20&&(D=20),D<1&&(D=1),this.setZoom({factor:D}),O=e};i.addEventListener("wheel",A);const L=new Map;let M=!1;const F=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],n=t.touches[1],r=L.get(i.identifier),s=L.get(n.identifier);if(!r||!s)break;let a=Math.pow(Math.pow(r.x-s.x,2)+Math.pow(r.y-s.y,2),.5),o=Math.pow(Math.pow(i.clientX-n.clientX,2)+Math.pow(i.clientY-n.clientY,2),.5),l=Date.now();if(M||l-O<100)return;l-O>1e3&&(D=this.getZoomSettings().factor),D*=o/a,D>20&&(D=20),D<1&&(D=1);let h=!1;"safari"==(null===(e=null==ze?void 0:ze.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(o/a>1&&D<2?(D=2,h=!0):o/a<1&&D<2&&(D=1,h=!0)),M=!0,h&&b("zooming..."),await this.setZoom({factor:D}),h&&(u.textContent=""),M=!1,O=Date.now();break}L.clear();for(let e of t.touches)L.set(e.identifier,{x:e.clientX,y:e.clientY})};n.addEventListener("touchstart",F),n.addEventListener("touchmove",F),n.addEventListener("touchend",F),n.addEventListener("touchcancel",F),p.unbind=()=>{null==t||t.removeEventListener("pointerdown",_),null==e||e.removeEventListener("pointerdown",v),null==r||r.removeEventListener("pointerdown",y);for(let t of[a,s])null==t||t.removeEventListener("pointerdown",w);for(let t of[l,o])null==t||t.removeEventListener("pointerdown",E);n.removeEventListener("click",C),null==d||d.removeEventListener("click",I),null==f||f.removeEventListener("pointerdown",x),null==g||g.removeEventListener("pointerdown",R),i.removeEventListener("wheel",A),n.removeEventListener("touchstart",F),n.removeEventListener("touchmove",F),n.removeEventListener("touchend",F),n.removeEventListener("touchcancel",F),delete n.dceMnFs,i.style.display="none"},i.style.display="",t&&null==this.isTorchOn&&setTimeout((()=>{this.turnAutoTorch(1e3)}),0)}this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const r=this.getResolution();e.width=r.width,e.height=r.height,e.deviceId=this.getSelectedCamera().deviceId}return Xe(this,ss,"open"),t&&(t._innerComponent.style.display="",He(this,is,"m",ys).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!1}),t.eventHandler.fire("videoEl:resized",null,{async:!1}))),He(this,as,"f").fire("opened",null,{target:this,async:!1}),e}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),He(this,is,"m",ys).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}Xe(this,ss,"closed"),He(this,_s,"f").stopCharging(),e&&(e._innerComponent.style.display="none",He(this,is,"m",ys).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),He(this,as,"f").fire("closed",null,{target:this,async:!1})}pause(){if(He(this,is,"m",ys).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!He(this,is,"m",ys).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(He(this,is,"m",ys).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(e),this.isTorchOn=!1;const i=this.getResolution(),n=this.cameraView;return n&&!n.disposed&&(n._stopLoading(),n._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),n._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?He(this,as,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?He(this,as,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._on(n,e)}off(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._off(n,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(He(this,is,"m",ys).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(He(this,is,"m",ys).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){if(null!=this._taskid4AutoTorch){if(!(t{var t,r,s;if(this.disposed||e||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++n>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let a;try{a=this.fetchImage()}catch(t){}if(!a||!a.width||!a.height)return;let o=0;if(l.IPF_GRAYSCALED===a.format){for(let t=0;t=this.maxDarkCount4AutoTroch){null===(t=Rs._onLog)||void 0===t||t.call(Rs,`darkCount ${i}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(r=null==t?void 0:t.dceMnFs)||void 0===r||r.funcShowToast("Torch Auto On")}catch(t){console.warn(t),e=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,null===(s=null==i?void 0:i.dceMnFs)||void 0===s||s.funcShowToast("Torch Not Supported")}}}else i=0};this._taskid4AutoTorch=setInterval(r,t),this.isTorchOn=void 0,r();let s=this.cameraView.getUIElement();s=s.shadowRoot||s,s.elTorchAuto&&(s.elTorchAuto.style.display=""),s.elTorchOn&&(s.elTorchOn.style.display="none"),s.elTorchOff&&(s.elTorchOff.style.display="none")}async setColorTemperature(t){if(He(this,is,"m",ys).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(He(this,is,"m",ys).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,n;if(He(this,is,"m",ys).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(n=null==e?void 0:e.dceMnFs)||void 0===n||n.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(He(this,is,"m",ys).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(He(this,is,"m",ys).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(He(this,is,"m",ys).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){He(this,ps,"f").minValue=t.min,He(this,ps,"f").maxValue=t.max}getAutoZoomRange(){return{min:He(this,ps,"f").minValue,max:He(this,ps,"f").maxValue}}async enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=ct.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==gt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&ri.EF_ENHANCED_FOCUS&&(He(this,ms,"f").enhancedFocus=!0),t&ri.EF_AUTO_ZOOM&&(He(this,ms,"f").autoZoom=!0),t&ri.EF_TAP_TO_FOCUS&&(He(this,ms,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&ri.EF_ENHANCED_FOCUS&&(He(this,ms,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),t&ri.EF_AUTO_ZOOM&&(He(this,ms,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),t&ri.EF_TAP_TO_FOCUS&&(He(this,ms,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),He(this,is,"m",Es).call(this)&&He(this,is,"m",ws).call(this)||He(this,_s,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!w(t)&&!I(t))throw TypeError("Invalid 'region'.");Xe(this,us,t?JSON.parse(JSON.stringify(t)):null),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(He(this,us,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");Xe(this,cs,t)}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||He(this,is,"m",ys).call(this))}startFetching(){if(He(this,is,"m",ys).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");He(this,fs,"f")||(Xe(this,fs,!0),He(this,is,"m",Cs).call(this))}stopFetching(){He(this,fs,"f")&&(Rs._onLog&&Rs._onLog("DCE: stop fetching loop: "+Date.now()),He(this,gs,"f")&&clearTimeout(He(this,gs,"f")),Xe(this,fs,!1))}fetchImage(){if(He(this,is,"m",ys).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let e;if(e=ki.convert(He(this,us,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height}),e.x>t.width||e.y>t.height)throw new Error("Invalid scan region.");e.x+e.width>t.width&&(e.width=t.width-e.x),e.y+e.height>t.height&&(e.height=t.height-e.y);const i={sx:e.x,sy:e.y,sWidth:e.width,sHeight:e.height,dWidth:e.width,dHeight:e.height},n=Math.max(i.dWidth,i.dHeight);if(this.canvasSizeLimit&&n>this.canvasSizeLimit){const t=this.canvasSizeLimit/n;i.dWidth>i.dHeight?(i.dWidth=this.canvasSizeLimit,i.dHeight=Math.round(i.dHeight*t)):(i.dWidth=Math.round(i.dWidth*t),i.dHeight=this.canvasSizeLimit)}const r=this.cameraManager.getFrameData({position:i,pixelFormat:this.getPixelFormat()===l.IPF_GRAYSCALED?Wn.GREY:Wn.RGBA});if(!r)return null;let s;s=r.pixelFormat===Wn.GREY?r.width:4*r.width;let a=!0;return 0===i.sx&&0===i.sy&&i.sWidth===t.width&&i.sHeight===t.height&&(a=!1),{bytes:r.data,width:r.width,height:r.height,stride:s,format:Is.get(r.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:wt.ITT_VIDEO_FRAME,isCropped:a,cropRegion:{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:r.width,currentHeight:r.height,timeSpent:r.timeSpent,timeStamp:r.timeStamp},toCanvas:He(this,hs,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,He(this,fs,"f")&&(He(this,gs,"f")&&clearTimeout(He(this,gs,"f")),Xe(this,gs,setTimeout((()=>{this.disposed||He(this,is,"m",Cs).call(this)}),t)))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){Xe(this,ds,t)}getPixelFormat(){return He(this,ds,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(He(this,is,"m",ys).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],n=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise(((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let a=ki.convert(He(this,us,"f"),r,s);a||(a={x:0,y:0,width:r,height:s});const o=He(this,ls,"f").call(this,n,r,s,a);t&&t(o)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=He(this,is,"m",Ss).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=He(this,is,"m",Ss).call(this,t);return{x:e.clientX,y:e.clientY}}convertToScanRegionCoordinates(t){if(!He(this,us,"f"))return JSON.parse(JSON.stringify(t));let e,i,n=He(this,us,"f").left||He(this,us,"f").x||0,r=He(this,us,"f").top||He(this,us,"f").y||0;if(!He(this,us,"f").isMeasuredInPercentage)return{x:t.x-n,y:t.y-r};if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!He(this,is,"m",ys).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(He(this,is,"m",ys).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(He(this,is,"m",ys).call(this)){const t=this.cameraView._innerComponent.getElement("content");e=t.width,i=t.height}else{const t=this.getVideoEl();e=t.videoWidth,i=t.videoHeight}return{x:t.x-Math.round(n*e/100),y:t.y-Math.round(r*i/100)}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),Xe(this,vs,!0)}}var Os,Ds,As,Ls,Ms,Fs,Ps,ks;ns=Rs,ss=new WeakMap,as=new WeakMap,os=new WeakMap,ls=new WeakMap,hs=new WeakMap,cs=new WeakMap,us=new WeakMap,ds=new WeakMap,fs=new WeakMap,gs=new WeakMap,ms=new WeakMap,ps=new WeakMap,_s=new WeakMap,vs=new WeakMap,is=new WeakSet,ys=function(){return"disabled"!==this.singleFrameMode},ws=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},Es=function(){for(let t in He(this,ms,"f"))if(1==He(this,ms,"f")[t])return!0;return!1},Cs=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!He(this,fs,"f"))return He(this,gs,"f")&&clearTimeout(He(this,gs,"f")),void Xe(this,gs,setTimeout((()=>{this.disposed||He(this,is,"m",t).call(this)}),this.fetchInterval));const e=()=>{var t;let e;Rs._onLog&&Rs._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=He(this,cs,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=He(this,cs,"f"))||void 0===t||t.onErrorReceived(_t.EC_IMAGE_READ_FAILED,i)}),0);console.warn(e)}e?(this.addImageToBuffer(e),Rs._onLog&&Rs._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),He(this,as,"f").fire("frameAddedToBuffer",null,{async:!1})):Rs._onLog&&Rs._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case a.BOPM_BLOCK:break;case a.BOPM_UPDATE:e()}else e();He(this,gs,"f")&&clearTimeout(He(this,gs,"f")),Xe(this,gs,setTimeout((()=>{this.disposed||He(this,is,"m",t).call(this)}),this.fetchInterval))},Ss=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!He(this,is,"m",ys).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(He(this,is,"m",ys).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,n=e.top,r=i+window.scrollX,s=n+window.scrollY,{width:a,height:o}=this.cameraView._innerComponent.getBoundingClientRect();if(a<=0||o<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let l,h,c;if(He(this,is,"m",ys).call(this)){const t=this.cameraView._innerComponent.getElement("content");l=t.width,h=t.height,c="contain"}else{const t=this.getVideoEl();l=t.videoWidth,h=t.videoHeight,c=this.cameraView.getVideoFit()}const u=a/o,d=l/h;let f,g,m,p,_=1;if("contain"===c)u{var e;if(!this.isUseMagnifier)return;if(He(this,Ls,"f")||Xe(this,Ls,new Ns),!He(this,Ls,"f").magnifierCanvas)return;document.body.contains(He(this,Ls,"f").magnifierCanvas)||(He(this,Ls,"f").magnifierCanvas.style.position="fixed",He(this,Ls,"f").magnifierCanvas.style.boxSizing="content-box",He(this,Ls,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(He(this,Ls,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void He(this,Fs,"f").call(this);const n=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!n)return;const r=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*r,a=[{image:i,width:i.width,height:i.height},{image:n,width:n.width,height:n.height}];He(this,Ls,"f").update(s,t.pointer,r,a);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(He(this,Ls,"f").magnifierCanvas.style.left="auto",He(this,Ls,"f").magnifierCanvas.style.top="0",He(this,Ls,"f").magnifierCanvas.style.right="0"):(He(this,Ls,"f").magnifierCanvas.style.left="0",He(this,Ls,"f").magnifierCanvas.style.top="0",He(this,Ls,"f").magnifierCanvas.style.right="auto")}He(this,Ls,"f").show()})),Fs.set(this,(()=>{He(this,Ls,"f")&&He(this,Ls,"f").hide()})),Ps.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await Wi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=document.createElement("dce-component"),e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let n=this._innerComponent.getElement("content");n||(n=document.createElement("canvas"),n.style.objectFit="contain",this._innerComponent.setElement("content",n)),n.width===e&&n.height===i||(n.width=e,n.height=i);const r=n.getContext("2d");r.clearRect(0,0,n.width,n.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),r.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&r.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(y(t)){Xe(this,As,t);const{width:e,height:i,bytes:n,format:r}=Object.assign({},t);let s;if(r===l.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const n=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new ai.Control({positionHandler:Ci,actionHandler:bi(i>0?i-1:n,Ti),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let n=t.x-i.pathOffset.x,r=t.y-i.pathOffset.y;const s=ai.util.transformPoint({x:n,y:r},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){He(this,Oi,"f")&&this.setLine(He(this,Oi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!C(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else Xe(this,Oi,JSON.parse(JSON.stringify(t)))}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return He(this,Oi,"f")?JSON.parse(JSON.stringify(He(this,Oi,"f"))):null}},QuadDrawingItem:Ai,RectDrawingItem:Ei,TextDrawingItem:Ri});function Gs(t){delete t.moduleId;const e=JSON.parse(t.jsonString).ResultInfo,i=t.fullCodeString;t.getFieldValue=t=>"fullcodestring"===t.toLowerCase()?i:Ws(e,t,"map"),t.getFieldRawValue=t=>Ws(e,t,"raw"),t.getFieldMappingStatus=t=>Ys(e,t),t.getFieldValidationStatus=t=>zs(e,t),delete t.fullCodeString}function Ws(t,e,i){for(let n of t){if(n.FieldName===e)return"raw"===i&&n.RawValue?n.RawValue:n.Value;if(n.ChildFields&&n.ChildFields.length>0){let t;for(let r of n.ChildFields)t=Ws(r,e,i);if(void 0!==t)return t}}}function Ys(t,e){for(let i of t){if(i.FieldName===e)return i.MappingStatus?Number(Vs[i.MappingStatus]):Vs.MS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=Ys(n,e);if(void 0!==t)return t}}}function zs(t,e){for(let i of t){if(i.FieldName===e&&i.ValidationStatus)return i.ValidationStatus?Number(js[i.ValidationStatus]):js.VS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=zs(n,e);if(void 0!==t)return t}}}function Hs(t){if(t.disposed)throw new Error('"CodeParser" instance has been disposed')}!function(t){t[t.MS_NONE=0]="MS_NONE",t[t.MS_SUCCEEDED=1]="MS_SUCCEEDED",t[t.MS_FAILED=2]="MS_FAILED"}(Vs||(Vs={})),function(t){t[t.VS_NONE=0]="VS_NONE",t[t.VS_SUCCEEDED=1]="VS_SUCCEEDED",t[t.VS_FAILED=2]="VS_FAILED"}(js||(js={}));const Xs=t=>t&&"object"==typeof t&&"function"==typeof t.then,Zs=(async()=>{})().constructor;let qs=class extends Zs{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Xs(t)?e=t:"function"==typeof t&&(e=new Zs(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(Xs(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Js="undefined"==typeof self,Ks="function"==typeof importScripts,$s=(()=>{if(!Ks){if(!Js&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})();gt.engineResourcePaths.dcp={version:"2.4.32",path:$s,isInternal:!0},ut.dcp={js:!0,wasm:!0,deps:["license"]},ct.dcp={handleParsedResultItem:Gs};const Qs="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&R(gt.engineResourcePaths.std.version,Qs)<0&&(gt.engineResourcePaths.std={version:Qs,path:(t=>{if(null==t&&(t="./"),Js||Ks);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})($s+`../../dynamsoft-capture-vision-std@${Qs}/dist/`),isInternal:!0});let ta=class{static getVersion(){const t=ht.dcp&&ht.dcp.wasm;return`2.4.32(Worker: ${ht.dcp&&ht.dcp.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadSpec(t,e){return await ft("dcp"),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success)return i();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},e&&!e.endsWith("/")&&(e+="/");const s=t instanceof Array?t:[t],a=O(gt.engineResourcePaths);et.postMessage({type:"dcp_appendResourceBuffer",id:r,body:{specificationPath:e||a.dcp+"specification/",specificationNames:s}})}))}};var ea=Object.freeze({__proto__:null,CodeParser:class t{constructor(){this._instanceID=void 0,this.bDestroyed=!1}static async createInstance(){if(!ct.license)throw Error("Module `license` is not existed.");await ct.license.dynamsoft(),await ft("dcp");const e=new t,i=new qs;let n=nt();return rt[n]=async t=>{if(t.success)e._instanceID=t.instanceID,i.resolve(e);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),i.reject(e)}},et.postMessage({type:"dcp_createInstance",id:n}),i}async dispose(){Hs(this);let t=nt();this.bDestroyed=!0,rt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},et.postMessage({type:"dcp_dispose",id:t,instanceID:this._instanceID})}get disposed(){return this.bDestroyed}async initSettings(t){return Hs(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?t.trimStart().startsWith("{")||(t=await x(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise(((e,i)=>{let n=nt();rt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Init Settings Failed.");return t.errorCode=n.errorCode,i(t)}return e(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},et.postMessage({type:"dcp_initSettings",id:n,instanceID:this._instanceID,body:{settings:t}})}))):console.error("Invalid settings.")}async resetSettings(){return Hs(this),await new Promise(((t,e)=>{let i=nt();rt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},et.postMessage({type:"dcp_resetSettings",id:i,instanceID:this._instanceID})}))}async parse(t,e=""){if(Hs(this),!t||!(t instanceof Array||t instanceof Uint8Array||"string"==typeof t))throw new Error("`parse` must pass in an Array or Uint8Array or string");return await new Promise(((i,n)=>{let r=nt();t instanceof Array&&(t=Uint8Array.from(t)),"string"==typeof t&&(t=Uint8Array.from(function(t){let e=[];for(let i=0;i{if(t.success){let e=JSON.parse(t.parseResponse);return e.errorCode?n(new Error(e.errorString)):(Gs(e),i(e))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},et.postMessage({type:"dcp_parse",id:r,instanceID:this._instanceID,body:{source:t,taskSettingName:e}})}))}},CodeParserModule:ta,get EnumMappingStatus(){return Vs},get EnumValidationStatus(){return js}});const ia="undefined"==typeof self,na="function"==typeof importScripts,ra=(()=>{if(!na){if(!ia&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),sa=t=>{if(null==t&&(t="./"),ia||na);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};gt.engineResourcePaths.dlr={version:"3.4.32",path:ra,isInternal:!0},null==gt.engineResourcePaths.dlrData&&(gt.engineResourcePaths.dlrData={version:"1.0.11",path:sa(ra+"../../dynamsoft-label-recognizer-data@1.0.11/dist/"),isInternal:!0}),ut.dlr={js:!0,wasm:!0,deps:["license","dip","dnn"]},ut.dnn={wasm:!0,deps:["dip"]};const aa="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&R(gt.engineResourcePaths.std.version,aa)<0&&(gt.engineResourcePaths.std={version:aa,path:sa(ra+`../../dynamsoft-capture-vision-std@${aa}/dist/`),isInternal:!0});const oa="2.4.31";(!gt.engineResourcePaths.dip||"string"!=typeof gt.engineResourcePaths.dip&&R(gt.engineResourcePaths.dip.version,oa)<0)&&(gt.engineResourcePaths.dip={version:oa,path:sa(ra+`../../dynamsoft-image-processing@${oa}/dist/`),isInternal:!0});const la="1.0.20";(!gt.engineResourcePaths.dnn||"string"!=typeof gt.engineResourcePaths.dnn&&R(gt.engineResourcePaths.dnn.version,la)<0)&&(gt.engineResourcePaths.dnn={version:la,path:sa(ra+`../../dynamsoft-capture-vision-dnn@${la}/dist/`),isInternal:!0});let ha=!1,ca=class{static getVersion(){const t=ht.dlr&&ht.dlr.wasm;return`3.4.32(Worker: ${ht.dlr&&ht.dlr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadRecognitionData(t,e){return await ft("dlr"),await new Promise(((i,n)=>{let r=nt();rt[r]=async t=>{if(t.success){const e=t.result;if(0!==e.errorCode){let t=new Error(e.errorString);return t.errorCode=e.errorCode,n(t)}return e.isModel||(ha=!0),i(e)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},e&&!e.endsWith("/")&&(e+="/");const s=O(gt.engineResourcePaths);e||"ConfusableChars"!==t||(e=s.dlr),et.postMessage({type:"dlr_loadData",id:r,body:{dataName:t,dataPath:e||s.dlrData}})}))}};ct.dlr={loadRecognitionData:ca.loadRecognitionData,get bLoadConfusableCharsData(){return ha}};const ua={filterVINResult:function(t){let e="";if(18===t.characterResults.length){let e=t.characterResults[9].location.points[0].x-t.characterResults[8].location.points[1].x;e<2&&(e=2);let i=t.characterResults[1].location.points[0].x-t.characterResults[0].location.points[1].x,n=t.characterResults[17].location.points[0].x-t.characterResults[16].location.points[1].x,r=2===e?3:e;i-e>=r&&n-e=r&&i-et.characterResults[17].characterHConfidence?t.characterResults.pop():t.characterResults.shift()}else if(19===t.characterResults.length){let e=t.characterResults[10].location.points[0].x-t.characterResults[9].location.points[1].x;e<2&&(e=2);let i,n,r,s=t.characterResults[1].location.points[0].x-t.characterResults[0].location.points[1].x,a=t.characterResults[18].location.points[0].x-t.characterResults[17].location.points[1].x,o=t.characterResults[2].location.points[0].x-t.characterResults[1].location.points[1].x,l=t.characterResults[17].location.points[0].x-t.characterResults[16].location.points[1].x,h=2===e?3:e;if("1"===t.characterResults[1].characterH||"1"===t.characterResults[2].characterH||"1"===t.characterResults[16].characterH||"1"===t.characterResults[17].characterH){for(let e=9;e=(i||h)&&l-e<(n||h))t.characterResults.splice(0,2);else if(l-e>=(n||h)&&o-e<(i||h))t.characterResults.splice(17,2);else if(s>e&&a>e)t.characterResults.pop(),t.characterResults.shift();else{let e=t.characterResults[0].characterHConfidence+t.characterResults[1].characterHConfidence,i=t.characterResults[17].characterHConfidence+t.characterResults[18].characterHConfidence,n=t.characterResults[0].characterHConfidence+t.characterResults[18].characterHConfidence,r=Math.min(e,i,n);r===e?t.characterResults.splice(0,2):r===i?t.characterResults.splice(17,2):r===n&&(t.characterResults.pop(),t.characterResults.shift())}}for(let i of t.characterResults)e+=i.characterH;return e},checkValidVIN:function(t){return!(!t||17!=t.length)&&(t=>{const e=new Map([["A",1],["B",2],["C",3],["D",4],["E",5],["F",6],["G",7],["H",8],["J",1],["K",2],["L",3],["M",4],["N",5],["P",7],["R",9],["S",2],["T",3],["U",4],["V",5],["W",6],["X",7],["Y",8],["Z",9],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9]]),i=[8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2];let n=0;for(let r=0;r{const n=new Map([["<",0],["0",0],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9],["A",10],["B",11],["C",12],["D",13],["E",14],["F",15],["G",16],["H",17],["I",18],["J",19],["K",20],["L",21],["M",22],["N",23],["O",24],["P",25],["Q",26],["R",27],["S",28],["T",29],["U",30],["V",31],["W",32],["X",33],["Y",34],["Z",35]]),r=[7,3,1];let s=0;for(let a=e,o=0;a<=i;a++){let e=n.get(t[a]);e&&(s+=e*r[o%3]),o++}return s%10},i=t.slice(0,10)+t.slice(13,20)+t.slice(21,43),n=e(t,0,8).toString(),r=e(t,13,18).toString(),s=e(t,21,26).toString(),a=e(t,28,41).toString(),o=e(i,0,i.length).toString();return n===t[9]&&r===t[19]&&s===t[27]&&a===t[42]&&o===t[43]},checkValidMRV:function(t){if(!t||44!=t.length&&36!=t.length)return!1;const e=(t,e,i)=>{const n=new Map([["<",0],["0",0],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9],["A",10],["B",11],["C",12],["D",13],["E",14],["F",15],["G",16],["H",17],["I",18],["J",19],["K",20],["L",21],["M",22],["N",23],["O",24],["P",25],["Q",26],["R",27],["S",28],["T",29],["U",30],["V",31],["W",32],["X",33],["Y",34],["Z",35]]),r=[7,3,1];let s=0;for(let a=e,o=0;a<=i;a++){let e=n.get(t[a]);e&&(s+=e*r[o%3]),o++}return s%10},i=e(t,0,8).toString(),n=e(t,13,18).toString(),r=e(t,21,26).toString();return i===t[9]&&n===t[19]&&r===t[27]},checkValidIDCard:function(t,e){if(!t||30!=t.length&&36!=t.length)return!1;const i=(t,e,i)=>{const n=new Map([["<",0],["0",0],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9],["A",10],["B",11],["C",12],["D",13],["E",14],["F",15],["G",16],["H",17],["I",18],["J",19],["K",20],["L",21],["M",22],["N",23],["O",24],["P",25],["Q",26],["R",27],["S",28],["T",29],["U",30],["V",31],["W",32],["X",33],["Y",34],["Z",35]]),r=[7,3,1];let s=0;for(let a=e,o=0;a<=i;a++){let e=n.get(t[a]);e&&(s+=e*r[o%3]),o++}return s%10};if(30===t.length){if(e&&t===e)return i(t,5,13).toString()===t[14];if(e&&t!==e){const n=`${e.substring(5,30)}${t.substring(0,7)}${t.substring(8,15)}${t.substring(18,29)}`;return i(n,0,n.length-1).toString()===t[29]}}else if(36===t.length){const e=i(t,0,8).toString(),n=i(t,13,18).toString(),r=i(t,21,26).toString(),s=`${t.substring(0,10)}${t.substring(13,20)}${t.substring(21,28)}`,a=i(s,0,s.length-1).toString();return e===t[9]&&n===t[19]&&r===t[27]&&a===t[35]}}};var da;!function(t){t[t.RTLS_LOCALIZED=0]="RTLS_LOCALIZED",t[t.RTLS_RECOGNITION_FAILED=1]="RTLS_RECOGNITION_FAILED",t[t.RTLS_RECOGNITION_SUCCEEDED=2]="RTLS_RECOGNITION_SUCCEEDED"}(da||(da={})),rt[-1]=async t=>{ca.onDataLoadProgressChanged&&ca.onDataLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})};var fa=Object.freeze({__proto__:null,get EnumRawTextLineStatus(){return da},LabelRecognizerModule:ca,utilsFuncs:ua});const ga=async t=>{let e;await new Promise(((i,n)=>{e=new Image,e.onload=()=>i(e),e.onerror=n,e.src=URL.createObjectURL(t)}));const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e.width,i.height=e.height,n.drawImage(e,0,0),{bytes:Uint8Array.from(n.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:10}};const ma="undefined"==typeof self,pa="function"==typeof importScripts,_a=(()=>{if(!pa){if(!ma&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),va=t=>{if(null==t&&(t="./"),ma||pa);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};gt.engineResourcePaths.utility={version:"1.4.32",path:_a,isInternal:!0},ut.utility={js:!0,wasm:!0};const ya="1.4.21";"string"!=typeof gt.engineResourcePaths.std&&R(gt.engineResourcePaths.std.version,ya)<0&&(gt.engineResourcePaths.std={version:ya,path:va(_a+`../../dynamsoft-capture-vision-std@${ya}/dist/`),isInternal:!0});const wa="2.4.31";(!gt.engineResourcePaths.dip||"string"!=typeof gt.engineResourcePaths.dip&&R(gt.engineResourcePaths.dip.version,wa)<0)&&(gt.engineResourcePaths.dip={version:wa,path:va(_a+`../../dynamsoft-image-processing@${wa}/dist/`),isInternal:!0});function Ea(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}var Ca,Sa,Ta,ba,Ia;function xa(t,e){let i=!0;for(let a=0;a1)return Math.sqrt((l-a)**2+(h-o)**2);{const t=r+u*(a-r),e=s+u*(o-s);return Math.sqrt((l-t)**2+(h-e)**2)}}function Da(t){const e=[];for(let i=0;i=0&&l<=1&&h>=0&&h<=1?{x:t.x+h*r,y:t.y+h*s}:null}function Ma(t){let e=0;for(let i=0;i0}function Pa(t,e){for(let i=0;i<4;i++)if(!Fa(t.points[i],t.points[(i+1)%4],e))return!1;return!0}"function"==typeof SuppressedError&&SuppressedError;function ka(t,e,i,n){const r=t.points,s=e.points;let a=8*i;a=Math.max(a,5);const o=Da(r)[3],l=Da(r)[1],h=Da(s)[3],c=Da(s)[1];let u,d=0;if(u=Math.max(Math.abs(Oa(o,e.points[0])),Math.abs(Oa(o,e.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Oa(l,e.points[1])),Math.abs(Oa(l,e.points[2]))),u>d&&(d=u),u=Math.max(Math.abs(Oa(h,t.points[0])),Math.abs(Oa(h,t.points[3]))),u>d&&(d=u),u=Math.max(Math.abs(Oa(c,t.points[1])),Math.abs(Oa(c,t.points[2]))),u>d&&(d=u),d>a)return!1;const f=Aa(Da(r)[0]),g=Aa(Da(r)[2]),m=Aa(Da(s)[0]),p=Aa(Da(s)[2]),_=Ra(f,p),v=Ra(m,g),y=_>v,w=Math.min(_,v),E=Ra(f,g),C=Ra(m,p);let S=12*i;return S=Math.max(S,5),S=Math.min(S,E),S=Math.min(S,C),!!(w{e.x+=t,e.y+=i})),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,n=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-n.area)>.4*i.area)return!1;let r=new Array(4).fill(0),s=new Array(4).fill(0),a=0,o=0;for(let t=0;t<4;++t)r[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,a+=r[t],s[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,o+=s[t];a/=4,o/=4;for(let t=0;t<4;++t){if(Math.abs(r[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1;if(Math.abs(s[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1}return e.x=a,e.y=o,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(Pa(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(Pa(this.location,e))return!0}else{for(let e=0;e<4;e++)if(Pa(t,this.location.points[e]))return!0;if(Pa(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const n=[this.location.points[0],this.location.points[3]],r=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?n:r;if(Math.abs(Oa(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const n=t.location.points[i],r=this.location.points[i];if(!(Math.abs(r.x+e.x-n.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const n=Object.assign({},t.location);for(let t=0;t<4;t++)n.points[t].x-=e.x,n.points[t].y-=e.y;if(!this.isLocationOverlap(n,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let n=0;n<4;n++)for(let r=0;r<4;r++){const s=La(t[n],t[(n+1)%4],e[r],e[(r+1)%4]);s&&i.push(s)}return t.forEach((t=>{xa(e,t)&&i.push(t)})),e.forEach((e=>{xa(t,e)&&i.push(e)})),Ma(function(t){if(t.length<=1)return t;t.sort(((t,e)=>t.x-e.x||t.y-e.y));const e=t.shift();return t.sort(((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x))),[e,...t]}(i))}([...this.location.points],n.points)>this.locationArea*t}return!0}}const Ba={BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096)},Va={barcode:2,text_line:4,detected_quad:8,normalized_image:16},ja=t=>Object.values(Va).includes(t)||Va.hasOwnProperty(t),Ua=(t,e)=>"string"==typeof t?e[Va[t]]:e[t],Ga=(t,e,i)=>{"string"==typeof t?e[Va[t]]=i:e[t]=i},Wa=(t,e,i)=>{const n=[8,16].includes(i);if(!n&&t.isResultCrossVerificationEnabled(i))for(let t=0;t{Ga(e,this.verificationEnabled,t)})),Ea(this,Sa,"f").forEach(((t,e)=>{Ga(e,this.duplicateFilterEnabled,t)})),Ea(this,Ta,"f").forEach(((t,e)=>{Ga(e,this.duplicateForgetTime,t)})),Ea(this,ba,"f").forEach(((t,e)=>{Ga(e,this.latestOverlappingEnabled,t)})),Ea(this,Ia,"f").forEach(((t,e)=>{Ga(e,this.maxOverlappingFrames,t)}))}enableResultCrossVerification(t,e){ja(t)&&Ea(this,Ca,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!ja(t)&&Ua(t,this.verificationEnabled)}enableResultDeduplication(t,e){ja(t)&&(e&&this.enableLatestOverlapping(t,!1),Ea(this,Sa,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!ja(t)&&Ua(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){ja(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),Ea(this,Ta,"f").set(t,e))}getDuplicateForgetTime(t){return ja(t)?Ua(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){ja(t)&&Ea(this,Ia,"f").set(t,e)}getMaxOverlappingFrames(t){return ja(t)?Ua(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){ja(t)&&(e&&this.enableResultDeduplication(t,!1),Ea(this,ba,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!ja(t)&&Ua(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[mt.CRIT_BARCODE,mt.CRIT_TEXT_LINE,mt.CRIT_DETECTED_QUAD,mt.CRIT_NORMALIZED_IMAGE];for(let i=0;i{if(1!==t.type){const e=(BigInt(t.format)&BigInt(Ba.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Ba.BF_GS1_DATABAR))!=BigInt(0);return new Na(l,e?1:2,e,t)}})).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(h).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t)).length;r>p&&(p=r,m=n,g.x=i.x,g.y=i.y)}}if(0===p){for(let e=0;e-1!=t)).length}let i=this.overlapSet.length<=3?p>=1:p>=2;if(!i&&s&&u>0){let t=0;for(let e=0;e=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach(((t,e)=>{if(1!==t.type){const i=Object.assign({},t),n=(BigInt(t.format)&BigInt(Ba.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Ba.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0)))}f.sort(((t,e)=>e-t)).forEach(((e,i)=>{t.items.splice(e,1)})),d.forEach((e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))}))}}onDecodedBarcodesReceived(t){this.latestOverlappingFilter(t),Wa(this,t.items,mt.CRIT_BARCODE)}onRecognizedTextLinesReceived(t){Wa(this,t.items,mt.CRIT_TEXT_LINE)}onDetectedQuadsReceived(t){Wa(this,t.items,mt.CRIT_DETECTED_QUAD)}onNormalizedImagesReceived(t){Wa(this,t.items,mt.CRIT_NORMALIZED_IMAGE)}}Ca=new WeakMap,Sa=new WeakMap,Ta=new WeakMap,ba=new WeakMap,Ia=new WeakMap;var za,Ha,Xa,Za=Object.freeze({__proto__:null,ImageManager:class{async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const n=M(t);return D(n,e,i)}async drawOnImage(t,e,i,n=4294901760,r=1,s){let a;if(t instanceof Blob)a=await ga(t);else if("string"==typeof t){let e=await x(t,"blob");a=await ga(e)}return await new Promise(((t,o)=>{let l=nt();rt[l]=async e=>{if(e.success)return s&&this.saveToFile(e.image,"test.png",s),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,o(t)}},et.postMessage({type:"utility_drawOnImage",id:l,body:{dsImage:a,drawingItem:e instanceof Array?e:[e],color:n,thickness:r,type:i}})}))}},MultiFrameResultCrossFilter:Ya,UtilityModule:class{static getVersion(){return`1.4.32(Worker: ${ht.utility&&ht.utility.worker||"Not Loaded"}, Wasm: ${ht.utility&&ht.utility.wasm||"Not Loaded"})`}}});t.EnumMRZScanMode=void 0,(za=t.EnumMRZScanMode||(t.EnumMRZScanMode={})).Passport="passport",za.TD1="td1",za.TD2="td2",za.PassportAndTD1="passportAndTd1",za.PassportAndTD2="passportAndTd2",za.TD1AndTD2="td1AndTd2",za.All="all",t.EnumMRZDocumentType=void 0,(Ha=t.EnumMRZDocumentType||(t.EnumMRZDocumentType={})).Passport="passport",Ha.TD1="td1",Ha.TD2="td2",t.EnumMRZScannerViews=void 0,(Xa=t.EnumMRZScannerViews||(t.EnumMRZScannerViews={})).Scanner="scanner",Xa.Result="scan-result";const qa={[t.EnumMRZScanMode.Passport]:"ReadPassport",[t.EnumMRZScanMode.TD1]:"ReadId-TD1",[t.EnumMRZScanMode.TD2]:"ReadId-TD2",[t.EnumMRZScanMode.PassportAndTD1]:"ReadPassportAndId-TD1",[t.EnumMRZScanMode.PassportAndTD2]:"ReadPassportAndId-TD2",[t.EnumMRZScanMode.TD1AndTD2]:"ReadId",[t.EnumMRZScanMode.All]:"ReadPassportAndId"};var Ja;function Ka(t){if("string"==typeof t){const e=document.querySelector(t);if(!e)throw new Error("Element not found");return e}return t instanceof HTMLElement?t:null}t.EnumResultStatus=void 0,(Ja=t.EnumResultStatus||(t.EnumResultStatus={}))[Ja.RS_SUCCESS=0]="RS_SUCCESS",Ja[Ja.RS_CANCELLED=1]="RS_CANCELLED",Ja[Ja.RS_FAILED=2]="RS_FAILED";function $a(t,e){if(!document.getElementById(t)){const i=document.createElement("style");i.id=t,i.textContent=e,document.head.appendChild(i)}}const Qa=t=>!t||0===Object.keys(t).length;function to(t){return t?t.charAt(0).toUpperCase()+t.slice(1):""}const eo={"4k":{width:3840,height:2160},"2k":{width:2560,height:1440},"1080p":{width:1920,height:1080},"720p":{width:1280,height:720},"480p":{width:640,height:480}};function io(t,e={}){const{message:i,spinnerSize:n=32}=e,r=document.createElement("div");r.className="dynamsoft-mrz-loading-screen";const s=document.createElement("div");s.className="dynamsoft-mrz-loading";const a=document.createElement("div");a.className="dynamsoft-mrz-loading-content";const o=`\n \n \n \n `;if(a.innerHTML=o,i){const t=document.createElement("div");t.className="dynamsoft-mrz-loading-message",t.textContent=i,a.appendChild(t)}return s.appendChild(a),r.appendChild(s),t.appendChild(r),{element:r,updateMessage:t=>{let e=s.querySelector(".dynamsoft-mrz-loading-message");null!==t?e?e.textContent=t:(e=document.createElement("div"),e.className="dynamsoft-mrz-loading-message",e.textContent=t,a.appendChild(e)):null==e||e.remove()},hide:()=>{r&&r.parentNode&&(r.classList.add("fade-out"),setTimeout((()=>{var t;null===(t=r.parentNode)||void 0===t||t.removeChild(r)}),200))}}}const no='\n .dynamsoft-mrz-loading-screen {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: #323234;\n z-index: 998;\n opacity: 1;\n transition: opacity 0.2s ease-out;\n }\n\n .dynamsoft-mrz-loading-screen.fade-out {\n opacity: 0;\n }\n\n .dynamsoft-mrz-loading {\n position: absolute;\n left: 50%;\n top: 50%;\n color: white;\n z-index: 999;\n transform: translate(-50%, -50%);\n }\n\n .dynamsoft-mrz-loading-content {\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 16px;\n }\n\n .dynamsoft-mrz-loading svg {\n animation: spin 1s linear infinite;\n }\n\n .dynamsoft-mrz-loading-message {\n color: white;\n font-family: "Verdana";\n font-size: 14px;\n text-align: center;\n max-width: 200px;\n line-height: 1.4;\n opacity: 0.9;\n }\n\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n';var ro;t.EnumMRZData=void 0,(ro=t.EnumMRZData||(t.EnumMRZData={})).InvalidFields="invalidFields",ro.DocumentType="documentType",ro.DocumentNumber="documentNumber",ro.MRZText="mrzText",ro.FirstName="firstName",ro.LastName="lastName",ro.Age="age",ro.Sex="sex",ro.IssuingState="issuingState",ro.IssuingStateRaw="issuingStateRaw",ro.Nationality="nationality",ro.NationalityRaw="nationalityRaw",ro.DateOfBirth="dateOfBirth",ro.DateOfExpiry="dateOfExpiry";const so={[t.EnumMRZData.InvalidFields]:"Invalid Fields",[t.EnumMRZData.DocumentType]:"Document Type",[t.EnumMRZData.DocumentNumber]:"Document Number",[t.EnumMRZData.MRZText]:"MRZ Text",[t.EnumMRZData.FirstName]:"Given Name(s)",[t.EnumMRZData.LastName]:"Surname",[t.EnumMRZData.Age]:"Age",[t.EnumMRZData.Sex]:"Sex",[t.EnumMRZData.IssuingState]:"Issuing State",[t.EnumMRZData.IssuingStateRaw]:"Issuing State (Raw Value)",[t.EnumMRZData.Nationality]:"Nationality",[t.EnumMRZData.NationalityRaw]:"Nationality State (Raw Value)",[t.EnumMRZData.DateOfBirth]:"Date Of Birth (YYYY-MM-DD)",[t.EnumMRZData.DateOfExpiry]:"Date Of Expiry (YYYY-MM-DD)"};function ao(t,e,i,n=!1){const r=parseInt(t,10);let s;if(n)s=r>=60?1900+r:2e3+r;else{s=r>(new Date).getFullYear()%100?1900+r:2e3+r}return{year:s,month:parseInt(e,10),day:parseInt(i,10)}}function oo(t){const e=t=>{var e;return 1===(null===(e=`${t}`)||void 0===e?void 0:e.length)?`0${t}`:t};return`${null==t?void 0:t.year}-${e(null==t?void 0:t.month)}${(null==t?void 0:t.day)&&`-${e(null==t?void 0:t.day)}`}`}function lo(t){return"D<<"===t?"D":t}function ho(e,i){const n=[],r=t=>i.getFieldValidationStatus(t)===js.VS_FAILED,s=i.codeType,a=function(e){switch(e){case"MRTD_TD1_ID":return t.EnumMRZDocumentType.TD1;case"MRTD_TD2_ID":case"MRTD_TD2_VISA":case"MRTD_TD2_FRENCH_ID":return t.EnumMRZDocumentType.TD2;case"MRTD_TD3_PASSPORT":case"MRTD_TD3_VISA":return t.EnumMRZDocumentType.Passport;default:throw new Error(`Unknown document type: ${e}`)}}(s),o=function(t){switch(t){case"MRTD_TD1_ID":return"ID (TD1)";case"MRTD_TD2_ID":return"ID (TD2)";case"MRTD_TD2_VISA":return"ID (VISA)";case"MRTD_TD2_FRENCH_ID":return"French ID (TD2)";case"MRTD_TD3_PASSPORT":return"Passport (TD3)";case"MRTD_TD3_VISA":return"Visa (TD3)";default:throw new Error(`Unknown document type: ${t}`)}}(s),l=a===t.EnumMRZDocumentType.Passport&&"MRTD_TD3_PASSPORT"===s?"passportNumber":"documentNumber",h=ao(i.getFieldValue("birthYear"),i.getFieldValue("birthMonth"),i.getFieldValue("birthDay")),c=ao(i.getFieldValue("expiryYear"),i.getFieldValue("expiryMonth"),i.getFieldValue("expiryDay"),!0);["birthYear","birthMonth","birthDay"].forEach((e=>{r(e)&&n.push(t.EnumMRZData.DateOfBirth)})),["expiryYear","expiryMonth","expiryDay"].forEach((e=>{r(e)&&n.push(t.EnumMRZData.DateOfExpiry)}));const u={[t.EnumMRZData.LastName]:i.getFieldValue("primaryIdentifier"),[t.EnumMRZData.FirstName]:i.getFieldValue("secondaryIdentifier"),[t.EnumMRZData.Nationality]:i.getFieldValue("nationality"),[t.EnumMRZData.NationalityRaw]:lo(i.getFieldRawValue("nationality")),[t.EnumMRZData.DocumentNumber]:i.getFieldValue(l)||i.getFieldValue("longDocumentNumber"),[t.EnumMRZData.IssuingState]:i.getFieldValue("issuingState"),[t.EnumMRZData.IssuingStateRaw]:lo(i.getFieldRawValue("issuingState")),[t.EnumMRZData.Sex]:to(i.getFieldValue("sex"))};Object.keys(u).forEach((e=>{let i=!1;switch(e){case t.EnumMRZData.FirstName:i=r("secondaryIdentifier");break;case t.EnumMRZData.LastName:i=r("primaryIdentifier");break;case t.EnumMRZData.DocumentNumber:i=r(l)||r("longDocumentNumber");break;default:i=r(e)}i&&n.push(e)}));const d=function(t){const e=new Date,i=e.getMonth()+1>t.month||e.getMonth()+1===t.month&&e.getDate()>=t.day;return e.getFullYear()-t.year-(i?0:1)}(h);d<1&&n.push(t.EnumMRZData.Age);return{[t.EnumMRZData.InvalidFields]:n,[t.EnumMRZData.FirstName]:u[t.EnumMRZData.FirstName],[t.EnumMRZData.LastName]:u[t.EnumMRZData.LastName],[t.EnumMRZData.Age]:d,[t.EnumMRZData.DateOfBirth]:h,[t.EnumMRZData.Sex]:u[t.EnumMRZData.Sex],[t.EnumMRZData.Nationality]:u[t.EnumMRZData.Nationality],[t.EnumMRZData.NationalityRaw]:u[t.EnumMRZData.NationalityRaw],[t.EnumMRZData.DocumentNumber]:u[t.EnumMRZData.DocumentNumber],[t.EnumMRZData.DateOfExpiry]:c,[t.EnumMRZData.IssuingState]:u[t.EnumMRZData.IssuingState],[t.EnumMRZData.IssuingStateRaw]:u[t.EnumMRZData.IssuingStateRaw],[t.EnumMRZData.DocumentType]:to(o),[t.EnumMRZData.MRZText]:e}}const co={[t.EnumMRZDocumentType.TD1]:{width:85.6,height:53.98},[t.EnumMRZDocumentType.TD2]:{width:105,height:74},[t.EnumMRZDocumentType.Passport]:{width:125,height:88}};class uo{showScannerLoadingOverlay(t){const e=Ka(this.config.container);this.loadingScreen=io(e,{message:t}),e.style.display="block",e.style.position="relative"}hideScannerLoadingOverlay(t=!1){this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,t&&(Ka(this.config.container).style.display="none"))}constructor(e,i){this.resources=e,this.config=i,this.isSoundFeedbackOn=!1,this.scanModeManager={[t.EnumMRZDocumentType.Passport]:!0,[t.EnumMRZDocumentType.TD1]:!0,[t.EnumMRZDocumentType.TD2]:!0},this.currentScanMode=t.EnumMRZScanMode.All,this.resizeTimer=null,this.capturedResultItems=[],this.originalImageData=null,this.initialized=!1,this.initializedDCE=!1,this.DCE_ELEMENTS={selectCameraBtn:null,uploadImageBtn:null,soundFeedbackBtn:null,closeScannerBtn:null,scanModeSelectContainer:null,passportModeOption:null,td1ModeOption:null,td2ModeOption:null,toast:null},this.loadingScreen=null,this.handleResize=()=>{this.toggleScanGuide(!1),this.resizeTimer&&window.clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout((()=>{this.toggleScanGuide(!0)}),500)}}async initialize(){if(!this.initialized){this.initializeScanModeManager(),this.currentScanMode=this.getScanMode(),$a("dynamsoft-mrz-loading-screen-style",no);try{const{cameraView:t,cameraEnhancer:e,cvRouter:i}=this.resources;if(t.setScanRegionMaskStyle({strokeStyle:"transparent",fillStyle:"transparent",lineWidth:0}),t.setVideoFit("cover"),i.setInput(e),await i.initSettings(this.config.templateFilePath),!0===this.config.enableMultiFrameCrossFilter){const t=new Ya;t.enableResultCrossVerification(mt.CRIT_TEXT_LINE,!0),t.enableResultDeduplication(mt.CRIT_TEXT_LINE,!0),await i.addResultFilter(t)}const n=new Pe;n.onCapturedResultReceived=t=>this.handleMRZResult(t),await i.addResultReceiver(n),this.toggleSoundFeedback(!1),!1===this.config.showScanGuide&&this.toggleScanGuide(!1),this.initialized=!0}catch(e){let i=(null==e?void 0:e.message)||e;console.error(i),alert(i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:"Dynamsoft MRZ Scanner initialize error"}};this.currentScanResolver(n)}}}initializeElements(){var t;const e=Ka(this.config.container),i=e.children[e.children.length-1];if(!(null==i?void 0:i.shadowRoot))throw new Error("Shadow root not found");if(this.DCE_ELEMENTS={selectCameraBtn:i.shadowRoot.querySelector(".dce-mn-select-camera-icon"),uploadImageBtn:i.shadowRoot.querySelector(".dce-mn-upload-image-icon"),soundFeedbackBtn:i.shadowRoot.querySelector(".dce-mn-sound-feedback"),closeScannerBtn:i.shadowRoot.querySelector(".dce-mn-close"),scanModeSelectContainer:i.shadowRoot.querySelector(".dce-mn-scan-mode-select"),passportModeOption:i.shadowRoot.querySelector(".scan-mode-option-passport"),td1ModeOption:i.shadowRoot.querySelector(".scan-mode-option-td1"),td2ModeOption:i.shadowRoot.querySelector(".scan-mode-option-td2"),toast:i.shadowRoot.querySelector(".dce-mn-toast")},this.setupScanModeSelector(),this.assignDCEClickEvents(),this.DCE_ELEMENTS.toast.style.display="none",!1===this.config.showUploadImage&&(this.DCE_ELEMENTS.uploadImageBtn.style.visibility="hidden"),!1===this.config.showSoundToggle&&(this.DCE_ELEMENTS.soundFeedbackBtn.style.visibility="hidden"),!1===(null===(t=this.config)||void 0===t?void 0:t.showPoweredByDynamsoft)){i.shadowRoot.querySelector(".dce-mn-msg-poweredby").style.display="none"}this.initializedDCE=!0}setupScanModeSelector(){if(!1!==this.config.showFormatSelector)switch(this.currentScanMode){case t.EnumMRZScanMode.PassportAndTD1:this.DCE_ELEMENTS.td2ModeOption.style.display="none";break;case t.EnumMRZScanMode.PassportAndTD2:this.DCE_ELEMENTS.td1ModeOption.style.display="none";break;case t.EnumMRZScanMode.TD1AndTD2:this.DCE_ELEMENTS.passportModeOption.style.display="none";break;case t.EnumMRZScanMode.All:break;default:this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}else this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}assignDCEClickEvents(){if(!Object.values(this.DCE_ELEMENTS).every(Boolean))throw new Error("Camera control elements not found");this.closeCamera=this.closeCamera.bind(this),this.DCE_ELEMENTS.uploadImageBtn.onclick=()=>this.uploadFile(),this.DCE_ELEMENTS.soundFeedbackBtn.onclick=()=>this.toggleSoundFeedback(),this.DCE_ELEMENTS.closeScannerBtn.onclick=()=>this.handleCloseBtn(),this.DCE_ELEMENTS.selectCameraBtn.onclick=t=>{t.stopPropagation(),this.toggleSelectCameraBox()},this.DCE_ELEMENTS.passportModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.passportModeOption.style.display&&await this.toggleScanDocType(t.EnumMRZDocumentType.Passport)},this.DCE_ELEMENTS.td1ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td1ModeOption.style.display&&await this.toggleScanDocType(t.EnumMRZDocumentType.TD1)},this.DCE_ELEMENTS.td2ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td2ModeOption.style.display&&await this.toggleScanDocType(t.EnumMRZDocumentType.TD2)}}handleCloseBtn(){this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:t.EnumResultStatus.RS_CANCELLED,message:"Cancelled"}})}attachOptionClickListeners(){const t=Ka(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))return;const i=e.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings");[...e.shadowRoot.querySelectorAll(".dce-mn-camera-option"),...e.shadowRoot.querySelectorAll(".dce-mn-resolution-option")].forEach((t=>{t.addEventListener("click",(async e=>{const n=t.getAttribute("data-davice-id"),r=t.getAttribute("data-height"),s=t.getAttribute("data-width");n?this.resources.cameraEnhancer.selectCamera(n).then((()=>{this.toggleScanGuide()})):r&&s&&this.resources.cameraEnhancer.setResolution({width:parseInt(s),height:parseInt(r)}).then((()=>{this.toggleScanGuide()})),"none"!==i.style.display&&this.toggleSelectCameraBox()}))}))}highlightCameraAndResolutionOption(){const t=Ka(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))return;const i=e.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings"),n=i.querySelectorAll(".dce-mn-camera-option"),r=i.querySelectorAll(".dce-mn-resolution-option"),s=this.resources.cameraEnhancer.getSelectedCamera(),a=this.resources.cameraEnhancer.getResolution();n.forEach((t=>{const e=t;e.getAttribute("data-davice-id")===(null==s?void 0:s.deviceId)?e.style.border="2px solid #fe814a":e.style.border="none"}));const o={"480p":"480","720p":"720","1080p":"1080","2k":"1440","4k":"2160"},l=function(t){const e=t.width*t.height,i=t.width/t.height;let n="480p",r=Number.MAX_VALUE;for(const[t,s]of Object.entries(eo)){const a=s.width*s.height,o=s.width/s.height,l=.7*Math.abs(a-e)+Math.abs(o-i)*a*.3;l{const e=t,i=e.getAttribute("data-height");e.style.border=i===o[l]?"2px solid #fe814a":"none"}))}toggleSelectCameraBox(){const t=Ka(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))return;const i=e.shadowRoot.querySelector(".dce-mn-resolution-box");this.highlightCameraAndResolutionOption(),this.attachOptionClickListeners(),i.click()}async relaunch(){}async uploadFile(){var e,i,n,r;const{cvRouter:s}=this.resources,a=document.createElement("input");a.type="file",a.accept=null!==(e=this.config.uploadAcceptedTypes)&&void 0!==e?e:"image/*",a.style.display="none",document.body.appendChild(a);try{this.showScannerLoadingOverlay("Processing file..."),await this.closeCamera(!1);const e=await new Promise(((t,e)=>{a.onchange=i=>{var n;const r=null===(n=i.target.files)||void 0===n?void 0:n[0];r?t(r):e(new Error("No file selected"))},a.addEventListener("cancel",(async()=>{this.hideScannerLoadingOverlay(!1),await this.openCamera(),await this.startCapturing(),this.toggleScanGuide()})),a.click()}));if(!e)return;let o;if(this.config.uploadFileConverter&&!e.type.startsWith("image/"))try{o=await this.config.uploadFileConverter(e)}catch(t){throw new Error(`Error converting file: ${t.message}`)}else{if(!e.type.startsWith("image/"))throw new Error("Unsupported file type. Please provide a converter function for this file type.");o=e}const l=this.config.utilizedTemplateNames[this.currentScanMode];if(!1!==this.config.showScanGuide){const t=await s.getSimplifiedSettings(l);t.roiMeasuredInPercentage=!0,t.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await s.updateSettings(l,t)}const h=await s.capture(o,l);this.capturedResultItems=h.items;const c=this.capturedResultItems.filter((t=>t.type===mt.CRIT_ORIGINAL_IMAGE));if(0===c.length)throw new Error("No image data found in the captured result");const u=c[0].imageData;u.toCanvas=()=>A(u),u.toBlob=async()=>await L("image/png",u),this.originalImageData=u;const d=null==h?void 0:h.textLineResultItems,f=null==h?void 0:h.parsedResultItems;let g={};if(null==d?void 0:d.length){const t=(null===(i=d[0])||void 0===i?void 0:i.text)||"";g=ho(t,f[0])}const m={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,data:g,imageData:!0,_imageData:this.originalImageData};null===(r=(n=this.resources).onResultUpdated)||void 0===r||r.call(n,m),this.currentScanResolver(m)}catch(e){let i=(null==e?void 0:e.message)||e;console.error(i),alert(i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:`Error processing file: ${i}`}};this.currentScanResolver(n)}finally{this.hideScannerLoadingOverlay(!0),document.body.removeChild(a)}}toggleSoundFeedback(t){this.isSoundFeedbackOn=void 0!==t?t:!this.isSoundFeedbackOn;const e=Ka(this.config.container),i=e.children[e.children.length-1];if(!(null==i?void 0:i.shadowRoot))return;const n=i.shadowRoot.querySelector(".dce-mn-sound-feedback"),r=n.querySelector(".dce-mn-sound-feedback-on");n.querySelector(".dce-mn-sound-feedback-off").style.display=this.isSoundFeedbackOn?"none":"block",r.style.display=this.isSoundFeedbackOn?"block":"none"}calculateScanRegion(t){const{cameraEnhancer:e,cameraView:i}=this.resources;if(!e||!e.isOpen())return;const n=i.getVisibleRegionOfVideo({inPixels:!0});if(!n)return;const r=i.getVideoElement(),s=r.videoWidth,a=r.videoHeight,o=co[t];let l;const h=n.height-80;if(n.width>n.height){l=.75*h/o.height;l*o.width>.9*n.width&&(l=.9*n.width/o.width)}else{l=.9*n.width/o.width;l*o.height>.75*h&&(l=.75*h/o.height)}const c=l*o.width,u=l*o.height,d=(n.width-c)/2,f=(h-u)/2,g=d,m=d+c,p=f,_=f+u,v=(n.x+g)/s*100,y=(n.x+m)/s*100,w=(n.y+p)/a*100,E=(n.y+_)/a*100,C={left:Math.round(v),right:Math.round(y),top:Math.round(w),bottom:Math.round(E),isMeasuredInPercentage:!0};null==i||i.setScanRegionMaskVisible(!0),e.setScanRegion(C)}toggleScanGuide(e){const i=Ka(this.config.container),n=i.children[i.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const r=n.shadowRoot.querySelector(".dce-scanguide-passport"),s=n.shadowRoot.querySelector(".dce-scanguide-td1"),a=n.shadowRoot.querySelector(".dce-scanguide-td2");if(!1===e||!1===this.config.showScanGuide)return r.style.display="none",s.style.display="none",void(a.style.display="none");switch(this.currentScanMode){case t.EnumMRZScanMode.All:case t.EnumMRZScanMode.Passport:case t.EnumMRZScanMode.PassportAndTD1:case t.EnumMRZScanMode.PassportAndTD2:r.style.display="block",s.style.display="none",a.style.display="none",this.calculateScanRegion(t.EnumMRZDocumentType.Passport);break;case t.EnumMRZScanMode.TD1:case t.EnumMRZScanMode.TD1AndTD2:r.style.display="none",s.style.display="block",a.style.display="none",this.calculateScanRegion(t.EnumMRZDocumentType.TD1);break;case t.EnumMRZScanMode.TD2:r.style.display="none",s.style.display="none",a.style.display="block",this.calculateScanRegion(t.EnumMRZDocumentType.TD2)}}async openCamera(){try{this.showScannerLoadingOverlay("Initializing camera...");const{cameraEnhancer:t,cameraView:e}=this.resources,i=Ka(this.config.container);if(i.style.display="block",t.isOpen())t.isPaused()&&await t.resume();else{const n=e.getUIElement();n.parentElement||i.append(n),await t.open()}await t.setResolution({width:2560,height:1440}),!this.initializedDCE&&t.isOpen()&&await this.initializeElements(),window.addEventListener("resize",this.handleResize);const n=i.children[i.children.length-1];if(!(null==n?void 0:n.shadowRoot))throw new Error("Shadow root not found");n.shadowRoot.querySelector(".dce-mn-torch-off").style.display="none",n.shadowRoot.querySelector(".dce-mn-torch-on").style.display="none"}catch(e){let i=(null==e?void 0:e.message)||e;console.error(i),alert(i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:"MRZ Scanner Open Camera Error"}};this.currentScanResolver(n)}finally{this.hideScannerLoadingOverlay()}}async closeCamera(t=!0){try{window.removeEventListener("resize",this.handleResize),this.resizeTimer&&(window.clearTimeout(this.resizeTimer),this.resizeTimer=null);const{cameraEnhancer:e,cameraView:i}=this.resources,n=Ka(this.config.container);n.style.display=t?"none":"block",(null==i?void 0:i.getUIElement().parentElement)&&n.removeChild(i.getUIElement()),e.close(),this.stopCapturing()}catch(t){let e=(null==t?void 0:t.message)||t;console.error(`Close Camera error: ${e}`)}}pauseCamera(){const{cameraEnhancer:t}=this.resources;t.pause()}stopCapturing(){const{cameraView:t,cvRouter:e}=this.resources;e.stopCapturing(),t.clearAllInnerDrawingItems()}async handleMRZResult(e){var i;if(this.capturedResultItems=e.items,!(e.items.length<=1))try{const{onResultUpdated:n}=this.resources,r=e.items.filter((t=>t.type===mt.CRIT_ORIGINAL_IMAGE))[0].imageData;r.toCanvas=()=>A(r),r.toBlob=async()=>await L("image/png",r),this.originalImageData=r;const s=null==e?void 0:e.textLineResultItems,a=null==e?void 0:e.parsedResultItems;if(s){this.isSoundFeedbackOn&&bs.beep();const e=(null===(i=null==s?void 0:s[0])||void 0===i?void 0:i.text)||"",r=ho(e,a[0]);this.closeCamera();const o={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,data:r,imageData:!0,_imageData:this.originalImageData};null==n||n(o),this.currentScanResolver(o)}}catch(e){let i=(null==e?void 0:e.message)||e;console.error(i),alert(i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:"Error capturing image"}};this.currentScanResolver(n)}}initializeScanModeManager(){const{mrzFormatType:e}=this.config;if(this.scanModeManager={[t.EnumMRZDocumentType.Passport]:!0,[t.EnumMRZDocumentType.TD1]:!0,[t.EnumMRZDocumentType.TD2]:!0},!e||Array.isArray(e)&&0===e.length)return;Object.keys(this.scanModeManager).forEach((t=>{this.scanModeManager[t]=!1}));(Array.isArray(e)?e:[e]).forEach((t=>{this.scanModeManager[t]=!0}))}getScanMode(){const e=Object.entries(this.scanModeManager).filter((([t,e])=>e)).map((([t])=>t)).sort().join(",");return{[t.EnumMRZDocumentType.Passport]:t.EnumMRZScanMode.Passport,[t.EnumMRZDocumentType.TD1]:t.EnumMRZScanMode.TD1,[t.EnumMRZDocumentType.TD2]:t.EnumMRZScanMode.TD2,[`${t.EnumMRZDocumentType.Passport},${t.EnumMRZDocumentType.TD1}`]:t.EnumMRZScanMode.PassportAndTD1,[`${t.EnumMRZDocumentType.Passport},${t.EnumMRZDocumentType.TD2}`]:t.EnumMRZScanMode.PassportAndTD2,[`${t.EnumMRZDocumentType.TD1},${t.EnumMRZDocumentType.TD2}`]:t.EnumMRZScanMode.TD1AndTD2,[`${t.EnumMRZDocumentType.Passport},${t.EnumMRZDocumentType.TD1},${t.EnumMRZDocumentType.TD2}`]:t.EnumMRZScanMode.All,"":t.EnumMRZScanMode.All}[e]}DCEShowToast(t,e=3e3){this.DCE_ELEMENTS.toast&&(this.DCE_ELEMENTS.toast.textContent=t,this.DCE_ELEMENTS.toast.style.display="",setTimeout((()=>{this.DCE_ELEMENTS.toast.style.display="none"}),e))}async startCapturing(){const{cvRouter:e,cameraEnhancer:i}=this.resources,n=this.config.utilizedTemplateNames[this.currentScanMode];try{if(!1!==this.config.showScanGuide){const t=await e.getSimplifiedSettings(n);t.roiMeasuredInPercentage=!0,t.roi.points=[{x:0,y:50},{x:100,y:50},{x:100,y:100},{x:0,y:100}],await e.updateSettings(n,t)}await e.startCapturing(n),i.setPixelFormat(l.IPF_ABGR_8888)}catch(e){let i=(null==e?void 0:e.message)||e;console.error("Failed to start capturing:",i),this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:t.EnumResultStatus.RS_FAILED,message:"Failed to start capturing"}})}}async toggleScanDocType(e){try{if(this.scanModeManager[e]&&0===Object.entries(this.scanModeManager).filter((([t,i])=>i&&t!==e)).length)return console.warn("MRZ Scanner - At least one mode must be enabled"),void this.DCEShowToast("At least one mode must be enabled");this.scanModeManager[e]=!this.scanModeManager[e],this.currentScanMode=this.getScanMode(),this.stopCapturing(),await this.startCapturing(),this.toggleScanGuide(),this.DCE_ELEMENTS.td1ModeOption.classList.toggle("selected",this.scanModeManager[t.EnumMRZDocumentType.TD1]),this.DCE_ELEMENTS.td2ModeOption.classList.toggle("selected",this.scanModeManager[t.EnumMRZDocumentType.TD2]),this.DCE_ELEMENTS.passportModeOption.classList.toggle("selected",this.scanModeManager[t.EnumMRZDocumentType.Passport])}catch(e){let i=(null==e?void 0:e.message)||e;console.error("MRZ Scanner switch scan mode error: ",i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:"MRZ Scanner switch scan mode error"}};this.currentScanResolver(n)}}async launch(){try{await this.initialize();const{cvRouter:t,cameraEnhancer:e}=this.resources;return new Promise((async t=>{this.currentScanResolver=t,await this.openCamera(),!this.initializedDCE&&e.isOpen()&&await this.initializeElements(),await this.startCapturing(),this.toggleScanGuide()}))}catch(e){let i=(null==e?void 0:e.message)||e;console.error("MRZ Scanner launch error: ",i),this.closeCamera();const n={status:{code:t.EnumResultStatus.RS_FAILED,message:"MRZ Scanner launch error"}};this.currentScanResolver(n)}}}const fo={rescan:'\n\n\n \n\n\n\n\n\n\n\n',complete:'\n\n\n\n \n\n\n\n\n\n\n\n',failed:'\n \n \n \n\n',info:'\n\n \n \n \n\n'};class go{constructor(t,e,i){this.resources=t,this.config=e,this.scannerView=i,this.editedFields={}}async launch(){try{return Ka(this.config.container).textContent="",await this.initialize(),Ka(this.config.container).style.display="flex",new Promise((t=>{this.currentScanResultViewResolver=t}))}catch(t){let e=(null==t?void 0:t.message)||t;throw console.error(e),e}}async handleRescan(){var e;try{if(!this.scannerView)return void console.error("Scanner View not initialized");this.hideView();const i=await this.scannerView.launch();if((null===(e=null==i?void 0:i.status)||void 0===e?void 0:e.code)===t.EnumResultStatus.RS_FAILED)return void(this.currentScanResultViewResolver&&this.currentScanResultViewResolver(i));this.resources.onResultUpdated&&((null==i?void 0:i.status.code)===t.EnumResultStatus.RS_CANCELLED?this.resources.onResultUpdated(this.resources.result):(null==i?void 0:i.status.code)===t.EnumResultStatus.RS_SUCCESS&&this.resources.onResultUpdated(i)),this.dispose(!0),await this.initialize(),Ka(this.config.container).style.display="flex"}catch(e){throw console.error("Error in rescan handler:",e),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:t.EnumResultStatus.RS_FAILED,message:(null==e?void 0:e.message)||e}}),e}}async handleDone(){var e,i;try{(null===(e=this.resources.result)||void 0===e?void 0:e.data)&&!Qa(this.editedFields)&&(this.resources.result.data=Object.assign(Object.assign({},this.resources.result.data),this.editedFields),this.resources.onResultUpdated&&this.resources.onResultUpdated(this.resources.result)),(null===(i=this.config)||void 0===i?void 0:i.onDone)&&await this.config.onDone(this.resources.result),this.currentScanResultViewResolver&&this.resources.result&&this.currentScanResultViewResolver(this.resources.result),this.hideView(),this.dispose()}catch(e){throw console.error("Error in done handler:",e),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:t.EnumResultStatus.RS_FAILED,message:(null==e?void 0:e.message)||e}}),e}}createControls(){var t,e,i,n,r,s,a,o;const{toolbarButtonsConfig:l}=this.config;return function(t){$a("dynamsoft-mrz-controls-style","\n .dynamsoft-mrz-controls {\n display: flex;\n height: 6rem;\n background-color: #323234;\n align-items: center;\n font-size: 12px;\n font-family: Verdana;\n color: white;\n width: 100%;\n }\n\n .dynamsoft-mrz-control-btn {\n background-color: #323234;\n color: white;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n height: 100%;\n width: 100%;\n gap: 0.5rem;\n text-align: center;\n user-select: none;\n }\n\n .dynamsoft-mrz-control-btn.hide {\n display: none;\n }\n\n .dynamsoft-mrz-control-btn.disabled {\n opacity: 0.4;\n pointer-events: none;\n cursor: default;\n }\n\n .dynamsoft-mrz-control-icon-wrapper {\n flex: 0.75;\n display: flex;\n align-items: flex-end;\n justify-content: center;\n min-height: 40px;\n }\n\n .dynamsoft-mrz-control-icon img,\n .dynamsoft-mrz-control-icon svg {\n width: 32px;\n height: 32px;\n fill: #fe8e14;\n }\n\n .dynamsoft-mrz-control-text {\n flex: 0.5;\n display: flex;\n align-items: flex-start;\n justify-content: center;\n padding-bottom: 0.5rem;\n }\n\n \n @media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-controls {\n flex-direction: column;\n height: 100%;\n width: 5rem;\n }\n\n .dynamsoft-mrz-control-text {\n padding: 0 0.5rem 0.5rem;\n }\n }\n");const e=document.createElement("div");return e.className="dynamsoft-mrz-controls",t.forEach((t=>{const i=document.createElement("div");i.className=`dynamsoft-mrz-control-btn ${null==t?void 0:t.className}`;const n=document.createElement("div");if(n.className="dynamsoft-mrz-control-icon-wrapper",(r=t.icon).trim().startsWith(""))n.innerHTML=t.icon;else{const e=document.createElement("img");e.src=t.icon,e.alt=t.label,e.width=24,e.height=24,n.appendChild(e)}var r;const s=document.createElement("div");s.className="dynamsoft-mrz-control-text",s.textContent=t.label,t.isDisabled&&i.classList.add("disabled"),t.isHidden&&i.classList.add("hide"),i.appendChild(n),i.appendChild(s),t.onClick&&!t.isDisabled&&i.addEventListener("click",t.onClick),e.appendChild(i)})),e}([{id:"dynamsoft-mrz-scanResult-rescan",icon:(null===(t=null==l?void 0:l.rescan)||void 0===t?void 0:t.icon)||fo.rescan,label:(null===(e=null==l?void 0:l.rescan)||void 0===e?void 0:e.label)||"Re-scan",onClick:()=>this.handleRescan(),className:`${(null===(i=null==l?void 0:l.rescan)||void 0===i?void 0:i.className)||""}`,isHidden:(null===(n=null==l?void 0:l.rescan)||void 0===n?void 0:n.isHidden)||!1,isDisabled:!this.scannerView},{id:"dynamsoft-mrz-scanResult-done",icon:(null===(r=null==l?void 0:l.done)||void 0===r?void 0:r.icon)||fo.complete,label:(null===(s=null==l?void 0:l.done)||void 0===s?void 0:s.label)||"Done",className:`${(null===(a=null==l?void 0:l.done)||void 0===a?void 0:a.className)||""}`,isHidden:(null===(o=null==l?void 0:l.done)||void 0===o?void 0:o.isHidden)||!1,onClick:()=>this.handleDone()}])}handleFieldEdit(e,i){if(e===t.EnumMRZData.DateOfBirth||e===t.EnumMRZData.DateOfExpiry)try{const[t,n,r]=i.split(/[\/\-\.]/);r&&n&&t&&(this.editedFields[e]={day:parseInt(r,10),month:parseInt(n,10),year:parseInt(t,10)})}catch(t){console.error("Error parsing date",t)}else this.editedFields[e]=i}createMRZDataDisplay(){var e;const i=(null===(e=this.resources.result)||void 0===e?void 0:e.data)||{},n=!!this.config.allowResultEditing,r=i.invalidFields||[],s=document.createElement("div");if(s.className="dynamsoft-mrz-data-container",Qa(i)){const t=document.createElement("div");return t.className="dynamsoft-mrz-data-row empty",t.innerText="No MRZ detected. Please try again.",s.appendChild(t),s}if(r.length>0){const t=document.createElement("div");t.className="dynamsoft-mrz-error-notification",t.innerHTML=`\n
${fo.failed}
\n
\n ${n?"Some fields require correction. Please review highlighted fields.":"Some fields contain invalid information. Please rescan the document."}\n
\n `,s.appendChild(t)}else if(0===r.length&&n){const t=document.createElement("div");t.className="dynamsoft-mrz-info-notification",t.innerHTML=`\n
${fo.info}
\n
\n Please review all fields to ensure the information is correct.\n
\n `,s.appendChild(t)}return Object.entries(i).forEach((([e,i])=>{var a;if(e===t.EnumMRZData.InvalidFields||!i)return;if(e===t.EnumMRZData.MRZText&&!1===(null===(a=this.config)||void 0===a?void 0:a.showMRZText))return;const o=document.createElement("div");o.className="dynamsoft-mrz-data-row";const l=r.includes(e);l&&o.classList.add("invalid-field");const h=[t.EnumMRZData.MRZText,t.EnumMRZData.DocumentType,t.EnumMRZData.IssuingStateRaw,t.EnumMRZData.NationalityRaw],c=document.createElement("span");if(c.className="dynamsoft-mrz-data-label",c.innerText=so[e]||e,l){const t=document.createElement("span");if(t.className="dynamsoft-mrz-error-icon",t.innerHTML=fo.failed,c.appendChild(t),n){const t=document.createElement("span");t.className="dynamsoft-mrz-error-hint",t.textContent="Please correct this field",c.appendChild(t)}}const u=document.createElement("div");if(u.className="dynamsoft-mrz-data-value",n&&!h.includes(e)){const n=document.createElement("input");n.className="dynamsoft-mrz-data-input",l&&n.classList.add("invalid"),e===t.EnumMRZData.DateOfBirth||e===t.EnumMRZData.DateOfExpiry?(n.value=oo(i),n.setAttribute("placeholder","YYYY-MM-DD")):n.value=i,n.addEventListener("input",(t=>{if(this.handleFieldEdit(e,t.target.value),l){n.classList.remove("invalid"),o.classList.remove("invalid-field"),this.editedFields.invalidFields||(this.editedFields.invalidFields=[...r]);const t=this.editedFields.invalidFields.indexOf(e);t>-1&&this.editedFields.invalidFields.splice(t,1)}})),u.appendChild(n)}else e===t.EnumMRZData.MRZText?(u.classList.add("code"),u.innerText=i):e===t.EnumMRZData.DateOfBirth||e===t.EnumMRZData.DateOfExpiry?u.innerText=oo(i):u.innerText=i,l&&u.classList.add("invalid-value");o.appendChild(c),o.appendChild(u),s.appendChild(o)})),s}async initialize(){try{if(!this.resources.result)throw Error("Captured image is missing. Please capture an image first!");if(!this.config.container)throw new Error("Please create a Scan Result View Container element");$a("dynamsoft-mrz-result-view-style",mo);const t=document.createElement("div");if(t.className="dynamsoft-mrz-result-view-container",!1!==this.config.showOriginalImage){const e=this.resources.result.originalImageResult,i=document.createElement("div");let n;i.className="dynamsoft-mrz-result-view-image-container",(null==e?void 0:e.toCanvas)&&(n=null==e?void 0:e.toCanvas()),Object.assign(n.style,{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}),i.appendChild(n),t.appendChild(i)}const e=this.createMRZDataDisplay();t.appendChild(e);const i=this.createControls();t.appendChild(i),Ka(this.config.container).appendChild(t)}catch(t){let e=(null==t?void 0:t.message)||t;console.error(e),alert(e)}}hideView(){Ka(this.config.container).style.display="none"}dispose(t=!1){Ka(this.config.container).textContent="",t||(this.currentScanResultViewResolver=void 0)}}const mo="\n .dynamsoft-mrz-result-view-container {\n display: flex;\n width: 100%;\n height: 100%;\n background-color:#575757;\n font-size: 12px;\n flex-direction: column;\n align-items: center;\n }\n\n .dynamsoft-mrz-result-view-image-container {\n width: 100%;\n height: 200px;\n display: flex;\n justify-content: center;\n align-items: center;\n background-color: #323234;\n }\n\n \n.dynamsoft-mrz-data-container {\n font-size: 16px;\n font-family: Verdana;\n color: white;\n overflow: auto;\n width: 100%;\n height: 100%;\n min-height: 0;\n margin: 1rem 0;\n}\n\n.dynamsoft-mrz-data-row {\n padding: 0.5rem 2rem;\n display: flex;\n flex-direction: column;\n gap: 0.5rem;\n transition: background-color 0.3s ease;\n}\n\n.dynamsoft-mrz-data-row.invalid-field {\n background-color: rgba(231, 76, 60, 0.1);\n border-left: 3px solid #e74c3c;\n padding-left: calc(2rem - 3px);\n}\n\n.dynamsoft-mrz-data-label {\n color: #aaa;\n display: flex;\n gap: 0.5rem;\n align-items: end;\n flex-wrap: wrap;\n}\n\n.dynamsoft-mrz-error-notification,\n.dynamsoft-mrz-info-notification {\n color: white;\n padding: 1rem;\n margin: 0.5rem 2rem;\n border-radius: 4px;\n display: flex;\n align-items: center;\n gap: 1rem;\n text-align: start;\n}\n\n.dynamsoft-mrz-error-notification {\n background-color: rgba(231, 76, 60, 0.2);\n}\n\n.dynamsoft-mrz-info-notification {\n background-color: rgba(196, 231, 60, 0.2);\n}\n\n.dynamsoft-mrz-edit-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #aaa;\n}\n\n.dynamsoft-mrz-error-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-info-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: white;\n}\n\n.dynamsoft-mrz-info-message,\n.dynamsoft-mrz-error-message {\n flex: 1;\n}\n\n.dynamsoft-mrz-error-hint {\n font-size: 0.8rem;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-value {\n word-wrap: break-word;\n text-align: start;\n}\n\n.dynamsoft-mrz-data-value.code {\n font-family: monospace;\n}\n\n.dynamsoft-mrz-data-value.invalid-value {\n color: #e74c3c;\n text-decoration: wavy underline #e74c3c;\n text-decoration-skip-ink: none;\n}\n\n.dynamsoft-mrz-data-input {\n width: 100%;\n padding: 5px;\n background-color: rgba(255, 255, 255, 0.1);\n border: 1px solid rgba(255, 255, 255, 0.3);\n color: white;\n border-radius: 4px;\n font-size: 14px;\n transition: all 0.3s ease;\n}\n\n.dynamsoft-mrz-data-input.invalid {\n background-color: rgba(231, 76, 60, 0.1);\n border-color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-input:focus {\n background-color: rgba(255, 255, 255, 0.2);\n border-color: #fe8e14;\n outline: none;\n}\n\n@media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-result-view-container {\n flex-direction: row;\n }\n\n .dynamsoft-mrz-result-view-image-container{\n flex: 1;\n height: 100%;\n }\n\n .dynamsoft-mrz-data-container{\n flex: 1;\n }\n\n .dynamsoft-mrz-data-row:first-of-type {\n padding-top: 2rem;\n }\n\n .dynamsoft-mrz-data-row:last-of-type {\n padding-bottom: 2rem;\n }\n\n .dynamsoft-mrz-data-row.empty {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n padding-top: 0;\n padding-bottom: 0;\n }\n}\n",po={rootDirectory:"https://cdn.jsdelivr.net/npm/"};class _o{showLoadingOverlay(t){var e,i;const n=Ka(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)||Ka(null===(i=this.config.resultViewConfig)||void 0===i?void 0:i.container);this.loadingScreen=io(n,{message:t}),n.style.display="block",n.style.position="relative"}hideLoadingOverlay(t=!1){var e,i,n;const r=Ka(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)||Ka(null===(i=this.config.resultViewConfig)||void 0===i?void 0:i.container);this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,r.style.display="none",t&&(null===(n=this.config)||void 0===n?void 0:n.container)&&(Ka(this.config.container).style.display="none"))}constructor(t){this.config=t,this.resources={},this.isInitialized=!1,this.isCapturing=!1,this.loadingScreen=null}async initialize(){if(this.isInitialized)return{resources:this.resources,components:{scannerView:this.scannerView,resultView:this.resultView}};try{if(!this.initializeMRZScannerConfig())return console.error("Failed to initialize mrz scanner config"),{resources:this.resources,components:{}};$a("dynamsoft-mrz-loading-screen-style",no),this.showLoadingOverlay("Loading...");if(!await this.initializeDCVResources())return this.hideLoadingOverlay(!0),console.error("Failed to initialize DCV resources"),{resources:this.resources,components:{}};this.resources.onResultUpdated=t=>{this.resources.result=t};const t={};return this.config.scannerViewConfig&&(this.scannerView=new uo(this.resources,this.config.scannerViewConfig),t.scannerView=this.scannerView,await this.scannerView.initialize()),this.config.resultViewConfig&&(this.resultView=new go(this.resources,this.config.resultViewConfig,this.scannerView),t.resultView=this.resultView),this.isInitialized=!0,{resources:this.resources,components:t}}catch(t){this.isInitialized=!1;const e=`Initialization Failed: ${(null==t?void 0:t.message)||t}`;return console.error(e),{resources:this.resources,components:{}}}finally{this.hideLoadingOverlay(!0)}}async initializeDCVResources(){var t,e,i;try{return gt.engineResourcePaths=Qa(null===(t=this.config)||void 0===t?void 0:t.engineResourcePaths)?po:this.config.engineResourcePaths,Zt._onAuthMessage=t=>t.replace("(https://www.dynamsoft.com/customer/license/trialLicense?product=unknown&deploymenttype=unknown)","(https://www.dynamsoft.com/customer/license/trialLicense?product=mrz&deploymenttype=web)"),await Zt.initLicense((null===(e=this.config)||void 0===e?void 0:e.license)||"",{executeNow:!0}),gt.loadWasm(["DLR","DCP"]),ta.loadSpec("MRTD_TD3_PASSPORT"),ta.loadSpec("MRTD_TD1_ID"),ta.loadSpec("MRTD_TD2_ID"),ca.loadRecognitionData("MRZ"),this.resources.cameraView=await An.createInstance(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.cameraEnhancerUIPath),this.resources.cameraEnhancer=await Rs.createInstance(this.resources.cameraView),this.resources.cvRouter=await Ae.createInstance(),!0}catch(t){let e=(null==t?void 0:t.message)||t;if(null==e?void 0:e.toLowerCase().includes("license")){const t="The MRZ Scanner license is invalid or has expired. Please contact the site administrator to resolve this issue.";alert(t),console.error(t)}else{const t=`Resource Initialization Failed: ${e}`;alert(t),console.error(t)}return!1}}shouldCreateDefaultContainer(){var t,e;const i=!this.config.container,n=!((null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)||(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container));return i&&n}createDefaultMRZScannerContainer(){const t=document.createElement("div");return t.className="mrz-scanner-main-container",Object.assign(t.style,{height:"100dvh",width:"100%",position:"absolute",left:"0",top:"0",zIndex:"999"}),document.body.append(t),t}checkForTemporaryLicense(t){return!(null==t?void 0:t.length)||(null==t?void 0:t.startsWith("A"))||(null==t?void 0:t.startsWith("L"))||(null==t?void 0:t.startsWith("P"))||(null==t?void 0:t.startsWith("Y"))?"DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9":t}validateViewConfigs(){var t,e,i,n,r,s,a,o;if(!this.config.container){if((null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)&&this.config.showResultView&&!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container)){const t="MRZResultView container is required when showResultView is true";return alert(t),console.error(t),!1}if(!(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.container)&&(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container)&&!this.resources.result){const t="Result is needed to create MRZResultView without a scanner view";return alert(t),console.error(t),!1}}try{if(this.config.container&&!Ka(this.config.container)){const t="Invalid main container reference";return alert(t),console.error(t),!1}if((null===(r=this.config.scannerViewConfig)||void 0===r?void 0:r.container)&&!Ka(null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.container)){const t="Invalid scanner view container reference";return alert(t),console.error(t),!1}if((null===(a=this.config.resultViewConfig)||void 0===a?void 0:a.container)&&!Ka(null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)){const t="Invalid result view container reference";return alert(t),console.error(t),!1}}catch(t){const e=`Error accessing container references: ${t.message}`;return alert(e),console.error(e),!1}return!0}showResultView(){var t,e;return!1!==this.config.showResultView&&(this.config.container?!(void 0!==this.config.showResultView||!(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container)&&!this.config.container)||!!this.config.showResultView:this.config.showResultView&&!!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container))}initializeMRZScannerConfig(){var e,i,n,r,s,a,o;this.config=null!==(e=this.config)&&void 0!==e?e:{};if(!this.validateViewConfigs())return!1;this.shouldCreateDefaultContainer()?this.config.container=this.createDefaultMRZScannerContainer():this.config.container&&(this.config.container=Ka(this.config.container));const l=this.config.container?this.createViewContainers(Ka(this.config.container)):{},h={license:this.checkForTemporaryLicense(this.config.license),utilizedTemplateNames:Object.fromEntries(Object.values(t.EnumMRZScanMode).map((t=>{var e;return[t,(null===(e=this.config.utilizedTemplateNames)||void 0===e?void 0:e[t])||qa[t]]}))),templateFilePath:(null===(i=this.config)||void 0===i?void 0:i.templateFilePath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.1.0-beta.0514202501/dist/mrz-scanner.template.json"},c=Object.assign(Object.assign({},this.config.scannerViewConfig),{container:l[t.EnumMRZScannerViews.Scanner]||Ka(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)||null,cameraEnhancerUIPath:(null===(r=this.config.scannerViewConfig)||void 0===r?void 0:r.cameraEnhancerUIPath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.1.0-beta.0514202501/dist/mrz-scanner.ui.html",templateFilePath:h.templateFilePath,utilizedTemplateNames:h.utilizedTemplateNames,enableMultiFrameCrossFilter:null===(a=null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.enableMultiFrameCrossFilter)||void 0===a||a,mrzFormatType:this.config.mrzFormatType}),u=this.showResultView()?Object.assign(Object.assign({},this.config.resultViewConfig),{container:l[t.EnumMRZScannerViews.Result]||Ka(null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)||null}):void 0;return Object.assign(this.config,Object.assign(Object.assign({},h),{scannerViewConfig:c,resultViewConfig:u})),!0}createViewContainers(e){e.textContent="";const i=[t.EnumMRZScannerViews.Scanner];return this.showResultView()&&i.push(t.EnumMRZScannerViews.Result),i.reduce(((t,i)=>{const n=document.createElement("div");return n.className=`mrz-scanner-${i}-view-container`,Object.assign(n.style,{height:"100%",width:"100%",display:"none",position:"relative"}),e.append(n),t[i]=n,t}),{})}dispose(){var t,e;this.resultView&&(this.resultView.dispose(),this.resultView=null),this.scannerView=null,this.resources.cameraEnhancer&&(this.resources.cameraEnhancer.dispose(),this.resources.cameraEnhancer=null),this.resources.cameraView&&(this.resources.cameraView.dispose(),this.resources.cameraView=null),this.resources.cvRouter&&(this.resources.cvRouter.dispose(),this.resources.cvRouter=null),this.resources.result=null,this.resources.onResultUpdated=null;const i=t=>{const e=Ka(t);e&&(e.style.display="none",e.textContent="")};i(this.config.container),i(null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container),i(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container),this.isInitialized=!1}async processUploadedFile(e){var i,n,r,s;try{this.showLoadingOverlay("Processing File...");const{cvRouter:a}=this.resources,o=null===(i=this.config.utilizedTemplateNames)||void 0===i?void 0:i.all,l=await a.getSimplifiedSettings(o);l.roiMeasuredInPercentage=!0,l.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await a.updateSettings(o,l);const h=await a.capture(e,o),c=h.items,u=c.filter((t=>t.type===mt.CRIT_ORIGINAL_IMAGE))[0].imageData;u.toCanvas=()=>A(u),u.toBlob=async()=>await L("image/png",u);const d=null==h?void 0:h.textLineResultItems,f=null==h?void 0:h.parsedResultItems;let g={};if(null==d?void 0:d.length){const t=(null===(n=d[0])||void 0===n?void 0:n.text)||"";g=ho(t,f[0])}const m={status:{code:t.EnumResultStatus.RS_SUCCESS,message:"Success"},originalImageResult:u,data:g,imageData:!0,_imageData:u};null===(s=(r=this.resources).onResultUpdated)||void 0===s||s.call(r,m)}catch(e){return console.error("Failed to process uploaded file:",e),{status:{code:t.EnumResultStatus.RS_FAILED,message:`Failed to process image: ${e.message||e}`}}}finally{this.hideLoadingOverlay(!1)}}async launch(e){if(this.isCapturing)throw new Error("Capture session already in progress");try{this.isCapturing=!0;const{components:i}=await this.initialize();if(Qa(i))throw new Error("MRZ Scanner initialization failed.");if(this.config.container&&(Ka(this.config.container).style.display="block"),e&&(i.scannerView=null,await this.processUploadedFile(e)),!i.scannerView&&this.resources.result&&i.resultView)return await i.resultView.launch();if(!i.scannerView&&!this.resources.result)throw new Error("Scanner view is required when no previous result exists");if(i.scannerView){const e=await i.scannerView.launch();if((null==e?void 0:e.status.code)!==t.EnumResultStatus.RS_SUCCESS)return{status:{code:null==e?void 0:e.status.code,message:(null==e?void 0:e.status.message)||"Failed to capture image"}};if(i.resultView)return await i.resultView.launch()}return this.resources.result}catch(e){return alert((null==e?void 0:e.message)||e),console.error((null==e?void 0:e.message)||e),{status:{code:t.EnumResultStatus.RS_FAILED,message:(null==e?void 0:e.message)||e}}}finally{this.isCapturing=!1,this.dispose()}}}const vo={MRZScanner:_o,MRZScannerView:uo,MRZResultView:go};t.CVR=Ne,t.Core=xt,t.DCE=Us,t.DCP=ea,t.DEFAULT_TEMPLATE_NAMES=qa,t.DLR=fa,t.DynamsoftMRZScanner=vo,t.License=Jt,t.MRZDataLabel=so,t.MRZResultView=go,t.MRZScanner=_o,t.MRZScannerView=uo,t.Utility=Za,t.displayMRZDate=oo})); diff --git a/dist/mrz-scanner.bundle.mjs b/dist/mrz-scanner.bundle.mjs index 4165951..6816d26 100644 --- a/dist/mrz-scanner.bundle.mjs +++ b/dist/mrz-scanner.bundle.mjs @@ -1 +1 @@ -const t=t=>t&&"object"==typeof t&&"function"==typeof t.then,e=(async()=>{})().constructor;class i extends e{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(i){let n;this._task=i,t(i)?n=i:"function"==typeof i&&(n=new e(i)),n&&(async()=>{try{const t=await n;i===this._task&&this.resolve(t)}catch(t){i===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}constructor(e){let i,n;super(((t,e)=>{i=t,n=e})),this._s="pending",this.resolve=e=>{this.isPending&&(t(e)?this.task=e:(this._s="fulfilled",i(e)))},this.reject=t=>{this.isPending&&(this._s="rejected",n(t))},this.task=e}}function n(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function r(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,i),i}var s,a,o;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(s||(s={})),function(t){t[t.CCUT_AUTO=0]="CCUT_AUTO",t[t.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",t[t.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",t[t.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",t[t.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",t[t.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(a||(a={})),function(t){t[t.IPF_BINARY=0]="IPF_BINARY",t[t.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",t[t.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",t[t.IPF_NV21=3]="IPF_NV21",t[t.IPF_RGB_565=4]="IPF_RGB_565",t[t.IPF_RGB_555=5]="IPF_RGB_555",t[t.IPF_RGB_888=6]="IPF_RGB_888",t[t.IPF_ARGB_8888=7]="IPF_ARGB_8888",t[t.IPF_RGB_161616=8]="IPF_RGB_161616",t[t.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",t[t.IPF_ABGR_8888=10]="IPF_ABGR_8888",t[t.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",t[t.IPF_BGR_888=12]="IPF_BGR_888",t[t.IPF_BINARY_8=13]="IPF_BINARY_8",t[t.IPF_NV12=14]="IPF_NV12",t[t.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(o||(o={}));const l="undefined"==typeof self,h="function"==typeof importScripts,c=(()=>{if(!h){if(!l&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),d=t=>{if(null==t&&(t="./"),l||h);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},u=t=>Object.prototype.toString.call(t),f=t=>Array.isArray?Array.isArray(t):"[object Array]"===u(t),g=t=>"[object Boolean]"===u(t),m=t=>"number"==typeof t&&!Number.isNaN(t),p=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),_=t=>!(!p(t)||!m(t.x)||!m(t.y)||!m(t.radius)||t.radius<0||!m(t.startAngle)||!m(t.endAngle)),v=t=>!!p(t)&&!!f(t.points)&&0!=t.points.length&&!t.points.some((t=>!T(t))),y=t=>!(!p(t)||!m(t.width)||t.width<=0||!m(t.height)||t.height<=0||!m(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!S(t.tag)),w=t=>!(!y(t)||!m(t.bytes.length)&&!m(t.bytes.ptr)),C=t=>!!y(t)&&t.bytes instanceof Uint8Array,E=t=>!(!p(t)||!m(t.left)||t.left<0||!m(t.top)||t.top<0||!m(t.right)||t.right<0||!m(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom||!g(t.isMeasuredInPercentage)),S=t=>null===t||!!p(t)&&!!m(t.imageId)&&"type"in t,b=t=>!(!p(t)||!T(t.startPoint)||!T(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),T=t=>!!p(t)&&!!m(t.x)&&!!m(t.y),x=t=>!!p(t)&&!!f(t.points)&&0!=t.points.length&&!t.points.some((t=>!T(t))),I=t=>!!p(t)&&!!f(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some((t=>!T(t))),O=t=>!(!p(t)||!m(t.x)||!m(t.y)||!m(t.width)||t.width<0||!m(t.height)||t.height<0||"isMeasuredInPercentage"in t&&!g(t.isMeasuredInPercentage)),A=async(t,e)=>await new Promise(((i,n)=>{let r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType=e,r.send(),r.onloadend=async()=>{r.status<200||r.status>=300?n(new Error(t+" "+r.status)):i(r.response)},r.onerror=()=>{n(new Error("Network Error: "+r.statusText))}})),R=t=>/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t),D=(t,e)=>{let i=t.split("."),n=e.split(".");for(let t=0;t{const e={},i={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcpd:"dynamsoft-code-parser",dlrData:"dynamsoft-label-recognizer-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer"};for(let n in t){if("rootDirectory"===n)continue;let r=n,s=t[r],a=s&&"object"==typeof s&&s.path?s.path:s,o=t.rootDirectory;if(o&&!o.endsWith("/")&&(o+="/"),"object"==typeof s&&s.isInternal)o&&(a=t[r].version?`${o}${i[r]}@${t[r].version}/dist/${"ddv"===r?"engine":""}`:`${o}${i[r]}/dist/${"ddv"===r?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof a&&(a=a.replace(i,o||"")),"object"==typeof a&&"dwt"===r){const n=t[r].resourcesPath,s=t[r].serviceInstallerLocation;e[r]={resourcesPath:n.replace(i,o||""),serviceInstallerLocation:s.replace(i,o||"")};continue}}e[r]=d(a)}return e},M=async(t,e,i)=>await new Promise((async(n,r)=>{try{const r=e.split(".");let s=r[r.length-1];const a=await k(`image/${s}`,t);r.length<=1&&(s="png");const o=new File([a],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(o),i=document.createElement("a");i.href=t,i.download=e,i.click()}return n(o)}catch(t){return r()}})),F=t=>{C(t)&&(t=N(t));const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},P=(t,e)=>{C(e)&&(e=N(e));const i=F(e);let n=new Image,r=i.toDataURL(t);return n.src=r,n},k=async(t,e)=>{C(e)&&(e=N(e));const i=F(e);return new Promise(((e,n)=>{i.toBlob((t=>e(t)),t)}))},N=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===o.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n=r)break;e[a]=e[a+1]=e[a+2]=(128&n)/128*255,e[a+3]=255,n<<=1}}}else if(Number(t.format)===o.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n=r)break;e[a]=e[a+1]=e[a+2]=128&n?0:255,e[a+3]=255,n<<=1}}}return new ImageData(e,t.width,t.height)};var B,j,V,U,G,W,Y,z;let H,X,Z,q,J,K=class t{get _isFetchingStarted(){return n(this,G,"f")}constructor(){B.add(this),j.set(this,[]),V.set(this,1),U.set(this,s.BOPM_BLOCK),G.set(this,!1),W.set(this,void 0),Y.set(this,a.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!C(t))throw new TypeError("Invalid 'image'.");if((null===(e=t.tag)||void 0===e?void 0:e.hasOwnProperty("imageId"))&&"number"==typeof t.tag.imageId&&this.hasImage(t.tag.imageId))throw new Error("Existed imageId.");if(n(this,j,"f").length>=n(this,V,"f"))switch(n(this,U,"f")){case s.BOPM_BLOCK:break;case s.BOPM_UPDATE:if(n(this,j,"f").push(t),p(n(this,W,"f"))&&m(n(this,W,"f").imageId)&&1==n(this,W,"f").keepInBuffer)for(;n(this,j,"f").length>n(this,V,"f");){const t=n(this,j,"f").findIndex((t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==n(this,W,"f").imageId}));n(this,j,"f").splice(t,1)}else n(this,j,"f").splice(0,n(this,j,"f").length-n(this,V,"f"))}else n(this,j,"f").push(t)}getImage(){if(0===n(this,j,"f").length)return null;let e;if(n(this,W,"f")&&m(n(this,W,"f").imageId)){const t=n(this,B,"m",z).call(this,n(this,W,"f").imageId);if(t<0)throw new Error(`Image with id ${n(this,W,"f").imageId} doesn't exist.`);e=n(this,j,"f").slice(t,t+1)[0]}else e=n(this,j,"f").pop();if([o.IPF_RGB_565,o.IPF_RGB_555,o.IPF_RGB_888,o.IPF_ARGB_8888,o.IPF_RGB_161616,o.IPF_ARGB_16161616,o.IPF_ABGR_8888,o.IPF_ABGR_16161616,o.IPF_BGR_888].includes(e.format)){if(n(this,Y,"f")===a.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t0!==t.length&&t.every((t=>m(t))))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&!g(e))throw new TypeError("Invalid 'keepInBuffer'.");r(this,W,{imageId:t,keepInBuffer:e})}_resetNextReturnedImage(){r(this,W,null)}hasImage(t){return n(this,B,"m",z).call(this,t)>=0}startFetching(){r(this,G,!0)}stopFetching(){r(this,G,!1)}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(r(this,V,t);n(this,j,"f")&&n(this,j,"f").length>t;)n(this,j,"f").shift()}getMaxImageCount(){return n(this,V,"f")}getImageCount(){return n(this,j,"f").length}clearBuffer(){n(this,j,"f").length=0}isBufferEmpty(){return 0===n(this,j,"f").length}setBufferOverflowProtectionMode(t){r(this,U,t)}getBufferOverflowProtectionMode(){return n(this,U,"f")}setColourChannelUsageType(t){r(this,Y,t)}getColourChannelUsageType(){return n(this,Y,"f")}};j=new WeakMap,V=new WeakMap,U=new WeakMap,G=new WeakMap,W=new WeakMap,Y=new WeakMap,B=new WeakSet,z=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return n(this,j,"f").findIndex((e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t}))},"undefined"!=typeof navigator&&(H=navigator,X=H.userAgent,Z=H.platform,q=H.mediaDevices),function(){if(!l){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:H.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Z,search:"Win"},Mac:{str:Z},Linux:{str:Z}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||X,a=r.search||e,o=r.verStr||X,l=r.verSearch||e;if(l instanceof Array||(l=[l]),-1!=s.indexOf(a)){i=e;for(let t of l){let e=o.indexOf(t);if(-1!=e){n=parseFloat(o.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||X,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=X.indexOf("Windows NT")&&(r="HarmonyOS"),J={browser:i,version:n,OS:r}}l&&(J={browser:"ssr",version:0,OS:"ssr"})}();const $="undefined"!=typeof WebAssembly&&X&&!(/Safari/.test(X)&&!/Chrome/.test(X)&&/\(.+\s11_2_([2-6]).*\)/.test(X)),Q=!("undefined"==typeof Worker),tt=!(!q||!q.getUserMedia),et=async()=>{let t=!1;if(tt)try{(await q.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===J.browser&&J.version>66||"Safari"===J.browser&&J.version>13||"OPR"===J.browser&&J.version>43||"Edge"===J.browser&&J.version;const it={},nt=async t=>{let e="string"==typeof t?[t]:t,n=[];for(let t of e)n.push(it[t]=it[t]||new i);await Promise.all(n)},rt=async(t,e)=>{let n,r="string"==typeof t?[t]:t,s=[];for(let t of r){let r;s.push(r=it[t]=it[t]||new i(n=n||e())),r.isEmpty&&(r.task=n=n||e())}await Promise.all(s)};let st,at=0;const ot=()=>at++,lt={};let ht;const ct=t=>{ht=t,st&&st.postMessage({type:"setBLog",body:{value:!!t}})};let dt=!1;const ut=t=>{dt=t,st&&st.postMessage({type:"setBDebug",body:{value:!!t}})},ft={},gt={},mt={dip:{wasm:!0}},pt={std:{version:"1.4.21",path:d(c+"../../dynamsoft-capture-vision-std@1.4.21/dist/"),isInternal:!0},core:{version:"3.4.31",path:c,isInternal:!0}},_t=async t=>{let e;t instanceof Array||(t=t?[t]:[]);let n=it.core;e=!n||n.isEmpty;let r=new Map;const s=t=>{if("std"==(t=t.toLowerCase())||"core"==t)return;if(!mt[t])throw Error("The '"+t+"' module cannot be found.");let e=mt[t].deps;if(null==e?void 0:e.length)for(let t of e)s(t);let i=it[t];r.has(t)||r.set(t,!i||i.isEmpty)};for(let e of t)s(e);let a=[];e&&a.push("core"),a.push(...r.keys());const o=[...r.entries()].filter((t=>!t[1])).map((t=>t[0]));await rt(a,(async()=>{const t=[...r.entries()].filter((t=>t[1])).map((t=>t[0]));await nt(o);const n=L(pt),s={};for(let e of t)s[e]=mt[e];const a={engineResourcePaths:n,autoResources:s,names:t};let l=new i;if(e){a.needLoadCore=!0;let t=n.core+vt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),st=new Worker(t),st.onerror=t=>{let e=new Error(t.message);l.reject(e)},st.addEventListener("message",(t=>{let e=t.data?t.data:t,i=e.type,n=e.id,r=e.body;switch(i){case"log":ht&&ht(e.message);break;case"task":try{lt[n](r),delete lt[n]}catch(t){throw delete lt[n],t}break;case"event":try{lt[n](r)}catch(t){throw t}break;default:console.log(t)}})),a.bLog=!!ht,a.bd=dt,a.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await nt("core");let h=at++;lt[h]=t=>{if(t.success)Object.assign(ft,t.versions),"{}"!==JSON.stringify(t.versions)&&(vt._versions=t.versions),l.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),l.reject(e)}},st.postMessage({type:"loadWasm",body:a,id:h}),await l}))};class vt{static get engineResourcePaths(){return pt}static set engineResourcePaths(t){Object.assign(pt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return ht}static set _onLog(t){ct(t)}static get _bDebug(){return dt}static set _bDebug(t){ut(t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!it[t]&&it[t].isFulfilled}static async loadWasm(t){return await _t(t)}static async detectEnvironment(){return await(async()=>({wasm:$,worker:Q,getUserMedia:tt,camera:await et(),browser:J.browser,version:J.version,OS:J.OS}))()}static async getModuleVersion(){return await new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success)return t(i.versions);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"getModuleVersion",id:i})}))}static getVersion(){return`3.4.31(Worker: ${ft.core&&ft.core.worker||"Not Loaded"}, Wasm: ${ft.core&&ft.core.wasm||"Not Loaded"})`}static enableLogging(){K._onLog=console.log,vt._onLog=console.log}static disableLogging(){K._onLog=null,vt._onLog=null}static async cfd(t){return await new Promise(((e,i)=>{let n=ot();lt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cfd",id:n,body:{count:t}})}))}}var yt,wt,Ct,Et,St,bt,Tt,xt,It;vt._bSupportDce4Module=-1,vt._bSupportIRTModule=-1,vt._versions=null,vt._workerName="core.worker.js",vt.browserInfo=J,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT"}(yt||(yt={})),function(t){t[t.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",t[t.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",t[t.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",t[t.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(wt||(wt={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",t[t.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",t[t.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",t[t.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",t[t.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",t[t.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",t[t.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",t[t.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",t[t.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",t[t.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",t[t.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",t[t.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",t[t.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",t[t.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",t[t.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",t[t.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",t[t.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",t[t.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",t[t.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",t[t.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",t[t.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",t[t.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",t[t.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(Ct||(Ct={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV"}(Et||(Et={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV"}(St||(St={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(bt||(bt={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(Tt||(Tt={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(xt||(xt={})),function(t){t[t.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",t[t.CVS_PASSED=1]="CVS_PASSED",t[t.CVS_FAILED=2]="CVS_FAILED"}(It||(It={}));const Ot={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_DOWN_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_UP_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_NORMALIZED_IMAGES:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var At,Rt;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_NORMALIZED_IMAGE=6]="ROET_NORMALIZED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI"}(At||(At={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_NORMALIZATION=7]="ST_DOCUMENT_NORMALIZATION"}(Rt||(Rt={}));const Dt="undefined"==typeof self,Lt=Dt?{}:self,Mt="function"==typeof importScripts,Ft=(()=>{if(!Mt){if(!Dt&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),Pt=t=>t&&"object"==typeof t&&"function"==typeof t.then,kt=(async()=>{})().constructor;let Nt=class extends kt{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Pt(t)?e=t:"function"==typeof t&&(e=new kt(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(Pt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Bt=" is not allowed to change after `createInstance` or `loadWasm` is called.",jt=!Dt&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",Vt=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Bt);i._license=e}};!Dt&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Ut=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=Ut(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Bt);i._licenseServer=e}},Wt=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Bt);i._deviceFriendlyName=e}};let Yt,zt,Ht,Xt,Zt;"undefined"!=typeof navigator&&(Yt=navigator,zt=Yt.userAgent,Ht=Yt.platform,Xt=Yt.mediaDevices),function(){if(!Dt){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Yt.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Ht,search:"Win"},Mac:{str:Ht},Linux:{str:Ht}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||zt,a=r.search||e,o=r.verStr||zt,l=r.verSearch||e;if(l instanceof Array||(l=[l]),-1!=s.indexOf(a)){i=e;for(let t of l){let e=o.indexOf(t);if(-1!=e){n=parseFloat(o.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||zt,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=zt.indexOf("Windows NT")&&(r="HarmonyOS"),Zt={browser:i,version:n,OS:r}}Dt&&(Zt={browser:"ssr",version:0,OS:"ssr"})}(),Xt&&Xt.getUserMedia,"Chrome"===Zt.browser&&Zt.version>66||"Safari"===Zt.browser&&Zt.version>13||"OPR"===Zt.browser&&Zt.version>43||"Edge"===Zt.browser&&Zt.version;const qt=()=>(_t("license"),rt("dynamsoft_inited",(async()=>{let{lt:t,l:e,ls:i,sp:n,rmk:r,cv:s}=((t,e=!1)=>{const i=Kt;if(i._pLoad.isEmpty){let n,r,s,a=i._license||"",o=JSON.parse(JSON.stringify(i._licenseServer)),l=i._sessionPassword,h=0;if(a.startsWith("t")||a.startsWith("f"))h=0;else if(0===a.length||a.startsWith("P")||a.startsWith("L")||a.startsWith("Y")||a.startsWith("A"))h=1;else{h=2;const e=a.indexOf(":");-1!=e&&(a=a.substring(e+1));const i=a.indexOf("?");if(-1!=i&&(r=a.substring(i+1),a=a.substring(0,i)),a.startsWith("DLC2"))h=0;else{if(a.startsWith("DLS2")){let e;try{let t=a.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(a=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof a&&(a=JSON.stringify(a)),0===o.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),o=Ut(t)}!l&&e.sessionPassword&&(l=e.sessionPassword),n=e.remark}a&&"200001"!==a&&!a.startsWith("200001-")||(h=1)}}if(h&&(e||(Lt.crypto||(s="Please upgrade your browser to support online key."),Lt.crypto.subtle||(s="Require https to use online key in this browser."))),s)throw new Error(s);return 1===h&&(a="",console.warn("Applying for a public trial license ...")),{lt:h,l:a,ls:o,sp:l,rmk:n,cv:r}}throw new Error("Can't preprocess license again"+Bt)})(),a=new Nt;Kt._pLoad.task=a,(async()=>{try{await Kt._pLoad}catch(t){}})();let o=ot();lt[o]=e=>{if(e.message&&Kt._onAuthMessage){let t=Kt._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,n=!1;if(1===t&&(n=!0),e.success?(ht&&ht("init license success"),e.message&&console.warn(e.message),vt._bSupportIRTModule=e.bSupportIRTModule,vt._bSupportDce4Module=e.bSupportDce4Module,Kt.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):a.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),n||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(n=!0)),n){const t=L(vt.engineResourcePaths);(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let n=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!n.ok)throw Error("Get license dialog fail. Network Error: "+n.statusText);let r=await n.text();if(!r.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.innerHTML=r;let a=[];for(let t=0;t{if(t==e.target){o.remove();for(let t of a)t.remove()}}));else if(!h&&t.classList.contains("dls-license-icon-close"))h=t,t.addEventListener("click",(()=>{o.remove();for(let t of a)t.remove()}));else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-icon-warn"))d=t,"warn"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-msg-content")){u=t;let e=i;for(;e;){let i=e.indexOf("["),n=e.indexOf("]",i),r=e.indexOf("(",n),s=e.indexOf(")",r);if(-1==i||-1==n||-1==r||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let a=document.createElement("a"),o=e.substring(i+1,n);a.innerText=o;let l=e.substring(r+1,s);a.setAttribute("href",l),a.setAttribute("target","_blank"),t.appendChild(a),e=e.substring(s+1)}}document.body.appendChild(o)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:Kt._bNeverShowDialog,engineResourcePath:t.license,_onLog:ht},e.success?"warn":"error",e.message)}e.success?a.resolve(void 0):a.reject(i)},await nt("core"),st.postMessage({type:"license_dynamsoft",body:{v:"3.4.31",brtk:!!t,bptk:1===t,l:e,os:Zt,fn:Kt.deviceFriendlyName,ls:i,sp:n,rmk:r,cv:s},id:o}),Kt.bCallInitLicense=!0,await a})));let Jt;gt.license={},gt.license.dynamsoft=qt,gt.license.getAR=async()=>{{let t=it.dynamsoft_inited;t&&t.isRejected&&await t}return st?new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success){delete i.success;{let t=Kt.license;t&&(t.startsWith("t")||t.startsWith("f"))&&(i.pk=t)}if(Object.keys(i).length){if(i.lem){let t=Error(i.lem);t.ltsErrorCode=i.lec,delete i.lem,delete i.lec,i.ae=t}t(i)}else t(null)}else{let t=Error(i.message);i.stack&&(t.stack=i.stack),e(t)}},st.postMessage({type:"license_getAR",id:i})})):null};let Kt=class t{static setLicenseServer(e){Gt(t,e)}static get license(){return this._license}static set license(e){Vt(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Gt(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){Wt(t,e)}static initLicense(e,i){if(Vt(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return qt()}static setDeviceFriendlyName(e){Wt(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await rt("dynamsoft_uuid",(async()=>{await _t();let t=new Nt,e=ot();lt[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},st.postMessage({type:"license_getDeviceUUID",id:e}),Jt=await t})),Jt))()}};Kt._pLoad=new Nt,Kt.bPassValidation=!1,Kt.bCallInitLicense=!1,Kt._license=jt,Kt._licenseServer=[],Kt._deviceFriendlyName="",vt.engineResourcePaths.license={version:"3.4.31",path:Ft,isInternal:!0},mt.license={wasm:!0,js:!0},gt.license.LicenseManager=Kt;const $t="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,$t)<0&&(vt.engineResourcePaths.std={version:$t,path:(t=>{if(null==t&&(t="./"),Dt||Mt);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(Ft+`../../dynamsoft-capture-vision-std@${$t}/dist/`),isInternal:!0});let Qt=class{static getVersion(){return`3.4.31(Worker: ${ft.license&&ft.license.worker||"Not Loaded"}, Wasm: ${ft.license&&ft.license.wasm||"Not Loaded"})`}};function te(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function ee(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const ie=t=>t&&"object"==typeof t&&"function"==typeof t.then,ne=(async()=>{})().constructor;class re extends ne{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,ie(t)?e=t:"function"==typeof t&&(e=new ne(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(ie(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class se{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success)return t(i.count);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})}))}async setMaxBufferedItems(t){return await new Promise(((e,i)=>{let n=ot();lt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_setMaxBufferedItems",id:n,instanceID:this._cvr._instanceID,body:{count:t}})}))}async getBufferedCharacterItemSet(){return await new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success)return t(i.itemSet);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})}))}}var ae={onTaskResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onColourImageUnitReceived:!1,onScaledDownColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledUpBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesReceived:!1};const oe=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};class le{constructor(t){this._irrRegistryState=ae,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),oe(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach(((t,e)=>{i[e]=t})),t._observedTaskMap.clear()}return await new Promise(((t,n)=>{let r=ot();lt[r]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},st.postMessage({type:"cvr_setIrrRegistry",id:r,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})}))}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),oe(this),await new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})}))}getOriginalImage(){return this._cvr._dsImage}}const he="undefined"==typeof self,ce="function"==typeof importScripts,de=(()=>{if(!ce){if(!he&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),ue=t=>{if(null==t&&(t="./"),he||ce);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var fe;vt.engineResourcePaths.cvr={version:"2.4.33",path:de,isInternal:!0},mt.cvr={js:!0,wasm:!0,deps:["license","dip"]},gt.cvr={};const ge="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,ge)<0&&(vt.engineResourcePaths.std={version:ge,path:ue(de+`../../dynamsoft-capture-vision-std@${ge}/dist/`),isInternal:!0});const me="2.4.31";(!vt.engineResourcePaths.dip||"string"!=typeof vt.engineResourcePaths.dip&&D(vt.engineResourcePaths.dip.version,me)<0)&&(vt.engineResourcePaths.dip={version:me,path:ue(de+`../../dynamsoft-image-processing@${me}/dist/`),isInternal:!0});class pe{static getVersion(){return this._version}}pe._version=`2.4.33(Worker: ${null===(fe=ft.cvr)||void 0===fe?void 0:fe.worker}, Wasm: loading...`;const _e={barcodeResultItems:{type:yt.CRIT_BARCODE,reveiver:"onDecodedBarcodesReceived",isNeedFilter:!0},textLineResultItems:{type:yt.CRIT_TEXT_LINE,reveiver:"onRecognizedTextLinesReceived",isNeedFilter:!0},detectedQuadResultItems:{type:yt.CRIT_DETECTED_QUAD,reveiver:"onDetectedQuadsReceived",isNeedFilter:!1},normalizedImageResultItems:{type:yt.CRIT_NORMALIZED_IMAGE,reveiver:"onNormalizedImagesReceived",isNeedFilter:!1},parsedResultItems:{type:yt.CRIT_PARSED_RESULT,reveiver:"onParsedResultsReceived",isNeedFilter:!1}};var ve,ye,we,Ce,Ee,Se,be,Te,xe,Ie,Oe,Ae,Re;function De(t,e){if(t&&t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;De(t.referencedItem,e)}}function Le(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}!function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(ve||(ve={}));const Me={onTaskResultsReceived:()=>{},isFilter:!0};class Fe{constructor(){this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(vt.browserInfo.OS)?2048:4096,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,ye.set(this,null),we.set(this,null),Ce.set(this,null),Ee.set(this,null),Se.set(this,null),be.set(this,new Set),Te.set(this,new Set),xe.set(this,new Set),Ie.set(this,0),Oe.set(this,!1),Ae.set(this,!1),Re.set(this,!1),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return te(this,Re,"f")}static async createInstance(){if(!gt.license)throw Error("Module `license` is not existed.");await gt.license.dynamsoft(),await _t(["cvr"]);const t=new Fe,e=new re;let i=ot();return lt[i]=async i=>{var n;if(i.success)t._instanceID=i.instanceID,t._currentSettings=JSON.parse(JSON.parse(i.outputSettings).data),pe._version=`2.4.33(Worker: ${null===(n=ft.cvr)||void 0===n?void 0:n.worker}, Wasm: ${i.version})`,ee(t,Ae,!0),ee(t,Ee,t.getIntermediateResultManager()),ee(t,Ae,!1),e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},st.postMessage({type:"cvr_createInstance",id:i}),e}async _singleFrameModeCallback(t){for(let e of te(this,be,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;const n={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of te(this,be,"f"))if(t.isDce)t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1});else{for(let e in _e){const r=e,s=_e[r];t[s.reveiver]&&i[r]&&t[s.reveiver](Object.assign(Object.assign({},n),{[r]:i[r]}))}t.onCapturedResultReceived&&t.onCapturedResultReceived(i)}}setInput(t){if(Le(this),t){if(ee(this,ye,t),t.isCameraEnhancer){te(this,Ee,"f")&&(te(this,ye,"f")._intermediateResultReceiver.isDce=!0,te(this,Ee,"f").addResultReceiver(te(this,ye,"f")._intermediateResultReceiver));const t=te(this,ye,"f").getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,te(this,be,"f").add(e)}}}else ee(this,ye,null)}getInput(){return te(this,ye,"f")}addImageSourceStateListener(t){if(Le(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&te(this,Te,"f").add(t)}removeImageSourceStateListener(t){return Le(this),te(this,Te,"f").delete(t)}addResultReceiver(t){if(Le(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(te(this,be,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){Le(this),te(this,be,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onParsedResultsReceived:!1};for(let e of te(this,be,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onDetectedQuadsReceived=!!e.onDetectedQuadsReceived,t.onNormalizedImagesReceived=!!e.onNormalizedImagesReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new re;let i=ot();return lt[i]=async t=>{if(t.success)e.resolve();else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject()}},st.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(Le(this),!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");te(this,xe,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){Le(this),te(this,xe,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(te(this,Ee,"f").removeResultReceiver(Me),0===te(this,xe,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[yt.CRIT_BARCODE]:!1,[yt.CRIT_TEXT_LINE]:!1,[yt.CRIT_DETECTED_QUAD]:!1,[yt.CRIT_NORMALIZED_IMAGE]:!1},e={[yt.CRIT_BARCODE]:!1,[yt.CRIT_TEXT_LINE]:!1,[yt.CRIT_DETECTED_QUAD]:!1,[yt.CRIT_NORMALIZED_IMAGE]:!1};return await Pe(this,t),void await ke(this,e)}for(let t of te(this,xe,"f")){if(this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(yt.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(yt.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(yt.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(yt.CRIT_NORMALIZED_IMAGE),t.isLatestOverlappingEnabled(yt.CRIT_BARCODE)){[...te(this,Ee,"f")._intermediateResultReceiverSet.values()].find((t=>t.isFilter))||te(this,Ee,"f").addResultReceiver(Me)}await Pe(this,t.verificationEnabled),await ke(this,t.duplicateFilterEnabled),await Ne(this,t.duplicateForgetTime)}}async startCapturing(t){var e,i;if(Le(this),!this._isPauseScan)return;if(!te(this,ye,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");t||(t=Fe._defaultTemplate);const n=await this.containsTask(t);await _t(n);for(let t of te(this,xe,"f"))await this.addResultFilter(t);if(n.includes("dlr")&&!(null===(e=gt.dlr)||void 0===e?void 0:e.bLoadConfusableCharsData)){const t=L(vt.engineResourcePaths);await(null===(i=gt.dlr)||void 0===i?void 0:i.loadRecognitionData("ConfusableChars",t.dlr))}if(te(this,ye,"f").isCameraEnhancer&&(n.includes("ddn")?te(this,ye,"f").setPixelFormat(o.IPF_ABGR_8888):te(this,ye,"f").setPixelFormat(o.IPF_GRAYSCALED)),void 0!==te(this,ye,"f").singleFrameMode&&"disabled"!==te(this,ye,"f").singleFrameMode)return this._templateName=t,void te(this,ye,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind);return te(this,ye,"f").getColourChannelUsageType()===a.CCUT_AUTO&&te(this,ye,"f").setColourChannelUsageType(n.includes("ddn")?a.CCUT_FULL_CHANNEL:a.CCUT_Y_CHANNEL_ONLY),te(this,Ce,"f")&&te(this,Ce,"f").isPending?te(this,Ce,"f"):(ee(this,Ce,new re(((e,i)=>{if(this.disposed)return;let n=ot();lt[n]=async n=>{if(te(this,Ce,"f")&&!te(this,Ce,"f").isFulfilled){if(!n.success){let t=new Error(n.message);return t.stack=n.stack+"\n"+t.stack,i(t)}this._isPauseScan=!1,this._isOutputOriginalImage=n.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((async()=>{-1!==this._minImageCaptureInterval&&te(this,ye,"f").startFetching(),this._loopReadVideo(t),e()}),0)}},st.postMessage({type:"cvr_startCapturing",id:n,instanceID:this._instanceID,body:{templateName:t}})}))),await te(this,Ce,"f"))}stopCapturing(){Le(this),te(this,ye,"f")&&(te(this,ye,"f").isCameraEnhancer&&void 0!==te(this,ye,"f").singleFrameMode&&"disabled"!==te(this,ye,"f").singleFrameMode?te(this,ye,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(!async function(t){let e=ot();const i=new re;lt[e]=async t=>{if(t.success)return i.resolve();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i.reject(e)}},st.postMessage({type:"cvr_clearVerifyList",id:e,instanceID:t._instanceID})}(this),te(this,ye,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,ee(this,Ce,null),te(this,ye,"f").setColourChannelUsageType(a.CCUT_AUTO)))}async containsTask(t){return Le(this),await new Promise(((e,i)=>{let n=ot();lt[n]=async t=>{if(t.success)return e(JSON.parse(t.tasks));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_containsTask",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async _loopReadVideo(t){if(this.disposed||this._isPauseScan)return;if(ee(this,Oe,!0),te(this,ye,"f").isBufferEmpty())if(te(this,ye,"f").hasNextImageToFetch())for(let t of te(this,Te,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ve.ISS_BUFFER_EMPTY);else if(!te(this,ye,"f").hasNextImageToFetch())for(let t of te(this,Te,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ve.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||te(this,ye,"f").isBufferEmpty())try{te(this,ye,"f").isBufferEmpty()&&Fe._onLog&&Fe._onLog("buffer is empty so fetch image"),Fe._onLog&&Fe._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=te(this,ye,"f").fetchImage(),Fe._onLog&&Fe._onLog(`DCE: finish fetching a frame: ${Date.now()}`),te(this,ye,"f").setImageFetchInterval(this._averageTime)}catch(e){return void this._reRunCurrnetFunc(t)}else if(te(this,ye,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=te(this,ye,"f").getImage(),this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(t);if(!this._dsImage)return void this._reRunCurrnetFunc(t);for(let t of te(this,be,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const e=Date.now();this._captureDsimage(this._dsImage,t).then((async i=>{if(Fe._onLog&&Fe._onLog("no js handle time: "+(Date.now()-e)),this._isPauseScan)return void this._reRunCurrnetFunc(t);i.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;const n={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of te(this,be,"f"))if(t.isDce){const e=Date.now();if(t.onCapturedResultReceived(i,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),Fe._onLog){const t=Date.now()-e;t>10&&Fe._onLog(`draw result time: ${t}`)}}else{for(let e in _e){const r=e,s=_e[r];t[s.reveiver],t[s.reveiver]&&i[r]&&t[s.reveiver](Object.assign(Object.assign({},n),{[r]:i[r].filter((t=>!s.isNeedFilter||!t.isFilter))})),i[r]&&(i[r]=i[r].filter((t=>!s.isNeedFilter||!t.isFilter)))}t.onCapturedResultReceived&&(i.items=i.items.filter((t=>[yt.CRIT_DETECTED_QUAD,yt.CRIT_NORMALIZED_IMAGE].includes(t.type)||!t.isFilter)),t.onCapturedResultReceived(i))}const r=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-e),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,Fe._onLog&&(Fe._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),Fe._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),Fe._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),Fe._onLog(`averageTime: ${this._averageTime}`))),Fe._onLog){const t=Date.now()-r;t>10&&Fe._onLog(`fetch image calculate time: ${t}`)}Fe._onLog&&Fe._onLog(`time finish decode: ${Date.now()}`),Fe._onLog&&Fe._onLog("main time: "+(Date.now()-e)),Fe._onLog&&Fe._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,0))})).catch((e=>{te(this,ye,"f").stopFetching(),e.errorCode&&0===e.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{te(this,ye,"f").startFetching(),this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,1e3))),"platform error"!==e.message&&setTimeout((()=>{throw e}),0)}))}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),0)}async capture(t,e){var i,n;Le(this),e||(e=Fe._defaultTemplate);const r=await this.containsTask(e);if(await _t(r),r.includes("dlr")&&!(null===(i=gt.dlr)||void 0===i?void 0:i.bLoadConfusableCharsData)){const t=L(vt.engineResourcePaths);await(null===(n=gt.dlr)||void 0===n?void 0:n.loadRecognitionData("ConfusableChars",t.dlr))}let s;if(ee(this,Oe,!1),C(t))s=await this._captureDsimage(t,e);else if("string"==typeof t)s="data:image/"==t.substring(0,11)?await this._captureBase64(t,e):await this._captureUrl(t,e);else if(t instanceof Blob)s=await this._captureBlob(t,e);else if(t instanceof HTMLImageElement)s=await this._captureImage(t,e);else if(t instanceof HTMLCanvasElement)s=await this._captureCanvas(t,e);else{if(!(t instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");s=await this._captureVideo(t,e)}return s}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await A(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),n=i.length,r=new Uint8Array(n);for(;n--;)r[n]=i.charCodeAt(n);return await this._captureBlob(new Blob([r]),e)}async _captureBlob(t,e){let i=null,n=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(n=await async function(t){return await new Promise(((e,i)=>{let n=URL.createObjectURL(t),r=new Image;r.src=n,r.onload=()=>{URL.revokeObjectURL(r.dbrObjUrl),e(r)},r.onerror=t=>{i(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))}(t));let r=await this._captureImage(i||n,e);return i&&i.close(),r}async _captureImage(t,e){let i,n,r=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,a=Math.max(r,s);a>this.maxImageSideLength?(ee(this,Ie,this.maxImageSideLength/a),i=Math.round(r*te(this,Ie,"f")),n=Math.round(s*te(this,Ie,"f"))):(i=r,n=s),te(this,we,"f")||ee(this,we,document.createElement("canvas"));const o=te(this,we,"f");o.width===i&&o.height===n||(o.width=i,o.height=n),o.ctx2d||(o.ctx2d=o.getContext("2d",{willReadFrequently:!0}));return o.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(o,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),n={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(n,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,n,r=t.videoWidth,s=t.videoHeight,a=Math.max(r,s);a>this.maxImageSideLength?(ee(this,Ie,this.maxImageSideLength/a),i=Math.round(r*te(this,Ie,"f")),n=Math.round(s*te(this,Ie,"f"))):(i=r,n=s),te(this,we,"f")||ee(this,we,document.createElement("canvas"));const o=te(this,we,"f");o.width===i&&o.height===n||(o.width=i,o.height=n),o.ctx2d||(o.ctx2d=o.getContext("2d",{willReadFrequently:!0}));return o.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),await this._captureCanvas(o,e)}async _captureInWorker(t,e){const{bytes:i,width:n,height:r,stride:s,format:a}=t;let o=ot();const l=new re;return lt[o]=async e=>{var i,n;if(!e.success){let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l.reject(t)}{const r=Date.now();Fe._onLog&&(Fe._onLog(`get result time from worker: ${r}`),Fe._onLog("worker to main time consume: "+(r-e.workerReturnMsgTime)));try{const r=e.captureResult;if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,l.reject(t)}t.bytes=e.bytes;for(let e of r.items)0!==te(this,Ie,"f")&&De(e,te(this,Ie,"f")),e.type===yt.CRIT_ORIGINAL_IMAGE?e.imageData=t:e.type===yt.CRIT_NORMALIZED_IMAGE?null===(i=gt.ddn)||void 0===i||i.handleNormalizedImageResultItem(e):e.type===yt.CRIT_PARSED_RESULT&&(null===(n=gt.dcp)||void 0===n||n.handleParsedResultItem(e));if(te(this,Oe,"f"))for(let t of te(this,xe,"f"))t.onDecodedBarcodesReceived(r),t.onRecognizedTextLinesReceived(r),t.onDetectedQuadsReceived(r),t.onNormalizedImagesReceived(r);for(let t in _e){const e=t,i=r.items.filter((t=>t.type===_e[e].type));i.length&&(r[t]=i)}if(!this._isPauseScan||!te(this,Oe,"f")){const e=r.intermediateResult;if(e){let i=0;for(let n of te(this,Ee,"f")._intermediateResultReceiverSet){i++;for(let r of e){if("onTaskResultsReceived"===r.info.callbackName){for(let e of r.intermediateResultUnits)e.originalImageTag=t.tag?t.tag:null;n[r.info.callbackName]&&n[r.info.callbackName]({intermediateResultUnits:r.intermediateResultUnits},r.info)}else n[r.info.callbackName]&&n[r.info.callbackName](r.result,r.info);i===te(this,Ee,"f")._intermediateResultReceiverSet.size&&delete r.info.callbackName}}}}return r&&r.hasOwnProperty("intermediateResult")&&delete r.intermediateResult,ee(this,Ie,0),l.resolve(r)}catch(t){return l.reject(t)}}},Fe._onLog&&Fe._onLog(`send buffer to worker: ${Date.now()}`),st.postMessage({type:"cvr_capture",id:o,instanceID:this._instanceID,body:{bytes:i,width:n,height:r,stride:s,format:a,templateName:e||"",isScanner:te(this,Oe,"f")}},[i.buffer]),l}async initSettings(t){return Le(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?t.trimStart().startsWith("{")||(t=await A(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise(((e,i)=>{let n=ot();lt[n]=async n=>{if(n.success){const r=JSON.parse(n.response);if(0!==r.errorCode){let t=new Error(r.errorString?r.errorString:"Init Settings Failed.");return t.errorCode=r.errorCode,i(t)}const s=JSON.parse(t);this._currentSettings=s;let a=[],o=s.CaptureVisionTemplates;for(let t=0;t{let n=ot();lt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,i(t)}return e(JSON.parse(n.data))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_outputSettings",id:n,instanceID:this._instanceID,body:{templateName:t||"*"}})}))}async outputSettingsToFile(t,e,i){const n=await this.outputSettings(t),r=new Blob([JSON.stringify(n,null,2,(function(t,e){return e instanceof Array?JSON.stringify(e):e}),2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(r),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout((()=>{URL.revokeObjectURL(t.href)}),500)},t.click()}return r}async getTemplateNames(){return Le(this),await new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,e(t)}return t(JSON.parse(n.data))}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})}))}async getSimplifiedSettings(t){Le(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const e=await this.containsTask(t);return await _t(e),await new Promise(((e,i)=>{let n=ot();lt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,i(t)}const r=JSON.parse(n.data,((t,e)=>"barcodeFormatIds"===t?BigInt(e):e));return r.minImageCaptureInterval=this._minImageCaptureInterval,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_getSimplifiedSettings",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async updateSettings(t,e){Le(this);const i=await this.containsTask(t);return await _t(i),await new Promise(((i,n)=>{let r=ot();lt[r]=async t=>{if(t.success){const r=JSON.parse(t.response);if(e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==r.errorCode){let t=new Error(r.errorString?r.errorString:"Update Settings Failed.");return t.errorCode=r.errorCode,n(t)}return this._currentSettings=await this.outputSettings("*"),i(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},st.postMessage({type:"cvr_updateSettings",id:r,instanceID:this._instanceID,body:{settings:e,templateName:t}})}))}async resetSettings(){return Le(this),await new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Reset Settings Failed.");return t.errorCode=n.errorCode,e(t)}return this._currentSettings=await this.outputSettings("*"),t(n)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})}))}getBufferedItemsManager(){return te(this,Se,"f")||ee(this,Se,new se(this)),te(this,Se,"f")}getIntermediateResultManager(){if(Le(this),!te(this,Ae,"f")&&0!==vt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return te(this,Ee,"f")||ee(this,Ee,new le(this)),te(this,Ee,"f")}async parseRequiredResources(t){return Le(this),await new Promise(((e,i)=>{let n=ot();lt[n]=async t=>{if(t.success)return e(JSON.parse(t.resources));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_parseRequiredResources",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async dispose(){Le(this),te(this,Ce,"f")&&this.stopCapturing(),ee(this,ye,null),te(this,be,"f").clear(),te(this,Te,"f").clear(),te(this,xe,"f").clear(),te(this,Ee,"f")._intermediateResultReceiverSet.clear(),ee(this,Re,!0);let t=ot();lt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},st.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:te(this,ye,"f"),promiseStartScan:te(this,Ce,"f"),intermediateResultManager:te(this,Ee,"f"),bufferdItemsManager:te(this,Se,"f"),resultReceiverSet:te(this,be,"f"),isaStateListenerSet:te(this,Te,"f"),resultFilterSet:te(this,xe,"f"),compressRate:te(this,Ie,"f"),canvas:te(this,we,"f"),isScanner:te(this,Oe,"f"),innerUseTag:te(this,Ae,"f"),isDestroyed:te(this,Re,"f")}}async _getWasmFilterState(){return await new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})}))}}async function Pe(t,e){return Le(t),await new Promise(((i,n)=>{let r=ot();lt[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},st.postMessage({type:"cvr_enableResultCrossVerification",id:r,instanceID:t._instanceID,body:{verificationEnabled:e}})}))}async function ke(t,e){return Le(t),await new Promise(((i,n)=>{let r=ot();lt[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},st.postMessage({type:"cvr_enableResultDeduplication",id:r,instanceID:t._instanceID,body:{duplicateFilterEnabled:e}})}))}async function Ne(t,e){return Le(t),await new Promise(((i,n)=>{let r=ot();lt[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},st.postMessage({type:"cvr_setDuplicateForgetTime",id:r,instanceID:t._instanceID,body:{duplicateForgetTime:e}})}))}ye=new WeakMap,we=new WeakMap,Ce=new WeakMap,Ee=new WeakMap,Se=new WeakMap,be=new WeakMap,Te=new WeakMap,xe=new WeakMap,Ie=new WeakMap,Oe=new WeakMap,Ae=new WeakMap,Re=new WeakMap,Fe._defaultTemplate="Default";class Be{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}}class je{constructor(){this._observedResultUnitTypes=Ot.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledDownColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}var Ve;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadBarcodes_Balanced",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(Ve||(Ve={}));const Ue="undefined"==typeof self,Ge="function"==typeof importScripts,We=(()=>{if(!Ge){if(!Ue&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})();vt.engineResourcePaths.dce={version:"4.1.1",path:We,isInternal:!0},mt.dce={wasm:!1,js:!1},gt.dce={};let Ye,ze,He,Xe,Ze,qe=class{static getVersion(){return"4.1.1"}};function Je(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Ke(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(Ye=navigator,ze=Ye.userAgent,He=Ye.platform,Xe=Ye.mediaDevices),function(){if(!Ue){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Ye.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:He,search:"Win"},Mac:{str:He},Linux:{str:He}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||ze,a=r.search||e,o=r.verStr||ze,l=r.verSearch||e;if(l instanceof Array||(l=[l]),-1!=s.indexOf(a)){i=e;for(let t of l){let e=o.indexOf(t);if(-1!=e){n=parseFloat(o.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||ze,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=ze.indexOf("Windows NT")&&(r="HarmonyOS"),Ze={browser:i,version:n,OS:r}}Ue&&(Ze={browser:"ssr",version:0,OS:"ssr"})}();const $e="undefined"!=typeof WebAssembly&&ze&&!(/Safari/.test(ze)&&!/Chrome/.test(ze)&&/\(.+\s11_2_([2-6]).*\)/.test(ze)),Qe=!("undefined"==typeof Worker),ti=!(!Xe||!Xe.getUserMedia),ei=async()=>{let t=!1;if(ti)try{(await Xe.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===Ze.browser&&Ze.version>66||"Safari"===Ze.browser&&Ze.version>13||"OPR"===Ze.browser&&Ze.version>43||"Edge"===Ze.browser&&Ze.version;var ii={653:(t,e,i)=>{var n,r,s,a,o,l,h,c,d,u,f,g,m,p,_,v,y,w,C,E,S,b=b||{version:"5.2.1"};if(e.fabric=b,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?b.document=document:b.document=document.implementation.createHTMLDocument(""),b.window=window;else{var T=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;b.document=T.document,b.jsdomImplForWrapper=i(898).implForWrapper,b.nodeCanvas=i(245).Canvas,b.window=T,DOMParser=b.window.DOMParser}function x(t,e){var i=t.canvas,n=e.targetCanvas,r=n.getContext("2d");r.translate(0,n.height),r.scale(1,-1);var s=i.height-n.height;r.drawImage(i,0,s,n.width,n.height,0,0,n.width,n.height)}function I(t,e){var i=e.targetCanvas.getContext("2d"),n=e.destinationWidth,r=e.destinationHeight,s=n*r*4,a=new Uint8Array(this.imageBuffer,0,s),o=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,a);var l=new ImageData(o,n,r);i.putImageData(l,0,0)}b.isTouchSupported="ontouchstart"in b.window||"ontouchstart"in b.document||b.window&&b.window.navigator&&b.window.navigator.maxTouchPoints>0,b.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,b.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],b.DPI=96,b.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",b.commaWsp="(?:\\s+,?\\s*|,\\s*)",b.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,b.reNonWord=/[ \n\.,;!\?\-]/,b.fontPaths={},b.iMatrix=[1,0,0,1,0,0],b.svgNS="http://www.w3.org/2000/svg",b.perfLimitSizeTotal=2097152,b.maxCacheSideLimit=4096,b.minCacheSideLimit=256,b.charWidthsCache={},b.textureSize=2048,b.disableStyleCopyPaste=!1,b.enableGLFiltering=!0,b.devicePixelRatio=b.window.devicePixelRatio||b.window.webkitDevicePixelRatio||b.window.mozDevicePixelRatio||1,b.browserShadowBlurConstant=1,b.arcToSegmentsCache={},b.boundsOfCurveCache={},b.cachesBoundsOfCurve=!0,b.forceGLPutImageData=!1,b.initFilterBackend=function(){return b.enableGLFiltering&&b.isWebglSupported&&b.isWebglSupported(b.textureSize)?(console.log("max texture size: "+b.maxTextureSize),new b.WebglFilterBackend({tileSize:b.textureSize})):b.Canvas2dFilterBackend?new b.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=b),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:b.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}b.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var n=0,r=i.length;n-1||!!e&&this._objects.some((function(e){return"function"==typeof e.contains&&e.contains(t,!0)}))},complexity:function(){return this._objects.reduce((function(t,e){return t+(e.complexity?e.complexity():0)}),0)}},b.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof b.Gradient||this.set(e,new b.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof b.Pattern?i&&i():this.set(e,new b.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},n=e,r=Math.sqrt,s=Math.atan2,a=Math.pow,o=Math.PI/180,l=Math.PI/2,b.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/l){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/l){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*o},radiansToDegrees:function(t){return t/o},rotatePoint:function(t,e,i){var n=new b.Point(t.x-e.x,t.y-e.y),r=b.util.rotateVector(n,i);return new b.Point(r.x,r.y).addEquals(e)},rotateVector:function(t,e){var i=b.util.sin(e),n=b.util.cos(e);return{x:t.x*n-t.y*i,y:t.x*i+t.y*n}},createVector:function(t,e){return new b.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new b.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var n=b.util.createVector(t,e),r=b.util.createVector(t,i),s=b.util.calcAngleBetweenVectors(n,r),a=s*(0===b.util.calcAngleBetweenVectors(b.util.rotateVector(n,s),r)?1:-1)/2;return{vector:b.util.getHatVector(b.util.rotateVector(n,a)),angle:s}},projectStrokeOnPoints:function(t,e,i){var n=[],r=e.strokeWidth/2,s=e.strokeUniform?new b.Point(1/e.scaleX,1/e.scaleY):new b.Point(1,1),a=function(t){var e=r/Math.hypot(t.x,t.y);return new b.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach((function(o,l){var h,c,d=new b.Point(o.x,o.y);0===l?(c=t[l+1],h=i?a(b.util.createVector(c,d)).addEquals(d):t[t.length-1]):l===t.length-1?(h=t[l-1],c=i?a(b.util.createVector(h,d)).addEquals(d):t[0]):(h=t[l-1],c=t[l+1]);var u,f,g=b.util.getBisector(d,h,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(u=-r/Math.sin(p/2),f=new b.Point(m.x*u*s.x,m.y*u*s.y),Math.hypot(f.x,f.y)/r<=e.strokeMiterLimit))return n.push(d.add(f)),void n.push(d.subtract(f));u=-r*Math.SQRT2,f=new b.Point(m.x*u*s.x,m.y*u*s.y),n.push(d.add(f)),n.push(d.subtract(f))})),n},transformPoint:function(t,e,i){return i?new b.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new b.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>n?e-=n:e=0,i>n?i-=n:i=0);var r,s=!0,a=t.getImageData(e,i,2*n||1,2*n||1),o=a.data.length;for(r=3;r=r?s-r:2*Math.PI-(r-s)}function s(t,e,i){for(var s=i[1],a=i[2],o=i[3],l=i[4],h=i[5],c=function(t,e,i,s,a,o,l){var h=Math.PI,c=l*h/180,d=b.util.sin(c),u=b.util.cos(c),f=0,g=0,m=-u*t*.5-d*e*.5,p=-u*e*.5+d*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,C=_*v-_*y-v*w,E=0;if(C<0){var S=Math.sqrt(1-C/(_*v));i*=S,s*=S}else E=(a===o?-1:1)*Math.sqrt(C/(_*y+v*w));var T=E*i*p/s,x=-E*s*m/i,I=u*T-d*x+.5*t,O=d*T+u*x+.5*e,A=r(1,0,(m-T)/i,(p-x)/s),R=r((m-T)/i,(p-x)/s,(-m-T)/i,(-p-x)/s);0===o&&R>0?R-=2*h:1===o&&R<0&&(R+=2*h);for(var D=Math.ceil(Math.abs(R/h*2)),L=[],M=R/D,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=A+M,k=0;kE)for(var T=1,x=m.length;T2;for(e=e||0,h&&(o=t[2].xt[i-2].x?1:r.x===t[i-2].x?0:-1,l=r.y>t[i-2].y?1:r.y===t[i-2].y?0:-1),n.push(["L",r.x+o*e,r.y+l*e]),n},b.util.getPathSegmentsInfo=u,b.util.getBoundsOfCurve=function(e,i,n,r,s,a,o,l){var h;if(b.cachesBoundsOfCurve&&(h=t.call(arguments),b.boundsOfCurveCache[h]))return b.boundsOfCurveCache[h];var c,d,u,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,C=Math.abs,E=[],S=[[],[]];d=6*e-12*n+6*s,c=-3*e+9*n-9*s+3*o,u=3*n-3*e;for(var T=0;T<2;++T)if(T>0&&(d=6*i-12*r+6*a,c=-3*i+9*r-9*a+3*l,u=3*r-3*i),C(c)<1e-12){if(C(d)<1e-12)continue;0<(f=-u/d)&&f<1&&E.push(f)}else(p=d*d-4*u*c)<0||(0<(g=(-d+(_=v(p)))/(2*c))&&g<1&&E.push(g),0<(m=(-d-_)/(2*c))&&m<1&&E.push(m));for(var x,I,O,A=E.length,R=A;A--;)x=(O=1-(f=E[A]))*O*O*e+3*O*O*f*n+3*O*f*f*s+f*f*f*o,S[0][A]=x,I=O*O*O*i+3*O*O*f*r+3*O*f*f*a+f*f*f*l,S[1][A]=I;S[0][R]=e,S[1][R]=i,S[0][R+1]=o,S[1][R+1]=l;var D=[{x:y.apply(null,S[0]),y:y.apply(null,S[1])},{x:w.apply(null,S[0]),y:w.apply(null,S[1])}];return b.cachesBoundsOfCurve&&(b.boundsOfCurveCache[h]=D),D},b.util.getPointOnPath=function(t,e,i){i||(i=u(t));for(var n=0;e-i[n].length>0&&n1e-4;)i=l(s),r=s,(n=a(h.x,h.y,i.x,i.y))+o>e?(s-=c,c/=2):(h=i,s+=c,o+=n);return i.angle=d(r),i}(s,e)}},b.util.transformPath=function(t,e,i){return i&&(e=b.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map((function(t){for(var i=t.slice(0),n={},r=1;r=e}))}}}(),function(){function t(e,i,n){if(n)if(!b.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var r=0,s=i.length;r57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var n=t.charCodeAt(e+1);if(56320>n||n>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var r=t.charCodeAt(e-1);if(55296>r||r>56319)throw"Low surrogate without preceding high surrogate";return!1}b.util.string={camelize:function(t){return t.replace(/-+(.)?/g,(function(t,e){return e?e.toUpperCase():""}))},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,n=0,r=[];for(n=0;n-1?t.prototype[r]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=n;var r=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return r}}(r):t.prototype[r]=e[r],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function r(){}function s(e){for(var i=null,n=this;n.constructor.superclass;){var r=n.constructor.superclass.prototype[e];if(n[e]!==r){i=r;break}n=n.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}b.util.createClass=function(){var i=null,a=t.call(arguments,0);function o(){this.initialize.apply(this,arguments)}"function"==typeof a[0]&&(i=a.shift()),o.superclass=i,o.subclasses=[],i&&(r.prototype=i.prototype,o.prototype=new r,i.subclasses.push(o));for(var l=0,h=a.length;l-1||"touch"===t.pointerType},u="string"==typeof(d=b.document.createElement("div")).style.opacity,f="string"==typeof d.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},u?m=function(t,e){return t.style.opacity=e,t}:f&&(m=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),b.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var n in e)"opacity"===n?m(t,e[n]):i["float"===n||"cssFloat"===n?void 0===i.styleFloat?"cssFloat":"styleFloat":n]=e[n];return t},function(){var t,e,i,n,r=Array.prototype.slice,s=function(t){return r.call(t,0)};try{t=s(b.document.childNodes)instanceof Array}catch(t){}function a(t,e){var i=b.document.createElement(t);for(var n in e)"class"===n?i.className=e[n]:"for"===n?i.htmlFor=e[n]:i.setAttribute(n,e[n]);return i}function o(t){for(var e=0,i=0,n=b.document.documentElement,r=b.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===b.document?(e=r.scrollLeft||n.scrollLeft||0,i=r.scrollTop||n.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=b.document.defaultView&&b.document.defaultView.getComputedStyle?function(t,e){var i=b.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=b.document.documentElement.style,n="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",b.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=b.util.falseFunction),n?t.style[n]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},b.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),n?t.style[n]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},b.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},b.util.getById=function(t){return"string"==typeof t?b.document.getElementById(t):t},b.util.toArray=s,b.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},b.util.makeElement=a,b.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=a(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},b.util.getScrollLeftTop=o,b.util.getElementOffset=function(t){var i,n,r=t&&t.ownerDocument,s={left:0,top:0},a={left:0,top:0},l={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!r)return a;for(var h in l)a[l[h]]+=parseInt(e(t,h),10)||0;return i=r.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),n=o(t),{left:s.left+n.left-(i.clientLeft||0)+a.left,top:s.top+n.top-(i.clientTop||0)+a.top}},b.util.getNodeCanvas=function(t){var e=b.jsdomImplForWrapper(t);return e._canvas||e._image},b.util.cleanUpJsdomNode=function(t){if(b.isLikelyNode){var e=b.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}b.util.request=function(e,i){i||(i={});var n=i.method?i.method.toUpperCase():"GET",r=i.onComplete||function(){},s=new b.window.XMLHttpRequest,a=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(r(s),s.onreadystatechange=t)},"GET"===n&&(a=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(n,e,!0),"POST"!==n&&"PUT"!==n||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(a),s}}(),b.log=console.log,b.warn=console.warn,function(){var t=b.util.object.extend,e=b.util.object.clone,i=[];function n(){return!1}function r(t,e,i,n){return-i*Math.cos(t/n*(Math.PI/2))+i+e}b.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach((function(t){t.cancel()})),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter((function(e){return"object"==typeof e.target&&e.target.canvas===t}));return e.forEach((function(t){t.cancel()})),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach((function(t){t.cancel()})),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find((function(e){return e.cancel===t}))},findAnimationsByTarget:function(t){return t?this.filter((function(e){return e.target===t})):[]}});var s=b.window.requestAnimationFrame||b.window.webkitRequestAnimationFrame||b.window.mozRequestAnimationFrame||b.window.oRequestAnimationFrame||b.window.msRequestAnimationFrame||function(t){return b.window.setTimeout(t,1e3/60)},a=b.window.cancelAnimationFrame||b.window.clearTimeout;function o(){return s.apply(b.window,arguments)}b.util.animate=function(i){i||(i={});var s,a=!1,l=function(){var t=b.runningAnimations.indexOf(s);return t>-1&&b.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return a=!0,l()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),b.runningAnimations.push(s),o((function(t){var e,h=t||+new Date,c=i.duration||500,d=h+c,u=i.onChange||n,f=i.abort||n,g=i.onComplete||n,m=i.easing||r,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map((function(t,e){return v[e]-_[e]})):v-_);i.onStart&&i.onStart(),function t(i){var n=(e=i||+new Date)>d?c:e-h,r=n/c,w=p?_.map((function(t,e){return m(n,_[e],y[e],c)})):m(n,_,y,c),C=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=C,s.durationRate=r,!a){if(!f(w,C,r))return e>d?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,u(p?v.slice():v,1,1),g(v,1,1),void l()):(u(w,C,r),void o(t));l()}}(h)})),s.cancel},b.util.requestAnimFrame=o,b.util.cancelAnimFrame=function(){return a.apply(b.window,arguments)},b.runningAnimations=i}(),function(){function t(t,e,i){var n="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(n+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}b.util.animateColor=function(e,i,n,r){var s=new b.Color(e).getSource(),a=new b.Color(i).getSource(),o=r.onComplete,l=r.onChange;return r=r||{},b.util.animate(b.util.object.extend(r,{duration:n||500,startValue:s,endValue:a,byValue:a,easing:function(e,i,n,s){return t(i,n,r.colorEasing?r.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,n){if(o)return o(t(a,a,0),i,n)},onChange:function(e,i,n){if(l){if(Array.isArray(e))return l(t(e,e,0),i,n);l(e,i,n)}}}))}}(),function(){function t(t,e,i,n){return t-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===t||"xlink:href"===t||"font"===t)return i;if("imageSmoothing"===t)return"optimizeQuality"===i;o=l?i.map(s):s(i,r)}}else i="";return!l&&isNaN(o)?i:o}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,n,r,s,a=[];for(r=0,s=e.length;r1;)l.shift(),h=e.util.multiplyTransformMatrices(h,l[0]);return h}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,n,r,a,o,l,h=t.getAttribute("viewBox"),c=1,d=1,u=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!h||!(h=h.match(v)),y=!u||!f||"100%"===u||"100%"===f,w=_&&y,C={},E="",S=0,b=0;if(C.width=0,C.height=0,C.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") ",o=(t.getAttribute("transform")||"")+E,t.setAttribute("transform",o),t.removeAttribute("x"),t.removeAttribute("y")),w)return C;if(_)return C.width=s(u),C.height=s(f),C;if(i=-parseFloat(h[1]),n=-parseFloat(h[2]),r=parseFloat(h[3]),a=parseFloat(h[4]),C.minX=i,C.minY=n,C.viewBoxWidth=r,C.viewBoxHeight=a,y?(C.width=r,C.height=a):(C.width=s(u),C.height=s(f),c=C.width/r,d=C.height/a),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(d=c=c>d?d:c),"slice"===p.meetOrSlice&&(d=c=c>d?c:d),S=C.width-r*c,b=C.height-a*c,"Mid"===p.alignX&&(S/=2),"Mid"===p.alignY&&(b/=2),"Min"===p.alignX&&(S=0),"Min"===p.alignY&&(b=0)),1===c&&1===d&&0===i&&0===n&&0===g&&0===m)return C;if((g||m)&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") "),o=E+" matrix("+c+" 0 0 "+d+" "+(i*c+S)+" "+(n*d+b)+") ","svg"===t.nodeName){for(l=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)l.appendChild(t.firstChild);t.appendChild(l)}else(l=t).removeAttribute("x"),l.removeAttribute("y"),o=l.getAttribute("transform")+o;return l.setAttribute("transform",o),C}function w(t,e){var i="xlink:href",n=_(t,e.getAttribute(i).slice(1));if(n&&n.getAttribute(i)&&w(t,n),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(t){n&&!e.hasAttribute(t)&&n.hasAttribute(t)&&e.setAttribute(t,n.getAttribute(t))})),!e.children.length)for(var r=n.cloneNode(!0);r.firstChild;)e.appendChild(r.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,r,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),n=0;i.length&&nt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,n,r,s){var a,o=(s.x-r.x)*(t.y-r.y)-(s.y-r.y)*(t.x-r.x),l=(n.x-t.x)*(t.y-r.y)-(n.y-t.y)*(t.x-r.x),h=(s.y-r.y)*(n.x-t.x)-(s.x-r.x)*(n.y-t.y);if(0!==h){var c=o/h,d=l/h;0<=c&&c<=1&&0<=d&&d<=1?(a=new i("Intersection")).appendPoint(new e.Point(t.x+c*(n.x-t.x),t.y+c*(n.y-t.y))):a=new i}else a=new i(0===o||0===l?"Coincident":"Parallel");return a},e.Intersection.intersectLinePolygon=function(t,e,n){var r,s,a,o,l=new i,h=n.length;for(o=0;o0&&(l.status="Intersection"),l},e.Intersection.intersectPolygonPolygon=function(t,e){var n,r=new i,s=t.length;for(n=0;n0&&(r.status="Intersection"),r},e.Intersection.intersectPolygonRectangle=function(t,n,r){var s=n.min(r),a=n.max(r),o=new e.Point(a.x,s.y),l=new e.Point(s.x,a.y),h=i.intersectLinePolygon(s,o,t),c=i.intersectLinePolygon(o,a,t),d=i.intersectLinePolygon(a,l,t),u=i.intersectLinePolygon(l,s,t),f=new i;return f.appendPoints(h.points),f.appendPoints(c.points),f.appendPoints(d.points),f.appendPoints(u.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function n(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,n){t/=255,i/=255,n/=255;var r,s,a,o=e.util.array.max([t,i,n]),l=e.util.array.min([t,i,n]);if(a=(o+l)/2,o===l)r=s=0;else{var h=o-l;switch(s=a>.5?h/(2-o-l):h/(o+l),o){case t:r=(i-n)/h+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+d(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var n=i.transform.target,r=n.canvas,s=e.util.object.clone(i);s.target=n,r&&r.fire("object:"+t,s),n.fire(t,i)}function m(t,e){var i=e.canvas,n=t[i.uniScaleKey];return i.uniformScaling&&!n||!i.uniformScaling&&n}function p(t){return t.originX===h&&t.originY===h}function _(t,e,i){var n=t.lockScalingX,r=t.lockScalingY;return!((!n||!r)&&(e||!n&&!r||!i)&&(!n||"x"!==e)&&(!r||"y"!==e))}function v(t,e,i,n){return{e:t,transform:e,pointer:{x:i,y:n}}}function y(t){return function(e,i,n,r){var s=i.target,a=s.getCenterPoint(),o=s.translateToOriginPoint(a,i.originX,i.originY),l=t(e,i,n,r);return s.setPositionByOrigin(o,i.originX,i.originY),l}}function w(t,e){return function(i,n,r,s){var a=e(i,n,r,s);return a&&g(t,v(i,n,r,s)),a}}function C(t,i,n,r,s){var a=t.target,o=a.controls[t.corner],l=a.canvas.getZoom(),h=a.padding/l,c=a.toLocalPoint(new e.Point(r,s),i,n);return c.x>=h&&(c.x-=h),c.x<=-h&&(c.x+=h),c.y>=h&&(c.y-=h),c.y<=h&&(c.y+=h),c.x-=o.offsetX,c.y-=o.offsetY,c}function E(t){return t.flipX!==t.flipY}function S(t,e,i,n,r){if(0!==t[e]){var s=r/t._getTransformedDimensions()[n]*t[i];t.set(i,s)}}function b(t,e,i,n){var r,h=e.target,c=h._getTransformedDimensions(0,h.skewY),u=C(e,e.originX,e.originY,i,n),f=Math.abs(2*u.x)-c.x,g=h.skewX;f<2?r=0:(r=d(Math.atan2(f/h.scaleX,c.y/h.scaleY)),e.originX===s&&e.originY===l&&(r=-r),e.originX===o&&e.originY===a&&(r=-r),E(h)&&(r=-r));var m=g!==r;if(m){var p=h._getTransformedDimensions().y;h.set("skewX",r),S(h,"skewY","scaleY","y",p)}return m}function T(t,e,i,n){var r,h=e.target,c=h._getTransformedDimensions(h.skewX,0),u=C(e,e.originX,e.originY,i,n),f=Math.abs(2*u.y)-c.y,g=h.skewY;f<2?r=0:(r=d(Math.atan2(f/h.scaleY,c.x/h.scaleX)),e.originX===s&&e.originY===l&&(r=-r),e.originX===o&&e.originY===a&&(r=-r),E(h)&&(r=-r));var m=g!==r;if(m){var p=h._getTransformedDimensions().x;h.set("skewY",r),S(h,"skewX","scaleX","x",p)}return m}function x(t,e,i,n,r){r=r||{};var s,a,o,l,h,d,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=r.by,w=m(t,f),E=_(f,y,w),S=e.gestureScale;if(E)return!1;if(S)a=e.scaleX*S,o=e.scaleY*S;else{if(s=C(e,e.originX,e.originY,i,n),h="y"!==y?u(s.x):1,d="x"!==y?u(s.y):1,e.signX||(e.signX=h),e.signY||(e.signY=d),f.lockScalingFlip&&(e.signX!==h||e.signY!==d))return!1;if(l=f._getTransformedDimensions(),w&&!y){var b=Math.abs(s.x)+Math.abs(s.y),T=e.original,x=b/(Math.abs(l.x*T.scaleX/f.scaleX)+Math.abs(l.y*T.scaleY/f.scaleY));a=T.scaleX*x,o=T.scaleY*x}else a=Math.abs(s.x*f.scaleX/l.x),o=Math.abs(s.y*f.scaleY/l.y);p(e)&&(a*=2,o*=2),e.signX!==h&&"y"!==y&&(e.originX=c[e.originX],a*=-1,e.signX=h),e.signY!==d&&"x"!==y&&(e.originY=c[e.originY],o*=-1,e.signY=d)}var I=f.scaleX,O=f.scaleY;return y?("x"===y&&f.set("scaleX",a),"y"===y&&f.set("scaleY",o)):(!g&&f.set("scaleX",a),!v&&f.set("scaleY",o)),I!==f.scaleX||O!==f.scaleY}r.scaleCursorStyleHandler=function(t,e,n){var r=m(t,n),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(n,s,r))return"not-allowed";var a=f(n,e);return i[a]+"-resize"},r.skewCursorStyleHandler=function(t,e,i){var r="not-allowed";if(0!==e.x&&i.lockSkewingY)return r;if(0!==e.y&&i.lockSkewingX)return r;var s=f(i,e)%4;return n[s]+"-resize"},r.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?r.skewCursorStyleHandler(t,e,i):r.scaleCursorStyleHandler(t,e,i)},r.rotationWithSnapping=w("rotating",y((function(t,e,i,n){var r=e,s=r.target,a=s.translateToOriginPoint(s.getCenterPoint(),r.originX,r.originY);if(s.lockRotation)return!1;var o,l=Math.atan2(r.ey-a.y,r.ex-a.x),h=Math.atan2(n-a.y,i-a.x),c=d(h-l+r.theta);if(s.snapAngle>0){var u=s.snapAngle,f=s.snapThreshold||u,g=Math.ceil(c/u)*u,m=Math.floor(c/u)*u;Math.abs(c-m)0?s:o:(c>0&&(r=d===a?s:o),c<0&&(r=d===a?o:s),E(l)&&(r=r===s?o:s)),e.originX=r,w("skewing",y(b))(t,e,i,n))},r.skewHandlerY=function(t,e,i,n){var r,o=e.target,c=o.skewY,d=e.originX;return!o.lockSkewingY&&(0===c?r=C(e,h,h,i,n).y>0?a:l:(c>0&&(r=d===s?a:l),c<0&&(r=d===s?l:a),E(o)&&(r=r===a?l:a)),e.originY=r,w("skewing",y(T))(t,e,i,n))},r.dragHandler=function(t,e,i,n){var r=e.target,s=i-e.offsetX,a=n-e.offsetY,o=!r.get("lockMovementX")&&r.left!==s,l=!r.get("lockMovementY")&&r.top!==a;return o&&r.set("left",s),l&&r.set("top",a),(o||l)&&g("moving",v(t,e,i,n)),o||l},r.scaleOrSkewActionName=function(t,e,i){var n=t[i.canvas.altActionKey];return 0===e.x?n?"skewX":"scaleY":0===e.y?n?"skewY":"scaleX":void 0},r.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},r.fireEvent=g,r.wrapWithFixedAnchor=y,r.wrapWithFireEvent=w,r.getLocalPoint=C,e.controlsUtils=r}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,n=e.controlsUtils;n.renderCircleControl=function(t,e,i,n,r){n=n||{};var s,a=this.sizeX||n.cornerSize||r.cornerSize,o=this.sizeY||n.cornerSize||r.cornerSize,l=void 0!==n.transparentCorners?n.transparentCorners:r.transparentCorners,h=l?"stroke":"fill",c=!l&&(n.cornerStrokeColor||r.cornerStrokeColor),d=e,u=i;t.save(),t.fillStyle=n.cornerColor||r.cornerColor,t.strokeStyle=n.cornerStrokeColor||r.cornerStrokeColor,a>o?(s=a,t.scale(1,o/a),u=i*a/o):o>a?(s=o,t.scale(a/o,1),d=e*o/a):s=a,t.lineWidth=1,t.beginPath(),t.arc(d,u,s/2,0,2*Math.PI,!1),t[h](),c&&t.stroke(),t.restore()},n.renderSquareControl=function(t,e,n,r,s){r=r||{};var a=this.sizeX||r.cornerSize||s.cornerSize,o=this.sizeY||r.cornerSize||s.cornerSize,l=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,h=l?"stroke":"fill",c=!l&&(r.cornerStrokeColor||s.cornerStrokeColor),d=a/2,u=o/2;t.save(),t.fillStyle=r.cornerColor||s.cornerColor,t.strokeStyle=r.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,n),t.rotate(i(s.angle)),t[h+"Rect"](-d,-u,a,o),c&&t.strokeRect(-d,-u,a,o),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,n,r,s){var a,o,l,h,c=s?this.touchSizeX:this.sizeX,d=s?this.touchSizeY:this.sizeY;if(c&&d&&c!==d){var u=Math.atan2(d,c),f=Math.sqrt(c*c+d*d)/2,g=u-e.util.degreesToRadians(t),m=Math.PI/2-u-e.util.degreesToRadians(t);a=f*e.util.cos(g),o=f*e.util.sin(g),l=f*e.util.cos(m),h=f*e.util.sin(m)}else f=.7071067812*(c&&d?c:i),g=e.util.degreesToRadians(45-t),a=l=f*e.util.cos(g),o=h=f*e.util.sin(g);return{tl:{x:n-h,y:r-l},tr:{x:n+a,y:r-o},bl:{x:n-a,y:r+o},br:{x:n+h,y:r+l}}},render:function(t,i,n,r,s){"circle"===((r=r||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,n,r,s):e.controlsUtils.renderSquareControl.call(this,t,i,n,r,s)}}}(e),function(){function t(t,e){var i,n,r,s,a=t.getAttribute("style"),o=t.getAttribute("offset")||0;if(o=(o=parseFloat(o)/(/%$/.test(o)?100:1))<0?0:o>1?1:o,a){var l=a.split(/\s*;\s*/);for(""===l[l.length-1]&&l.pop(),s=l.length;s--;){var h=l[s].split(/\s*:\s*/),c=h[0].trim(),d=h[1].trim();"stop-color"===c?i=d:"stop-opacity"===c&&(r=d)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),r||(r=t.getAttribute("stop-opacity")),n=(i=new b.Color(i)).getAlpha(),r=isNaN(parseFloat(r))?1:parseFloat(r),r*=n*e,{offset:o,color:i.toRgb(),opacity:r}}var e=b.util.object.clone;b.Gradient=b.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach((function(e){i[e]=t[e]})),this.id?this.id+="_"+b.Object.__uid++:this.id=b.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new b.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return b.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var n,r,s,a,o=e(this.coords,!0),l=(i=i||{},e(this.colorStops,!0)),h=o.r1>o.r2,c=this.gradientTransform?this.gradientTransform.concat():b.iMatrix.concat(),d=-this.offsetX,u=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(l.sort((function(t,e){return t.offset-e.offset})),"objectBoundingBox"===g?(d/=t.width,u/=t.height):(d+=t.width/2,u+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(d-=t.pathOffset.x,u-=t.pathOffset.y),c[4]-=d,c[5]-=u,a='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',a+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+b.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(h)for((l=l.concat()).reverse(),n=0,r=l.length;n0){var p=m/Math.max(o.r1,o.r2);for(n=0,r=l.length;n\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,n,r=b.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(r.x1,r.y1,r.x2,r.y2):"radial"===this.type&&(e=t.createRadialGradient(r.x1,r.y1,r.r1,r.x2,r.y2,r.r2)),i=0,n=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var a,o,l,h,c=e.getElementsByTagName("stop"),d="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",u=e.getAttribute("gradientTransform")||"",f=[],g=0,m=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(a="linear",o=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(a="radial",o=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),l=c.length;l--;)f.push(t(c[l],s));return h=b.parseTransformAttribute(u),function(t,e,i,n){var r,s;Object.keys(e).forEach((function(t){"Infinity"===(r=e[t])?s=1:"-Infinity"===r?s=0:(s=parseFloat(e[t],10),"string"==typeof r&&/^(\d+\.\d+)%|(\d+)%$/.test(r)&&(s*=.01,"pixels"===n&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s}))}(0,o,r,d),"pixels"===d&&(g=-i.left,m=-i.top),new b.Gradient({id:e.getAttribute("id"),type:a,coords:o,colorStops:f,gradientUnits:d,gradientTransform:h,offsetX:g,offsetY:m})}})}(),_=b.util.toFixed,b.Pattern=b.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=b.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=b.util.createImage(),b.util.loadImage(t.source,(function(t,n){i.source=t,e&&e(i,n)}),null,this.crossOrigin)}},toObject:function(t){var e,i,n=b.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:_(this.offsetX,n),offsetY:_(this.offsetY,n),patternTransform:this.patternTransform?this.patternTransform.concat():null},b.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,n=e.height/t.height,r=this.offsetX/t.width,s=this.offsetY/t.height,a="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(n=1,s&&(n+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,r&&(i+=Math.abs(r))),e.src?a=e.src:e.toDataURL&&(a=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),n=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(n[1],10)||0,offsetY:parseFloat(n[2],10)||0,blur:parseFloat(n[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var n=40,r=40,s=e.Object.NUM_FRACTION_DIGITS,a=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),o=new e.Color(this.color);return t.width&&t.height&&(n=100*i((Math.abs(a.x)+this.blur)/t.width,s)+20,r=100*i((Math.abs(a.y)+this.blur)/t.height,s)+20),t.flipX&&(a.x*=-1),t.flipY&&(a.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(e){this[e]!==i[e]&&(t[e]=this[e])}),this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(b.StaticCanvas)b.warn("fabric.StaticCanvas is already defined.");else{var t=b.util.object.extend,e=b.util.getElementOffset,i=b.util.removeFromArray,n=b.util.toFixed,r=b.util.transformPoint,s=b.util.invertTransform,a=b.util.getNodeCanvas,o=b.util.createCanvasElement,l=new Error("Could not initialize `canvas` element");b.StaticCanvas=b.util.createClass(b.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:b.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return b.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,b.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=b.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,n){return"string"==typeof e?b.util.loadImage(e,(function(e,r){if(e){var s=new b.Image(e,n);this[t]=s,s.canvas=this}i&&i(e,r)}),this,n&&n.crossOrigin):(n&&e.setOptions(n),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=o();if(!t)throw l;if(t.style||(t.style={}),void 0===t.getContext)throw l;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=b.util.getById(t)||this._createCanvasElement(),b.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var n in e=e||{},t)i=t[n],e.cssOnly||(this._setBackstoreDimension(n,t[n]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(n,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,n,r=this._activeObject,s=this.backgroundImage,a=this.overlayImage;for(this.viewportTransform=t,i=0,n=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,r=e.width||this.width,s=e.height||this.height,a='viewBox="0 0 '+this.width+" "+this.height+'" ',o=b.Object.NUM_FRACTION_DIGITS;e.viewBox?a='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,a='viewBox="'+n(-i[4]/i[0],o)+" "+n(-i[5]/i[3],o)+" "+n(this.width/i[0],o)+" "+n(this.height/i[3],o)+'" '),t.push("\n',"Created with Fabric.js ",b.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+b.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map((function(e){var i=t[e+"Color"];if(i&&i.toLive){var n=t[e+"Vpt"],r=t.viewportTransform,s={width:t.width/(n?r[0]:1),height:t.height/(n?r[3]:1)};return i.toSVG(s,{additionalTransform:n?b.util.matrixToSVG(r):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,n,r,s,a,o,l="",h={},c=b.fontPaths,d=[];for(this._objects.forEach((function t(e){d.push(e),e._objects&&e._objects.forEach(t)})),a=0,o=d.length;a',"\n",l,"","\n"].join("")),l},_setSVGObjects:function(t,e){var i,n,r,s=this._objects;for(n=0,r=s.length;n\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(r=s._objects).length;e--;)n=r[e],i(this._objects,n),this._objects.unshift(n);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(r=s._objects,e=0;e0+h&&(a=s-1,i(this._objects,r),this._objects.splice(a,0,r)),h++;else 0!==(s=this._objects.indexOf(t))&&(a=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(a,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var n,r;if(i){for(n=e,r=e-1;r>=0;--r)if(t.intersectsWithObject(this._objects[r])||t.isContainedWithinObject(this._objects[r])||this._objects[r].isContainedWithinObject(t)){n=r;break}}else n=e-1;return n},bringForward:function(t,e){if(!t)return this;var n,r,s,a,o,l=this._activeObject,h=0;if(t===l&&"activeSelection"===t.type)for(n=(o=l._objects).length;n--;)r=o[n],(s=this._objects.indexOf(r))"}}),t(b.StaticCanvas.prototype,b.Observable),t(b.StaticCanvas.prototype,b.Collection),t(b.StaticCanvas.prototype,b.DataURLExporter),t(b.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=o();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),b.StaticCanvas.prototype.toJSON=b.StaticCanvas.prototype.toObject,b.isLikelyNode&&(b.StaticCanvas.prototype.createPNGStream=function(){var t=a(this.lowerCanvasEl);return t&&t.createPNGStream()},b.StaticCanvas.prototype.createJPEGStream=function(t){var e=a(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),b.BaseBrush=b.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,n=t.getZoom();t&&t._isRetinaScaling()&&(n*=b.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*n,i.shadowOffsetX=e.offsetX*n,i.shadowOffsetY=e.offsetY*n}},needsFullRender:function(){return new b.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),b.PencilBrush=b.util.createClass(b.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var n=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,n.x,n.y),n},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,n=i.length,r=this.canvas.contextTop;this._saveAndTransform(r),this.oldEnd&&(r.beginPath(),r.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(r,i[n-2],i[n-1],!0),r.stroke(),r.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new b.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new b.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,n=this._points[0],r=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&n.x===r.x&&n.y===r.y){var s=this.width/1e3;n=new b.Point(n.x,n.y),r=new b.Point(r.x,r.y),n.x-=s,r.x+=s}for(t.moveTo(n.x,n.y),e=1,i=this._points.length;e=r&&(a=t[i],o.push(a));return o.push(t[s]),o},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),b.CircleBrush=b.util.createClass(b.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,n=this.points;for(this._saveAndTransform(i),t=0,e=n.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var r=0,s=this._objects.length;r1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),n=b.util.invertTransform(i),r=this.restorePointerVpt(e);return b.util.transformPoint(r,n)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var n=this._normalizePointer(t,{x:e,y:i}),r=Math.max(t.cacheTranslationX+n.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+n.y*t.zoomY,0);return b.util.isTransparent(t._cacheContext,Math.round(r),Math.round(s),this.targetFindTolerance)}var a=this.contextCache,o=t.selectionBackgroundColor,l=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(a),a.save(),a.transform(l[0],l[1],l[2],l[3],l[4],l[5]),t.render(a),a.restore(),t.selectionBackgroundColor=o,b.util.isTransparent(a,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(e){return!0===t[e]})):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),n=this._activeObject;return!e||e&&n&&i.length>1&&-1===i.indexOf(e)&&n!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&n&&n!==e},_shouldCenterTransform:function(t,e,i){var n;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?n=this.centeredScaling||t.centeredScaling:"rotate"===e&&(n=this.centeredRotation||t.centeredRotation),n?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,n){if(!e||!t)return"drag";var r=n.controls[e];return r.getActionName(i,r,n)},_setupCurrentTransform:function(t,i,n){if(i){var r=this.getPointer(t),s=i.__corner,a=i.controls[s],o=n&&s?a.getActionHandler(t,i,a):b.controlsUtils.dragHandler,l=this._getActionFromCorner(n,s,t,i),h=this._getOriginFromCorner(i,s),c=t[this.centeredKey],d={target:i,action:l,actionHandler:o,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:r.x-i.left,offsetY:r.y-i.top,originX:h.x,originY:h.y,ex:r.x,ey:r.y,lastX:r.x,lastY:r.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:b.util.saveObjectTransform(i)};this._shouldCenterTransform(i,l,c)&&(d.originX="center",d.originY="center"),d.original.originX=h.x,d.original.originY=h.y,this._currentTransform=d,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new b.Point(e.ex,e.ey),n=b.util.transformPoint(i,this.viewportTransform),r=new b.Point(e.ex+e.left,e.ey+e.top),s=b.util.transformPoint(r,this.viewportTransform),a=Math.min(n.x,s.x),o=Math.min(n.y,s.y),l=Math.max(n.x,s.x),h=Math.max(n.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(a,o,l-a,h-o)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,a+=c,o+=c,l-=c,h-=c,b.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(a,o,l-a,h-o))},findTarget:function(t,e){if(!this.skipTargetFind){var n,r,s=this.getPointer(t,!0),a=this._activeObject,o=this.getActiveObjects(),l=i(t),h=o.length>1&&!e||1===o.length;if(this.targets=[],h&&a._findTargetCorner(s,l))return a;if(o.length>1&&!e&&a===this._searchPossibleTargets([a],s))return a;if(1===o.length&&a===this._searchPossibleTargets([a],s)){if(!this.preserveObjectStacking)return a;n=a,r=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&n&&c!==n&&(c=n,this.targets=r),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,n,r=t.length;r--;){var s=t[r],a=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(a,s,e)){(i=t[r]).subTargetCheck&&i instanceof b.Group&&(n=this._searchPossibleTargets(i._objects,e))&&this.targets.push(n);break}}return i},restorePointerVpt:function(t){return b.util.transformPoint(t,b.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var n,r=t(e),s=this.upperCanvasEl,a=s.getBoundingClientRect(),o=a.width||0,l=a.height||0;o&&l||("top"in a&&"bottom"in a&&(l=Math.abs(a.top-a.bottom)),"right"in a&&"left"in a&&(o=Math.abs(a.right-a.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,i||(r=this.restorePointerVpt(r));var h=this.getRetinaScaling();return 1!==h&&(r.x/=h,r.y/=h),n=0===o||0===l?{width:1,height:1}:{width:s.width/o,height:s.height/l},{x:r.x*n.width,y:r.y*n.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),b.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=b.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),b.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),b.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;b.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,b.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,n=this.getActiveObjects(),r=[],s=[];t.forEach((function(t){-1===n.indexOf(t)&&(i=!0,t.fire("deselected",{e,target:t}),s.push(t))})),n.forEach((function(n){-1===t.indexOf(n)&&(i=!0,n.fire("selected",{e,target:n}),r.push(n))})),t.length>0&&n.length>0?i&&this.fire("selection:updated",{e,selected:r,deselected:s}):n.length>0?this.fire("selection:created",{e,selected:r}):t.length>0&&this.fire("selection:cleared",{e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){b.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,b.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(t),r=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,n),r},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){e[i]=t[i]})),b.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,n)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),b.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),b.StaticCanvas)"prototype"!==n&&(b.Canvas[n]=b.StaticCanvas[n])}(),function(){var t=b.util.addListener,e=b.util.removeListener,i={passive:!1};function n(t,e){return t.button&&t.button===e-1}b.util.object.extend(b.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var n=this.upperCanvasEl,r=this._getEventPrefix();t(b.window,"resize",this._onResize),t(n,r+"down",this._onMouseDown),t(n,r+"move",this._onMouseMove,i),t(n,r+"out",this._onMouseOut),t(n,r+"enter",this._onMouseEnter),t(n,"wheel",this._onMouseWheel),t(n,"contextmenu",this._onContextMenu),t(n,"dblclick",this._onDoubleClick),t(n,"dragover",this._onDragOver),t(n,"dragenter",this._onDragEnter),t(n,"dragleave",this._onDragLeave),t(n,"drop",this._onDrop),this.enablePointerEvents||t(n,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](n,"gesture",this._onGesture),eventjs[e](n,"drag",this._onDrag),eventjs[e](n,"orientation",this._onOrientationChange),eventjs[e](n,"shake",this._onShake),eventjs[e](n,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(b.document,t+"up",this._onMouseUp),e(b.document,"touchend",this._onTouchEnd,i),e(b.document,t+"move",this._onMouseMove,i),e(b.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach((function(n){i.fire("mouse:out",{target:e,e:t}),n&&e.fire("mouseout",{e:t})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(t){t.isEditing&&t.hiddenTextarea.focus()}))},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(n){n.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(n)),this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();t(b.document,"touchend",this._onTouchEnd,i),t(b.document,"touchmove",this._onMouseMove,i),e(r,s+"down",this._onMouseDown)},_onMouseDown:function(n){this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();e(r,s+"move",this._onMouseMove,i),t(b.document,s+"up",this._onMouseUp),t(b.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(n){if(!(n.touches.length>0)){this.__onMouseUp(n),this._resetTransformEventData(),this.mainTouchId=null;var r=this._getEventPrefix();e(b.document,"touchend",this._onTouchEnd,i),e(b.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){t(s.upperCanvasEl,r+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(n){this.__onMouseUp(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(n)&&(e(b.document,s+"up",this._onMouseUp),e(b.document,s+"move",this._onMouseMove,i),t(r,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,r=this._groupSelector,s=!1,a=!r||0===r.left&&0===r.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),n(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,a);else{if(n(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,a),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!a){var o=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!o&&e===this._activeObject)}var l,h;if(e){if(l=e._findTargetCorner(this.getPointer(t,!0),b.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[l],d=c&&c.getMouseUpHandler(t,e,c);d&&d(t,i,(h=this.getPointer(t)).x,h.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==l)){var u=i.target&&i.target.controls[i.corner],f=u&&u.getMouseUpHandler(t,e,c);h=h||this.getPointer(t),f&&f(t,i,h.x,h.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,a),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():a||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),n=this.targets,r={e,target:i,subTargets:n};if(this.fire(t,r),i&&i.fire(t,r),!n)return i;for(var s=0;s1&&(e=new b.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],n=this._groupSelector.ex,r=this._groupSelector.ey,s=n+this._groupSelector.left,a=r+this._groupSelector.top,o=new b.Point(v(n,s),v(r,a)),l=new b.Point(y(n,s),y(r,a)),h=!this.selectionFullyContained,c=n===s&&r===a,d=this._objects.length;d--&&!((e=this._objects[d])&&e.selectable&&e.visible&&(h&&e.intersectsWithRect(o,l,!0)||e.isContainedWithinRect(o,l,!0)||h&&e.containsPoint(o,null,!0)||h&&e.containsPoint(l,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter((function(e){return!e.onSelect({e:t})}))),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),b.util.object.extend(b.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,n=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),r=this.toCanvasElement(n,t);return b.util.toDataURL(r,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,n=(e.height||this.height)*t,r=this.getZoom(),s=this.width,a=this.height,o=r*t,l=this.viewportTransform,h=(l[4]-(e.left||0))*t,c=(l[5]-(e.top||0))*t,d=this.interactive,u=[o,0,0,o,h,c],f=this.enableRetinaScaling,g=b.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=n,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=u,this.width=i,this.height=n,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=l,this.width=s,this.height=a,this.calcViewportBoundaries(),this.interactive=d,this.enableRetinaScaling=f,this.contextTop=m,g}}),b.util.object.extend(b.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var n="string"==typeof t?JSON.parse(t):b.util.object.clone(t),r=this,s=n.clipPath,a=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete n.clipPath,this._enlivenObjects(n.objects,(function(t){r.clear(),r._setBgOverlay(n,(function(){s?r._enlivenObjects([s],(function(i){r.clipPath=i[0],r.__setupCanvas.call(r,n,t,a,e)})):r.__setupCanvas.call(r,n,t,a,e)}))}),i),this}},__setupCanvas:function(t,e,i,n){var r=this;e.forEach((function(t,e){r.insertAt(t,e)})),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),n&&n()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var n=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,n),this.__setBgOverlay("overlayImage",t.overlayImage,i,n),this.__setBgOverlay("backgroundColor",t.background,i,n),this.__setBgOverlay("overlayColor",t.overlay,i,n)}else e&&e()},__setBgOverlay:function(t,e,i,n){var r=this;if(!e)return i[t]=!0,void(n&&n());"backgroundImage"===t||"overlayImage"===t?b.util.enlivenObjects([e],(function(e){r[t]=e[0],i[t]=!0,n&&n()})):this["set"+b.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,n&&n()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?b.util.enlivenObjects(t,(function(t){e&&e(t)}),null,i):e&&e([])},_toDataURL:function(t,e){this.clone((function(i){e(i.toDataURL(t))}))},_toDataURLWithMultiplier:function(t,e,i){this.clone((function(n){i(n.toDataURLWithMultiplier(t,e))}))},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData((function(e){e.loadFromJSON(i,(function(){t&&t(e)}))}))},cloneWithoutData:function(t){var e=b.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new b.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),t&&t(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r=e.util.toFixed,s=e.util.string.capitalize,a=e.util.degreesToRadians,o=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:o,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,n=t.width,r=t.height,s=e.maxCacheSideLimit,a=e.minCacheSideLimit;if(n<=s&&r<=s&&n*r<=i)return nc&&(t.zoomX/=n/c,t.width=c,t.capped=!0),r>d&&(t.zoomY/=r/d,t.height=d,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,n=e.y*t.scaleY/this.scaleY;return{width:i+2,height:n+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:n}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,n=t._currentTransform.action;if(this===i&&n.slice&&"scale"===n.slice(0,5))return!1}var r,s,a=this._cacheCanvas,o=this._limitCacheSize(this._getCacheCanvasDimensions()),l=e.minCacheSideLimit,h=o.width,c=o.height,d=o.zoomX,u=o.zoomY,f=h!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==d||this.zoomY!==u,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,C=h>y||c>w;v=C||(h<.9*y||c<.9*w)&&y>l&&w>l,C&&!o.capped&&(h>l||c>l)&&(p=.1*h,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(a.width=Math.ceil(h+p),a.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,a.width,a.height)),r=o.x/2,s=o.y/2,this.cacheTranslationX=Math.round(a.width/2-r)+r,this.cacheTranslationY=Math.round(a.height/2-s)+s,this.cacheWidth=h,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(d,u),this.zoomX=d,this.zoomY=u,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,n={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:r(this.left,i),top:r(this.top,i),width:r(this.width,i),height:r(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:r(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:r(this.strokeMiterLimit,i),scaleX:r(this.scaleX,i),scaleY:r(this.scaleY,i),angle:r(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:r(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:r(this.skewX,i),skewY:r(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(n.clipPath=this.clipPath.toObject(t),n.clipPath.inverted=this.clipPath.inverted,n.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,n,t),this.includeDefaultValues||(n=this._removeDefaultValues(n)),n},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach((function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])})),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var n=this.canvas.getZoom(),r=this.canvas.getRetinaScaling();e*=n*r,i*=n*r}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var n="scaleX"===t||"scaleY"===t,r=this[t]!==i,s=!1;return n&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,r&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var n=e.util.invertTransform(this.calcTransformMatrix());t.transform(n[0],n[1],n[2],n[3],n[4],n[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=n},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var n,r,s,o=this.getViewportTransform(),l=this.calcTransformMatrix();r=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,l=e.util.multiplyTransformMatrices(o,l),n=e.util.qrDecompose(l),t.save(),t.translate(n.translateX,n.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(n.angle-=180),t.rotate(a(this.group?n.angle:this.angle)),i.forActiveSelection||this.group?r&&this.drawBordersInGroup(t,n,i):r&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,n=this.shadow,r=this.canvas,s=r&&r.viewportTransform[0]||1,a=r&&r.viewportTransform[3]||1;i=n.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),r&&r._isRetinaScaling()&&(s*=e.devicePixelRatio,a*=e.devicePixelRatio),t.shadowColor=n.color,t.shadowBlur=n.blur*e.browserShadowBlurConstant*(s+a)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=n.offsetX*s*i.scaleX,t.shadowOffsetY=n.offsetY*a*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,n=-this.width/2+e.offsetX||0,r=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,n,r):t.transform(1,0,0,1,n,r),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:n,offsetY:r}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var n,r=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),a=this.canvas.getRetinaScaling(),o=r.x/this.scaleX/a,l=r.y/this.scaleY/a;s.width=o,s.height=l,(n=s.getContext("2d")).beginPath(),n.moveTo(0,0),n.lineTo(o,0),n.lineTo(o,l),n.lineTo(0,l),n.closePath(),n.translate(o/2,l/2),n.scale(r.zoomX/this.scaleX/a,r.zoomY/this.scaleY/a),this._applyPatternGradientTransform(n,i),n.fillStyle=i.toLive(t),n.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(a*this.scaleX/r.zoomX,a*this.scaleY/r.zoomY),t.strokeStyle=n.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var n=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(n,t):e.Object._fromObject("Object",n,t)},cloneAsImage:function(t,i){var n=this.toCanvasElement(i);return t&&t(new e.Image(n)),this},toCanvasElement:function(t){t||(t={});var i=e.util,n=i.saveObjectTransform(this),r=this.group,s=this.shadow,a=Math.abs,o=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var l,h,c,d,u=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(h=g.blur,l=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(a(g.offsetX)+h)*a(l.scaleX),m.y=2*Math.round(a(g.offsetY)+h)*a(l.scaleY)),c=f.width+m.x,d=f.height+m.y,u.width=Math.ceil(c),u.height=Math.ceil(d);var p=new e.StaticCanvas(u,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var _=this.canvas;p.add(this);var v=p.toCanvasElement(o||1,t);return this.shadow=s,this.set("canvas",_),r&&(this.group=r),this.set(n).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var n=new e.Point(i.x,i.y),r=this._getLeftTopCoords();return this.angle&&(n=e.util.rotatePoint(n,r,a(-this.angle))),{x:n.x-r.x,y:n.y-r.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,r,s){var a=e[t];i=n(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],(function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,(function(){var t=s?new a(i[s],i):new a(i);r&&r(t)}))}))},e.Object.__uid=0)}(e),w=b.util.degreesToRadians,C={left:-.5,center:0,right:.5},E={top:-.5,center:0,bottom:.5},b.util.object.extend(b.Object.prototype,{translateToGivenOrigin:function(t,e,i,n,r){var s,a,o,l=t.x,h=t.y;return"string"==typeof e?e=C[e]:e-=.5,"string"==typeof n?n=C[n]:n-=.5,"string"==typeof i?i=E[i]:i-=.5,"string"==typeof r?r=E[r]:r-=.5,a=r-i,((s=n-e)||a)&&(o=this._getTransformedDimensions(),l=t.x+s*o.x,h=t.y+a*o.y),new b.Point(l,h)},translateToCenterPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?b.util.rotatePoint(n,t,w(this.angle)):n},translateToOriginPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?b.util.rotatePoint(n,t,w(this.angle)):n},getCenterPoint:function(){var t=new b.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var n,r,s=this.getCenterPoint();return n=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new b.Point(this.left,this.top),r=new b.Point(t.x,t.y),this.angle&&(r=b.util.rotatePoint(r,s,-w(this.angle))),r.subtractEquals(n)},setPositionByOrigin:function(t,e,i){var n=this.translateToCenterPoint(t,e,i),r=this.translateToOriginPoint(n,this.originX,this.originY);this.set("left",r.x),this.set("top",r.y)},adjustPosition:function(t){var e,i,n=w(this.angle),r=this.getScaledWidth(),s=b.util.cos(n)*r,a=b.util.sin(n)*r;e="string"==typeof this.originX?C[this.originX]:this.originX-.5,i="string"==typeof t?C[t]:t-.5,this.left+=s*(i-e),this.top+=a*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=b.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,n=t.transformPoint;t.object.extend(b.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new b.Point(i.tl.x,i.tl.y),new b.Point(i.tr.x,i.tr.y),new b.Point(i.br.x,i.br.y),new b.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,n){var r=this.getCoords(i,n);return"Intersection"===b.Intersection.intersectPolygonRectangle(r,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===b.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var n=this.getCoords(e,i),r=e?t.aCoords:t.lineCoords,s=0,a=t._getImageLines(r);s<4;s++)if(!t.containsPoint(n[s],a))return!1;return!0},isContainedWithinRect:function(t,e,i,n){var r=this.getBoundingRect(i,n);return r.left>=t.x&&r.left+r.width<=e.x&&r.top>=t.y&&r.top+r.height<=e.y},containsPoint:function(t,e,i,n){var r=this._getCoords(i,n),s=(e=e||this._getImageLines(r),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some((function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y}))||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var n={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(n,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every((function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)}))&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,n,r,s=0;for(var a in e)if(!((r=e[a]).o.y=t.y&&r.d.y>=t.y||(r.o.x===r.d.x&&r.o.x>=t.x?n=r.o.x:(i=(r.d.y-r.o.y)/(r.d.x-r.o.x),n=-(t.y-0*t.x-(r.o.y-i*r.o.x))/(0-i)),n>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var n=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(n)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,n=e.additionalTransform||"",r=[this.getSvgTransform(!0,n),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=r,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,n,r=(e=e||{}).noStyle,s=e.reviver,a=r?"":'style="'+this.getSvgStyles()+'" ',o=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",l=this.clipPath,h=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=l&&l.absolutePositioned,d=this.stroke,u=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return l&&(l.clipPathId="CLIPPATH_"+b.Object.__uid++,n='\n'+l.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[a,h,r?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=i,u&&u.toLive&&g.push(u.toSVG(this)),d&&d.toLive&&g.push(d.toSVG(this)),f&&g.push(f.toSVG(this)),l&&g.push(n),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=b.util.object.extend,e="stateProperties";function i(e,i,n){var r={};n.forEach((function(t){r[t]=e[t]})),t(e[i],r,!0)}function n(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var r=0,s=t.length;r=0;l--)if(r=o[l],this.isControlVisible(r)&&(n=this._getImageLines(e?this.oCoords[r].touchCorner:this.oCoords[r].corner),0!==(i=this._findCrossPoints({x:s,y:a},n))&&i%2==1))return this.__corner=r,r;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),n=this._calculateCurrentDimensions(),r=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/r[0],1/r[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-n.x/2,-n.y/2,n.x,n.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),n=this.borderScaleFactor,r=i.x+n,s=i.y+n,a=void 0!==e.hasControls?e.hasControls:this.hasControls,o=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-r/2,-s/2,r,s),a&&(t.beginPath(),this.forEachControl((function(e,i,n){e.withConnection&&e.getVisibility(n,i)&&(o=!0,t.moveTo(e.x*r,e.y*s),t.lineTo(e.x*r+e.offsetX,e.y*s+e.offsetY))})),o&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var n=b.util.sizeAfterTransform(this.width,this.height,e),r=this.strokeWidth,s=this.strokeUniform,a=this.borderScaleFactor,o=n.x+r*(s?this.canvas.getZoom():e.scaleX)+a,l=n.y+r*(s?this.canvas.getZoom():e.scaleY)+a;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-o/2,-l/2,o,l),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,n,r=this.canvas.getRetinaScaling();return t.setTransform(r,0,0,r,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(r,s,a){n=a.oCoords[s],r.getVisibility(a,s)&&(i&&(n=b.util.transformPoint(n,i)),r.render(t,n.x,n.y,e,a))})),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),b.util.object.extend(b.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxCenterObjectV:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxRemove:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),r()},onComplete:function(){s.remove(t),n()}})}}),b.util.object.extend(b.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],n=[];for(t in arguments[0])i.push(t);for(var r=0,s=i.length;r-1||r&&s.colorProperties.indexOf(r[1])>-1,o=r?this.get(r[0])[r[1]]:this.get(t);"from"in i||(i.from=o),a||(e=~e.indexOf("=")?o+parseFloat(e.replace("=","")):parseFloat(e));var l={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,n){return i.abort.call(s,t,e,n)},onChange:function(e,a,o){r?s[r[0]][r[1]]=e:s.set(t,e),n||i.onChange&&i.onChange(e,a,o)},onComplete:function(t,e,r){n||(s.setCoords(),i.onComplete&&i.onComplete(t,e,r))}};return a?b.util.animateColor(l.startValue,l.endValue,l.duration,l):b.util.animate(l)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,n=t.axis1,r=t.axis2,s=t.dimension,a=e.nearest,o=e.center,l=e.farthest;return function(){switch(this.get(i)){case a:return Math.min(this.get(n),this.get(r));case o:return Math.min(this.get(n),this.get(r))+.5*this.get(s);case l:return Math.max(this.get(n),this.get(r))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==r[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,n=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:n,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,n,r){r=r||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),a=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];n(new e.Line(a,i(s,r)))},e.Line.fromObject=function(t,i){var r=n(t,!0);r.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",r,(function(t){delete t.points,i&&i(t)}),"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,n=(this.endAngle-this.startAngle)%360;if(0===n)t=["\n'];else{var r=i(this.startAngle),s=i(this.endAngle),a=this.radius;t=['180?"1":"0")+" 1"," "+e.util.cos(s)*a+" "+e.util.sin(s)*a,'" ',"COMMON_PARTS"," />\n"]}return t},_render:function(t){t.beginPath(),t.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(t)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(t){return this.radius=t,this.set("width",2*t).set("height",2*t)}}),e.Circle.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),e.Circle.fromElement=function(t,i){var n,r=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(n=r)&&n.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");r.left=(r.left||0)-r.radius,r.top=(r.top||0)-r.radius,i(new e.Circle(r))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var n=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);n.left=(n.left||0)-n.rx,n.top=(n.top||0)-n.ry,i(new e.Ellipse(n))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,n=this.width,r=this.height,s=-this.width/2,a=-this.height/2,o=0!==e||0!==i,l=.4477152502;t.beginPath(),t.moveTo(s+e,a),t.lineTo(s+n-e,a),o&&t.bezierCurveTo(s+n-l*e,a,s+n,a+l*i,s+n,a+i),t.lineTo(s+n,a+r-i),o&&t.bezierCurveTo(s+n,a+r-l*i,s+n-l*e,a+r,s+n-e,a+r),t.lineTo(s+e,a+r),o&&t.bezierCurveTo(s+l*e,a+r,s,a+r-l*i,s,a+r-i),t.lineTo(s,a+i),o&&t.bezierCurveTo(s,a+l*i,s+l*e,a,s+e,a),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,n,r){if(!t)return n(null);r=r||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var a=new e.Rect(i(r?e.util.object.clone(r):{},s));a.visible=a.visible&&a.width>0&&a.height>0,n(a)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.array.min,r=e.util.array.max,s=e.util.toFixed,a=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return a(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),n=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-n,this.height=i.height-n,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+n/2,y:i.top-this.strokeWidth/2+n/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+n/2,y:i.top+this.height/2+n/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=n(t,"x")||0,i=n(t,"y")||0;return{left:e,top:i,width:(r(t,"x")||0)-e,height:(r(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,n=this.pathOffset.y,r=e.Object.NUM_FRACTION_DIGITS,a=0,o=this.points.length;a\n']},commonRender:function(t){var e,i=this.points.length,n=this.pathOffset.x,r=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-n,this.points[0].y-r);for(var s=0;s"},toObject:function(t){return r(this.callSuper("toObject",t),{path:this.path.map((function(t){return t.slice()}))})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+a(-this.pathOffset.x,t)+", "+a(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,r,s=[],a=[],o=0,l=0,h=0,c=0,d=0,u=this.path.length;d"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var n=this._objects.length;if(this.useSetOnGroup)for(;n--;)this._objects[n].setOnGroup(t,i);if("canvas"===t)for(;n--;)this._objects[n]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,n=this._objects.filter((function(t){return!t.excludeFromExport})).map((function(e){var n=e.includeDefaultValues;e.includeDefaultValues=i;var r=e.toObject(t);return e.includeDefaultValues=n,r})),r=e.Object.prototype.toObject.call(this,t);return r.objects=n,r},toDatalessObject:function(t){var i,n=this.sourcePath;if(n)i=n;else{var r=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=r;var n=e.toDatalessObject(t);return e.includeDefaultValues=i,n}))}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,n=this._objects.length;i\n"],i=0,n=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,n=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var n=0,r=this._objects.length;n\n','\t\n',"\n"),a=' clip-path="url(#imageCrop_'+l+')" '}if(this.imageSmoothing||(o='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var h=this.fill;this.fill=null,t=["\t\n'],this.fill=h}return"fill"!==this.paintFirst?e.concat(t,i):e.concat(i,t)},getSrc:function(t){var e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src"):e.src:this.src||""},setSrc:function(t,e,i){return b.util.loadImage(t,(function(t,n){this.setElement(t,i),this._setWidthHeight(),e&&e(this,n)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),n=i.scaleX,r=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||n>e&&r>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=n,void(this._lastScaleY=r);b.filterBackend||(b.filterBackend=b.initFilterBackend());var a=b.util.createCanvasElement(),o=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,l=s.width,h=s.height;a.width=l,a.height=h,this._element=a,this._lastScaleX=t.scaleX=n,this._lastScaleY=t.scaleY=r,b.filterBackend.applyFilters([t],s,l,h,this._element,o),this._filterScalingX=a.width/this._originalElement.width,this._filterScalingY=a.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter((function(t){return t&&!t.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,n=e.naturalHeight||e.height;if(this._element===this._originalElement){var r=b.util.createCanvasElement();r.width=i,r.height=n,this._element=r,this._filteredEl=r}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,n),this._lastScaleX=1,this._lastScaleY=1;return b.filterBackend||(b.filterBackend=b.initFilterBackend()),b.filterBackend.applyFilters(t,this._originalElement,i,n,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),b.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,n=this._filterScalingY,r=this.width,s=this.height,a=Math.min,o=Math.max,l=o(this.cropX,0),h=o(this.cropY,0),c=e.naturalWidth||e.width,d=e.naturalHeight||e.height,u=l*i,f=h*n,g=a(r*i,c-u),m=a(s*n,d-f),p=-r/2,_=-s/2,v=a(r,c/i-l),y=a(s,d/n-h);e&&t.drawImage(e,u,f,g,m,p,_,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(b.util.getById(t),e),b.util.addClass(this.getElement(),b.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?b.util.enlivenObjects(t,(function(t){e&&e(t)}),"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=b.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,n=this._element.height,r=1,s=1,a=0,o=0,l=0,h=0,c=this.width,d=this.height,u={width:c,height:d};return!e||"none"===e.alignX&&"none"===e.alignY?(r=c/i,s=d/n):("meet"===e.meetOrSlice&&(t=(c-i*(r=s=b.util.findScaleToFit(this._element,u)))/2,"Min"===e.alignX&&(a=-t),"Max"===e.alignX&&(a=t),t=(d-n*s)/2,"Min"===e.alignY&&(o=-t),"Max"===e.alignY&&(o=t)),"slice"===e.meetOrSlice&&(t=i-c/(r=s=b.util.findScaleToCover(this._element,u)),"Mid"===e.alignX&&(l=t/2),"Max"===e.alignX&&(l=t),t=n-d/s,"Mid"===e.alignY&&(h=t/2),"Max"===e.alignY&&(h=t),i=c/r,n=d/s)),{width:i,height:n,scaleX:r,scaleY:s,offsetLeft:a,offsetTop:o,cropX:l,cropY:h}}}),b.Image.CSS_CANVAS="canvas-img",b.Image.prototype.getSvgSrc=b.Image.prototype.getSrc,b.Image.fromObject=function(t,e){var i=b.util.object.clone(t);b.util.loadImage(i.src,(function(t,n){n?e&&e(null,!0):b.Image.prototype._initFilters.call(i,i.filters,(function(n){i.filters=n||[],b.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(n){i.resizeFilter=n[0],b.util.enlivenObjectEnlivables(i,i,(function(){var n=new b.Image(t,i);e(n,!1)}))}))}))}),null,i.crossOrigin)},b.Image.fromURL=function(t,e,i){b.util.loadImage(t,(function(t,n){e&&e(new b.Image(t,i),n)}),null,i&&i.crossOrigin)},b.Image.ATTRIBUTE_NAMES=b.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),b.Image.fromElement=function(t,i,n){var r=b.parseAttributes(t,b.Image.ATTRIBUTE_NAMES);b.Image.fromURL(r["xlink:href"],i,e(n?b.util.object.clone(n):{},r))})}(e),b.util.object.extend(b.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,n=t.onChange||e,r=this;return b.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){r.rotate(t),n()},onComplete:function(){r.setCoords(),i()}})}}),b.util.object.extend(b.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",n=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(n,i),t.compileShader(n),!!t.getShaderParameter(n,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}b.isWebglSupported=function(e){if(b.isLikelyNode)return!1;e=e||b.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),n=i.getContext("webgl")||i.getContext("experimental-webgl"),r=!1;if(n){b.maxTextureSize=n.getParameter(n.MAX_TEXTURE_SIZE),r=b.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],a=0;a<3;a++)if(t(n,s[a])){b.webGlPrecision=s[a];break}}return this.isSupported=r,r},b.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,n=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var r="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(n&&i&&r&&s){var a=b.util.createCanvasElement(),o=new ArrayBuffer(t*e*4);if(b.forceGLPutImageData)return this.imageBuffer=o,void(this.copyGLTo2D=I);var l,h,c={imageBuffer:o,destinationWidth:t,destinationHeight:e,targetCanvas:a};a.width=t,a.height=e,l=window.performance.now(),x.call(c,this.gl,c),h=window.performance.now()-l,l=window.performance.now(),I.call(c,this.gl,c),h>window.performance.now()-l?(this.imageBuffer=o,this.copyGLTo2D=I):this.copyGLTo2D=x}},createWebGLCanvas:function(t,e){var i=b.util.createCanvasElement();i.width=t,i.height=e;var n={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},r=i.getContext("webgl",n);r||(r=i.getContext("experimental-webgl",n)),r&&(r.clearColor(0,0,0,0),this.canvas=i,this.gl=r)},applyFilters:function(t,e,i,n,r,s){var a,o=this.gl;s&&(a=this.getCachedTexture(s,e));var l={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:n,destinationWidth:i,destinationHeight:n,context:o,sourceTexture:this.createTexture(o,i,n,!a&&e),targetTexture:this.createTexture(o,i,n),originalTexture:a||this.createTexture(o,i,n,!a&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:r},h=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,h),t.forEach((function(t){t&&t.applyTo(l)})),function(t){var e=t.targetCanvas,i=e.width,n=e.height,r=t.destinationWidth,s=t.destinationHeight;i===r&&n===s||(e.width=r,e.height=s)}(l),this.copyGLTo2D(o,l),o.bindTexture(o.TEXTURE_2D,null),o.deleteTexture(l.sourceTexture),o.deleteTexture(l.targetTexture),o.deleteFramebuffer(h),r.getContext("2d").setTransform(1,0,0,1,0,0),l},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,n){var r=t.createTexture();return t.bindTexture(t.TEXTURE_2D,r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),n?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,n):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),r},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:x,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var n=t.getParameter(i.UNMASKED_RENDERER_WEBGL),r=t.getParameter(i.UNMASKED_VENDOR_WEBGL);n&&(e.renderer=n.toLowerCase()),r&&(e.vendor=r.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}b.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,n,r){var s=r.getContext("2d");s.drawImage(e,0,0,i,n);var a={sourceWidth:i,sourceHeight:n,imageData:s.getImageData(0,0,i,n),originalEl:e,originalImageData:s.getImageData(0,0,i,n),canvasEl:r,ctx:s,filterBackend:this};return t.forEach((function(t){t.applyTo(a)})),a.imageData.width===i&&a.imageData.height===n||(r.width=a.imageData.width,r.height=a.imageData.height),s.putImageData(a.imageData,0,0),a}}}(),b.Image=b.Image||{},b.Image.filters=b.Image.filters||{},b.Image.filters.BaseFilter=b.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==b.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+b.webGlPrecision+" float"));var n=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var r=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var s=t.createProgram();if(t.attachShader(s,n),t.attachShader(s,r),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var a=this.getAttributeLocations(t,s),o=this.getUniformLocations(t,s)||{};return o.uStepW=t.getUniformLocation(s,"uStepW"),o.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:a,uniformLocations:o}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var n=e.aPosition,r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,n=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(n.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(n,e,i)),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t.targetTexture,0)):(n.bindFramebuffer(n.FRAMEBUFFER,null),n.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=b.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),b.Image.filters.BaseFilter.fromObject=function(t,e){var i=new b.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.ColorMatrix=n(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,n,r,s,a=t.imageData.data,o=a.length,l=this.matrix,h=this.colorsOnly;for(s=0;s=w||a<0||a>=y||(l=4*(o*y+a),h=p[f*_+u],e+=m[l]*h,i+=m[l+1]*h,n+=m[l+2]*h,S||(r+=m[l+3]*h));E[s]=e,E[s+1]=i,E[s+2]=n,E[s+3]=S?m[s+3]:r}t.imageData=C},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Grayscale=n(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,n=t.imageData.data,r=n.length,s=this.mode;for(e=0;eh[0]&&r>h[1]&&s>h[2]&&n 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,n,r,s,a,o,l,h=t.imageData.data,c=h.length,d=1-this.alpha;i=(l=new e.Color(this.color).getSource())[0]*this.alpha,n=l[1]*this.alpha,r=l[2]*this.alpha;for(var u=0;u=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return o(e)/e*o(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,n=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/n;var r,s=e.width,o=e.height,l=a(s*i),h=a(o*n);"sliceHack"===this.resizeType?r=this.sliceByTwo(t,s,o,l,h):"hermite"===this.resizeType?r=this.hermiteFastResize(t,s,o,l,h):"bilinear"===this.resizeType?r=this.bilinearFiltering(t,s,o,l,h):"lanczos"===this.resizeType&&(r=this.lanczosResize(t,s,o,l,h)),t.imageData=r},sliceByTwo:function(t,i,r,s,a){var o,l,h=t.imageData,c=.5,d=!1,u=!1,f=i*c,g=r*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((o=m.sliceByTwo).width<1.5*i||o.height=e)){L=n(1e3*s(b-C.x)),w[L]||(w[L]={});for(var F=E.y-y;F<=E.y+y;F++)F<0||F>=a||(M=n(1e3*s(F-C.y)),w[L][M]||(w[L][M]=f(r(i(L*p,2)+i(M*_,2))/1e3)),(T=w[L][M])>0&&(I+=T,O+=T*c[x=4*(F*e+b)],A+=T*c[x+1],R+=T*c[x+2],D+=T*c[x+3]))}u[x=4*(S*o+l)]=O/I,u[x+1]=A/I,u[x+2]=R/I,u[x+3]=D/I}return++l1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(T+=y*f[3+(L=4*(D+I*e))],C+=y,f[L+3]<255&&(y=y*f[L+3]/250),E+=y*f[L],S+=y*f[L+1],b+=y*f[L+2],w+=y)}m[v]=E/w,m[v+1]=S/w,m[v+2]=b/w,m[v+3]=T/C}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Contrast=n(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,n=i.length,r=Math.floor(255*this.contrast),s=259*(r+255)/(255*(259-r));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Gamma=n(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,n=this.gamma,r=i.length,s=1/n[0],a=1/n[1],o=1/n[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,r=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=n)}return t},_renderTextLine:function(t,e,i,n,r,s){this._renderChars(t,e,i,n,r,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,n,r,s,a,o,l=t.fillStyle,h=this._getLeftOffset(),c=this._getTopOffset(),d=0,u=0,f=this.path,g=0,m=this._textLines.length;g=0:io?d%=o:d<0&&(d+=o),this._setGraphemeOnPath(d,s,a),d+=s.kernedWidth}return{width:l,numOfSpaces:0}},_setGraphemeOnPath:function(t,i,n){var r=t+i.kernedWidth/2,s=this.path,a=e.util.getPointOnPath(s.path,r,s.segmentsInfo);i.renderLeft=a.x-n.x,i.renderTop=a.y-n.y,i.angle=a.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,n,r){var s,a=this.getCompleteStyleDeclaration(e,i),o=n?this.getCompleteStyleDeclaration(e,i-1):{},l=this._measureChar(t,a,n,o),h=l.kernedWidth,c=l.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),h+=s);var d={width:c,left:0,height:a.fontSize,kernedWidth:h,deltaY:a.deltaY};if(i>0&&!r){var u=this.__charBounds[e][i-1];d.left=u.left+u.width+l.kernedWidth-l.width}return d},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),n=1,r=e.length;n0){var I=v+s+d;"rtl"===this.direction&&(I=this.width-I-u),h&&_&&(t.fillStyle=_,t.fillRect(I,c+E*n+a,u,this.fontSize/15)),d=f.left,u=f.width,h=g,_=p,n=r,a=o}else u+=f.kernedWidth;I=v+s+d,"rtl"===this.direction&&(I=this.width-I-u),t.fillStyle=p,g&&p&&t.fillRect(I,c+E*n+a,u-C,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var n=t||this,r=this.fontFamily,s=e.Text.genericFonts.indexOf(r.toLowerCase())>-1,a=void 0===r||r.indexOf("'")>-1||r.indexOf(",")>-1||r.indexOf('"')>-1||s?n.fontFamily:'"'+n.fontFamily+'"';return[e.isLikelyNode?n.fontWeight:n.fontStyle,e.isLikelyNode?n.fontStyle:n.fontWeight,i?this.CACHE_FONT_SIZE+"px":n.fontSize+"px",a].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),n=new Array(i.length),r=["\n"],s=[],a=0;a-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}b.IText=b.util.createClass(b.Text,b.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:n.left,topOffset:n.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,n,r,s=0,a=0,o=this.get2DCursorLocation(t);n=o.charIndex,i=o.lineIndex;for(var l=0;l0?a:0)},"rtl"===this.direction&&(r.left*=-1),this.cursorOffsetCache=r,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),n=i.lineIndex,r=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(n,r,"fontSize"),a=this.scaleX*this.canvas.getZoom(),o=this.cursorWidth/a,l=t.topOffset,h=this.getValueOfPropertyAt(n,r,"deltaY");l+=(1-this._fontSizeFraction)*this.getHeightOfLine(n)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(n,r,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-o/2,l+t.top+h,o,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,n=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,r=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),a=this.get2DCursorLocation(n),o=s.lineIndex,l=a.lineIndex,h=s.charIndex<0?0:s.charIndex,c=a.charIndex<0?0:a.charIndex,d=o;d<=l;d++){var u,f=this._getLineLeftOffset(d)||0,g=this.getHeightOfLine(d),m=0,p=0;if(d===o&&(m=this.__charBounds[o][h].left),d>=o&&d1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+C,y,w),t.topOffset+=u}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),b.IText.fromObject=function(e,i){if(t(e),e.styles)for(var n in e.styles)for(var r in e.styles[n])t(e.styles[n][r]);b.Object._fromObject("IText",e,i,"text")}}(),S=b.util.object.clone,b.util.object.extend(b.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",(function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))}))},initRemovedHandler:function(){var t=this;this.on("removed",(function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],b.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))}))},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach((function(t){t.__isMousedown=!1}))},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,n){var r;return r={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){r.isAborted||t[n]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return r.isAborted}}),r},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){e._tick()}),i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&nthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var n=i.slice(0,t),r=b.util.string.graphemeSplit(n).length;if(t===e)return{selectionStart:r,selectionEnd:r};var s=i.slice(t,e);return{selectionStart:r,selectionEnd:r+b.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var n=i.slice(0,t).join("").length;return t===e?{selectionStart:n,selectionEnd:n}:{selectionStart:n,selectionEnd:n+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),n=i.lineIndex,r=i.charIndex,s=this.getValueOfPropertyAt(n,r,"fontSize")*this.lineHeight,a=e.leftOffset,o=this.calcTransformMatrix(),l={x:e.left+a,y:e.top+e.topOffset+s},h=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,d=c.width/h,u=c.height/h,f=d-s,g=u-s,m=c.clientWidth/d,p=c.clientHeight/u;return l=b.util.transformPoint(l,o),(l=b.util.transformPoint(l,this.canvas.viewportTransform)).x*=m,l.y*=p,l.x<0&&(l.x=0),l.x>f&&(l.x=f),l.y<0&&(l.y=0),l.y>g&&(l.y=g),l.x+=this.canvas._offset.left,l.y+=this.canvas._offset.top,{left:l.x+"px",top:l.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,n,r=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),a=r.lineIndex,o=r.charIndex,l=s.lineIndex,h=s.charIndex;if(a!==l){if(this.styles[a])for(i=o;i=h&&(n[c-u]=n[d],delete n[d])}},shiftLineStyles:function(t,e){var i=S(this.styles);for(var n in this.styles){var r=parseInt(n,10);r>t&&(this.styles[r+e]=i[r],i[r-e]||delete this.styles[r])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,n){var r,s={},a=!1,o=this._unwrappedTextLines[t].length===e;for(var l in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(r=this.styles[t][0===e?e:e-1]),this.styles[t]){var h=parseInt(l,10);h>=e&&(a=!0,s[h-e]=this.styles[t][l],o&&0===e||delete this.styles[t][l])}var c=!1;for(a&&!o&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)n&&n[i-1]?this.styles[t+i]={0:S(n[i-1])}:r?this.styles[t+i]={0:S(r)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,n){this.styles||(this.styles={});var r=this.styles[t],s=r?S(r):{};for(var a in i||(i=1),s){var o=parseInt(a,10);o>=e&&(r[o+i]=s[o],s[o-i]||delete r[o])}if(this._forceClearCache=!0,n)for(;i--;)Object.keys(n[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=S(n[i]));else if(r)for(var l=r[e?e-1:1];l&&i--;)this.styles[t][e+i]=S(l)},insertNewStyleBlock:function(t,e,i){for(var n=this.get2DCursorLocation(e,!0),r=[0],s=0,a=0;a0&&(this.insertCharStyleObject(n.lineIndex,n.charIndex,r[0],i),i=i&&i.slice(r[0]+1)),s&&this.insertNewlineStyleObject(n.lineIndex,n.charIndex+r[0],s),a=1;a0?this.insertCharStyleObject(n.lineIndex+a,0,r[a],i):i&&this.styles[n.lineIndex+a]&&i[0]&&(this.styles[n.lineIndex+a][0]=i[0]),i=i&&i.slice(r[a]+1);r[a]>0&&this.insertCharStyleObject(n.lineIndex+a,0,r[a],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),b.util.object.extend(b.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,n=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,n,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),n=0,r=0,s=0,a=0,o=0,l=0,h=this._textLines.length;l0&&(a+=this._textLines[l-1].length+this.missingNewlineOffset(l-1));r=this._getLineLeftOffset(o)*this.scaleX,e=this._textLines[o],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+r);for(var c=0,d=e.length;cs||a<0?0:1);return this.flipX&&(o=r-o),o>this._text.length&&(o=this._text.length),o}}),b.util.object.extend(b.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=b.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):b.document.body.appendChild(this.hiddenTextarea),b.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),b.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),b.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),b.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(b.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,n,r,s,a,o=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,l=this._text.length,h=o.length,c=h-l,d=this.selectionStart,u=this.selectionEnd,f=d!==u;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=d>g.selectionStart;f?(i=this._text.slice(d,u),c+=u-d):h0&&(n+=(i=this.__charBounds[t][e-1]).left+i.width),n},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(r===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=n.charIndex,a=this._getWidthBeforeCursor(r,s),o=this._getIndexOnLine(r+1,a);return this._textLines[r].slice(s).length+o+1+this.missingNewlineOffset(r)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(0===r||t.metaKey||33===t.keyCode)return-i;var s=n.charIndex,a=this._getWidthBeforeCursor(r,s),o=this._getIndexOnLine(r-1,a),l=this._textLines[r].slice(0,s),h=this.missingNewlineOffset(r-1);return-this._textLines[r-1].length+o-l.length+(1-h)},_getIndexOnLine:function(t,e){for(var i,n,r=this._textLines[t],s=this._getLineLeftOffset(t),a=0,o=0,l=r.length;oe){n=!0;var h=s-i,c=s,d=Math.abs(h-e);a=Math.abs(c-e)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)},moveCursorUp:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)},_moveCursorUpOrDown:function(t,e){var i=this["get"+t+"CursorOffset"](e,"right"===this._selectionDirection);e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(t){var e="left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t},moveCursorWithoutShift:function(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t},moveCursorLeft:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)},_move:function(t,e,i){var n;if(t.altKey)n=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;n=this["findLineBoundary"+i](this[e])}if(void 0!==typeof n&&this[e]!==n)return this[e]=n,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,n){void 0===n&&(n=i),n>i&&this.removeStyleFromTo(i,n);var r=b.util.string.graphemeSplit(t);this.insertNewStyleBlock(r,i,e),this._text=[].concat(this._text.slice(0,i),r,this._text.slice(n)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=b.util.toFixed,e=/ +/g;b.util.object.extend(b.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,n=[],r=[],s=t;this._setSVGBg(r);for(var a=0,o=this._textLines.length;a",b.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,n){var r,s,a,o,l,h=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),d="",u=0,f=this._textLines[e];n+=h*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)l=g===m||this.charSpacing,d+=f[g],a=this.__charBounds[e][g],0===u?(i+=a.kernedWidth-a.width,u+=a.width):u+=a.kernedWidth,c&&!l&&this._reSpaceAndTab.test(f[g])&&(l=!0),l||(r=r||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),l=this._hasStyleChangedForSvg(r,s)),l&&(o=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(d,o,i,n)),d="",r=s,i+=u,u=0)},_pushTextBgRect:function(e,i,n,r,s,a){var o=b.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,n){for(var r,s,a=this._textLines[e],o=this.getHeightOfLine(e)/this.lineHeight,l=0,h=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),d=0,u=a.length;dthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,n=0,r={},s=0;s0?(i=0,n++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[n])&&s>0&&(i++,n++),r[s]={line:e,offset:i},n+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return r},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var n=this._styleMap[i];n&&(i=n.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,n=0,r=!1,s=this._styleMap[t],a=this._styleMap[t+1];for(var o in s&&(t=s.line,n=s.offset),a&&(r=a.line===t,e=a.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var l in i[o])if(l>=n&&(!r||ln&&!p?(o.push(l),l=[],s=f,p=!0):s+=_,p||a||l.push(u),l=l.concat(c),g=a?0:this._measureWord([u],i,d),d++,p=!1,f>m&&(m=f);return v&&o.push(l),m+r>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+r),o},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),n=this._wrapText(i.lines,this.width),r=new Array(n.length),s=0;s{},898:()=>{},245:()=>{}},ni={};function ri(t){var e=ni[t];if(void 0!==e)return e.exports;var i=ni[t]={exports:{}};return ii[t](i,i.exports,ri),i.exports}ri.d=(t,e)=>{for(var i in e)ri.o(e,i)&&!ri.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},ri.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var si={};(()=>{let t;ri.d(si,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?ri(653).fabric:{version:"5.2.1"}})();var ai,oi,li,hi,ci=si.R;!function(t){t[t.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",t[t.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",t[t.DIMT_TEXT=4]="DIMT_TEXT",t[t.DIMT_ARC=8]="DIMT_ARC",t[t.DIMT_IMAGE=16]="DIMT_IMAGE",t[t.DIMT_POLYGON=32]="DIMT_POLYGON",t[t.DIMT_LINE=64]="DIMT_LINE",t[t.DIMT_GROUP=128]="DIMT_GROUP"}(ai||(ai={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(oi||(oi={})),function(t){t[t.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",t[t.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",t[t.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS"}(li||(li={})),function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(hi||(hi={}));const di=t=>"number"==typeof t&&!Number.isNaN(t),ui=t=>"string"==typeof t;var fi,gi,mi,pi,_i,vi,yi,wi,Ci,Ei,Si;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(_i||(_i={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(vi||(vi={}));class bi{get mediaType(){return new Map([["rect",ai.DIMT_RECTANGLE],["quad",ai.DIMT_QUADRILATERAL],["text",ai.DIMT_TEXT],["arc",ai.DIMT_ARC],["image",ai.DIMT_IMAGE],["polygon",ai.DIMT_POLYGON],["line",ai.DIMT_LINE],["group",ai.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(Je(this,gi,"f")){case oi.DIS_DEFAULT:return"default";case oi.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===Je(this,mi,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===Je(this,mi,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),Ke(this,mi,t)}get coordinateBase(){return Je(this,mi,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(fi.add(this),gi.set(this,void 0),mi.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=e&&!di(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(oi.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.setState(oi.DIS_SELECTED)})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(oi.DIS_SELECTED):this.setState(oi.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){Ke(this,gi,t)}getState(){return Je(this,gi,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),n=this.mapEvent_Callbacks.get(i);if(!n)throw new Error(`Event '${t}' does not exist.`);let r=n.get(e);r||(r=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const n={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,r,s;const a=i.target.getBoundingClientRect();t=a.left,e=a.top,r=t+window.scrollX,s=e+window.scrollY;const{width:o,height:l}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),h=this._drawingLayer.width,c=this._drawingLayer.height,d=o/l,u=h/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)d0?i-1:n,Oi),actionName:"modifyPolygon",pointIndex:i}),t}),{}),Ke(this,wi,JSON.parse(JSON.stringify(t))),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,n){return t["p"+n]=new ci.Control({positionHandler:xi,actionHandler:Ai(n>0?n-1:i,Oi),actionName:"modifyPolygon",pointIndex:n}),t}),{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let n=i.x-e.pathOffset.x,r=i.y-e.pathOffset.y;const s=ci.util.transformPoint({x:n,y:r},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){Je(this,wi,"f")&&this.setPolygon(Je(this,wi,"f"))}setPolygon(t){if(!x(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Ke(this,wi,JSON.parse(JSON.stringify(t)))}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Je(this,wi,"f")?JSON.parse(JSON.stringify(Je(this,wi,"f"))):null}}wi=new WeakMap;class Di extends bi{set maintainAspectRatio(t){t&&this.set("scaleY",this.get("scaleX"))}get maintainAspectRatio(){return Je(this,Ei,"f")}constructor(t,e,i,n){if(super(null,n),Ci.set(this,void 0),Ei.set(this,void 0),!O(e))throw new TypeError("Invalid 'rect'.");if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this._setFabricObject(new ci.Image(t,{left:e.x,top:e.y}));else{if(!C(t))throw new TypeError("Invalid 'image'.");{const i=document.createElement("canvas");let n;if(i.width=t.width,i.height=t.height,t.format===o.IPF_GRAYSCALED){n=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let n=0;ni&&(i=r.length)}if(-1===i)break;for(let n=0;n=t[n].length-1)continue;let r=" ".repeat(i+2-t[n][e].length);t[n][e]=t[n][e].concat(r)}}})(e),(t=>{let e="";for(let i=0;i({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const n=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new ci.Control({positionHandler:xi,actionHandler:Ai(i>0?i-1:n,Oi),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let n=t.x-i.pathOffset.x,r=t.y-i.pathOffset.y;const s=ci.util.transformPoint({x:n,y:r},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){Je(this,Fi,"f")&&this.setLine(Je(this,Fi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!b(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else Ke(this,Fi,JSON.parse(JSON.stringify(t)))}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return Je(this,Fi,"f")?JSON.parse(JSON.stringify(Je(this,Fi,"f"))):null}}Fi=new WeakMap;class Ni extends Ri{constructor(t,e){if(super({points:null==t?void 0:t.points},e),Pi.set(this,void 0),!I(t))throw new TypeError("Invalid 'quad'.");Ke(this,Pi,JSON.parse(JSON.stringify(t))),this._mediaType="quad"}setPosition(t){this.setQuad(t)}getPosition(){return this.getQuad()}updatePosition(){Je(this,Pi,"f")&&this.setQuad(Je(this,Pi,"f"))}setPolygon(){}getPolygon(){return null}setQuad(t){if(!I(t))throw new TypeError("Invalid 'quad'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Ke(this,Pi,JSON.parse(JSON.stringify(t)))}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Je(this,Pi,"f")?JSON.parse(JSON.stringify(Je(this,Pi,"f"))):null}}Pi=new WeakMap;class Bi extends bi{constructor(t){super(new ci.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.setState(oi.DIS_SELECTED);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.setState(oi.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}setChildDrawingItems(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}}const ji=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),Vi=t=>!!ui(t)&&""!==t,Ui=t=>!(!ji(t)||"id"in t&&!di(t.id)||"lineWidth"in t&&!di(t.lineWidth)||"fillStyle"in t&&!Vi(t.fillStyle)||"strokeStyle"in t&&!Vi(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!Vi(t.fontFamily)||"fontSize"in t&&!di(t.fontSize));class Gi{static convert(t,e,i){const n={x:0,y:0,width:e,height:i};if(!t)return n;if(O(t))t.isMeasuredInPercentage?(n.x=t.x/100*e,n.y=t.y/100*i,n.width=t.width/100*e,n.height=t.height/100*i):(n.x=t.x,n.y=t.y,n.width=t.width,n.height=t.height);else{if(!E(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?(n.x=t.left/100*e,n.y=t.top/100*i,n.width=(t.right-t.left)/100*e,n.height=(t.bottom-t.top)/100*i):(n.x=t.left,n.y=t.top,n.width=t.right-t.left,n.height=t.bottom-t.top)}return n.x=Math.round(n.x),n.y=Math.round(n.y),n.width=Math.round(n.width),n.height=Math.round(n.height),n}}var Wi,Yi;class zi{constructor(){Wi.set(this,new Map),Yi.set(this,!1)}get disposed(){return Je(this,Yi,"f")}on(t,e){t=t.toLowerCase();const i=Je(this,Wi,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else Je(this,Wi,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=Je(this,Wi,"f").get(t);if(!i)return;const n=i.indexOf(e);-1!==n&&i.splice(n,1)}offAll(t){t=t.toLowerCase();const e=Je(this,Wi,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const n=Je(this,Wi,"f").get(t);if(n&&n.length){i=Object.assign({async:!1,copy:!0},i);for(let r of n){if(!r)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let a=!1;if(i.async)setTimeout((()=>{this.disposed||n.includes(r)&&r.apply(i.target,s)}),0);else try{a=r.apply(i.target,s)}catch(t){}if(!0===a)break}}}dispose(){Ke(this,Yi,!0)}}function Hi(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function Xi(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function Zi(t,e,i,n){let r=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(n[1]-e[1])+e[0]*(t[1]-n[1])+n[0]*(e[1]-t[1]);return!((r^s)>=0&&0!==r&&0!==s||(r=i[0]*(t[1]-n[1])+n[0]*(i[1]-t[1])+t[0]*(n[1]-i[1]),s=i[0]*(e[1]-n[1])+n[0]*(i[1]-e[1])+e[0]*(n[1]-i[1]),(r^s)>=0&&0!==r&&0!==s))}Wi=new WeakMap,Yi=new WeakMap;const qi=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const n=document.createElement("div");if(n.insertAdjacentHTML("beforeend",i),1===n.childElementCount&&n.firstChild instanceof HTMLTemplateElement)return n.firstChild.content;const r=new DocumentFragment;for(let t of n.children)r.append(t);return r};var Ji,Ki,$i,Qi,tn,en,nn,rn,sn,an,on,ln,hn,cn,dn,un,fn,gn,mn,pn,_n,vn,yn,wn,Cn,En,Sn,bn,Tn,xn,In,On,An,Rn;class Dn{static createDrawingStyle(t){if(!Ui(t))throw new Error("Invalid style definition.");let e,i=Dn.USER_START_STYLE_ID;for(;Je(Dn,Ji,"f",Ki).has(i);)i++;e=i;const n=JSON.parse(JSON.stringify(t));n.id=e;for(let t in Je(Dn,Ji,"f",$i))n.hasOwnProperty(t)||(n[t]=Je(Dn,Ji,"f",$i)[t]);return Je(Dn,Ji,"f",Ki).set(e,n),n.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=Je(Dn,Ji,"f",Ki).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(Je(Dn,Ji,"f",Ki).values())))}static _updateDrawingStyle(t,e){if(!Ui(e))throw new Error("Invalid style definition.");const i=Je(Dn,Ji,"f",Ki).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}Ji=Dn,Dn.STYLE_BLUE_STROKE=1,Dn.STYLE_GREEN_STROKE=2,Dn.STYLE_ORANGE_STROKE=3,Dn.STYLE_YELLOW_STROKE=4,Dn.STYLE_BLUE_STROKE_FILL=5,Dn.STYLE_GREEN_STROKE_FILL=6,Dn.STYLE_ORANGE_STROKE_FILL=7,Dn.STYLE_YELLOW_STROKE_FILL=8,Dn.STYLE_BLUE_STROKE_TRANSPARENT=9,Dn.STYLE_GREEN_STROKE_TRANSPARENT=10,Dn.STYLE_ORANGE_STROKE_TRANSPARENT=11,Dn.USER_START_STYLE_ID=1024,Ki={value:new Map([[Dn.STYLE_BLUE_STROKE,{id:Dn.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_GREEN_STROKE,{id:Dn.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_ORANGE_STROKE,{id:Dn.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_YELLOW_STROKE,{id:Dn.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_BLUE_STROKE_FILL,{id:Dn.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_GREEN_STROKE_FILL,{id:Dn.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_ORANGE_STROKE_FILL,{id:Dn.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_YELLOW_STROKE_FILL,{id:Dn.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_BLUE_STROKE_TRANSPARENT,{id:Dn.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_GREEN_STROKE_TRANSPARENT,{id:Dn.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_ORANGE_STROKE_TRANSPARENT,{id:Dn.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},$i={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(ci.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(ci.util.cancelAnimFrame(this.isRendering),this.isRendering=0),this.forEachObject((function(t){t.dispose&&t.dispose()})),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose&&this.backgroundImage.dispose(),this.backgroundImage=null,this.overlayImage&&this.overlayImage.dispose&&this.overlayImage.dispose(),this.overlayImage=null,this._iTextInstances=null,this.contextContainer=null,this.lowerCanvasEl.classList.remove("lower-canvas"),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),ci.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},ci.Object.prototype.transparentCorners=!1,ci.Object.prototype.cornerSize=20,ci.Object.prototype.touchCornerSize=100,ci.Object.prototype.cornerColor="rgb(254,142,20)",ci.Object.prototype.cornerStyle="circle",ci.Object.prototype.strokeUniform=!0,ci.Object.prototype.hasBorders=!1,ci.Canvas.prototype.containerClass="",ci.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i,n=this.upperCanvasEl,r=ci.util.getPointer(t,n),s=n.getBoundingClientRect(),a=s.width||0,o=s.height||0;a&&o||("top"in s&&"bottom"in s&&(o=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(a=Math.abs(s.right-s.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,e||(r=this.restorePointerVpt(r));var l=this.getRetinaScaling();if(1!==l&&(r.x/=l,r.y/=l),0!==a&&0!==o){var h=window.getComputedStyle(n).objectFit,c=n.width,d=n.height,u=a,f=o;i={width:c/u,height:d/f};var g,m,p=c/d,_=u/f;return"contain"===h?p>_?(g=u,m=u/p,{x:r.x*i.width,y:(r.y-(f-m)/2)*i.width}):(g=f*p,m=f,{x:(r.x-(u-g)/2)*i.height,y:r.y*i.height}):"cover"===h?p>_?{x:(c-i.height*u)/2+r.x*i.height,y:r.y*i.height}:{x:r.x*i.width,y:(d-i.width*f)/2+r.y*i.width}:{x:r.x*i.width,y:r.y*i.height}}return i={width:1,height:1},{x:r.x*i.width,y:r.y*i.height}},ci.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,n=this._getEventPrefix();ci.util.addListener(ci.document,"touchend",this._onTouchEnd,{passive:!1}),ci.util.addListener(ci.document,"touchmove",this._onMouseMove,{passive:!1}),ci.util.removeListener(i,n+"down",this._onMouseDown)},ci.Textbox.prototype._wrapLine=function(t,e,i,n){const r=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!r||!r.length);var a=0,o=this.splitByGrapheme||s,l=[],h=[],c=o?ci.util.string.graphemeSplit(t):t.split(this._wordJoiners),d="",u=0,f=o?"":" ",g=0,m=0,p=0,_=!0,v=this._getWidthOfCharSpacing();n=n||0,0===c.length&&c.push([]),i-=n;for(var y=0;yi&&!_?(l.push(h),h=[],a=g,_=!0):a+=v,_||o||h.push(f),h=h.concat(d),m=o?0:this._measureWord([f],e,u),u++,_=!1,g>p&&(p=g);return y&&l.push(h),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+n),l});class Ln{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){if(this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas"))this.fabricCanvas=t.getFabricCanvas();else{let e=this.fabricCanvas=new ci.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.on("selection:created",(function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])}),0)}})),e.on("before:selection:cleared",(function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{const e=[];for(let n of i)t.hasDrawingItem(n)&&e.push(n);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)}),0)}})),e.on("selection:updated",(function(t){const e=t.selected,i=t.deselected,n=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of n){const n=[],r=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&n.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&r.push(i)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(n,r)}),0)}})),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let n,r;switch(this.id=e,e){case Ln.DDN_LAYER_ID:n=Dn.getDrawingStyle(Dn.STYLE_BLUE_STROKE),r=Dn.getDrawingStyle(Dn.STYLE_BLUE_STROKE_FILL);break;case Ln.DBR_LAYER_ID:n=Dn.getDrawingStyle(Dn.STYLE_ORANGE_STROKE),r=Dn.getDrawingStyle(Dn.STYLE_ORANGE_STROKE_FILL);break;case Ln.DLR_LAYER_ID:n=Dn.getDrawingStyle(Dn.STYLE_GREEN_STROKE),r=Dn.getDrawingStyle(Dn.STYLE_GREEN_STROKE_FILL);break;default:n=Dn.getDrawingStyle(Dn.STYLE_YELLOW_STROKE),r=Dn.getDrawingStyle(Dn.STYLE_YELLOW_STROKE_FILL)}for(let t of bi.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:n.id,selected:r.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return Dn.getDrawingStyle(t.styleId);return Dn.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,n){const r=this.getDrawingItems((e=>e._mediaType===t));for(let t of r)t.styleSelector===e&&this._changeItemStyle(t,i,!0);n||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const n=t._getFabricObject();"number"==typeof t.styleId&&(e=Dn.getDrawingStyle(t.styleId)),n.strokeWidth=e.lineWidth,"fill"===e.paintMode?(n.fill=e.fillStyle,n.stroke=e.fillStyle):"stroke"===e.paintMode?(n.fill="transparent",n.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(n.fill=e.fillStyle,n.stroke=e.strokeStyle),n.fontFamily&&(n.fontFamily=e.fontFamily),n.fontSize&&(n.fontSize=e.fontSize),n.group||(n.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const n=t.getChildDrawingItems();if("add"===i){if(n.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=Dn.getDrawingStyle(e.styleId);else{const n=this.mapType_StateAndStyleId.get(e._mediaType);i=Dn.getDrawingStyle(n[t.styleSelector]);const r=()=>{this._changeItemStyle(e,Dn.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,Dn.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",r),e._on("deselected",s),e._funcChangeStyleToSelected=r,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!n.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof bi))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const n=this.fabricCanvas.getObjects();let r,s;if(n.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){r=t.getChildDrawingItems();for(let t of r)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(r){for(let t of r){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of bi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Dn.getDrawingStyle(t.styleId);else{s=Dn.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Dn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},n=()=>{this._changeItemStyle(t,Dn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of bi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Dn.getDrawingStyle(t.styleId);else{s=Dn.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Dn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},n=()=>{this._changeItemStyle(t,Dn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const a=this._arrFabricObject.length;let o=n.length;if(a)o=n.indexOf(this._arrFabricObject[a-1])+1;else for(let e=0;et.toLowerCase())):e=bi.arrMediaTypes,i?i.forEach((t=>t.toLowerCase())):i=bi.arrStyleSelectors;const n=Dn.getDrawingStyle(t);if(!n)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let r;for(let s of e)if(r=this.mapType_StateAndStyleId.get(s),r)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,n,!0),r[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const n=[];i&ai.DIMT_RECTANGLE&&n.push("rect"),i&ai.DIMT_QUADRILATERAL&&n.push("quad"),i&ai.DIMT_TEXT&&n.push("text"),i&ai.DIMT_ARC&&n.push("arc"),i&ai.DIMT_IMAGE&&n.push("image"),i&ai.DIMT_POLYGON&&n.push("polygon"),i&ai.DIMT_LINE&&n.push("line");const r=[];e&oi.DIS_DEFAULT&&r.push("default"),e&oi.DIS_SELECTED&&r.push("selected"),this._setDefaultStyle(t,n.length?n:null,r.length?r:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}Ln.DDN_LAYER_ID=1,Ln.DBR_LAYER_ID=2,Ln.DLR_LAYER_ID=3,Ln.USER_DEFINED_LAYER_BASE_ID=100,Ln.TIP_LAYER_ID=999;class Mn{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new Ln(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(t){const e=this.getDrawingLayer(t);if(!e)return;const i=this._arrDrawingLayer;e.dispose(),i.splice(i.indexOf(e),1),this._switchPointerEvent()}clearDrawingLayers(){for(let t of this._arrDrawingLayer)t.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(t){for(let e of this._arrDrawingLayer)if(e.getId()===t)return e;return null}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().getActiveObjects(),e=[];for(let i of t)e.push(i.getDrawingItem());return e}setDimensions(t,e){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(t,e)}setObjectFit(t){for(let e of this._arrDrawingLayer)e&&e._setObjectFit(t)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(t){if(!this._arrDrawingLayer.length)return;this._getFabricCanvas().wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class Fn extends Mi{constructor(t,e,i,n,r){super(t,{x:e,y:i,width:n,height:0},r),Qi.set(this,void 0),tn.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&Ke(this,tn,setTimeout((()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()}),Je(this,Qi,"f")))}getDuration(){return Je(this,Qi,"f")}}Qi=new WeakMap,tn=new WeakMap;class Pn{constructor(){en.add(this),nn.set(this,void 0),rn.set(this,void 0),sn.set(this,void 0),an.set(this,!0),this._drawingLayerManager=new Mn}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const n=document.createElement("canvas");return n.width==t&&n.height==e||(n.width=t,n.height=e),n.style.objectFit=i,n}_createDrawingLayer(t,e,i,n){if(!this._layerBaseCvs){let r;try{r=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==r?void 0:r.width)||1280),i||(i=(null==r?void 0:r.height)||720),n||(n=(null==r?void 0:r.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,n)}const r=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(r,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",r.parentElement),s}createDrawingLayer(){let t;for(let e=Ln.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==Ln.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(tt.getId()>=0&&t.getId()!==Ln.TIP_LAYER_ID))}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(ji(e=t)&&T(e.topLeftPoint)&&di(e.width))||e.width<=0||!di(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;Ke(this,nn,JSON.parse(JSON.stringify(t))),Je(this,nn,"f").coordinateBase||(Je(this,nn,"f").coordinateBase="view"),Ke(this,sn,t.duration),Je(this,en,"m",cn).call(this)}getTipConfig(){return Je(this,nn,"f")?Je(this,nn,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),Ke(this,an,t)}isTipVisible(){return Je(this,an,"f")}updateTipMessage(t){if(!Je(this,nn,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=Dn.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(Ln.TIP_LAYER_ID)||this._createDrawingLayer(Ln.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=Je(this,en,"m",on).call(this,t,Je(this,nn,"f").topLeftPoint.x,Je(this,nn,"f").topLeftPoint.y,Je(this,nn,"f").width,Je(this,nn,"f").coordinateBase,this._tipStyleId),Je(this,en,"m",ln).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",Je(this,an,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),Je(this,rn,"f")&&clearTimeout(Je(this,rn,"f")),Je(this,sn,"f")>=0&&Ke(this,rn,setTimeout((()=>{Je(this,en,"m",hn).call(this)}),Je(this,sn,"f")))}}nn=new WeakMap,rn=new WeakMap,sn=new WeakMap,an=new WeakMap,en=new WeakSet,on=function(t,e,i,n,r,s){const a=new Fn(t,e,i,n,s);return a.coordinateBase=r,a},ln=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},hn=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},cn=function(){if(!this._tip)return;const t=Je(this,nn,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class kn extends HTMLElement{constructor(){super(),dn.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),Ke(this,dn,e);const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const n=document.createElement("slot");n.setAttribute("name","content"),e.append(n);const r=document.createElement("slot");r.setAttribute("name","drawing-layer"),e.append(r);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return Je(this,dn,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach((t=>t.remove()))}}dn=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",kn);class Nn extends Pn{static get engineResourcePath(){return L(vt.engineResourcePaths).dce}static set defaultUIElementURL(t){Nn._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=Nn._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",Nn.engineResourcePath)}static async createInstance(t){const e=new Nn;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",Nn.engineResourcePath)),await e.setUIElement(t||Nn.defaultUIElementURL),e}static _transformCoordinates(t,e,i,n,r,s,a){const o=s/n,l=a/r;t.x=Math.round(t.x/o+e),t.y=Math.round(t.y/l+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==Je(this,Cn,"f")){if(Ke(this,Cn,t),Je(this,un,"m",bn).call(this))Ke(this,pn,null),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!Je(this,pn,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(Ze.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ke(this,pn,t);const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}Je(this,un,"m",bn).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return Je(this,Cn,"f")}get disposed(){return Je(this,Sn,"f")}constructor(){super(),un.add(this),fn.set(this,void 0),gn.set(this,void 0),mn.set(this,void 0),this.containerClassName="dce-video-container",pn.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,_n.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,vn.set(this,!1),yn.set(this,!1),wn.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{Je(this,un,"m",An).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout((()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&Je(this,un,"m",On).call(this))}),this._updateLayersTimeout)},this._windowResizeListener=()=>{Nn._onLog&&Nn._onLog("window resize event triggered."),Je(this,wn,"f").width===document.documentElement.clientWidth&&Je(this,wn,"f").height===document.documentElement.clientHeight||(Je(this,wn,"f").width=document.documentElement.clientWidth,Je(this,wn,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},Cn.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!Je(this,un,"m",bn).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise(((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i},i=(t,e,i,n)=>{t.width==i&&t.height==n||(t.width=i,t.height=n);const r=t.getContext("2d");r.clearRect(0,0,t.width,t.height),r.drawImage(e,0,0)},n=await t(e),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let a=this._cvsSingleFrameMode;const o=null==a?void 0:a.width,l=null==a?void 0:a.height;a||(a=document.createElement("canvas"),this._cvsSingleFrameMode=a),i(a,n,r,s),this._innerComponent.setElement("content",a),o===a.width&&l===a.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout((()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)}),0)})),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},En.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,n,r,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const a=t.originalImageTag;if(!a)return;const o=t.items;if(!(null==o?void 0:o.length))return;const l=(null===(i=a.cropRegion)||void 0===i?void 0:i.left)||0,h=(null===(n=a.cropRegion)||void 0===n?void 0:n.top)||0,c=(null===(r=a.cropRegion)||void 0===r?void 0:r.right)?a.cropRegion.right-l:a.originalWidth,d=(null===(s=a.cropRegion)||void 0===s?void 0:s.bottom)?a.cropRegion.bottom-h:a.originalHeight,u=a.currentWidth,f=a.currentHeight,g=(t,e,i,n,r,s,a,o,l=[],h)=>{e.forEach((t=>Nn._transformCoordinates(t,i,n,r,s,a,o)));const c=new Ni({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},h);for(let t of l)c.addNote(t);t.addDrawingItems([c]),Je(this,En,"f").push(c)};let m,p;for(let t of o)switch(t.type){case yt.CRIT_ORIGINAL_IMAGE:break;case yt.CRIT_BARCODE:m=this.getDrawingLayer(Ln.DBR_LAYER_ID),p=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?g(m,t.location.points,l,h,c,d,u,f,p):g(m,t.location.points,l,h,c,d,u,f,p,Dn.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,l,h,c,d,u,f,p);break;case yt.CRIT_TEXT_LINE:m=this.getDrawingLayer(Ln.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,l,h,c,d,u,f,p):g(m,t.location.points,l,h,c,d,u,f,p,Dn.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,l,h,c,d,u,f,p);break;case yt.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(Ln.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===It.CVS_PASSED?g(m,t.location.points,l,h,c,d,u,f,[]):g(m,t.location.points,l,h,c,d,u,f,[],Dn.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,l,h,c,d,u,f,[]);break;case yt.CRIT_NORMALIZED_IMAGE:m=this.getDrawingLayer(Ln.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===It.CVS_PASSED?g(m,t.location.points,l,h,c,d,u,f,[]):g(m,t.location.points,l,h,c,d,u,f,[],Dn.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,l,h,c,d,u,f,[]);break;case yt.CRIT_PARSED_RESULT:break;default:throw new Error("Illegal item type.")}}},Sn.set(this,!1),this.eventHandler=new zi,this.eventHandler.on("content:updated",(()=>{Je(this,fn,"f")&&clearTimeout(Je(this,fn,"f")),Ke(this,fn,setTimeout((()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)}),0))})),this.eventHandler.on("videoEl:resized",(()=>{Je(this,gn,"f")&&clearTimeout(Je(this,gn,"f")),Ke(this,gn,setTimeout((()=>{this.disposed||this._updateVideoContainer()}),0))}))}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await qi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let n=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!n)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=document.createElement("dce-component"),n.appendChild(this._innerComponent),Je(this,un,"m",bn).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(Ze.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ke(this,pn,t);const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._selRsl&&(this._hideDefaultSelection||Je(this,un,"m",bn).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||Je(this,un,"m",bn).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||Je(this,un,"m",An).call(this),Je(this,un,"m",bn).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),Je(this,un,"m",bn).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{var e;Nn._onLog&&Nn._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()})));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}Je(this,wn,"f").width=document.documentElement.clientWidth,Je(this,wn,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,n;Je(this,un,"m",bn).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),Je(this,un,"m",An).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,Ke(this,pn,null),null===(n=this._videoContainer)||void 0===n||n.remove(),this._videoContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let n of e){const e=document.createElement("option");e.value=n.deviceId,e.innerText=n.label,this._selCam.append(e),n.deviceId&&t&&t.deviceId==n.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),n=Math.min(t.width,t.height);e=n<=1080?n+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return Je(this,pn,"f")}isVideoLoaded(){return!(!Je(this,pn,"f")||!this.cameraEnhancer)&&this.cameraEnhancer.isOpen()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!Je(this,pn,"f"))return;if(Je(this,pn,"f").style.objectFit=t,Je(this,un,"m",bn).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Je(this,un,"m",Rn).call(this,e,this.getConvertedRegion()),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,n;let r,s,a;if(Je(this,un,"m",bn).call(this)?(r=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(n=this._cvsSingleFrameMode)||void 0===n?void 0:n.height,a="contain"):(r=null===(t=Je(this,pn,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=Je(this,pn,"f"))||void 0===e?void 0:e.videoHeight,a=this.getVideoFit()),!r||!s)throw new Error("Invalid content dimensions.");return{width:r,height:s,objectFit:a}}updateConvertedRegion(t){const e=Gi.convert(this.scanRegion,t.width,t.height);Ke(this,_n,e),Je(this,mn,"f")&&clearTimeout(Je(this,mn,"f")),Ke(this,mn,setTimeout((()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Je(this,un,"m",Tn).call(this,t,e),Je(this,un,"m",Rn).call(this,t,e)}),0))}getConvertedRegion(){return Je(this,_n,"f")}setScanRegion(t){if(null!=t&&!E(t)&&!O(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=Je(this,pn,"f").videoWidth,i=Je(this,pn,"f").videoHeight,n=this.getVideoFit(),{width:r,height:s}=this._innerComponent.getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");let a;const o={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===n&&(r/s1){const t=Je(this,pn,"f").videoWidth,e=Je(this,pn,"f").videoHeight,{width:n,height:r}=this._innerComponent.getBoundingClientRect(),s=t/e;if(n/rt.remove())),Je(this,En,"f").length=0}dispose(){this._unbindUI(),Ke(this,Sn,!0)}}function Bn(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function jn(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,i),i}fn=new WeakMap,gn=new WeakMap,mn=new WeakMap,pn=new WeakMap,_n=new WeakMap,vn=new WeakMap,yn=new WeakMap,wn=new WeakMap,Cn=new WeakMap,En=new WeakMap,Sn=new WeakMap,un=new WeakSet,bn=function(){return"disabled"!==this._singleFrameMode},Tn=function(t,e){!e||0===e.x&&0===e.y&&e.width===t.width&&e.height===t.height?this.clearScanRegionMask():this.setScanRegionMask(e.x,e.y,e.width,e.height)},xn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},In=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},On=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},An=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Rn=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:n,objectFit:r}=t;e||(e={x:0,y:0,width:i,height:n});const{width:s,height:a}=this._innerComponent.getBoundingClientRect();if(s<=0||a<=0)return;const o=s/a,l=i/n;let h,c,d,u,f=1;if("contain"===r)o66||"Safari"===zn.browser&&zn.version>13||"OPR"===zn.browser&&zn.version>43||"Edge"===zn.browser&&zn.version,"function"==typeof SuppressedError&&SuppressedError;class Zn{static multiply(t,e){const i=[];for(let n=0;n<3;n++){const r=e.slice(3*n,3*n+3);for(let e=0;e<3;e++){const n=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*r[i]),0);i.push(n)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return Zn.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),n=Math.sin(e);return Zn.multiply(t,[i,-n,0,n,i,0,0,0,1])}static scale(t,e,i){return Zn.multiply(t,[e,0,0,0,i,0,0,0,1])}}var qn,Jn,Kn,$n,Qn,tr,er,ir,nr,rr,sr,ar,or,lr,hr,cr,dr,ur,fr,gr,mr,pr,_r,vr,yr,wr,Cr,Er,Sr,br,Tr,xr,Ir,Or,Ar,Rr,Dr,Lr,Mr,Fr,Pr,kr,Nr,Br,jr,Vr,Ur,Gr,Wr,Yr;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(qn||(qn={}));class zr{static get version(){return"1.1.3"}static get webGLSupported(){return void 0===zr._webGLSupported&&(zr._webGLSupported=!!document.createElement("canvas").getContext("webgl")),zr._webGLSupported}get disposed(){return Hn(this,er,"f")}constructor(){Jn.set(this,qn.RGBA),Kn.set(this,null),$n.set(this,null),Qn.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,tr.set(this,null),er.set(this,!1)}drawImage(t,e,i,n,r,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!n)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if((null==s?void 0:s.bUseWebGL)&&!zr.webGLSupported)throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let a;zr._onLog&&(a=Date.now(),zr._onLog("drawImage(), START: "+a));let o=0,l=0,h=i,c=n,d=0,u=0,f=i,g=n;r&&(r.sx&&(o=Math.round(r.sx)),r.sy&&(l=Math.round(r.sy)),r.sWidth&&(h=Math.round(r.sWidth)),r.sHeight&&(c=Math.round(r.sHeight)),r.dx&&(d=Math.round(r.dx)),r.dy&&(u=Math.round(r.dy)),r.dWidth&&(f=Math.round(r.dWidth)),r.dHeight&&(g=Math.round(r.dHeight)));let m,p=qn.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!zr.webGLSupported||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){zr._onLog&&zr._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},n=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},r=(t,e,i)=>{const n=t.createShader(e);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(n)}.`);throw e.name="WebGLError",e}return n},s="\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\n\nuniform mat3 u_matrix;\nuniform mat3 u_textureMatrix;\n\nvarying vec2 v_texCoord;\nvoid main(void) {\ngl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\nv_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n}";let a="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(a=p.slice(0,3));const o=`\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_image;\nuniform float uColorFactor;\n\nvoid main() {\nvec4 sample = texture2D(u_image, v_texCoord);\nfloat grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\ngl_FragColor = vec4(sample.${a} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n}`,l=n(t,[r(t,t.VERTEX_SHADER,s),r(t,t.FRAGMENT_SHADER,o)]);Xn(this,$n,{program:l,attribLocations:{vertexPosition:t.getAttribLocation(l,"a_position"),texPosition:t.getAttribLocation(l,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(l,"u_image"),uColorFactor:t.getUniformLocation(l,"uColorFactor"),uMatrix:t.getUniformLocation(l,"u_matrix"),uTextureMatrix:t.getUniformLocation(l,"u_textureMatrix")}}),Xn(this,Qn,e(t)),Xn(this,Kn,i(t)),Xn(this,Jn,p)}const r=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const n=t.RGBA,r=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,n,r,s,i)},v=(t,e,s,a)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),r(t,s.positions,e.attribLocations.vertexPosition),r(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,a),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[qn.GREY,qn.GREY32].includes(p)?1:0);let m,_,v=Zn.translate(Zn.identity(),-1,-1);v=Zn.scale(v,2,2),v=Zn.scale(v,1/t.canvas.width,1/t.canvas.height),m=Zn.translate(v,d,u),m=Zn.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=Zn.translate(Zn.identity(),o/i,l/n),_=Zn.scale(_,h/i,c/n),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,Hn(this,Kn,"f"),e),v(t,Hn(this,$n,"f"),Hn(this,Qn,"f"),Hn(this,Kn,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(d,u,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){zr._onLog&&zr._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return zr._onLog&&zr._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-a)),{context:t,pixelFormat:p===qn.GREY?qn.GREY32:p,bUseWebGL:!0}}catch(a){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return zr._onLog&&zr._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,n,r,Object.assign({},s,{bUseWebGL:!1}));throw a.name="WebGLError",a}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let n,r=0,s=0,a=t.canvas.width,o=t.canvas.height;if(e&&(e.x&&(r=e.x),e.y&&(s=e.y),e.width&&(a=e.width),e.height&&(o=e.height)),(null==i?void 0:i.length)<4*a*o)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(r,s,a,o,e.RGBA,e.UNSIGNED_BYTE,i),n=new Uint8Array(i.buffer,0,4*a*o)):(n=new Uint8Array(4*a*o),e.readPixels(r,s,a,o,e.RGBA,e.UNSIGNED_BYTE,n))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(r,s,a,o),n=new Uint8Array(e.data.buffer),null==i||i.set(n)}return n}transformPixelFormat(t,e,i,n){let r,s;if(zr._onLog&&(r=Date.now(),zr._onLog("transformPixelFormat(), START: "+r)),e===i)return zr._onLog&&zr._onLog("transformPixelFormat() end. Costs: "+(Date.now()-r)),n?new Uint8Array(t):t;const a=[qn.RGBA,qn.RBGA,qn.GRBA,qn.GBRA,qn.BRGA,qn.BGRA];if(a.includes(e))if(i===qn.GREY){s=new Uint8Array(t.length/4);for(let e=0;el||e.sy+e.sHeight>h)throw new Error("Invalid position.");null===(n=zr._onLog)||void 0===n||n.call(zr,"getImageData(), START: "+(c=Date.now()));const u=Math.round(e.sx),f=Math.round(e.sy),g=Math.round(e.sWidth),m=Math.round(e.sHeight),p=Math.round(e.dWidth),_=Math.round(e.dHeight);let v,y=(null==i?void 0:i.pixelFormat)||qn.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(qn.GREY===y&&w.length{this.disposed||n.includes(r)&&r.apply(i.target,s)}),0);else try{a=r.apply(i.target,s)}catch(t){}if(!0===a)break}}}dispose(){jn(this,nr,!0)}}ir=new WeakMap,nr=new WeakMap;const Xr=(t,e,i,n)=>{if(!i)return t;let r=e+Math.round((t-e)/i)*i;return n&&(r=Math.min(r,n)),r};class Zr{static get version(){return"2.0.18"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],n=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],r=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!r.length)return null;const s=r.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const a=r.find((t=>{const e=t.label.toLowerCase();return n.some((t=>e.includes(t)))}));return a?a.deviceId:r[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(zn.OS))return Zr.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(zn.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(n,r)=>{let s;const a=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",d),t.removeEventListener("play",u),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let o=!1;const l=()=>{o=!0,s&&clearTimeout(s),a(),n(t)},h=t=>{s&&clearTimeout(s),a(),r(t)},c=()=>{t.addEventListener("abort",d,{once:!0})},d=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",h(t)},u=()=>{l()},f=()=>{h(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",u,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!o){i&&(s=setTimeout((()=>{a(),r(new Error("Failed to play video. Timeout."))}),i)),await m;try{await t.play(),l()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!o)try{await t.play(),l()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),h(t)}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let n;try{n=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==n||n.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!Bn(this,_r,"f"))return"closed";if("pending"===Bn(this,_r,"f"))return"opening";if("fulfilled"===Bn(this,_r,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Zr.isStorageAvailable("localStorage")?jn(this,fr,!0):(jn(this,fr,!1),console.warn("Local storage is unavailable")):jn(this,fr,!1)}get ifSaveLastUsedCamera(){return Bn(this,fr,"f")}get isVideoPlaying(){return!(!Bn(this,ar,"f")||Bn(this,ar,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,n;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=Bn(this,Sr,"f"))||void 0===e||e.removeEventListener("click",Bn(this,Er,"f")),null===(i=Bn(this,Sr,"f"))||void 0===i||i.removeEventListener("touchend",Bn(this,Er,"f")),null===(n=Bn(this,Sr,"f"))||void 0===n||n.removeEventListener("touchmove",Bn(this,Cr,"f")),jn(this,Sr,t),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(zn.OS)?(t.addEventListener("touchend",Bn(this,Er,"f")),t.addEventListener("touchmove",Bn(this,Cr,"f"))):t.addEventListener("click",Bn(this,Er,"f")))}get tapFocusEventBoundEl(){return Bn(this,Sr,"f")}get disposed(){return Bn(this,Lr,"f")}constructor(t){var e,i;sr.add(this),ar.set(this,null),or.set(this,void 0),lr.set(this,(()=>{"opened"===this.state&&Bn(this,Ir,"f").fire("resumed",null,{target:this,async:!1})})),hr.set(this,(()=>{Bn(this,Ir,"f").fire("paused",null,{target:this,async:!1})})),cr.set(this,void 0),dr.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],ur.set(this,void 0),fr.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,gr.set(this,void 0),mr.set(this,!0),pr.set(this,void 0),_r.set(this,void 0),vr.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},yr.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const r=window.getComputedStyle(Bn(this,ar,"f")).objectFit,s=this.getResolution(),a=Bn(this,ar,"f").getBoundingClientRect(),o=a.left,l=a.top,{width:h,height:c}=Bn(this,ar,"f").getBoundingClientRect();if(h<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const d=h/c,u=s.width/s.height;let f=1;if("contain"===r)u>d?(f=h/s.width,i=(t-o)/f,n=(e-l-(c-h/u)/2)/f):(f=c/s.height,n=(e-l)/f,i=(t-o-(h-c*u)/2)/f);else{if("cover"!==r)throw new Error("Unsupported object-fit.");u>d?(f=c/s.height,n=(e-l)/f,i=(t-o+(c*u-h)/2)/f):(f=h/s.width,i=(t-o)/f,n=(e-l+(h/u-c)/2)/f)}return{x:i,y:n}},wr.set(this,!1),Cr.set(this,(()=>{jn(this,wr,!0)})),Er.set(this,(async t=>{var e;if(Bn(this,wr,"f"))return void jn(this,wr,!1);if(!Bn(this,yr,"f"))return;if(!this.isVideoPlaying)return;if(!Bn(this,or,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,n=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,n=t.changedTouches[0].clientY}const r=this.getResolution(),s=2*Math.round(Math.min(r.width,r.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let a;try{a=this.calculateCoordInVideo(i,n)}catch(t){}if(a.x<0||a.x>r.width||a.y<0||a.y>r.height)return;const o={x:a.x+"px",y:a.y+"px"},l=s+"px",h=l;let c;Zr._onLog&&(c=Date.now());try{await Bn(this,sr,"m",Gr).call(this,o,l,h,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Zr._onLog)throw Zr._onLog(t),t}Zr._onLog&&Zr._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;Zr._onLog&&Zr._onLog("Back to continuous focus."),null===(t=Bn(this,or,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),Bn(this,Ir,"f").fire("tapfocus",null,{target:this,async:!1})})),Sr.set(this,null),br.set(this,1),Tr.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!Bn(this,ar,"f"))return;const t=Bn(this,br,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)Bn(this,ar,"f").style.transform="";else{const e=window.getComputedStyle(Bn(this,ar,"f")).objectFit,i=Bn(this,ar,"f").videoWidth,n=Bn(this,ar,"f").videoHeight,{width:r,height:s}=Bn(this,ar,"f").getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const a=r/s,o=i/n;let l=1;"contain"===e?l=aa?s/(i/t):r/(n/t));const h=l*(1-1/t)*(i/2-Bn(this,Tr,"f").x),c=l*(1-1/t)*(n/2-Bn(this,Tr,"f").y);Bn(this,ar,"f").style.transform=`translate(${h}px, ${c}px) scale(${t})`}},xr.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===qn.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(Zr._onLog&&Zr._onLog("document visible. video paused: "+(null===(t=Bn(this,ar,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Zr._onLog&&Zr._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Zr._onLog&&Zr._onLog("document visible. 1st resume video failed, try open instead.")}e||await Bn(this,sr,"m",Nr).call(this)}if(await new Promise((t=>setTimeout(t,300))),!this.isVideoPlaying){Zr._onLog&&Zr._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Zr._onLog&&Zr._onLog("document visible. 2rd resume video failed, try open instead.")}e||await Bn(this,sr,"m",Nr).call(this)}}}else"hidden"===document.visibilityState&&(Zr._onLog&&Zr._onLog("document hidden. video paused: "+(null===(e=Bn(this,ar,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())})),Lr.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{Zr.onWarning&&Zr.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),jn(this,Ir,new Hr),this.imageDataGetter=new zr,document.addEventListener("visibilitychange",Bn(this,Dr,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",Bn(this,lr,"f")),t.addEventListener("pause",Bn(this,hr,"f")),jn(this,ar,t)}getVideoEl(){return Bn(this,ar,"f")}releaseVideoEl(){var t,e;null===(t=Bn(this,ar,"f"))||void 0===t||t.removeEventListener("play",Bn(this,lr,"f")),null===(e=Bn(this,ar,"f"))||void 0===e||e.removeEventListener("pause",Bn(this,hr,"f")),jn(this,ar,null)}isVideoLoaded(){return!!Bn(this,ar,"f")&&4==Bn(this,ar,"f").readyState}async open(){if(Bn(this,pr,"f")&&!Bn(this,mr,"f")){if("pending"===Bn(this,_r,"f"))return Bn(this,pr,"f");if("fulfilled"===Bn(this,_r,"f"))return}Bn(this,Ir,"f").fire("before:open",null,{target:this}),await Bn(this,sr,"m",Nr).call(this),Bn(this,Ir,"f").fire("played",null,{target:this,async:!1}),Bn(this,Ir,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;Bn(this,Ir,"f").fire("before:close",null,{target:this});const t=Bn(this,pr,"f");if(Bn(this,sr,"m",jr).call(this),t&&"pending"===Bn(this,_r,"f")){try{await t}catch(t){}if(!1===Bn(this,mr,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}jn(this,pr,null),jn(this,_r,null),Bn(this,Ir,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");Bn(this,ar,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await Bn(this,ar,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof Bn(this,cr,"f").video&&(Bn(this,cr,"f").video={}),delete Bn(this,cr,"f").video.facingMode,Bn(this,cr,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&Bn(this,mr,"f"))){Bn(this,Ir,"f").fire("before:camera:change",[],{target:this,async:!1}),await Bn(this,sr,"m",Br).call(this);try{this.resetSoftwareScale()}catch(t){}return Bn(this,dr,"f")}}async switchToFrontCamera(t){if("object"!=typeof Bn(this,cr,"f").video&&(Bn(this,cr,"f").video={}),(null==t?void 0:t.resolution)&&(Bn(this,cr,"f").video.width={ideal:t.resolution.width},Bn(this,cr,"f").video.height={ideal:t.resolution.height}),delete Bn(this,cr,"f").video.deviceId,Bn(this,cr,"f").video.facingMode={exact:"user"},jn(this,ur,null),!("closed"===this.state||this.videoSrc||"opening"===this.state&&Bn(this,mr,"f"))){Bn(this,Ir,"f").fire("before:camera:change",[],{target:this,async:!1}),Bn(this,sr,"m",Br).call(this);try{this.resetSoftwareScale()}catch(t){}return Bn(this,dr,"f")}}getCamera(){var t;if(Bn(this,dr,"f"))return Bn(this,dr,"f");{let e=(null===(t=Bn(this,cr,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else n=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const r=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof Bn(this,cr,"f").video&&(Bn(this,cr,"f").video={}),i?(Bn(this,cr,"f").video.width={exact:t},Bn(this,cr,"f").video.height={exact:e}):(Bn(this,cr,"f").video.width={ideal:t},Bn(this,cr,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&Bn(this,mr,"f"))return null;Bn(this,Ir,"f").fire("before:resolution:change",[],{target:this,async:!1}),await Bn(this,sr,"m",Br).call(this);try{this.resetSoftwareScale()}catch(t){}const n=this.getResolution();return{width:n.width,height:n.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&Bn(this,ar,"f"))return{width:Bn(this,ar,"f").videoWidth,height:Bn(this,ar,"f").videoHeight};if(Bn(this,or,"f")){const t=Bn(this,or,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:Bn(this,ar,"f").videoWidth,height:Bn(this,ar,"f").videoHeight};{const t={width:0,height:0};let e=Bn(this,cr,"f").video.width||0,i=Bn(this,cr,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,n,r,s,a,o,l,h,c,d;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let u="";const f=(t,e)=>{const i=Bn(this,Ar,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){u=null===(d=Bn(this,dr,"f"))||void 0===d?void 0:d.deviceId;let e=Bn(this,Ar,"f").get(u);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],Bn(this,Ar,"f").set(u,e),jn(this,vr,!0);try{for(let t of this.detectedResolutions){await Bn(this,or,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),Bn(this,sr,"m",Fr).call(this);const i=Bn(this,or,"f").getSettings(),n={width:i.width,height:i.height};f(u,n)||e.push({width:n.width,height:n.height})}}catch(t){throw Bn(this,sr,"m",jr).call(this),jn(this,vr,!1),t}try{await Bn(this,sr,"m",Nr).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{jn(this,vr,!1)}return e}{const e=async(t,e,i)=>{const n={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let r=null;try{r=await navigator.mediaDevices.getUserMedia(n)}catch(t){return null}if(!r)return null;const s=r.getVideoTracks();let a=null;try{const t=s[0].getSettings();a={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=r,a={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach((t=>{t.stop()})),a};let i=(null===(s=null===(r=null===(n=Bn(this,cr,"f"))||void 0===n?void 0:n.video)||void 0===r?void 0:r.deviceId)||void 0===s?void 0:s.exact)||(null===(l=null===(o=null===(a=Bn(this,cr,"f"))||void 0===a?void 0:a.video)||void 0===o?void 0:o.deviceId)||void 0===l?void 0:l.ideal)||(null===(c=null===(h=Bn(this,cr,"f"))||void 0===h?void 0:h.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let d=Bn(this,Ar,"f").get(i);if(d&&!t)return JSON.parse(JSON.stringify(d));d=[],Bn(this,Ar,"f").set(i,d);for(let t of this.detectedResolutions){const n=await e(i,t.width,t.height);n&&!f(i,n)&&d.push({width:n.width,height:n.height})}return d}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");jn(this,cr,JSON.parse(JSON.stringify(t))),jn(this,ur,null),e&&Bn(this,sr,"m",Br).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(Bn(this,cr,"f")))}resetMediaStreamConstraints(){jn(this,cr,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null)}getCameraCapabilities(){if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Bn(this,or,"f").getCapabilities?Bn(this,or,"f").getCapabilities():{}}getCameraSettings(){if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Bn(this,or,"f").getSettings()}async turnOnTorch(){if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Bn(this,or,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Bn(this,or,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Xr(t,n.min,n.step,n.max)),await Bn(this,or,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Xr(t,n.min,n.step,n.max)),await Bn(this,or,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!n)throw Error("Not supported.");e&&(tn.max&&(t=n.max));const r=this.getResolution();return await Bn(this,or,"f").applyConstraints({width:{ideal:Math.max(r.width,r.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),n=null==i?void 0:i.focusMode,r=null==i?void 0:i.focusDistance;if(!n)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!n.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!r)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(ir.max&&(i=r.max),i=Xr(i,r.min,r.step,r.max)),this._focusParameters.focusArea=null,await Bn(this,or,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,n=t.area.height;if(!i||!n){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),n||(n=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:n},await Bn(this,sr,"m",Gr).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await Bn(this,or,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){jn(this,yr,!0)}disableTapToFocus(){jn(this,yr,!1)}isTapToFocusEnabled(){return Bn(this,yr,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?Bn(this,sr,"m",Wr).call(this,t.centerPoint):this.resetScaleCenter();try{if(Bn(this,sr,"m",Yr).call(this,Bn(this,Tr,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*Bn(this,br,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Xr(t,n.min,n.step,n.max)),await Bn(this,or,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&Bn(this,sr,"m",Wr).call(this,e),jn(this,br,t),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return Bn(this,br,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();jn(this,Tr,{x:t.width/2,y:t.height/2})}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(Bn(this,vr,"f"))return null;const e=Date.now();Zr._onLog&&Zr._onLog("getFrameData() START: "+e);const i=Bn(this,ar,"f").videoWidth,n=Bn(this,ar,"f").videoHeight;let r={sx:0,sy:0,sWidth:i,sHeight:n,dWidth:i,dHeight:n};(null==t?void 0:t.position)&&(r=JSON.parse(JSON.stringify(t.position)));let s=qn.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let a=Bn(this,br,"f");(null==t?void 0:t.scale)&&(a=t.scale);let o=Bn(this,Tr,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,r=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))r=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.scaleCenter.y)/100*n}if(isNaN(e)||isNaN(r))throw new Error("Invalid scale center.");o.x=Math.round(e),o.y=Math.round(r)}let l=null;if((null==t?void 0:t.bufferContainer)&&(l=t.bufferContainer),0==i||0==n)return null;1!==a&&(r.sWidth=Math.round(r.sWidth/a),r.sHeight=Math.round(r.sHeight/a),r.sx=Math.round((1-1/a)*o.x+r.sx/a),r.sy=Math.round((1-1/a)*o.y+r.sy/a));const h=this.imageDataGetter.getImageData(Bn(this,ar,"f"),r,{pixelFormat:s,bufferContainer:l});if(!h)return null;const c=Date.now();return Zr._onLog&&Zr._onLog("getFrameData() END: "+c),{data:h.data,width:h.width,height:h.height,pixelFormat:h.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:Bn(this,xr,"f")}}on(t,e){if(!Bn(this,Or,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);Bn(this,Ir,"f").on(t,e)}off(t,e){Bn(this,Ir,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),Bn(this,Ir,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",Bn(this,Dr,"f")),jn(this,Lr,!0)}}var qr,Jr,Kr,$r,Qr,ts,es,is,ns,rs,ss,as,os,ls,hs,cs,ds,us,fs,gs,ms,ps,_s,vs,ys,ws,Cs,Es,Ss,bs,Ts,xs,Is,Os,As;ar=new WeakMap,or=new WeakMap,lr=new WeakMap,hr=new WeakMap,cr=new WeakMap,dr=new WeakMap,ur=new WeakMap,fr=new WeakMap,gr=new WeakMap,mr=new WeakMap,pr=new WeakMap,_r=new WeakMap,vr=new WeakMap,yr=new WeakMap,wr=new WeakMap,Cr=new WeakMap,Er=new WeakMap,Sr=new WeakMap,br=new WeakMap,Tr=new WeakMap,xr=new WeakMap,Ir=new WeakMap,Or=new WeakMap,Ar=new WeakMap,Rr=new WeakMap,Dr=new WeakMap,Lr=new WeakMap,sr=new WeakSet,Mr=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(Bn(this,ur,"f"))delete t.video.facingMode,t.video.deviceId={exact:Bn(this,ur,"f")};else if(this.ifSaveLastUsedCamera&&Zr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(zn.OS)?(await this._getCameras(!1),Bn(this,sr,"m",Fr).call(this),e=Zr.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(zn.OS)||(await this._getCameras(!1),Bn(this,sr,"m",Fr).call(this),e=Zr.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const n=await e(i);n&&(delete t.video.facingMode,t.video.deviceId={exact:n})}return t},Fr=function(){if(Bn(this,mr,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},Pr=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;try{Zr._onLog&&Zr._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const r=async t=>{for(let r of e){r&&(await new Promise((t=>setTimeout(t,r))),Bn(this,sr,"m",Fr).call(this));try{Zr._onLog&&Zr._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),Bn(this,sr,"m",Fr).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Zr._onLog&&Zr._onLog(t.message||t)}}};if(await r(t),n||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await r(t)),!n&&t.video.facingMode&&(delete t.video.facingMode,await r(t)),n||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await r(t))),!n)throw i;return n}catch(t){throw null==n||n.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},kr=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),jn(this,or,null)},Nr=async function(){jn(this,mr,!1);const t=jn(this,gr,Symbol());if(Bn(this,pr,"f")&&"pending"===Bn(this,_r,"f")){try{await Bn(this,pr,"f")}catch(t){}Bn(this,sr,"m",Fr).call(this)}if(t!==Bn(this,gr,"f"))return;const e=jn(this,pr,(async()=>{jn(this,_r,"pending");try{if(this.videoSrc){if(!Bn(this,ar,"f"))throw new Error("'videoEl' should be set.");await Zr.playVideo(Bn(this,ar,"f"),this.videoSrc,this.cameraOpenTimeout),Bn(this,sr,"m",Fr).call(this)}else{let t=await Bn(this,sr,"m",Mr).call(this);Bn(this,sr,"m",kr).call(this);let e=await Bn(this,sr,"m",Pr).call(this,t);await this._getCameras(!1),Bn(this,sr,"m",Fr).call(this);const i=()=>{const t=e.getVideoTracks();let i,n;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,n=e;break}}return n},n=Bn(this,cr,"f");if("object"==typeof n.video){let r=n.video.facingMode;if(r instanceof Array&&r.length&&(r=r[0]),"object"==typeof r&&(r=r.exact||r.ideal),!(Bn(this,ur,"f")||this.ifSaveLastUsedCamera&&Zr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),s=Zr.findBestCamera(this._arrCameras,r,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==n?void 0:n.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await Bn(this,sr,"m",Pr).call(this,t),Bn(this,sr,"m",Fr).call(this))}}const r=i();(null==r?void 0:r.deviceId)&&(jn(this,ur,r&&r.deviceId),this.ifSaveLastUsedCamera&&Zr.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",Bn(this,ur,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),Bn(this,ar,"f")&&(await Zr.playVideo(Bn(this,ar,"f"),e,this.cameraOpenTimeout),Bn(this,sr,"m",Fr).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&jn(this,or,s[0]),jn(this,dr,r)}}catch(t){throw Bn(this,sr,"m",jr).call(this),jn(this,_r,null),t}jn(this,_r,"fulfilled")})());return e},Br=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=Bn(this,dr,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await Bn(this,sr,"m",Nr).call(this);const n=this.getResolution();e&&e!==Bn(this,dr,"f").deviceId&&Bn(this,Ir,"f").fire("camera:changed",[Bn(this,dr,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||Bn(this,Ir,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),Bn(this,Ir,"f").fire("played",null,{target:this,async:!1})},jr=function(){Bn(this,sr,"m",kr).call(this),jn(this,dr,null),Bn(this,ar,"f")&&(Bn(this,ar,"f").srcObject=null,this.videoSrc&&(Bn(this,ar,"f").pause(),Bn(this,ar,"f").currentTime=0)),jn(this,mr,!0);try{this.resetSoftwareScale()}catch(t){}},Vr=async function t(e,i){const n=t=>{if(!Bn(this,or,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){Bn(this,or,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;i=Xr(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await Bn(this,or,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),n(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,r)})),n(e);let s=e.focusL-e.focusW/2,a=e.focusT-e.focusH/2,o=e.focusW,l=e.focusH;const h=this.getResolution();s=Math.round(s),a=Math.round(a),o=Math.round(o),l=Math.round(l),o>h.width&&(o=h.width),l>h.height&&(l=h.height),s<0?s=0:s+o>h.width&&(s=h.width-o),a<0?a=0:a+l>h.height&&(a=h.height-l);const c=4*h.width*h.height*this._focusParameters.defaultTempBufferContainerLenRatio,d=4*o*l;let u=this._focusParameters.tempBufferContainer;if(u){const t=u.length;c>t&&c>=d?u=new Uint8Array(c):d>t&&d>=c&&(u=new Uint8Array(d))}else u=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,d));if(!this.imageDataGetter.getImageData(Bn(this,ar,"f"),{sx:s,sy:a,sWidth:o,sHeight:l,dWidth:o,dHeight:l},{pixelFormat:qn.RGBA,bufferContainer:u}))return Bn(this,sr,"m",t).call(this,e,i);const f=u;let g=0;for(let t=0,e=d-8;to&&od)return await Bn(this,sr,"m",t).call(this,e,a,o,r,s,c,d)}else{let l=await Bn(this,sr,"m",Vr).call(this,e,c);if(o>l)return await Bn(this,sr,"m",t).call(this,e,a,o,r,s,c,l);if(o==l)return await Bn(this,sr,"m",t).call(this,e,a,o,c,l);let d=await Bn(this,sr,"m",Vr).call(this,e,h);if(d>o&&oa.width||l<0||l>a.height)throw new Error("Invalid 'centerPoint'.");let h=0;if(e.endsWith("px"))h=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");h=parseFloat(e)/100*a.width}if(isNaN(h)||h<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*a.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==Bn(this,br,"f")){const t=Bn(this,br,"f"),e=Bn(this,Tr,"f");h/=t,c/=t,o=(1-1/t)*e.x+o/t,l=(1-1/t)*e.y+l/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const d={focusL:o,focusT:l,focusW:h,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},u=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let n=Xr(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=Xr(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Xr(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),a=await Bn(this,sr,"m",Vr).call(this,t,s),o=await Bn(this,sr,"m",Vr).call(this,t,r),l=await Bn(this,sr,"m",Vr).call(this,t,n);if(o>l&&la&&o>a){let e=await Bn(this,sr,"m",Vr).call(this,t,i);const r=await Bn(this,sr,"m",Ur).call(this,t,n,l,i,e,s,a);return this._focusParameters.isDoingFocus=0,r}if(o==l&&ll){const e=await Bn(this,sr,"m",Ur).call(this,t,n,l,s,a);return this._focusParameters.isDoingFocus=0,e}return u(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return u(d,n,r)},Wr=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,n=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))n=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(n))throw new Error("Invalid scale center.");jn(this,Tr,{x:i,y:n})},Yr=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},Zr.browserInfo=zn,Zr.onWarning=null===(rr=null===window||void 0===window?void 0:window.console)||void 0===rr?void 0:rr.warn;class Rs{constructor(t){qr.add(this),Jr.set(this,void 0),Kr.set(this,0),$r.set(this,void 0),Qr.set(this,0),ts.set(this,!1),Ke(this,Jr,t)}startCharging(){Je(this,ts,"f")||(Rs._onLog&&Rs._onLog("start charging."),Je(this,qr,"m",is).call(this),Ke(this,ts,!0))}stopCharging(){Je(this,$r,"f")&&clearTimeout(Je(this,$r,"f")),Je(this,ts,"f")&&(Rs._onLog&&Rs._onLog("stop charging."),Ke(this,Kr,Date.now()-Je(this,Qr,"f")),Ke(this,ts,!1))}}Jr=new WeakMap,Kr=new WeakMap,$r=new WeakMap,Qr=new WeakMap,ts=new WeakMap,qr=new WeakSet,es=function(){vt.cfd(1),Rs._onLog&&Rs._onLog("charge 1.")},is=function t(){0==Je(this,Kr,"f")&&Je(this,qr,"m",es).call(this),Ke(this,Qr,Date.now()),Je(this,$r,"f")&&clearTimeout(Je(this,$r,"f")),Ke(this,$r,setTimeout((()=>{Ke(this,Kr,0),Je(this,qr,"m",t).call(this)}),Je(this,Jr,"f")-Je(this,Kr,"f")))};class Ds{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-Je(this,ns,"f",as)<100)){if(Ke(this,ns,e,0,as),Je(this,ns,"f",rs).size&&(t=Je(this,ns,"f",rs).values().next().value,this.beepSoundSource==t.src?(Je(this,ns,"f",rs).delete(t),t.play()):t=null),!t)if(Je(this,ns,"f",ss).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{Je(this,ns,"f",ss).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,Je(this,ns,"f",ss).delete(t),Je(this,ns,"f",rs).add(t)}))}else Je(this,ns,"f",os)||(Ke(this,ns,!0,0,os),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&Je(this,ns,"f",ss).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(Ds.vibrateDuration)}}}ns=Ds,rs={value:new Set},ss={value:new Set},as={value:0},os={value:!1},Ds.allowBeep=!0,Ds.beepSoundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",Ds.allowVibrate=!0,Ds.vibrateDuration=300;const Ls=new Map([[qn.GREY,o.IPF_GRAYSCALED],[qn.RGBA,o.IPF_ABGR_8888]]),Ms="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class Fs extends K{static set _onLog(t){Ke(Fs,hs,t,0,cs),Zr._onLog=t,Rs._onLog=t}static get _onLog(){return Je(Fs,hs,"f",cs)}static async detectEnvironment(){return await(async()=>({wasm:$e,worker:Qe,getUserMedia:ti,camera:await ei(),browser:Ze.browser,version:Ze.version,OS:Ze.OS}))()}static async testCameraAccess(){const t=await Zr.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var e,i;if(t&&!(t instanceof Nn))throw new TypeError("Invalid view.");if(null===(e=gt.license)||void 0===e?void 0:e.LicenseManager){if(!(null===(i=gt.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await vt.loadWasm(["license"]),await gt.license.dynamsoft()}const n=new Fs(t);return Fs.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{Fs.onWarning&&Fs.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{Fs.onWarning&&Fs.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),n}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");Ke(this,fs,t)}get singleFrameMode(){return Je(this,fs,"f")}get _isFetchingStarted(){return Je(this,ys,"f")}get disposed(){return Je(this,bs,"f")}constructor(t){if(super(),ls.add(this),ds.set(this,"closed"),us.set(this,void 0),this.isTorchOn=void 0,fs.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},gs.set(this,((t,e,i,n)=>{const r=Date.now(),s={sx:n.x,sy:n.y,sWidth:n.width,sHeight:n.height,dWidth:n.width,dHeight:n.height},a=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&a>this.canvasSizeLimit){const t=this.canvasSizeLimit/a;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const l=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===o.IPF_GRAYSCALED?qn.GREY:qn.RGBA});let h=null;if(l){const t=Date.now();let a;a=l.pixelFormat===qn.GREY?l.width:4*l.width;let o=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(o=!1),h={bytes:l.data,width:l.width,height:l.height,stride:a,format:Ls.get(l.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:bt.ITT_FILE_IMAGE,isCropped:o,cropRegion:{left:n.x,top:n.y,right:n.x+n.width,bottom:n.y+n.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:l.width,currentHeight:l.height,timeSpent:t-r,timeStamp:t},toCanvas:Je(this,ms,"f"),isDCEFrame:!0}}return h})),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():Gi.convert(Je(this,_s,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=Je(this,gs,"f").call(this,t,t.width,t.height,e);Je(this,us,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},ms.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===o.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(Ze.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",(()=>{Je(this,Ss,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{Je(this,Ss,"f").stopCharging();const t=this.cameraView;t&&t.disposed})),this._on("resumed",(()=>{const t=this.cameraView;t&&t.disposed})),this._on("tapfocus",(()=>{Je(this,Cs,"f").tapToFocus&&Je(this,Ss,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,n,r,s;if(Je(this,ls,"m",Ts).call(this)||!this.isOpen()||this.isPaused())return;const a=t.intermediateResultUnits;Fs._onLog&&(Fs._onLog("intermediateResultUnits:"),Fs._onLog(a));let o=!1,l=!1;for(let t of a){if(t.unitType===Ot.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){o=!0;break}t.unitType===Ot.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(l=!0)}if(Fs._onLog&&(Fs._onLog("hasLocalizedBarcodes:"),Fs._onLog(l)),Je(this,Cs,"f").autoZoom||Je(this,Cs,"f").enhancedFocus)if(o)Je(this,Es,"f").autoZoomInFrameArray.length=0,Je(this,Es,"f").autoZoomOutFrameCount=0,Je(this,Es,"f").frameArrayInIdealZoom.length=0,Je(this,Es,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),Je(this,Cs,"f").autoZoom&&Je(this,Ss,"f").startCharging()},o=async t=>{await this.setFocus(t),Je(this,Cs,"f").enhancedFocus&&Je(this,Ss,"f").startCharging()};if(l){const l=a[0].originalImageTag,h=(null===(i=l.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(n=l.cropRegion)||void 0===n?void 0:n.top)||0,d=(null===(r=l.cropRegion)||void 0===r?void 0:r.right)?l.cropRegion.right-h:l.originalWidth,u=(null===(s=l.cropRegion)||void 0===s?void 0:s.bottom)?l.cropRegion.bottom-c:l.originalHeight,f=l.currentWidth,g=l.currentHeight;let m;{let t,e,i,n,r;{const t=this.video.videoWidth*(1-Je(this,Es,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+Je(this,Es,"f").autoZoomDetectionArea)/2,i=e,n=t,s=this.video.videoHeight*(1-Je(this,Es,"f").autoZoomDetectionArea)/2,a=s,o=this.video.videoHeight*(1+Je(this,Es,"f").autoZoomDetectionArea)/2;r=[{x:t,y:s},{x:e,y:a},{x:i,y:o},{x:n,y:o}]}Fs._onLog&&(Fs._onLog("detectionArea:"),Fs._onLog(r));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let n=!1;const r=t.length;if(r<=2)return!1;for(let s=0;s0!=Xi(o.y-i)>0&&Xi(e-(i-a.y)*(a.x-o.x)/(a.y-o.y)-a.x)<0&&(n=!n)}return n}(e,t.x,t.y)},n=(t,e)=>!!(Zi([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||Zi([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||Zi([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||Zi([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(n([e[0].x,e[0].y,e[1].x,e[1].y],t)||n([e[1].x,e[1].y,e[2].x,e[2].y],t)||n([e[2].x,e[2].y,e[3].x,e[3].y],t)||n([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of a)if(e.unitType===Ot.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach((t=>{Nn._transformCoordinates(t,h,c,d,u,f,g)})),t(r,e)&&s.push(i)}if(Fs._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=Dn.createDrawingStyle({strokeStyle:"red"}));for(let i of a)if(i.unitType===Ot.IRUT_LOCALIZED_BARCODES)for(let n of i.localizedBarcodes){if(!n)continue;const i=n.location.points,r=new Ri({points:i},e);t.addDrawingItems([r])}}}if(Fs._onLog&&(Fs._onLog("intersectedResults:"),Fs._onLog(s)),!s.length)return;let o;if(s.length){let t=s.filter((t=>t.possibleFormats==Ms.BF_QR_CODE||t.possibleFormats==Ms.BF_DATAMATRIX));if(t.length||(t=s.filter((t=>t.possibleFormats==Ms.BF_ONED)),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,n=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(n-g/2)*(n-g/2)};o=t[0];let i=e(o);if(1!=t.length)for(let n=1;n1.1*o.confidence||t[n].confidence>.9*o.confidence&&ri&&s>i&&a>i&&l>i&&m.result.moduleSize{})),Je(this,Es,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=Je(this,Es,"f").autoZoomInFrameLimit[1]){Je(this,Es,"f").autoZoomInFrameArray.length=0;const i=[(.5-n)/(.5-r),(.5-n)/(.5-s),(.5-n)/(.5-a),(.5-n)/(.5-l)].filter((t=>t>0)),o=Math.min(...i,Je(this,Es,"f").autoZoomInIdealModuleSize/m.result.moduleSize),h=this.getZoomSettings().factor;let c=Math.max(Math.pow(h*o,1/Je(this,Es,"f").autoZoomInMaxTimes),Je(this,Es,"f").autoZoomInMinStep);c=Math.min(c,o);let d=h*c;d=Math.max(Je(this,Es,"f").minValue,d),d=Math.min(Je(this,Es,"f").maxValue,d);try{await e({factor:d})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(Je(this,Es,"f").autoZoomInFrameArray.length=0,Je(this,Es,"f").frameArrayInIdealZoom.push(!0),Je(this,Es,"f").frameArrayInIdealZoom.splice(0,Je(this,Es,"f").frameArrayInIdealZoom.length-Je(this,Es,"f").frameLimitInIdealZoom[0]),Je(this,Es,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=Je(this,Es,"f").frameLimitInIdealZoom[1]&&(Je(this,Es,"f").frameArrayInIdealZoom.length=0,Je(this,Cs,"f").enhancedFocus)){const e=m.points;try{await o({mode:"manual",area:{centerPoint:{x:(e[0].x+e[2].x)/2+"px",y:(e[0].y+e[2].y)/2+"px"},width:e[2].x-e[0].x+"px",height:e[2].y-e[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!Je(this,Cs,"f").autoZoom&&Je(this,Cs,"f").enhancedFocus&&(Je(this,Es,"f").autoFocusFrameArray.push(!0),Je(this,Es,"f").autoFocusFrameArray.splice(0,Je(this,Es,"f").autoFocusFrameArray.length-Je(this,Es,"f").autoFocusFrameLimit[0]),Je(this,Es,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=Je(this,Es,"f").autoFocusFrameLimit[1])){Je(this,Es,"f").autoFocusFrameArray.length=0;try{const t=m.points;await o({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(Je(this,Cs,"f").autoZoom){if(Je(this,Es,"f").autoZoomInFrameArray.push(!1),Je(this,Es,"f").autoZoomInFrameArray.splice(0,Je(this,Es,"f").autoZoomInFrameArray.length-Je(this,Es,"f").autoZoomInFrameLimit[0]),Je(this,Es,"f").autoZoomOutFrameCount++,Je(this,Es,"f").frameArrayInIdealZoom.push(!1),Je(this,Es,"f").frameArrayInIdealZoom.splice(0,Je(this,Es,"f").frameArrayInIdealZoom.length-Je(this,Es,"f").frameLimitInIdealZoom[0]),Je(this,Es,"f").autoZoomOutFrameCount>=Je(this,Es,"f").autoZoomOutFrameLimit){Je(this,Es,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let n=i-Math.max((i-1)*Je(this,Es,"f").autoZoomOutStepRate,Je(this,Es,"f").autoZoomOutMinStep);n=Math.max(Je(this,Es,"f").minValue,n),n=Math.min(Je(this,Es,"f").maxValue,n);try{await e({factor:n})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}Je(this,Cs,"f").enhancedFocus&&o({mode:"continuous"}).catch((()=>{}))}!Je(this,Cs,"f").autoZoom&&Je(this,Cs,"f").enhancedFocus&&(Je(this,Es,"f").autoFocusFrameArray.length=0,o({mode:"continuous"}).catch((()=>{})))}}},Ke(this,Ss,new Rs(1e4))}setCameraView(t){if(!(t instanceof Nn))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),Je(this,ls,"m",Ts).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;Je(this,ls,"m",Ts).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return Je(this,ls,"m",Ts).call(this)?Je(this,ds,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=this.cameraView;if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,Je(this,ls,"m",Ts).call(this)?t._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(Je(this,ls,"m",Ts).call(this));else{try{await this.cameraManager.open()}catch(e){throw t&&t._stopLoading(),"NotFoundError"===e.name?new Error(`No camera devices were detected. Please ensure a camera is connected and recognized by your system. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):"NotAllowedError"===e.name?new Error(`Camera access is blocked. Please check your browser settings or grant permission to use the camera. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):e}let i,n=t.getUIElement();if(n=n.shadowRoot||n,i=n.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=n.elTorchAuto=n.querySelector(".dce-mn-torch-auto"),e=n.elTorchOn=n.querySelector(".dce-mn-torch-on"),r=n.elTorchOff=n.querySelector(".dce-mn-torch-off");t&&(e.style.display=null==this.isTorchOn?"":"none"),e&&(e.style.display=1==this.isTorchOn?"":"none"),r&&(r.style.display=0==this.isTorchOn?"":"none");let s=n.elBeepOn=n.querySelector(".dce-mn-beep-on"),a=n.elBeepOff=n.querySelector(".dce-mn-beep-off");s&&(s.style.display=Ds.allowBeep?"":"none"),a&&(a.style.display=Ds.allowBeep?"none":"");let o=n.elVibrateOn=n.querySelector(".dce-mn-vibrate-on"),l=n.elVibrateOff=n.querySelector(".dce-mn-vibrate-off");o&&(o.style.display=Ds.allowVibrate?"":"none"),l&&(l.style.display=Ds.allowVibrate?"none":""),n.elResolutionBox=n.querySelector(".dce-mn-resolution-box");let h,c=n.elZoom=n.querySelector(".dce-mn-zoom");c&&(c.style.display="none",h=n.elZoomSpan=c.querySelector("span"));let d=n.elToast=n.querySelector(".dce-mn-toast"),u=n.elCameraClose=n.querySelector(".dce-mn-camera-close"),f=n.elTakePhoto=n.querySelector(".dce-mn-take-photo"),g=n.elCameraSwitch=n.querySelector(".dce-mn-camera-switch"),m=n.elCameraAndResolutionSettings=n.querySelector(".dce-mn-camera-and-resolution-settings");m&&(m.style.display="none");const p=n.dceMnFs={},_=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",_);const v=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",v);const y=()=>{this.turnAutoTorch()};null==r||r.addEventListener("pointerdown",y);const w=()=>{Ds.allowBeep=!Ds.allowBeep,s&&(s.style.display=Ds.allowBeep?"":"none"),a&&(a.style.display=Ds.allowBeep?"none":"")};for(let t of[a,s])null==t||t.addEventListener("pointerdown",w);const C=()=>{Ds.allowVibrate=!Ds.allowVibrate,o&&(o.style.display=Ds.allowVibrate?"":"none"),l&&(l.style.display=Ds.allowVibrate?"none":"")};for(let t of[l,o])null==t||t.addEventListener("pointerdown",C);const E=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),n=parseInt(e.getAttribute("data-height")),r=await this.setResolution({width:i,height:n});{let e=Math.max(r.width,r.height),i=Math.min(r.width,r.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&T(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?m&&(m.style.display=m.style.display?"":"none"):m&&""===m.style.display&&(m.style.display="none"))};n.addEventListener("click",E);let S=null;p.funcInfoZoomChange=(t,e=3e3)=>{c&&h&&(h.textContent=t.toFixed(1),c.style.display="",null!=S&&(clearTimeout(S),S=null),S=setTimeout((()=>{c.style.display="none",S=null}),e))};let b=null,T=p.funcShowToast=(t,e=3e3)=>{d&&(d.textContent=t,d.style.display="",null!=b&&(clearTimeout(b),b=null),b=setTimeout((()=>{d.style.display="none",b=null}),e))};const x=()=>{this.close()};null==u||u.addEventListener("click",x);const I=()=>{};null==f||f.addEventListener("pointerdown",I);const O=()=>{var t,e;let i,n=this.getVideoSettings(),r=n.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),a=null==s?void 0:s.indexOf("front");-1===a&&(a=null==s?void 0:s.indexOf("前"));let o=null==s?void 0:s.indexOf("back");-1===o&&(o=null==s?void 0:s.indexOf("后")),"number"==typeof a&&-1!==a?i=!0:"number"==typeof o&&-1!==o&&(i=!1),void 0===i&&(i="user"===((null==r?void 0:r.ideal)||(null==r?void 0:r.exact)||r)),n.video.facingMode={ideal:i?"environment":"user"},delete n.video.deviceId,this.updateVideoSettings(n)};null==g||g.addEventListener("pointerdown",O);let A=-1/0,R=1;const D=t=>{let e=Date.now();e-A>1e3&&(R=this.getZoomSettings().factor),R-=t.deltaY/200,R>20&&(R=20),R<1&&(R=1),this.setZoom({factor:R}),A=e};i.addEventListener("wheel",D);const L=new Map;let M=!1;const F=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],n=t.touches[1],r=L.get(i.identifier),s=L.get(n.identifier);if(!r||!s)break;let a=Math.pow(Math.pow(r.x-s.x,2)+Math.pow(r.y-s.y,2),.5),o=Math.pow(Math.pow(i.clientX-n.clientX,2)+Math.pow(i.clientY-n.clientY,2),.5),l=Date.now();if(M||l-A<100)return;l-A>1e3&&(R=this.getZoomSettings().factor),R*=o/a,R>20&&(R=20),R<1&&(R=1);let h=!1;"safari"==(null===(e=null==Ze?void 0:Ze.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(o/a>1&&R<2?(R=2,h=!0):o/a<1&&R<2&&(R=1,h=!0)),M=!0,h&&T("zooming..."),await this.setZoom({factor:R}),h&&(d.textContent=""),M=!1,A=Date.now();break}L.clear();for(let e of t.touches)L.set(e.identifier,{x:e.clientX,y:e.clientY})};n.addEventListener("touchstart",F),n.addEventListener("touchmove",F),n.addEventListener("touchend",F),n.addEventListener("touchcancel",F),p.unbind=()=>{null==t||t.removeEventListener("pointerdown",_),null==e||e.removeEventListener("pointerdown",v),null==r||r.removeEventListener("pointerdown",y);for(let t of[a,s])null==t||t.removeEventListener("pointerdown",w);for(let t of[l,o])null==t||t.removeEventListener("pointerdown",C);n.removeEventListener("click",E),null==u||u.removeEventListener("click",x),null==f||f.removeEventListener("pointerdown",I),null==g||g.removeEventListener("pointerdown",O),i.removeEventListener("wheel",D),n.removeEventListener("touchstart",F),n.removeEventListener("touchmove",F),n.removeEventListener("touchend",F),n.removeEventListener("touchcancel",F),delete n.dceMnFs,i.style.display="none"},i.style.display="",t&&null==this.isTorchOn&&setTimeout((()=>{this.turnAutoTorch(1e3)}),0)}this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const r=this.getResolution();e.width=r.width,e.height=r.height,e.deviceId=this.getSelectedCamera().deviceId}return Ke(this,ds,"open"),t&&(t._innerComponent.style.display="",Je(this,ls,"m",Ts).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!1}),t.eventHandler.fire("videoEl:resized",null,{async:!1}))),Je(this,us,"f").fire("opened",null,{target:this,async:!1}),e}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),Je(this,ls,"m",Ts).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}Ke(this,ds,"closed"),Je(this,Ss,"f").stopCharging(),e&&(e._innerComponent.style.display="none",Je(this,ls,"m",Ts).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),Je(this,us,"f").fire("closed",null,{target:this,async:!1})}pause(){if(Je(this,ls,"m",Ts).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!Je(this,ls,"m",Ts).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(Je(this,ls,"m",Ts).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(e),this.isTorchOn=!1;const i=this.getResolution(),n=this.cameraView;return n&&!n.disposed&&(n._stopLoading(),n._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),n._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Je(this,us,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Je(this,us,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._on(n,e)}off(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._off(n,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(Je(this,ls,"m",Ts).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(Je(this,ls,"m",Ts).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){if(null!=this._taskid4AutoTorch){if(!(t{var t,r,s;if(this.disposed||e||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++n>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let a;try{a=this.fetchImage()}catch(t){}if(!a||!a.width||!a.height)return;let l=0;if(o.IPF_GRAYSCALED===a.format){for(let t=0;t=this.maxDarkCount4AutoTroch){null===(t=Fs._onLog)||void 0===t||t.call(Fs,`darkCount ${i}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(r=null==t?void 0:t.dceMnFs)||void 0===r||r.funcShowToast("Torch Auto On")}catch(t){console.warn(t),e=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,null===(s=null==i?void 0:i.dceMnFs)||void 0===s||s.funcShowToast("Torch Not Supported")}}}else i=0};this._taskid4AutoTorch=setInterval(r,t),this.isTorchOn=void 0,r();let s=this.cameraView.getUIElement();s=s.shadowRoot||s,s.elTorchAuto&&(s.elTorchAuto.style.display=""),s.elTorchOn&&(s.elTorchOn.style.display="none"),s.elTorchOff&&(s.elTorchOff.style.display="none")}async setColorTemperature(t){if(Je(this,ls,"m",Ts).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(Je(this,ls,"m",Ts).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,n;if(Je(this,ls,"m",Ts).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(n=null==e?void 0:e.dceMnFs)||void 0===n||n.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(Je(this,ls,"m",Ts).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(Je(this,ls,"m",Ts).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(Je(this,ls,"m",Ts).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){Je(this,Es,"f").minValue=t.min,Je(this,Es,"f").maxValue=t.max}getAutoZoomRange(){return{min:Je(this,Es,"f").minValue,max:Je(this,Es,"f").maxValue}}async enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=gt.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==vt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&li.EF_ENHANCED_FOCUS&&(Je(this,Cs,"f").enhancedFocus=!0),t&li.EF_AUTO_ZOOM&&(Je(this,Cs,"f").autoZoom=!0),t&li.EF_TAP_TO_FOCUS&&(Je(this,Cs,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&li.EF_ENHANCED_FOCUS&&(Je(this,Cs,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),t&li.EF_AUTO_ZOOM&&(Je(this,Cs,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),t&li.EF_TAP_TO_FOCUS&&(Je(this,Cs,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),Je(this,ls,"m",Is).call(this)&&Je(this,ls,"m",xs).call(this)||Je(this,Ss,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!E(t)&&!O(t))throw TypeError("Invalid 'region'.");Ke(this,_s,t?JSON.parse(JSON.stringify(t)):null),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(Je(this,_s,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");Ke(this,ps,t)}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||Je(this,ls,"m",Ts).call(this))}startFetching(){if(Je(this,ls,"m",Ts).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");Je(this,ys,"f")||(Ke(this,ys,!0),Je(this,ls,"m",Os).call(this))}stopFetching(){Je(this,ys,"f")&&(Fs._onLog&&Fs._onLog("DCE: stop fetching loop: "+Date.now()),Je(this,ws,"f")&&clearTimeout(Je(this,ws,"f")),Ke(this,ys,!1))}fetchImage(){if(Je(this,ls,"m",Ts).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let e;if(e=Gi.convert(Je(this,_s,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height}),e.x>t.width||e.y>t.height)throw new Error("Invalid scan region.");e.x+e.width>t.width&&(e.width=t.width-e.x),e.y+e.height>t.height&&(e.height=t.height-e.y);const i={sx:e.x,sy:e.y,sWidth:e.width,sHeight:e.height,dWidth:e.width,dHeight:e.height},n=Math.max(i.dWidth,i.dHeight);if(this.canvasSizeLimit&&n>this.canvasSizeLimit){const t=this.canvasSizeLimit/n;i.dWidth>i.dHeight?(i.dWidth=this.canvasSizeLimit,i.dHeight=Math.round(i.dHeight*t)):(i.dWidth=Math.round(i.dWidth*t),i.dHeight=this.canvasSizeLimit)}const r=this.cameraManager.getFrameData({position:i,pixelFormat:this.getPixelFormat()===o.IPF_GRAYSCALED?qn.GREY:qn.RGBA});if(!r)return null;let s;s=r.pixelFormat===qn.GREY?r.width:4*r.width;let a=!0;return 0===i.sx&&0===i.sy&&i.sWidth===t.width&&i.sHeight===t.height&&(a=!1),{bytes:r.data,width:r.width,height:r.height,stride:s,format:Ls.get(r.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:bt.ITT_VIDEO_FRAME,isCropped:a,cropRegion:{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:r.width,currentHeight:r.height,timeSpent:r.timeSpent,timeStamp:r.timeStamp},toCanvas:Je(this,ms,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,Je(this,ys,"f")&&(Je(this,ws,"f")&&clearTimeout(Je(this,ws,"f")),Ke(this,ws,setTimeout((()=>{this.disposed||Je(this,ls,"m",Os).call(this)}),t)))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){Ke(this,vs,t)}getPixelFormat(){return Je(this,vs,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(Je(this,ls,"m",Ts).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],n=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise(((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let a=Gi.convert(Je(this,_s,"f"),r,s);a||(a={x:0,y:0,width:r,height:s});const o=Je(this,gs,"f").call(this,n,r,s,a);t&&t(o)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=Je(this,ls,"m",As).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=Je(this,ls,"m",As).call(this,t);return{x:e.clientX,y:e.clientY}}convertToScanRegionCoordinates(t){if(!Je(this,_s,"f"))return JSON.parse(JSON.stringify(t));let e,i,n=Je(this,_s,"f").left||Je(this,_s,"f").x||0,r=Je(this,_s,"f").top||Je(this,_s,"f").y||0;if(!Je(this,_s,"f").isMeasuredInPercentage)return{x:t.x-n,y:t.y-r};if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Je(this,ls,"m",Ts).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Je(this,ls,"m",Ts).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(Je(this,ls,"m",Ts).call(this)){const t=this.cameraView._innerComponent.getElement("content");e=t.width,i=t.height}else{const t=this.getVideoEl();e=t.videoWidth,i=t.videoHeight}return{x:t.x-Math.round(n*e/100),y:t.y-Math.round(r*i/100)}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),Ke(this,bs,!0)}}var Ps,ks,Ns,Bs,js,Vs,Us,Gs;hs=Fs,ds=new WeakMap,us=new WeakMap,fs=new WeakMap,gs=new WeakMap,ms=new WeakMap,ps=new WeakMap,_s=new WeakMap,vs=new WeakMap,ys=new WeakMap,ws=new WeakMap,Cs=new WeakMap,Es=new WeakMap,Ss=new WeakMap,bs=new WeakMap,ls=new WeakSet,Ts=function(){return"disabled"!==this.singleFrameMode},xs=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},Is=function(){for(let t in Je(this,Cs,"f"))if(1==Je(this,Cs,"f")[t])return!0;return!1},Os=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!Je(this,ys,"f"))return Je(this,ws,"f")&&clearTimeout(Je(this,ws,"f")),void Ke(this,ws,setTimeout((()=>{this.disposed||Je(this,ls,"m",t).call(this)}),this.fetchInterval));const e=()=>{var t;let e;Fs._onLog&&Fs._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=Je(this,ps,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=Je(this,ps,"f"))||void 0===t||t.onErrorReceived(Ct.EC_IMAGE_READ_FAILED,i)}),0);console.warn(e)}e?(this.addImageToBuffer(e),Fs._onLog&&Fs._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),Je(this,us,"f").fire("frameAddedToBuffer",null,{async:!1})):Fs._onLog&&Fs._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case s.BOPM_BLOCK:break;case s.BOPM_UPDATE:e()}else e();Je(this,ws,"f")&&clearTimeout(Je(this,ws,"f")),Ke(this,ws,setTimeout((()=>{this.disposed||Je(this,ls,"m",t).call(this)}),this.fetchInterval))},As=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Je(this,ls,"m",Ts).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Je(this,ls,"m",Ts).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,n=e.top,r=i+window.scrollX,s=n+window.scrollY,{width:a,height:o}=this.cameraView._innerComponent.getBoundingClientRect();if(a<=0||o<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let l,h,c;if(Je(this,ls,"m",Ts).call(this)){const t=this.cameraView._innerComponent.getElement("content");l=t.width,h=t.height,c="contain"}else{const t=this.getVideoEl();l=t.videoWidth,h=t.videoHeight,c=this.cameraView.getVideoFit()}const d=a/o,u=l/h;let f,g,m,p,_=1;if("contain"===c)d{var e;if(!this.isUseMagnifier)return;if(Je(this,Bs,"f")||Ke(this,Bs,new Ws),!Je(this,Bs,"f").magnifierCanvas)return;document.body.contains(Je(this,Bs,"f").magnifierCanvas)||(Je(this,Bs,"f").magnifierCanvas.style.position="fixed",Je(this,Bs,"f").magnifierCanvas.style.boxSizing="content-box",Je(this,Bs,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(Je(this,Bs,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void Je(this,Vs,"f").call(this);const n=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!n)return;const r=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*r,a=[{image:i,width:i.width,height:i.height},{image:n,width:n.width,height:n.height}];Je(this,Bs,"f").update(s,t.pointer,r,a);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(Je(this,Bs,"f").magnifierCanvas.style.left="auto",Je(this,Bs,"f").magnifierCanvas.style.top="0",Je(this,Bs,"f").magnifierCanvas.style.right="0"):(Je(this,Bs,"f").magnifierCanvas.style.left="0",Je(this,Bs,"f").magnifierCanvas.style.top="0",Je(this,Bs,"f").magnifierCanvas.style.right="auto")}Je(this,Bs,"f").show()})),Vs.set(this,(()=>{Je(this,Bs,"f")&&Je(this,Bs,"f").hide()})),Us.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await qi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=document.createElement("dce-component"),e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let n=this._innerComponent.getElement("content");n||(n=document.createElement("canvas"),n.style.objectFit="contain",this._innerComponent.setElement("content",n)),n.width===e&&n.height===i||(n.width=e,n.height=i);const r=n.getContext("2d");r.clearRect(0,0,n.width,n.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),r.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&r.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(C(t)){Ke(this,Ns,t);const{width:e,height:i,bytes:n,format:r}=Object.assign({},t);let s;if(r===o.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t{if(!Hs){if(!zs&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),Zs=t=>{if(null==t&&(t="./"),zs||Hs);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};vt.engineResourcePaths.dlr={version:"3.4.32",path:Xs,isInternal:!0},null==vt.engineResourcePaths.dlrData&&(vt.engineResourcePaths.dlrData={version:"1.0.11",path:Zs(Xs+"../../dynamsoft-label-recognizer-data@1.0.11/dist/"),isInternal:!0}),mt.dlr={js:!0,wasm:!0,deps:["license","dip","dnn"]},mt.dnn={wasm:!0,deps:["dip"]};const qs="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,qs)<0&&(vt.engineResourcePaths.std={version:qs,path:Zs(Xs+`../../dynamsoft-capture-vision-std@${qs}/dist/`),isInternal:!0});const Js="2.4.31";(!vt.engineResourcePaths.dip||"string"!=typeof vt.engineResourcePaths.dip&&D(vt.engineResourcePaths.dip.version,Js)<0)&&(vt.engineResourcePaths.dip={version:Js,path:Zs(Xs+`../../dynamsoft-image-processing@${Js}/dist/`),isInternal:!0});const Ks="1.0.20";(!vt.engineResourcePaths.dnn||"string"!=typeof vt.engineResourcePaths.dnn&&D(vt.engineResourcePaths.dnn.version,Ks)<0)&&(vt.engineResourcePaths.dnn={version:Ks,path:Zs(Xs+`../../dynamsoft-capture-vision-dnn@${Ks}/dist/`),isInternal:!0});let $s=!1,Qs=class{static getVersion(){const t=ft.dlr&&ft.dlr.wasm;return`3.4.32(Worker: ${ft.dlr&&ft.dlr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadRecognitionData(t,e){return await _t("dlr"),await new Promise(((i,n)=>{let r=ot();lt[r]=async t=>{if(t.success){const e=t.result;if(0!==e.errorCode){let t=new Error(e.errorString);return t.errorCode=e.errorCode,n(t)}return e.isModel||($s=!0),i(e)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},e&&!e.endsWith("/")&&(e+="/");const s=L(vt.engineResourcePaths);e||"ConfusableChars"!==t||(e=s.dlr),st.postMessage({type:"dlr_loadData",id:r,body:{dataName:t,dataPath:e||s.dlrData}})}))}};gt.dlr={loadRecognitionData:Qs.loadRecognitionData,get bLoadConfusableCharsData(){return $s}};const ta={filterVINResult:function(t){let e="";if(18===t.characterResults.length){let e=t.characterResults[9].location.points[0].x-t.characterResults[8].location.points[1].x;e<2&&(e=2);let i=t.characterResults[1].location.points[0].x-t.characterResults[0].location.points[1].x,n=t.characterResults[17].location.points[0].x-t.characterResults[16].location.points[1].x,r=2===e?3:e;i-e>=r&&n-e=r&&i-et.characterResults[17].characterHConfidence?t.characterResults.pop():t.characterResults.shift()}else if(19===t.characterResults.length){let e=t.characterResults[10].location.points[0].x-t.characterResults[9].location.points[1].x;e<2&&(e=2);let i,n,r,s=t.characterResults[1].location.points[0].x-t.characterResults[0].location.points[1].x,a=t.characterResults[18].location.points[0].x-t.characterResults[17].location.points[1].x,o=t.characterResults[2].location.points[0].x-t.characterResults[1].location.points[1].x,l=t.characterResults[17].location.points[0].x-t.characterResults[16].location.points[1].x,h=2===e?3:e;if("1"===t.characterResults[1].characterH||"1"===t.characterResults[2].characterH||"1"===t.characterResults[16].characterH||"1"===t.characterResults[17].characterH){for(let e=9;e=(i||h)&&l-e<(n||h))t.characterResults.splice(0,2);else if(l-e>=(n||h)&&o-e<(i||h))t.characterResults.splice(17,2);else if(s>e&&a>e)t.characterResults.pop(),t.characterResults.shift();else{let e=t.characterResults[0].characterHConfidence+t.characterResults[1].characterHConfidence,i=t.characterResults[17].characterHConfidence+t.characterResults[18].characterHConfidence,n=t.characterResults[0].characterHConfidence+t.characterResults[18].characterHConfidence,r=Math.min(e,i,n);r===e?t.characterResults.splice(0,2):r===i?t.characterResults.splice(17,2):r===n&&(t.characterResults.pop(),t.characterResults.shift())}}for(let i of t.characterResults)e+=i.characterH;return e},checkValidVIN:function(t){return!(!t||17!=t.length)&&(t=>{const e=new Map([["A",1],["B",2],["C",3],["D",4],["E",5],["F",6],["G",7],["H",8],["J",1],["K",2],["L",3],["M",4],["N",5],["P",7],["R",9],["S",2],["T",3],["U",4],["V",5],["W",6],["X",7],["Y",8],["Z",9],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9]]),i=[8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2];let n=0;for(let r=0;r{const n=new Map([["<",0],["0",0],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9],["A",10],["B",11],["C",12],["D",13],["E",14],["F",15],["G",16],["H",17],["I",18],["J",19],["K",20],["L",21],["M",22],["N",23],["O",24],["P",25],["Q",26],["R",27],["S",28],["T",29],["U",30],["V",31],["W",32],["X",33],["Y",34],["Z",35]]),r=[7,3,1];let s=0;for(let a=e,o=0;a<=i;a++){let e=n.get(t[a]);e&&(s+=e*r[o%3]),o++}return s%10},i=t.slice(0,10)+t.slice(13,20)+t.slice(21,43),n=e(t,0,8).toString(),r=e(t,13,18).toString(),s=e(t,21,26).toString(),a=e(t,28,41).toString(),o=e(i,0,i.length).toString();return n===t[9]&&r===t[19]&&s===t[27]&&a===t[42]&&o===t[43]},checkValidMRV:function(t){if(!t||44!=t.length&&36!=t.length)return!1;const e=(t,e,i)=>{const n=new Map([["<",0],["0",0],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9],["A",10],["B",11],["C",12],["D",13],["E",14],["F",15],["G",16],["H",17],["I",18],["J",19],["K",20],["L",21],["M",22],["N",23],["O",24],["P",25],["Q",26],["R",27],["S",28],["T",29],["U",30],["V",31],["W",32],["X",33],["Y",34],["Z",35]]),r=[7,3,1];let s=0;for(let a=e,o=0;a<=i;a++){let e=n.get(t[a]);e&&(s+=e*r[o%3]),o++}return s%10},i=e(t,0,8).toString(),n=e(t,13,18).toString(),r=e(t,21,26).toString();return i===t[9]&&n===t[19]&&r===t[27]},checkValidIDCard:function(t,e){if(!t||30!=t.length&&36!=t.length)return!1;const i=(t,e,i)=>{const n=new Map([["<",0],["0",0],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9],["A",10],["B",11],["C",12],["D",13],["E",14],["F",15],["G",16],["H",17],["I",18],["J",19],["K",20],["L",21],["M",22],["N",23],["O",24],["P",25],["Q",26],["R",27],["S",28],["T",29],["U",30],["V",31],["W",32],["X",33],["Y",34],["Z",35]]),r=[7,3,1];let s=0;for(let a=e,o=0;a<=i;a++){let e=n.get(t[a]);e&&(s+=e*r[o%3]),o++}return s%10};if(30===t.length){if(e&&t===e)return i(t,5,13).toString()===t[14];if(e&&t!==e){const n=`${e.substring(5,30)}${t.substring(0,7)}${t.substring(8,15)}${t.substring(18,29)}`;return i(n,0,n.length-1).toString()===t[29]}}else if(36===t.length){const e=i(t,0,8).toString(),n=i(t,13,18).toString(),r=i(t,21,26).toString(),s=`${t.substring(0,10)}${t.substring(13,20)}${t.substring(21,28)}`,a=i(s,0,s.length-1).toString();return e===t[9]&&n===t[19]&&r===t[27]&&a===t[35]}}};var ea,ia,na;function ra(t){delete t.moduleId;const e=JSON.parse(t.jsonString).ResultInfo,i=t.fullCodeString;t.getFieldValue=t=>"fullcodestring"===t.toLowerCase()?i:sa(e,t,"map"),t.getFieldRawValue=t=>sa(e,t,"raw"),t.getFieldMappingStatus=t=>aa(e,t),t.getFieldValidationStatus=t=>oa(e,t),delete t.fullCodeString}function sa(t,e,i){for(let n of t){if(n.FieldName===e)return"raw"===i&&n.RawValue?n.RawValue:n.Value;if(n.ChildFields&&n.ChildFields.length>0){let t;for(let r of n.ChildFields)t=sa(r,e,i);if(void 0!==t)return t}}}function aa(t,e){for(let i of t){if(i.FieldName===e)return i.MappingStatus?Number(ia[i.MappingStatus]):ia.MS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=aa(n,e);if(void 0!==t)return t}}}function oa(t,e){for(let i of t){if(i.FieldName===e&&i.ValidationStatus)return i.ValidationStatus?Number(na[i.ValidationStatus]):na.VS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=oa(n,e);if(void 0!==t)return t}}}function la(t){if(t.disposed)throw new Error('"CodeParser" instance has been disposed')}!function(t){t[t.RTLS_LOCALIZED=0]="RTLS_LOCALIZED",t[t.RTLS_RECOGNITION_FAILED=1]="RTLS_RECOGNITION_FAILED",t[t.RTLS_RECOGNITION_SUCCEEDED=2]="RTLS_RECOGNITION_SUCCEEDED"}(ea||(ea={})),lt[-1]=async t=>{Qs.onDataLoadProgressChanged&&Qs.onDataLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})},function(t){t[t.MS_NONE=0]="MS_NONE",t[t.MS_SUCCEEDED=1]="MS_SUCCEEDED",t[t.MS_FAILED=2]="MS_FAILED"}(ia||(ia={})),function(t){t[t.VS_NONE=0]="VS_NONE",t[t.VS_SUCCEEDED=1]="VS_SUCCEEDED",t[t.VS_FAILED=2]="VS_FAILED"}(na||(na={}));const ha=t=>t&&"object"==typeof t&&"function"==typeof t.then,ca=(async()=>{})().constructor;let da=class extends ca{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,ha(t)?e=t:"function"==typeof t&&(e=new ca(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(ha(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}},ua=class t{constructor(){this._instanceID=void 0,this.bDestroyed=!1}static async createInstance(){if(!gt.license)throw Error("Module `license` is not existed.");await gt.license.dynamsoft(),await _t("dcp");const e=new t,i=new da;let n=ot();return lt[n]=async t=>{if(t.success)e._instanceID=t.instanceID,i.resolve(e);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),i.reject(e)}},st.postMessage({type:"dcp_createInstance",id:n}),i}async dispose(){la(this);let t=ot();this.bDestroyed=!0,lt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},st.postMessage({type:"dcp_dispose",id:t,instanceID:this._instanceID})}get disposed(){return this.bDestroyed}async initSettings(t){return la(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?t.trimStart().startsWith("{")||(t=await A(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise(((e,i)=>{let n=ot();lt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Init Settings Failed.");return t.errorCode=n.errorCode,i(t)}return e(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"dcp_initSettings",id:n,instanceID:this._instanceID,body:{settings:t}})}))):console.error("Invalid settings.")}async resetSettings(){return la(this),await new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"dcp_resetSettings",id:i,instanceID:this._instanceID})}))}async parse(t,e=""){if(la(this),!t||!(t instanceof Array||t instanceof Uint8Array||"string"==typeof t))throw new Error("`parse` must pass in an Array or Uint8Array or string");return await new Promise(((i,n)=>{let r=ot();t instanceof Array&&(t=Uint8Array.from(t)),"string"==typeof t&&(t=Uint8Array.from(function(t){let e=[];for(let i=0;i{if(t.success){let e=JSON.parse(t.parseResponse);return e.errorCode?n(new Error(e.errorString)):(ra(e),i(e))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},st.postMessage({type:"dcp_parse",id:r,instanceID:this._instanceID,body:{source:t,taskSettingName:e}})}))}};const fa="undefined"==typeof self,ga="function"==typeof importScripts,ma=(()=>{if(!ga){if(!fa&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})();vt.engineResourcePaths.dcp={version:"2.4.32",path:ma,isInternal:!0},mt.dcp={js:!0,wasm:!0,deps:["license"]},gt.dcp={handleParsedResultItem:ra};const pa="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,pa)<0&&(vt.engineResourcePaths.std={version:pa,path:(t=>{if(null==t&&(t="./"),fa||ga);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(ma+`../../dynamsoft-capture-vision-std@${pa}/dist/`),isInternal:!0});let _a=class{static getVersion(){const t=ft.dcp&&ft.dcp.wasm;return`2.4.32(Worker: ${ft.dcp&&ft.dcp.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadSpec(t,e){return await _t("dcp"),await new Promise(((i,n)=>{let r=ot();lt[r]=async t=>{if(t.success)return i();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},e&&!e.endsWith("/")&&(e+="/");const s=t instanceof Array?t:[t],a=L(vt.engineResourcePaths);st.postMessage({type:"dcp_appendResourceBuffer",id:r,body:{specificationPath:e||a.dcp+"specification/",specificationNames:s}})}))}};const va=async t=>{let e;await new Promise(((i,n)=>{e=new Image,e.onload=()=>i(e),e.onerror=n,e.src=URL.createObjectURL(t)}));const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e.width,i.height=e.height,n.drawImage(e,0,0),{bytes:Uint8Array.from(n.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:10}};class ya{async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const n=N(t);return M(n,e,i)}async drawOnImage(t,e,i,n=4294901760,r=1,s){let a;if(t instanceof Blob)a=await va(t);else if("string"==typeof t){let e=await A(t,"blob");a=await va(e)}return await new Promise(((t,o)=>{let l=ot();lt[l]=async e=>{if(e.success)return s&&this.saveToFile(e.image,"test.png",s),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,o(t)}},st.postMessage({type:"utility_drawOnImage",id:l,body:{dsImage:a,drawingItem:e instanceof Array?e:[e],color:n,thickness:r,type:i}})}))}}const wa="undefined"==typeof self,Ca="function"==typeof importScripts,Ea=(()=>{if(!Ca){if(!wa&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),Sa=t=>{if(null==t&&(t="./"),wa||Ca);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};vt.engineResourcePaths.utility={version:"1.4.32",path:Ea,isInternal:!0},mt.utility={js:!0,wasm:!0};const ba="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,ba)<0&&(vt.engineResourcePaths.std={version:ba,path:Sa(Ea+`../../dynamsoft-capture-vision-std@${ba}/dist/`),isInternal:!0});const Ta="2.4.31";(!vt.engineResourcePaths.dip||"string"!=typeof vt.engineResourcePaths.dip&&D(vt.engineResourcePaths.dip.version,Ta)<0)&&(vt.engineResourcePaths.dip={version:Ta,path:Sa(Ea+`../../dynamsoft-image-processing@${Ta}/dist/`),isInternal:!0});class xa{static getVersion(){return`1.4.32(Worker: ${ft.utility&&ft.utility.worker||"Not Loaded"}, Wasm: ${ft.utility&&ft.utility.wasm||"Not Loaded"})`}}function Ia(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}var Oa,Aa,Ra,Da,La;function Ma(t,e){let i=!0;for(let a=0;a1)return Math.sqrt((l-a)**2+(h-o)**2);{const t=r+d*(a-r),e=s+d*(o-s);return Math.sqrt((l-t)**2+(h-e)**2)}}function ka(t){const e=[];for(let i=0;i=0&&l<=1&&h>=0&&h<=1?{x:t.x+h*r,y:t.y+h*s}:null}function ja(t){let e=0;for(let i=0;i0}function Ua(t,e){for(let i=0;i<4;i++)if(!Va(t.points[i],t.points[(i+1)%4],e))return!1;return!0}"function"==typeof SuppressedError&&SuppressedError;function Ga(t,e,i,n){const r=t.points,s=e.points;let a=8*i;a=Math.max(a,5);const o=ka(r)[3],l=ka(r)[1],h=ka(s)[3],c=ka(s)[1];let d,u=0;if(d=Math.max(Math.abs(Pa(o,e.points[0])),Math.abs(Pa(o,e.points[3]))),d>u&&(u=d),d=Math.max(Math.abs(Pa(l,e.points[1])),Math.abs(Pa(l,e.points[2]))),d>u&&(u=d),d=Math.max(Math.abs(Pa(h,t.points[0])),Math.abs(Pa(h,t.points[3]))),d>u&&(u=d),d=Math.max(Math.abs(Pa(c,t.points[1])),Math.abs(Pa(c,t.points[2]))),d>u&&(u=d),u>a)return!1;const f=Na(ka(r)[0]),g=Na(ka(r)[2]),m=Na(ka(s)[0]),p=Na(ka(s)[2]),_=Fa(f,p),v=Fa(m,g),y=_>v,w=Math.min(_,v),C=Fa(f,g),E=Fa(m,p);let S=12*i;return S=Math.max(S,5),S=Math.min(S,C),S=Math.min(S,E),!!(w{e.x+=t,e.y+=i})),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,n=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-n.area)>.4*i.area)return!1;let r=new Array(4).fill(0),s=new Array(4).fill(0),a=0,o=0;for(let t=0;t<4;++t)r[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,a+=r[t],s[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,o+=s[t];a/=4,o/=4;for(let t=0;t<4;++t){if(Math.abs(r[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1;if(Math.abs(s[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1}return e.x=a,e.y=o,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(Ua(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(Ua(this.location,e))return!0}else{for(let e=0;e<4;e++)if(Ua(t,this.location.points[e]))return!0;if(Ua(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const n=[this.location.points[0],this.location.points[3]],r=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?n:r;if(Math.abs(Pa(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const n=t.location.points[i],r=this.location.points[i];if(!(Math.abs(r.x+e.x-n.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const n=Object.assign({},t.location);for(let t=0;t<4;t++)n.points[t].x-=e.x,n.points[t].y-=e.y;if(!this.isLocationOverlap(n,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let n=0;n<4;n++)for(let r=0;r<4;r++){const s=Ba(t[n],t[(n+1)%4],e[r],e[(r+1)%4]);s&&i.push(s)}return t.forEach((t=>{Ma(e,t)&&i.push(t)})),e.forEach((e=>{Ma(t,e)&&i.push(e)})),ja(function(t){if(t.length<=1)return t;t.sort(((t,e)=>t.x-e.x||t.y-e.y));const e=t.shift();return t.sort(((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x))),[e,...t]}(i))}([...this.location.points],n.points)>this.locationArea*t}return!0}}const Ya={BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096)},za={barcode:2,text_line:4,detected_quad:8,normalized_image:16},Ha=t=>Object.values(za).includes(t)||za.hasOwnProperty(t),Xa=(t,e)=>"string"==typeof t?e[za[t]]:e[t],Za=(t,e,i)=>{"string"==typeof t?e[za[t]]=i:e[t]=i},qa=(t,e,i)=>{const n=[8,16].includes(i);if(!n&&t.isResultCrossVerificationEnabled(i))for(let t=0;t{Za(e,this.verificationEnabled,t)})),Ia(this,Aa,"f").forEach(((t,e)=>{Za(e,this.duplicateFilterEnabled,t)})),Ia(this,Ra,"f").forEach(((t,e)=>{Za(e,this.duplicateForgetTime,t)})),Ia(this,Da,"f").forEach(((t,e)=>{Za(e,this.latestOverlappingEnabled,t)})),Ia(this,La,"f").forEach(((t,e)=>{Za(e,this.maxOverlappingFrames,t)}))}enableResultCrossVerification(t,e){Ha(t)&&Ia(this,Oa,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!Ha(t)&&Xa(t,this.verificationEnabled)}enableResultDeduplication(t,e){Ha(t)&&(e&&this.enableLatestOverlapping(t,!1),Ia(this,Aa,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!Ha(t)&&Xa(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){Ha(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),Ia(this,Ra,"f").set(t,e))}getDuplicateForgetTime(t){return Ha(t)?Xa(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){Ha(t)&&Ia(this,La,"f").set(t,e)}getMaxOverlappingFrames(t){return Ha(t)?Xa(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){Ha(t)&&(e&&this.enableResultDeduplication(t,!1),Ia(this,Da,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!Ha(t)&&Xa(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[yt.CRIT_BARCODE,yt.CRIT_TEXT_LINE,yt.CRIT_DETECTED_QUAD,yt.CRIT_NORMALIZED_IMAGE];for(let i=0;i{if(1!==t.type){const e=(BigInt(t.format)&BigInt(Ya.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Ya.BF_GS1_DATABAR))!=BigInt(0);return new Wa(l,e?1:2,e,t)}})).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(h).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t)).length;r>p&&(p=r,m=n,g.x=i.x,g.y=i.y)}}if(0===p){for(let e=0;e-1!=t)).length}let i=this.overlapSet.length<=3?p>=1:p>=2;if(!i&&s&&d>0){let t=0;for(let e=0;e=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach(((t,e)=>{if(1!==t.type){const i=Object.assign({},t),n=(BigInt(t.format)&BigInt(Ya.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Ya.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0)))}f.sort(((t,e)=>e-t)).forEach(((e,i)=>{t.items.splice(e,1)})),u.forEach((e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))}))}}onDecodedBarcodesReceived(t){this.latestOverlappingFilter(t),qa(this,t.items,yt.CRIT_BARCODE)}onRecognizedTextLinesReceived(t){qa(this,t.items,yt.CRIT_TEXT_LINE)}onDetectedQuadsReceived(t){qa(this,t.items,yt.CRIT_DETECTED_QUAD)}onNormalizedImagesReceived(t){qa(this,t.items,yt.CRIT_NORMALIZED_IMAGE)}}var Ka,$a,Qa;Oa=new WeakMap,Aa=new WeakMap,Ra=new WeakMap,Da=new WeakMap,La=new WeakMap,function(t){t.Passport="passport",t.TD1="td1",t.TD2="td2",t.PassportAndTD1="passportAndTd1",t.PassportAndTD2="passportAndTd2",t.TD1AndTD2="td1AndTd2",t.All="all"}(Ka||(Ka={})),function(t){t.Passport="passport",t.TD1="td1",t.TD2="td2"}($a||($a={})),function(t){t.Scanner="scanner",t.Result="scan-result"}(Qa||(Qa={}));const to={[Ka.Passport]:"ReadPassport",[Ka.TD1]:"ReadId-TD1",[Ka.TD2]:"ReadId-TD2",[Ka.PassportAndTD1]:"ReadPassportAndId-TD1",[Ka.PassportAndTD2]:"ReadPassportAndId-TD2",[Ka.TD1AndTD2]:"ReadId",[Ka.All]:"ReadPassportAndId"};var eo;function io(t){if("string"==typeof t){const e=document.querySelector(t);if(!e)throw new Error("Element not found");return e}return t instanceof HTMLElement?t:null}!function(t){t[t.RS_SUCCESS=0]="RS_SUCCESS",t[t.RS_CANCELLED=1]="RS_CANCELLED",t[t.RS_FAILED=2]="RS_FAILED"}(eo||(eo={}));function no(t,e){if(!document.getElementById(t)){const i=document.createElement("style");i.id=t,i.textContent=e,document.head.appendChild(i)}}const ro=t=>!t||0===Object.keys(t).length;function so(t){return t?t.charAt(0).toUpperCase()+t.slice(1):""}const ao={"4k":{width:3840,height:2160},"2k":{width:2560,height:1440},"1080p":{width:1920,height:1080},"720p":{width:1280,height:720},"480p":{width:640,height:480}};function oo(t,e={}){const{message:i,spinnerSize:n=32}=e,r=document.createElement("div");r.className="dynamsoft-mrz-loading-screen";const s=document.createElement("div");s.className="dynamsoft-mrz-loading";const a=document.createElement("div");a.className="dynamsoft-mrz-loading-content";const o=`\n \n \n \n `;if(a.innerHTML=o,i){const t=document.createElement("div");t.className="dynamsoft-mrz-loading-message",t.textContent=i,a.appendChild(t)}return s.appendChild(a),r.appendChild(s),t.appendChild(r),{element:r,updateMessage:t=>{let e=s.querySelector(".dynamsoft-mrz-loading-message");null!==t?e?e.textContent=t:(e=document.createElement("div"),e.className="dynamsoft-mrz-loading-message",e.textContent=t,a.appendChild(e)):null==e||e.remove()},hide:()=>{r&&r.parentNode&&(r.classList.add("fade-out"),setTimeout((()=>{var t;null===(t=r.parentNode)||void 0===t||t.removeChild(r)}),200))}}}const lo='\n .dynamsoft-mrz-loading-screen {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: #323234;\n z-index: 998;\n opacity: 1;\n transition: opacity 0.2s ease-out;\n }\n\n .dynamsoft-mrz-loading-screen.fade-out {\n opacity: 0;\n }\n\n .dynamsoft-mrz-loading {\n position: absolute;\n left: 50%;\n top: 50%;\n color: white;\n z-index: 999;\n transform: translate(-50%, -50%);\n }\n\n .dynamsoft-mrz-loading-content {\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 16px;\n }\n\n .dynamsoft-mrz-loading svg {\n animation: spin 1s linear infinite;\n }\n\n .dynamsoft-mrz-loading-message {\n color: white;\n font-family: "Verdana";\n font-size: 14px;\n text-align: center;\n max-width: 200px;\n line-height: 1.4;\n opacity: 0.9;\n }\n\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n';var ho;!function(t){t.InvalidFields="invalidFields",t.DocumentType="documentType",t.DocumentNumber="documentNumber",t.MRZText="mrzText",t.FirstName="firstName",t.LastName="lastName",t.Age="age",t.Sex="sex",t.IssuingState="issuingState",t.Nationality="nationality",t.DateOfBirth="dateOfBirth",t.DateOfExpiry="dateOfExpiry"}(ho||(ho={}));const co={[ho.InvalidFields]:"Invalid Fields",[ho.DocumentType]:"Document Type",[ho.DocumentNumber]:"Document Number",[ho.MRZText]:"MRZ Text",[ho.FirstName]:"Given Name(s)",[ho.LastName]:"Surname",[ho.Age]:"Age",[ho.Sex]:"Sex",[ho.IssuingState]:"Issuing State",[ho.Nationality]:"Nationality",[ho.DateOfBirth]:"Date Of Birth (YYYY-MM-DD)",[ho.DateOfExpiry]:"Date Of Expiry (YYYY-MM-DD)"};function uo(t,e,i,n=!1){const r=parseInt(t,10);let s;if(n)s=r>=60?1900+r:2e3+r;else{s=r>(new Date).getFullYear()%100?1900+r:2e3+r}return{year:s,month:parseInt(e,10),day:parseInt(i,10)}}function fo(t){const e=t=>{var e;return 1===(null===(e=`${t}`)||void 0===e?void 0:e.length)?`0${t}`:t};return`${null==t?void 0:t.year}-${e(null==t?void 0:t.month)}${(null==t?void 0:t.day)&&`-${e(null==t?void 0:t.day)}`}`}function go(t,e){const i=[],n=t=>e.getFieldValidationStatus(t)===na.VS_FAILED,r=e.codeType,s=function(t){switch(t){case"MRTD_TD1_ID":return $a.TD1;case"MRTD_TD2_ID":case"MRTD_TD2_VISA":case"MRTD_TD2_FRENCH_ID":return $a.TD2;case"MRTD_TD3_PASSPORT":case"MRTD_TD3_VISA":return $a.Passport;default:throw new Error(`Unknown document type: ${t}`)}}(r),a=function(t){switch(t){case"MRTD_TD1_ID":return"ID (TD1)";case"MRTD_TD2_ID":return"ID (TD2)";case"MRTD_TD2_VISA":return"ID (VISA)";case"MRTD_TD2_FRENCH_ID":return"French ID (TD2)";case"MRTD_TD3_PASSPORT":return"Passport (TD3)";case"MRTD_TD3_VISA":return"Visa (TD3)";default:throw new Error(`Unknown document type: ${t}`)}}(r),o=s===$a.Passport&&"MRTD_TD3_PASSPORT"===r?"passportNumber":"documentNumber",l=uo(e.getFieldValue("birthYear"),e.getFieldValue("birthMonth"),e.getFieldValue("birthDay")),h=uo(e.getFieldValue("expiryYear"),e.getFieldValue("expiryMonth"),e.getFieldValue("expiryDay"),!0);["birthYear","birthMonth","birthDay"].forEach((t=>{n(t)&&i.push(ho.DateOfBirth)})),["expiryYear","expiryMonth","expiryDay"].forEach((t=>{n(t)&&i.push(ho.DateOfExpiry)}));const c={[ho.LastName]:e.getFieldValue("primaryIdentifier"),[ho.FirstName]:e.getFieldValue("secondaryIdentifier"),[ho.Nationality]:e.getFieldRawValue("nationality"),[ho.DocumentNumber]:e.getFieldValue(o)||e.getFieldValue("longDocumentNumber"),[ho.IssuingState]:e.getFieldRawValue("issuingState"),[ho.Sex]:so(e.getFieldValue("sex"))};Object.keys(c).forEach((t=>{let e=!1;switch(t){case ho.FirstName:e=n("secondaryIdentifier");break;case ho.LastName:e=n("primaryIdentifier");break;case ho.DocumentNumber:e=n(o)||n("longDocumentNumber");break;default:e=n(t)}e&&i.push(t)}));const d=function(t){const e=new Date,i=e.getMonth()+1>t.month||e.getMonth()+1===t.month&&e.getDate()>=t.day;return e.getFullYear()-t.year-(i?0:1)}(l);d<1&&i.push(ho.Age);return{[ho.InvalidFields]:i,[ho.FirstName]:c[ho.FirstName],[ho.LastName]:c[ho.LastName],[ho.Age]:d,[ho.DateOfBirth]:l,[ho.Sex]:c[ho.Sex],[ho.Nationality]:c[ho.Nationality],[ho.DocumentNumber]:c[ho.DocumentNumber],[ho.DateOfExpiry]:h,[ho.IssuingState]:c[ho.IssuingState],[ho.DocumentType]:so(a),[ho.MRZText]:t}}const mo={[$a.TD1]:{width:85.6,height:53.98},[$a.TD2]:{width:105,height:74},[$a.Passport]:{width:125,height:88}};class po{showScannerLoadingOverlay(t){const e=io(this.config.container);this.loadingScreen=oo(e,{message:t}),e.style.display="block",e.style.position="relative"}hideScannerLoadingOverlay(t=!1){this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,t&&(io(this.config.container).style.display="none"))}constructor(t,e){this.resources=t,this.config=e,this.isSoundFeedbackOn=!1,this.scanModeManager={[$a.Passport]:!0,[$a.TD1]:!0,[$a.TD2]:!0},this.currentScanMode=Ka.All,this.resizeTimer=null,this.capturedResultItems=[],this.originalImageData=null,this.initialized=!1,this.initializedDCE=!1,this.DCE_ELEMENTS={selectCameraBtn:null,uploadImageBtn:null,soundFeedbackBtn:null,closeScannerBtn:null,scanModeSelectContainer:null,passportModeOption:null,td1ModeOption:null,td2ModeOption:null,toast:null},this.loadingScreen=null,this.handleResize=()=>{this.toggleScanGuide(!1),this.resizeTimer&&window.clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout((()=>{this.toggleScanGuide(!0)}),500)}}async initialize(){if(!this.initialized){this.initializeScanModeManager(),this.currentScanMode=this.getScanMode(),no("dynamsoft-mrz-loading-screen-style",lo);try{const{cameraView:t,cameraEnhancer:e,cvRouter:i}=this.resources;if(t.setScanRegionMaskStyle({strokeStyle:"transparent",fillStyle:"transparent",lineWidth:0}),t.setVideoFit("cover"),i.setInput(e),await i.initSettings(this.config.templateFilePath),!0===this.config.enableMultiFrameCrossFilter){const t=new Ja;t.enableResultCrossVerification(yt.CRIT_TEXT_LINE,!0),t.enableResultDeduplication(yt.CRIT_TEXT_LINE,!0),await i.addResultFilter(t)}const n=new Be;n.onCapturedResultReceived=t=>this.handleMRZResult(t),await i.addResultReceiver(n),this.toggleSoundFeedback(!1),!1===this.config.showScanGuide&&this.toggleScanGuide(!1),this.initialized=!0}catch(t){let e=(null==t?void 0:t.message)||t;console.error(e),alert(e),this.closeCamera();const i={status:{code:eo.RS_FAILED,message:"Dynamsoft MRZ Scanner initialize error"}};this.currentScanResolver(i)}}}initializeElements(){const t=io(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))throw new Error("Shadow root not found");this.DCE_ELEMENTS={selectCameraBtn:e.shadowRoot.querySelector(".dce-mn-select-camera-icon"),uploadImageBtn:e.shadowRoot.querySelector(".dce-mn-upload-image-icon"),soundFeedbackBtn:e.shadowRoot.querySelector(".dce-mn-sound-feedback"),closeScannerBtn:e.shadowRoot.querySelector(".dce-mn-close"),scanModeSelectContainer:e.shadowRoot.querySelector(".dce-mn-scan-mode-select"),passportModeOption:e.shadowRoot.querySelector(".scan-mode-option-passport"),td1ModeOption:e.shadowRoot.querySelector(".scan-mode-option-td1"),td2ModeOption:e.shadowRoot.querySelector(".scan-mode-option-td2"),toast:e.shadowRoot.querySelector(".dce-mn-toast")},this.setupScanModeSelector(),this.assignDCEClickEvents(),this.DCE_ELEMENTS.toast.style.display="none",!1===this.config.showUploadImage&&(this.DCE_ELEMENTS.uploadImageBtn.style.display="none"),!1===this.config.showSoundToggle&&(this.DCE_ELEMENTS.soundFeedbackBtn.style.display="none"),this.initializedDCE=!0}setupScanModeSelector(){if(!1!==this.config.showFormatSelector)switch(this.currentScanMode){case Ka.PassportAndTD1:this.DCE_ELEMENTS.td2ModeOption.style.display="none";break;case Ka.PassportAndTD2:this.DCE_ELEMENTS.td1ModeOption.style.display="none";break;case Ka.TD1AndTD2:this.DCE_ELEMENTS.passportModeOption.style.display="none";break;case Ka.All:break;default:this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}else this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}assignDCEClickEvents(){if(!Object.values(this.DCE_ELEMENTS).every(Boolean))throw new Error("Camera control elements not found");this.closeCamera=this.closeCamera.bind(this),this.DCE_ELEMENTS.uploadImageBtn.onclick=()=>this.uploadImage(),this.DCE_ELEMENTS.soundFeedbackBtn.onclick=()=>this.toggleSoundFeedback(),this.DCE_ELEMENTS.closeScannerBtn.onclick=()=>this.handleCloseBtn(),this.DCE_ELEMENTS.selectCameraBtn.onclick=t=>{t.stopPropagation(),this.toggleSelectCameraBox()},this.DCE_ELEMENTS.passportModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.passportModeOption.style.display&&await this.toggleScanDocType($a.Passport)},this.DCE_ELEMENTS.td1ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td1ModeOption.style.display&&await this.toggleScanDocType($a.TD1)},this.DCE_ELEMENTS.td2ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td2ModeOption.style.display&&await this.toggleScanDocType($a.TD2)}}handleCloseBtn(){this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:eo.RS_CANCELLED,message:"Cancelled"}})}attachOptionClickListeners(){const t=io(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))return;const i=e.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings");[...e.shadowRoot.querySelectorAll(".dce-mn-camera-option"),...e.shadowRoot.querySelectorAll(".dce-mn-resolution-option")].forEach((t=>{t.addEventListener("click",(async e=>{const n=t.getAttribute("data-davice-id"),r=t.getAttribute("data-height"),s=t.getAttribute("data-width");n?this.resources.cameraEnhancer.selectCamera(n).then((()=>{this.toggleScanGuide()})):r&&s&&this.resources.cameraEnhancer.setResolution({width:parseInt(s),height:parseInt(r)}).then((()=>{this.toggleScanGuide()})),"none"!==i.style.display&&this.toggleSelectCameraBox()}))}))}highlightCameraAndResolutionOption(){const t=io(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))return;const i=e.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings"),n=i.querySelectorAll(".dce-mn-camera-option"),r=i.querySelectorAll(".dce-mn-resolution-option"),s=this.resources.cameraEnhancer.getSelectedCamera(),a=this.resources.cameraEnhancer.getResolution();n.forEach((t=>{const e=t;e.getAttribute("data-davice-id")===(null==s?void 0:s.deviceId)?e.style.border="2px solid #fe814a":e.style.border="none"}));const o={"480p":"480","720p":"720","1080p":"1080","2k":"1440","4k":"2160"},l=function(t){const e=t.width*t.height,i=t.width/t.height;let n="480p",r=Number.MAX_VALUE;for(const[t,s]of Object.entries(ao)){const a=s.width*s.height,o=s.width/s.height,l=.7*Math.abs(a-e)+Math.abs(o-i)*a*.3;l{const e=t,i=e.getAttribute("data-height");e.style.border=i===o[l]?"2px solid #fe814a":"none"}))}toggleSelectCameraBox(){const t=io(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))return;const i=e.shadowRoot.querySelector(".dce-mn-resolution-box");this.highlightCameraAndResolutionOption(),this.attachOptionClickListeners(),i.click()}async uploadImage(){var t,e,i;const{cvRouter:n}=this.resources,r=document.createElement("input");r.type="file",r.accept="image/*",r.style.display="none",document.body.appendChild(r);try{this.showScannerLoadingOverlay("Processing image..."),await this.closeCamera(!1);const s=await new Promise(((t,e)=>{r.onchange=i=>{var n;const r=null===(n=i.target.files)||void 0===n?void 0:n[0];(null==r?void 0:r.type.startsWith("image/"))?t(r):e(new Error("Please select an image file"))},r.addEventListener("cancel",(async()=>{this.hideScannerLoadingOverlay(!1),await this.launch()})),r.click()}));if(!s)return this.hideScannerLoadingOverlay(!1),void await this.launch();const a=this.config.utilizedTemplateNames[this.currentScanMode];if(!1!==this.config.showScanGuide){const t=await n.getSimplifiedSettings(a);t.roiMeasuredInPercentage=!0,t.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await n.updateSettings(a,t)}const o=await n.capture(s,a);this.capturedResultItems=o.items;const l=this.capturedResultItems.filter((t=>t.type===yt.CRIT_ORIGINAL_IMAGE))[0].imageData;l.toCanvas=()=>{const t=document.createElement("canvas");t.width=l.width,t.height=l.height;const e=t.getContext("2d");if(!e)throw new Error("Failed to get canvas context");const i=new ImageData(new Uint8ClampedArray(l.bytes.buffer),l.width,l.height);return e.putImageData(i,0,0),t},this.originalImageData=l;const h=null==o?void 0:o.textLineResultItems,c=null==o?void 0:o.parsedResultItems;let d={};if(null==h?void 0:h.length){const e=(null===(t=h[0])||void 0===t?void 0:t.text)||"";d=go(e,c[0])}const u={status:{code:eo.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,_imageData:this.originalImageData,data:d};null===(i=(e=this.resources).onResultUpdated)||void 0===i||i.call(e,u),this.currentScanResolver(u),this.hideScannerLoadingOverlay(!0)}catch(t){let e=(null==t?void 0:t.message)||t;console.error(e),alert(e),this.closeCamera();const i={status:{code:eo.RS_FAILED,message:"Error processing uploaded image"}};this.currentScanResolver(i)}finally{document.body.removeChild(r)}}toggleSoundFeedback(t){this.isSoundFeedbackOn=void 0!==t?t:!this.isSoundFeedbackOn;const e=io(this.config.container),i=e.children[e.children.length-1];if(!(null==i?void 0:i.shadowRoot))return;const n=i.shadowRoot.querySelector(".dce-mn-sound-feedback"),r=n.querySelector(".dce-mn-sound-feedback-on");n.querySelector(".dce-mn-sound-feedback-off").style.display=this.isSoundFeedbackOn?"none":"block",r.style.display=this.isSoundFeedbackOn?"block":"none"}calculateScanRegion(t){const{cameraEnhancer:e,cameraView:i}=this.resources;if(!e||!e.isOpen())return;const n=i.getVisibleRegionOfVideo({inPixels:!0});if(!n)return;const r=i.getVideoElement(),s=r.videoWidth,a=r.videoHeight,o=mo[t];let l;const h=n.height-80;if(n.width>n.height){l=.75*h/o.height;l*o.width>.9*n.width&&(l=.9*n.width/o.width)}else{l=.9*n.width/o.width;l*o.height>.75*h&&(l=.75*h/o.height)}const c=l*o.width,d=l*o.height,u=(n.width-c)/2,f=(h-d)/2,g=u,m=u+c,p=f,_=f+d,v=(n.x+g)/s*100,y=(n.x+m)/s*100,w=(n.y+p)/a*100,C=(n.y+_)/a*100,E={left:Math.round(v),right:Math.round(y),top:Math.round(w),bottom:Math.round(C),isMeasuredInPercentage:!0};null==i||i.setScanRegionMaskVisible(!0),e.setScanRegion(E)}toggleScanGuide(t){const e=io(this.config.container),i=e.children[e.children.length-1];if(!(null==i?void 0:i.shadowRoot))return;const n=i.shadowRoot.querySelector(".dce-scanguide-passport"),r=i.shadowRoot.querySelector(".dce-scanguide-td1"),s=i.shadowRoot.querySelector(".dce-scanguide-td2");if(!1===t||!1===this.config.showScanGuide)return n.style.display="none",r.style.display="none",void(s.style.display="none");switch(this.currentScanMode){case Ka.All:case Ka.Passport:case Ka.PassportAndTD1:case Ka.PassportAndTD2:n.style.display="block",r.style.display="none",s.style.display="none",this.calculateScanRegion($a.Passport);break;case Ka.TD1:case Ka.TD1AndTD2:n.style.display="none",r.style.display="block",s.style.display="none",this.calculateScanRegion($a.TD1);break;case Ka.TD2:n.style.display="none",r.style.display="none",s.style.display="block",this.calculateScanRegion($a.TD2)}}async openCamera(){try{this.showScannerLoadingOverlay("Initializing camera...");const{cameraEnhancer:t,cameraView:e}=this.resources,i=io(this.config.container);if(i.style.display="block",t.isOpen())t.isPaused()&&await t.resume();else{const n=e.getUIElement();n.parentElement||i.append(n),await t.open()}!this.initializedDCE&&t.isOpen()&&await this.initializeElements(),window.addEventListener("resize",this.handleResize);const n=i.children[i.children.length-1];if(!(null==n?void 0:n.shadowRoot))throw new Error("Shadow root not found");n.shadowRoot.querySelector(".dce-mn-torch-off").style.display="none",n.shadowRoot.querySelector(".dce-mn-torch-on").style.display="none"}catch(t){let e=(null==t?void 0:t.message)||t;console.error(e),alert(e),this.closeCamera();const i={status:{code:eo.RS_FAILED,message:"MRZ Scanner Open Camera Error"}};this.currentScanResolver(i)}finally{this.hideScannerLoadingOverlay()}}async closeCamera(t=!0){try{window.removeEventListener("resize",this.handleResize),this.resizeTimer&&(window.clearTimeout(this.resizeTimer),this.resizeTimer=null);const{cameraEnhancer:e,cameraView:i}=this.resources,n=io(this.config.container);n.style.display=t?"none":"block",(null==i?void 0:i.getUIElement().parentElement)&&n.removeChild(i.getUIElement()),e.close(),this.stopCapturing()}catch(t){let e=(null==t?void 0:t.message)||t;console.error(`Close Camera error: ${e}`)}}pauseCamera(){const{cameraEnhancer:t}=this.resources;t.pause()}stopCapturing(){const{cameraView:t,cvRouter:e}=this.resources;e.stopCapturing(),t.clearAllInnerDrawingItems()}async handleMRZResult(t){var e;if(this.capturedResultItems=t.items,!(t.items.length<=1))try{const{onResultUpdated:i}=this.resources,n=t.items.filter((t=>t.type===yt.CRIT_ORIGINAL_IMAGE));this.originalImageData=n.length&&n[0].imageData;const r=null==t?void 0:t.textLineResultItems,s=null==t?void 0:t.parsedResultItems;if(r){this.isSoundFeedbackOn&&Ds.beep();const t=(null===(e=null==r?void 0:r[0])||void 0===e?void 0:e.text)||"",n=go(t,s[0]);this.closeCamera();const a={status:{code:eo.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,_imageData:this.originalImageData,data:n};null==i||i(a),this.currentScanResolver(a)}}catch(t){let e=(null==t?void 0:t.message)||t;console.error(e),alert(e),this.closeCamera();const i={status:{code:eo.RS_FAILED,message:"Error capturing image"}};this.currentScanResolver(i)}}initializeScanModeManager(){const{mrzFormatType:t}=this.config;if(this.scanModeManager={[$a.Passport]:!0,[$a.TD1]:!0,[$a.TD2]:!0},!t||Array.isArray(t)&&0===t.length)return;Object.keys(this.scanModeManager).forEach((t=>{this.scanModeManager[t]=!1}));(Array.isArray(t)?t:[t]).forEach((t=>{this.scanModeManager[t]=!0}))}getScanMode(){const t=Object.entries(this.scanModeManager).filter((([t,e])=>e)).map((([t])=>t)).sort().join(",");return{[$a.Passport]:Ka.Passport,[$a.TD1]:Ka.TD1,[$a.TD2]:Ka.TD2,[`${$a.Passport},${$a.TD1}`]:Ka.PassportAndTD1,[`${$a.Passport},${$a.TD2}`]:Ka.PassportAndTD2,[`${$a.TD1},${$a.TD2}`]:Ka.TD1AndTD2,[`${$a.Passport},${$a.TD1},${$a.TD2}`]:Ka.All,"":Ka.All}[t]}DCEShowToast(t,e=3e3){this.DCE_ELEMENTS.toast&&(this.DCE_ELEMENTS.toast.textContent=t,this.DCE_ELEMENTS.toast.style.display="",setTimeout((()=>{this.DCE_ELEMENTS.toast.style.display="none"}),e))}async startCapturing(){const{cvRouter:t,cameraEnhancer:e}=this.resources,i=this.config.utilizedTemplateNames[this.currentScanMode];try{if(!1!==this.config.showScanGuide){const e=await t.getSimplifiedSettings(i);e.roiMeasuredInPercentage=!0,e.roi.points=[{x:0,y:50},{x:100,y:50},{x:100,y:100},{x:0,y:100}],await t.updateSettings(i,e)}await t.startCapturing(i),e.setPixelFormat(o.IPF_ABGR_8888)}catch(t){let e=(null==t?void 0:t.message)||t;console.error("Failed to start capturing:",e),this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:eo.RS_FAILED,message:"Failed to start capturing"}})}}async toggleScanDocType(t){try{if(this.scanModeManager[t]&&0===Object.entries(this.scanModeManager).filter((([e,i])=>i&&e!==t)).length)return console.warn("MRZ Scanner - At least one mode must be enabled"),void this.DCEShowToast("At least one mode must be enabled");this.scanModeManager[t]=!this.scanModeManager[t],this.currentScanMode=this.getScanMode(),this.stopCapturing(),await this.startCapturing(),this.toggleScanGuide(),this.DCE_ELEMENTS.td1ModeOption.classList.toggle("selected",this.scanModeManager[$a.TD1]),this.DCE_ELEMENTS.td2ModeOption.classList.toggle("selected",this.scanModeManager[$a.TD2]),this.DCE_ELEMENTS.passportModeOption.classList.toggle("selected",this.scanModeManager[$a.Passport])}catch(t){let e=(null==t?void 0:t.message)||t;console.error("MRZ Scanner switch scan mode error: ",e),this.closeCamera();const i={status:{code:eo.RS_FAILED,message:"MRZ Scanner switch scan mode error"}};this.currentScanResolver(i)}}async launch(){try{await this.initialize();const{cvRouter:t,cameraEnhancer:e}=this.resources;return new Promise((async t=>{this.currentScanResolver=t,await this.openCamera(),!this.initializedDCE&&e.isOpen()&&await this.initializeElements(),await this.startCapturing(),this.toggleScanGuide()}))}catch(t){let e=(null==t?void 0:t.message)||t;console.error("MRZ Scanner launch error: ",e),this.closeCamera();const i={status:{code:eo.RS_FAILED,message:"MRZ Scanner launch error"}};this.currentScanResolver(i)}}}const _o={rescan:'\n\n\n \n\n\n\n\n\n\n\n',complete:'\n\n\n\n \n\n\n\n\n\n\n\n',failed:'\n \n \n \n\n',info:'\n\n \n \n \n\n'};class vo{constructor(t,e,i){this.resources=t,this.config=e,this.scannerView=i,this.editedFields={}}async launch(){try{return io(this.config.container).textContent="",await this.initialize(),io(this.config.container).style.display="flex",new Promise((t=>{this.currentScanResultViewResolver=t}))}catch(t){let e=(null==t?void 0:t.message)||t;throw console.error(e),e}}async handleRescan(){var t;try{if(!this.scannerView)return void console.error("Scanner View not initialized");this.hideView();const e=await this.scannerView.launch();if((null===(t=null==e?void 0:e.status)||void 0===t?void 0:t.code)===eo.RS_FAILED)return void(this.currentScanResultViewResolver&&this.currentScanResultViewResolver(e));this.resources.onResultUpdated&&((null==e?void 0:e.status.code)===eo.RS_CANCELLED?this.resources.onResultUpdated(this.resources.result):(null==e?void 0:e.status.code)===eo.RS_SUCCESS&&this.resources.onResultUpdated(e)),this.dispose(!0),await this.initialize(),io(this.config.container).style.display="flex"}catch(t){throw console.error("Error in rescan handler:",t),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:eo.RS_FAILED,message:(null==t?void 0:t.message)||t}}),t}}async handleDone(){var t,e;try{(null===(t=this.resources.result)||void 0===t?void 0:t.data)&&!ro(this.editedFields)&&(this.resources.result.data=Object.assign(Object.assign({},this.resources.result.data),this.editedFields),this.resources.onResultUpdated&&this.resources.onResultUpdated(this.resources.result)),(null===(e=this.config)||void 0===e?void 0:e.onDone)&&await this.config.onDone(this.resources.result),this.currentScanResultViewResolver&&this.resources.result&&this.currentScanResultViewResolver(this.resources.result),this.hideView(),this.dispose()}catch(t){throw console.error("Error in done handler:",t),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:eo.RS_FAILED,message:(null==t?void 0:t.message)||t}}),t}}createControls(){var t,e,i,n,r,s,a,o;const{toolbarButtonsConfig:l}=this.config;return function(t){no("dynamsoft-mrz-controls-style","\n .dynamsoft-mrz-controls {\n display: flex;\n height: 6rem;\n background-color: #323234;\n align-items: center;\n font-size: 12px;\n font-family: Verdana;\n color: white;\n width: 100%;\n }\n\n .dynamsoft-mrz-control-btn {\n background-color: #323234;\n color: white;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n height: 100%;\n width: 100%;\n gap: 0.5rem;\n text-align: center;\n user-select: none;\n }\n\n .dynamsoft-mrz-control-btn.hide {\n display: none;\n }\n\n .dynamsoft-mrz-control-btn.disabled {\n opacity: 0.4;\n pointer-events: none;\n cursor: default;\n }\n\n .dynamsoft-mrz-control-icon-wrapper {\n flex: 0.75;\n display: flex;\n align-items: flex-end;\n justify-content: center;\n min-height: 40px;\n }\n\n .dynamsoft-mrz-control-icon img,\n .dynamsoft-mrz-control-icon svg {\n width: 32px;\n height: 32px;\n fill: #fe8e14;\n }\n\n .dynamsoft-mrz-control-text {\n flex: 0.5;\n display: flex;\n align-items: flex-start;\n justify-content: center;\n padding-bottom: 0.5rem;\n }\n\n \n @media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-controls {\n flex-direction: column;\n height: 100%;\n width: 5rem;\n }\n\n .dynamsoft-mrz-control-text {\n padding: 0 0.5rem 0.5rem;\n }\n }\n");const e=document.createElement("div");return e.className="dynamsoft-mrz-controls",t.forEach((t=>{const i=document.createElement("div");i.className=`dynamsoft-mrz-control-btn ${null==t?void 0:t.className}`;const n=document.createElement("div");if(n.className="dynamsoft-mrz-control-icon-wrapper",(r=t.icon).trim().startsWith(""))n.innerHTML=t.icon;else{const e=document.createElement("img");e.src=t.icon,e.alt=t.label,e.width=24,e.height=24,n.appendChild(e)}var r;const s=document.createElement("div");s.className="dynamsoft-mrz-control-text",s.textContent=t.label,t.isDisabled&&i.classList.add("disabled"),t.isHidden&&i.classList.add("hide"),i.appendChild(n),i.appendChild(s),t.onClick&&!t.isDisabled&&i.addEventListener("click",t.onClick),e.appendChild(i)})),e}([{id:"dynamsoft-mrz-scanResult-rescan",icon:(null===(t=null==l?void 0:l.rescan)||void 0===t?void 0:t.icon)||_o.rescan,label:(null===(e=null==l?void 0:l.rescan)||void 0===e?void 0:e.label)||"Re-scan",onClick:()=>this.handleRescan(),className:`${(null===(i=null==l?void 0:l.rescan)||void 0===i?void 0:i.className)||""}`,isHidden:(null===(n=null==l?void 0:l.rescan)||void 0===n?void 0:n.isHidden)||!1,isDisabled:!this.scannerView},{id:"dynamsoft-mrz-scanResult-done",icon:(null===(r=null==l?void 0:l.done)||void 0===r?void 0:r.icon)||_o.complete,label:(null===(s=null==l?void 0:l.done)||void 0===s?void 0:s.label)||"Done",className:`${(null===(a=null==l?void 0:l.done)||void 0===a?void 0:a.className)||""}`,isHidden:(null===(o=null==l?void 0:l.done)||void 0===o?void 0:o.isHidden)||!1,onClick:()=>this.handleDone()}])}handleFieldEdit(t,e){if(t===ho.DateOfBirth||t===ho.DateOfExpiry)try{const[i,n,r]=e.split(/[\/\-\.]/);r&&n&&i&&(this.editedFields[t]={day:parseInt(r,10),month:parseInt(n,10),year:parseInt(i,10)})}catch(t){console.error("Error parsing date",t)}else this.editedFields[t]=e}createMRZDataDisplay(){var t;const e=(null===(t=this.resources.result)||void 0===t?void 0:t.data)||{},i=!!this.config.allowResultEditing,n=e.invalidFields||[],r=document.createElement("div");if(r.className="dynamsoft-mrz-data-container",ro(e)){const t=document.createElement("div");return t.className="dynamsoft-mrz-data-row empty",t.innerText="No MRZ detected. Please try again.",r.appendChild(t),r}if(n.length>0){const t=document.createElement("div");t.className="dynamsoft-mrz-error-notification",t.innerHTML=`\n
${_o.failed}
\n
\n ${i?"Some fields require correction. Please review highlighted fields.":"Some fields contain invalid information. Please rescan the document."}\n
\n `,r.appendChild(t)}else if(0===n.length&&i){const t=document.createElement("div");t.className="dynamsoft-mrz-info-notification",t.innerHTML=`\n
${_o.info}
\n
\n Please review all fields to ensure the information is correct.\n
\n `,r.appendChild(t)}return Object.entries(e).forEach((([t,e])=>{var s;if(t===ho.InvalidFields||!e)return;if(t===ho.MRZText&&!1===(null===(s=this.config)||void 0===s?void 0:s.showMRZText))return;const a=document.createElement("div");a.className="dynamsoft-mrz-data-row";const o=n.includes(t);o&&a.classList.add("invalid-field");const l=[ho.MRZText,ho.DocumentType],h=document.createElement("span");if(h.className="dynamsoft-mrz-data-label",h.innerText=co[t]||t,o){const t=document.createElement("span");if(t.className="dynamsoft-mrz-error-icon",t.innerHTML=_o.failed,h.appendChild(t),i){const t=document.createElement("span");t.className="dynamsoft-mrz-error-hint",t.textContent="Please correct this field",h.appendChild(t)}}const c=document.createElement("div");if(c.className="dynamsoft-mrz-data-value",i&&!l.includes(t)){const i=document.createElement("input");i.className="dynamsoft-mrz-data-input",o&&i.classList.add("invalid"),t===ho.DateOfBirth||t===ho.DateOfExpiry?(i.value=fo(e),i.setAttribute("placeholder","YYYY-MM-DD")):i.value=e,i.addEventListener("input",(e=>{if(this.handleFieldEdit(t,e.target.value),o){i.classList.remove("invalid"),a.classList.remove("invalid-field"),this.editedFields.invalidFields||(this.editedFields.invalidFields=[...n]);const e=this.editedFields.invalidFields.indexOf(t);e>-1&&this.editedFields.invalidFields.splice(e,1)}})),c.appendChild(i)}else t===ho.MRZText?(c.classList.add("code"),c.innerText=e):t===ho.DateOfBirth||t===ho.DateOfExpiry?c.innerText=fo(e):c.innerText=e,o&&c.classList.add("invalid-value");a.appendChild(h),a.appendChild(c),r.appendChild(a)})),r}async initialize(){try{if(!this.resources.result)throw Error("Captured image is missing. Please capture an image first!");if(!this.config.container)throw new Error("Please create a Scan Result View Container element");no("dynamsoft-mrz-result-view-style",yo);const t=document.createElement("div");if(t.className="dynamsoft-mrz-result-view-container",!1!==this.config.showOriginalImage){const e=this.resources.result.originalImageResult,i=document.createElement("div");let n;i.className="dynamsoft-mrz-result-view-image-container",(null==e?void 0:e.toCanvas)&&(n=null==e?void 0:e.toCanvas()),Object.assign(n.style,{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}),i.appendChild(n),t.appendChild(i)}const e=this.createMRZDataDisplay();t.appendChild(e);const i=this.createControls();t.appendChild(i),io(this.config.container).appendChild(t)}catch(t){let e=(null==t?void 0:t.message)||t;console.error(e),alert(e)}}hideView(){io(this.config.container).style.display="none"}dispose(t=!1){io(this.config.container).textContent="",t||(this.currentScanResultViewResolver=void 0)}}const yo="\n .dynamsoft-mrz-result-view-container {\n display: flex;\n width: 100%;\n height: 100%;\n background-color:#575757;\n font-size: 12px;\n flex-direction: column;\n align-items: center;\n }\n\n .dynamsoft-mrz-result-view-image-container {\n width: 100%;\n height: 200px;\n display: flex;\n justify-content: center;\n align-items: center;\n background-color: #323234;\n }\n\n \n.dynamsoft-mrz-data-container {\n font-size: 16px;\n font-family: Verdana;\n color: white;\n overflow: auto;\n width: 100%;\n height: 100%;\n min-height: 0;\n margin: 1rem 0;\n}\n\n.dynamsoft-mrz-data-row {\n padding: 0.5rem 2rem;\n display: flex;\n flex-direction: column;\n gap: 0.5rem;\n transition: background-color 0.3s ease;\n}\n\n.dynamsoft-mrz-data-row.invalid-field {\n background-color: rgba(231, 76, 60, 0.1);\n border-left: 3px solid #e74c3c;\n padding-left: calc(2rem - 3px);\n}\n\n.dynamsoft-mrz-data-label {\n color: #aaa;\n display: flex;\n gap: 0.5rem;\n align-items: end;\n flex-wrap: wrap;\n}\n\n.dynamsoft-mrz-error-notification,\n.dynamsoft-mrz-info-notification {\n color: white;\n padding: 1rem;\n margin: 0.5rem 2rem;\n border-radius: 4px;\n display: flex;\n align-items: center;\n gap: 1rem;\n text-align: start;\n}\n\n.dynamsoft-mrz-error-notification {\n background-color: rgba(231, 76, 60, 0.2);\n}\n\n.dynamsoft-mrz-info-notification {\n background-color: rgba(196, 231, 60, 0.2);\n}\n\n.dynamsoft-mrz-edit-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #aaa;\n}\n\n.dynamsoft-mrz-error-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-info-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: white;\n}\n\n.dynamsoft-mrz-info-message,\n.dynamsoft-mrz-error-message {\n flex: 1;\n}\n\n.dynamsoft-mrz-error-hint {\n font-size: 0.8rem;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-value {\n word-wrap: break-word;\n text-align: start;\n}\n\n.dynamsoft-mrz-data-value.code {\n font-family: monospace;\n}\n\n.dynamsoft-mrz-data-value.invalid-value {\n color: #e74c3c;\n text-decoration: wavy underline #e74c3c;\n text-decoration-skip-ink: none;\n}\n\n.dynamsoft-mrz-data-input {\n width: 100%;\n padding: 5px;\n background-color: rgba(255, 255, 255, 0.1);\n border: 1px solid rgba(255, 255, 255, 0.3);\n color: white;\n border-radius: 4px;\n font-size: 14px;\n transition: all 0.3s ease;\n}\n\n.dynamsoft-mrz-data-input.invalid {\n background-color: rgba(231, 76, 60, 0.1);\n border-color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-input:focus {\n background-color: rgba(255, 255, 255, 0.2);\n border-color: #fe8e14;\n outline: none;\n}\n\n@media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-result-view-container {\n flex-direction: row;\n }\n\n .dynamsoft-mrz-result-view-image-container{\n flex: 1;\n height: 100%;\n }\n\n .dynamsoft-mrz-data-container{\n flex: 1;\n }\n\n .dynamsoft-mrz-data-row:first-of-type {\n padding-top: 2rem;\n }\n\n .dynamsoft-mrz-data-row:last-of-type {\n padding-bottom: 2rem;\n }\n\n .dynamsoft-mrz-data-row.empty {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n padding-top: 0;\n padding-bottom: 0;\n }\n}\n",wo={rootDirectory:"https://cdn.jsdelivr.net/npm/"};class Co{showLoadingOverlay(t){var e,i;const n=io(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)||io(null===(i=this.config.resultViewConfig)||void 0===i?void 0:i.container);this.loadingScreen=oo(n,{message:t}),n.style.display="block",n.style.position="relative"}hideLoadingOverlay(t=!1){var e,i,n;const r=io(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)||io(null===(i=this.config.resultViewConfig)||void 0===i?void 0:i.container);this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,t&&(r.style.display="none",(null===(n=this.config)||void 0===n?void 0:n.container)&&(io(this.config.container).style.display="none")))}constructor(t){this.config=t,this.resources={},this.isInitialized=!1,this.isCapturing=!1,this.loadingScreen=null}async initialize(){if(this.isInitialized)return{resources:this.resources,components:{scannerView:this.scannerView,resultView:this.resultView}};try{if(!this.initializeMRZScannerConfig())return console.error("Failed to initialize mrz scanner config"),{resources:this.resources,components:{}};no("dynamsoft-mrz-loading-screen-style",lo),this.showLoadingOverlay("Loading...");if(!await this.initializeDCVResources())return this.hideLoadingOverlay(!0),console.error("Failed to initialize DCV resources"),{resources:this.resources,components:{}};this.resources.onResultUpdated=t=>{this.resources.result=t};const t={};return this.config.scannerViewConfig&&(this.scannerView=new po(this.resources,this.config.scannerViewConfig),t.scannerView=this.scannerView,await this.scannerView.initialize()),this.config.resultViewConfig&&(this.resultView=new vo(this.resources,this.config.resultViewConfig,this.scannerView),t.resultView=this.resultView),this.isInitialized=!0,{resources:this.resources,components:t}}catch(t){this.isInitialized=!1;const e=`Initialization Failed: ${(null==t?void 0:t.message)||t}`;return alert(e),console.error(e),{resources:this.resources,components:{}}}finally{this.hideLoadingOverlay(!0)}}async initializeDCVResources(){var t,e,i;try{return Kt.initLicense((null===(t=this.config)||void 0===t?void 0:t.license)||"",!0),vt.engineResourcePaths=ro(null===(e=this.config)||void 0===e?void 0:e.engineResourcePaths)?wo:this.config.engineResourcePaths,vt.loadWasm(["DLR","DCP"]),_a.loadSpec("MRTD_TD3_PASSPORT"),_a.loadSpec("MRTD_TD1_ID"),_a.loadSpec("MRTD_TD2_ID"),Qs.loadRecognitionData("MRZ"),this.resources.cameraView=await Nn.createInstance(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.cameraEnhancerUIPath),this.resources.cameraEnhancer=await Fs.createInstance(this.resources.cameraView),this.resources.cvRouter=await Fe.createInstance(),!0}catch(t){let e=(null==t?void 0:t.message)||t;if(null==e?void 0:e.toLowerCase().includes("license")){const t="The MRZ Scanner license is invalid or has expired. Please contact the site administrator to resolve this issue.";alert(t),console.error(t)}else{const t=`Resource Initialization Failed: ${e}`;alert(t),console.error(t)}return!1}}shouldCreateDefaultContainer(){var t,e;const i=!this.config.container,n=!((null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)||(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container));return i&&n}createDefaultMRZScannerContainer(){const t=document.createElement("div");return t.className="mrz-scanner-main-container",Object.assign(t.style,{height:"100dvh",width:"100%",position:"absolute",left:"0",top:"0",zIndex:"999"}),document.body.append(t),t}checkForTemporaryLicense(t){return!(null==t?void 0:t.length)||(null==t?void 0:t.startsWith("A"))||(null==t?void 0:t.startsWith("L"))||(null==t?void 0:t.startsWith("P"))||(null==t?void 0:t.startsWith("Y"))?"DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9":t}validateViewConfigs(){var t,e,i,n,r,s,a,o;if(!this.config.container){if((null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)&&this.config.showResultView&&!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container)){const t="MRZResultView container is required when showResultView is true";return alert(t),console.error(t),!1}if(!(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.container)&&(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container)&&!this.resources.result){const t="Result is needed to create MRZResultView without a scanner view";return alert(t),console.error(t),!1}}try{if(this.config.container&&!io(this.config.container)){const t="Invalid main container reference";return alert(t),console.error(t),!1}if((null===(r=this.config.scannerViewConfig)||void 0===r?void 0:r.container)&&!io(null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.container)){const t="Invalid scanner view container reference";return alert(t),console.error(t),!1}if((null===(a=this.config.resultViewConfig)||void 0===a?void 0:a.container)&&!io(null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)){const t="Invalid result view container reference";return alert(t),console.error(t),!1}}catch(t){const e=`Error accessing container references: ${t.message}`;return alert(e),console.error(e),!1}return!0}showResultView(){var t,e;return!1!==this.config.showResultView&&(this.config.container?!(void 0!==this.config.showResultView||!(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container)&&!this.config.container)||!!this.config.showResultView:this.config.showResultView&&!!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container))}initializeMRZScannerConfig(){var t,e,i,n,r,s,a;this.config=null!==(t=this.config)&&void 0!==t?t:{};if(!this.validateViewConfigs())return!1;this.shouldCreateDefaultContainer()?this.config.container=this.createDefaultMRZScannerContainer():this.config.container&&(this.config.container=io(this.config.container));const o=this.config.container?this.createViewContainers(io(this.config.container)):{},l={license:this.checkForTemporaryLicense(this.config.license),utilizedTemplateNames:Object.fromEntries(Object.values(Ka).map((t=>{var e;return[t,(null===(e=this.config.utilizedTemplateNames)||void 0===e?void 0:e[t])||to[t]]}))),templateFilePath:(null===(e=this.config)||void 0===e?void 0:e.templateFilePath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.0.0/dist/mrz-scanner.template.json"},h=Object.assign(Object.assign({},this.config.scannerViewConfig),{container:o[Qa.Scanner]||io(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.container)||null,cameraEnhancerUIPath:(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.cameraEnhancerUIPath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.0.0/dist/mrz-scanner.ui.html",templateFilePath:l.templateFilePath,utilizedTemplateNames:l.utilizedTemplateNames,enableMultiFrameCrossFilter:null===(s=null===(r=this.config.scannerViewConfig)||void 0===r?void 0:r.enableMultiFrameCrossFilter)||void 0===s||s,mrzFormatType:this.config.mrzFormatType}),c=this.showResultView()?Object.assign(Object.assign({},this.config.resultViewConfig),{container:o[Qa.Result]||io(null===(a=this.config.resultViewConfig)||void 0===a?void 0:a.container)||null}):void 0;return Object.assign(this.config,Object.assign(Object.assign({},l),{scannerViewConfig:h,resultViewConfig:c})),!0}createViewContainers(t){t.textContent="";const e=[Qa.Scanner];return this.showResultView()&&e.push(Qa.Result),e.reduce(((e,i)=>{const n=document.createElement("div");return n.className=`mrz-scanner-${i}-view-container`,Object.assign(n.style,{height:"100%",width:"100%",display:"none",position:"relative"}),t.append(n),e[i]=n,e}),{})}dispose(){var t,e;this.resultView&&(this.resultView.dispose(),this.resultView=null),this.scannerView=null,this.resources.cameraEnhancer&&(this.resources.cameraEnhancer.dispose(),this.resources.cameraEnhancer=null),this.resources.cameraView&&(this.resources.cameraView.dispose(),this.resources.cameraView=null),this.resources.cvRouter&&(this.resources.cvRouter.dispose(),this.resources.cvRouter=null),this.resources.result=null,this.resources.onResultUpdated=null;const i=t=>{const e=io(t);e&&(e.style.display="none",e.textContent="")};i(this.config.container),i(null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container),i(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container),this.isInitialized=!1}async launch(){if(this.isCapturing)throw new Error("Capture session already in progress");try{this.isCapturing=!0;const{components:t}=await this.initialize();if(ro(t))throw new Error("MRZ Scanner initialization failed.");if(this.config.container&&(io(this.config.container).style.display="block"),!t.scannerView&&this.resources.result&&t.resultView)return await t.resultView.launch();if(!t.scannerView&&!this.resources.result)throw new Error("Scanner view is required when no previous result exists");if(t.scannerView){const e=await t.scannerView.launch();if((null==e?void 0:e.status.code)!==eo.RS_SUCCESS)return{status:{code:null==e?void 0:e.status.code,message:(null==e?void 0:e.status.message)||"Failed to capture image"}};if(t.resultView)return await t.resultView.launch()}return this.resources.result}catch(t){return alert((null==t?void 0:t.message)||t),console.error((null==t?void 0:t.message)||t),{status:{code:eo.RS_FAILED,message:(null==t?void 0:t.message)||t}}}finally{this.isCapturing=!1,this.dispose()}}}const Eo={MRZScanner:Co,MRZScannerView:po,MRZResultView:vo};export{Fs as CameraEnhancer,qe as CameraEnhancerModule,Nn as CameraView,Fe as CaptureVisionRouter,pe as CaptureVisionRouterModule,Be as CapturedResultReceiver,ua as CodeParser,_a as CodeParserModule,vt as CoreModule,to as DEFAULT_TEMPLATE_NAMES,bi as DrawingItem,Dn as DrawingStyleManager,Eo as DynamsoftMRZScanner,s as EnumBufferOverflowProtectionMode,yt as EnumCapturedResultItemType,a as EnumColourChannelUsageType,wt as EnumCornerType,It as EnumCrossVerificationStatus,ai as EnumDrawingItemMediaType,oi as EnumDrawingItemState,li as EnumEnhancedFeatures,Ct as EnumErrorCode,Et as EnumGrayscaleEnhancementMode,St as EnumGrayscaleTransformationMode,o as EnumImagePixelFormat,ve as EnumImageSourceState,bt as EnumImageTagType,Ot as EnumIntermediateResultUnitType,ho as EnumMRZData,$a as EnumMRZDocumentType,Ka as EnumMRZScanMode,Qa as EnumMRZScannerViews,ia as EnumMappingStatus,Tt as EnumPDFReadingMode,Ve as EnumPresetTemplate,xt as EnumRasterDataSource,ea as EnumRawTextLineStatus,At as EnumRegionObjectElementType,eo as EnumResultStatus,Rt as EnumSectionType,na as EnumValidationStatus,Ds as Feedback,Bi as GroupDrawingItem,Di as ImageDrawingItem,Ys as ImageEditorView,ya as ImageManager,K as ImageSourceAdapter,je as IntermediateResultReceiver,Qs as LabelRecognizerModule,Kt as LicenseManager,Qt as LicenseModule,ki as LineDrawingItem,co as MRZDataLabel,vo as MRZResultView,Co as MRZScanner,po as MRZScannerView,Ja as MultiFrameResultCrossFilter,Ni as QuadDrawingItem,Ti as RectDrawingItem,Mi as TextDrawingItem,xa as UtilityModule,N as _getNorImageData,M as _saveToFile,k as _toBlob,F as _toCanvas,P as _toImage,dt as bDebug,R as checkIsLink,D as compareVersion,fo as displayMRZDate,rt as doOrWaitAsyncDependency,ot as getNextTaskID,L as handleEngineResourcePaths,ft as innerVersions,_ as isArc,v as isContour,C as isDSImageData,E as isDSRect,S as isImageTag,b as isLineSegment,p as isObject,w as isOriginalDsImageData,T as isPoint,x as isPolygon,I as isQuad,O as isRect,_t as loadWasm,it as mapAsyncDependency,gt as mapPackageRegister,lt as mapTaskCallBack,ht as onLog,A as requestResource,ut as setBDebug,ct as setOnLog,ta as utilsFuncs,nt as waitAsyncDependency,st as worker,mt as workerAutoResources}; +const t=t=>t&&"object"==typeof t&&"function"==typeof t.then,e=(async()=>{})().constructor;class i extends e{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(i){let n;this._task=i,t(i)?n=i:"function"==typeof i&&(n=new e(i)),n&&(async()=>{try{const t=await n;i===this._task&&this.resolve(t)}catch(t){i===this._task&&this.reject(t)}})()}get isEmpty(){return null==this._task}constructor(e){let i,n;super(((t,e)=>{i=t,n=e})),this._s="pending",this.resolve=e=>{this.isPending&&(t(e)?this.task=e:(this._s="fulfilled",i(e)))},this.reject=t=>{this.isPending&&(this._s="rejected",n(t))},this.task=e}}function n(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function r(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,i),i}var s,a,o;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.BOPM_BLOCK=0]="BOPM_BLOCK",t[t.BOPM_UPDATE=1]="BOPM_UPDATE"}(s||(s={})),function(t){t[t.CCUT_AUTO=0]="CCUT_AUTO",t[t.CCUT_FULL_CHANNEL=1]="CCUT_FULL_CHANNEL",t[t.CCUT_Y_CHANNEL_ONLY=2]="CCUT_Y_CHANNEL_ONLY",t[t.CCUT_RGB_R_CHANNEL_ONLY=3]="CCUT_RGB_R_CHANNEL_ONLY",t[t.CCUT_RGB_G_CHANNEL_ONLY=4]="CCUT_RGB_G_CHANNEL_ONLY",t[t.CCUT_RGB_B_CHANNEL_ONLY=5]="CCUT_RGB_B_CHANNEL_ONLY"}(a||(a={})),function(t){t[t.IPF_BINARY=0]="IPF_BINARY",t[t.IPF_BINARYINVERTED=1]="IPF_BINARYINVERTED",t[t.IPF_GRAYSCALED=2]="IPF_GRAYSCALED",t[t.IPF_NV21=3]="IPF_NV21",t[t.IPF_RGB_565=4]="IPF_RGB_565",t[t.IPF_RGB_555=5]="IPF_RGB_555",t[t.IPF_RGB_888=6]="IPF_RGB_888",t[t.IPF_ARGB_8888=7]="IPF_ARGB_8888",t[t.IPF_RGB_161616=8]="IPF_RGB_161616",t[t.IPF_ARGB_16161616=9]="IPF_ARGB_16161616",t[t.IPF_ABGR_8888=10]="IPF_ABGR_8888",t[t.IPF_ABGR_16161616=11]="IPF_ABGR_16161616",t[t.IPF_BGR_888=12]="IPF_BGR_888",t[t.IPF_BINARY_8=13]="IPF_BINARY_8",t[t.IPF_NV12=14]="IPF_NV12",t[t.IPF_BINARY_8_INVERTED=15]="IPF_BINARY_8_INVERTED"}(o||(o={}));const l="undefined"==typeof self,h="function"==typeof importScripts,c=(()=>{if(!h){if(!l&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),d=t=>{if(null==t&&(t="./"),l||h);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t},u=t=>Object.prototype.toString.call(t),f=t=>Array.isArray?Array.isArray(t):"[object Array]"===u(t),g=t=>"[object Boolean]"===u(t),m=t=>"number"==typeof t&&!Number.isNaN(t),p=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),_=t=>!(!p(t)||!m(t.x)||!m(t.y)||!m(t.radius)||t.radius<0||!m(t.startAngle)||!m(t.endAngle)),v=t=>!!p(t)&&!!f(t.points)&&0!=t.points.length&&!t.points.some((t=>!T(t))),y=t=>!(!p(t)||!m(t.width)||t.width<=0||!m(t.height)||t.height<=0||!m(t.stride)||t.stride<=0||!("format"in t)||"tag"in t&&!S(t.tag)),w=t=>!(!y(t)||!m(t.bytes.length)&&!m(t.bytes.ptr)),C=t=>!!y(t)&&t.bytes instanceof Uint8Array,E=t=>!(!p(t)||!m(t.left)||t.left<0||!m(t.top)||t.top<0||!m(t.right)||t.right<0||!m(t.bottom)||t.bottom<0||t.left>=t.right||t.top>=t.bottom||!g(t.isMeasuredInPercentage)),S=t=>null===t||!!p(t)&&!!m(t.imageId)&&"type"in t,b=t=>!(!p(t)||!T(t.startPoint)||!T(t.endPoint)||t.startPoint.x==t.endPoint.x&&t.startPoint.y==t.endPoint.y),T=t=>!!p(t)&&!!m(t.x)&&!!m(t.y),I=t=>!!p(t)&&!!f(t.points)&&0!=t.points.length&&!t.points.some((t=>!T(t))),x=t=>!!p(t)&&!!f(t.points)&&0!=t.points.length&&4==t.points.length&&!t.points.some((t=>!T(t))),O=t=>!(!p(t)||!m(t.x)||!m(t.y)||!m(t.width)||t.width<0||!m(t.height)||t.height<0||"isMeasuredInPercentage"in t&&!g(t.isMeasuredInPercentage)),A=async(t,e)=>await new Promise(((i,n)=>{let r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType=e,r.send(),r.onloadend=async()=>{r.status<200||r.status>=300?n(new Error(t+" "+r.status)):i(r.response)},r.onerror=()=>{n(new Error("Network Error: "+r.statusText))}})),R=t=>/^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)|^[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?/.test(t),D=(t,e)=>{let i=t.split("."),n=e.split(".");for(let t=0;t{const e={},i={std:"dynamsoft-capture-vision-std",dip:"dynamsoft-image-processing",core:"dynamsoft-core",dnn:"dynamsoft-capture-vision-dnn",license:"dynamsoft-license",utility:"dynamsoft-utility",cvr:"dynamsoft-capture-vision-router",dbr:"dynamsoft-barcode-reader",dlr:"dynamsoft-label-recognizer",ddn:"dynamsoft-document-normalizer",dcp:"dynamsoft-code-parser",dcpd:"dynamsoft-code-parser",dlrData:"dynamsoft-label-recognizer-data",dce:"dynamsoft-camera-enhancer",ddv:"dynamsoft-document-viewer"};for(let n in t){if("rootDirectory"===n)continue;let r=n,s=t[r],a=s&&"object"==typeof s&&s.path?s.path:s,o=t.rootDirectory;if(o&&!o.endsWith("/")&&(o+="/"),"object"==typeof s&&s.isInternal)o&&(a=t[r].version?`${o}${i[r]}@${t[r].version}/dist/${"ddv"===r?"engine":""}`:`${o}${i[r]}/dist/${"ddv"===r?"engine":""}`);else{const i=/^@engineRootDirectory(\/?)/;if("string"==typeof a&&(a=a.replace(i,o||"")),"object"==typeof a&&"dwt"===r){const n=t[r].resourcesPath,s=t[r].serviceInstallerLocation;e[r]={resourcesPath:n.replace(i,o||""),serviceInstallerLocation:s.replace(i,o||"")};continue}}e[r]=d(a)}return e},M=async(t,e,i)=>await new Promise((async(n,r)=>{try{const r=e.split(".");let s=r[r.length-1];const a=await k(`image/${s}`,t);r.length<=1&&(s="png");const o=new File([a],e,{type:`image/${s}`});if(i){const t=URL.createObjectURL(o),i=document.createElement("a");i.href=t,i.download=e,i.click()}return n(o)}catch(t){return r()}})),F=t=>{C(t)&&(t=N(t));const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e.getContext("2d",{willReadFrequently:!0}).putImageData(t,0,0),e},P=(t,e)=>{C(e)&&(e=N(e));const i=F(e);let n=new Image,r=i.toDataURL(t);return n.src=r,n},k=async(t,e)=>{C(e)&&(e=N(e));const i=F(e);return new Promise(((e,n)=>{i.toBlob((t=>e(t)),t)}))},N=t=>{let e,i=t.bytes;if(!(i&&i instanceof Uint8Array))throw Error("Parameter type error");if(Number(t.format)===o.IPF_BGR_888){const t=i.length/3;e=new Uint8ClampedArray(4*t);for(let n=0;n=r)break;e[a]=e[a+1]=e[a+2]=(128&n)/128*255,e[a+3]=255,n<<=1}}}else if(Number(t.format)===o.IPF_ABGR_8888){const t=i.length/4;e=new Uint8ClampedArray(i.length);for(let n=0;n=r)break;e[a]=e[a+1]=e[a+2]=128&n?0:255,e[a+3]=255,n<<=1}}}return new ImageData(e,t.width,t.height)};var B,j,V,U,G,W,Y,z;let H,X,Z,q,J,K=class t{get _isFetchingStarted(){return n(this,G,"f")}constructor(){B.add(this),j.set(this,[]),V.set(this,1),U.set(this,s.BOPM_BLOCK),G.set(this,!1),W.set(this,void 0),Y.set(this,a.CCUT_AUTO)}setErrorListener(t){}addImageToBuffer(t){var e;if(!C(t))throw new TypeError("Invalid 'image'.");if((null===(e=t.tag)||void 0===e?void 0:e.hasOwnProperty("imageId"))&&"number"==typeof t.tag.imageId&&this.hasImage(t.tag.imageId))throw new Error("Existed imageId.");if(n(this,j,"f").length>=n(this,V,"f"))switch(n(this,U,"f")){case s.BOPM_BLOCK:break;case s.BOPM_UPDATE:if(n(this,j,"f").push(t),p(n(this,W,"f"))&&m(n(this,W,"f").imageId)&&1==n(this,W,"f").keepInBuffer)for(;n(this,j,"f").length>n(this,V,"f");){const t=n(this,j,"f").findIndex((t=>{var e;return(null===(e=t.tag)||void 0===e?void 0:e.imageId)!==n(this,W,"f").imageId}));n(this,j,"f").splice(t,1)}else n(this,j,"f").splice(0,n(this,j,"f").length-n(this,V,"f"))}else n(this,j,"f").push(t)}getImage(){if(0===n(this,j,"f").length)return null;let e;if(n(this,W,"f")&&m(n(this,W,"f").imageId)){const t=n(this,B,"m",z).call(this,n(this,W,"f").imageId);if(t<0)throw new Error(`Image with id ${n(this,W,"f").imageId} doesn't exist.`);e=n(this,j,"f").slice(t,t+1)[0]}else e=n(this,j,"f").pop();if([o.IPF_RGB_565,o.IPF_RGB_555,o.IPF_RGB_888,o.IPF_ARGB_8888,o.IPF_RGB_161616,o.IPF_ARGB_16161616,o.IPF_ABGR_8888,o.IPF_ABGR_16161616,o.IPF_BGR_888].includes(e.format)){if(n(this,Y,"f")===a.CCUT_RGB_R_CHANNEL_ONLY){t._onLog&&t._onLog("only get R channel data.");const i=new Uint8Array(e.width*e.height);for(let t=0;t0!==t.length&&t.every((t=>m(t))))(t))throw new TypeError("Invalid 'imageId'.");if(void 0!==e&&!g(e))throw new TypeError("Invalid 'keepInBuffer'.");r(this,W,{imageId:t,keepInBuffer:e})}_resetNextReturnedImage(){r(this,W,null)}hasImage(t){return n(this,B,"m",z).call(this,t)>=0}startFetching(){r(this,G,!0)}stopFetching(){r(this,G,!1)}setMaxImageCount(t){if("number"!=typeof t)throw new TypeError("Invalid 'count'.");if(t<1||Math.round(t)!==t)throw new Error("Invalid 'count'.");for(r(this,V,t);n(this,j,"f")&&n(this,j,"f").length>t;)n(this,j,"f").shift()}getMaxImageCount(){return n(this,V,"f")}getImageCount(){return n(this,j,"f").length}clearBuffer(){n(this,j,"f").length=0}isBufferEmpty(){return 0===n(this,j,"f").length}setBufferOverflowProtectionMode(t){r(this,U,t)}getBufferOverflowProtectionMode(){return n(this,U,"f")}setColourChannelUsageType(t){r(this,Y,t)}getColourChannelUsageType(){return n(this,Y,"f")}};j=new WeakMap,V=new WeakMap,U=new WeakMap,G=new WeakMap,W=new WeakMap,Y=new WeakMap,B=new WeakSet,z=function(t){if("number"!=typeof t)throw new TypeError("Invalid 'imageId'.");return n(this,j,"f").findIndex((e=>{var i;return(null===(i=e.tag)||void 0===i?void 0:i.imageId)===t}))},"undefined"!=typeof navigator&&(H=navigator,X=H.userAgent,Z=H.platform,q=H.mediaDevices),function(){if(!l){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:H.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Z,search:"Win"},Mac:{str:Z},Linux:{str:Z}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||X,a=r.search||e,o=r.verStr||X,l=r.verSearch||e;if(l instanceof Array||(l=[l]),-1!=s.indexOf(a)){i=e;for(let t of l){let e=o.indexOf(t);if(-1!=e){n=parseFloat(o.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||X,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=X.indexOf("Windows NT")&&(r="HarmonyOS"),J={browser:i,version:n,OS:r}}l&&(J={browser:"ssr",version:0,OS:"ssr"})}();const $="undefined"!=typeof WebAssembly&&X&&!(/Safari/.test(X)&&!/Chrome/.test(X)&&/\(.+\s11_2_([2-6]).*\)/.test(X)),Q=!("undefined"==typeof Worker),tt=!(!q||!q.getUserMedia),et=async()=>{let t=!1;if(tt)try{(await q.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===J.browser&&J.version>66||"Safari"===J.browser&&J.version>13||"OPR"===J.browser&&J.version>43||"Edge"===J.browser&&J.version;const it={},nt=async t=>{let e="string"==typeof t?[t]:t,n=[];for(let t of e)n.push(it[t]=it[t]||new i);await Promise.all(n)},rt=async(t,e)=>{let n,r="string"==typeof t?[t]:t,s=[];for(let t of r){let r;s.push(r=it[t]=it[t]||new i(n=n||e())),r.isEmpty&&(r.task=n=n||e())}await Promise.all(s)};let st,at=0;const ot=()=>at++,lt={};let ht;const ct=t=>{ht=t,st&&st.postMessage({type:"setBLog",body:{value:!!t}})};let dt=!1;const ut=t=>{dt=t,st&&st.postMessage({type:"setBDebug",body:{value:!!t}})},ft={},gt={},mt={dip:{wasm:!0}},pt={std:{version:"1.4.21",path:d(c+"../../dynamsoft-capture-vision-std@1.4.21/dist/"),isInternal:!0},core:{version:"3.4.31",path:c,isInternal:!0}},_t=async t=>{let e;t instanceof Array||(t=t?[t]:[]);let n=it.core;e=!n||n.isEmpty;let r=new Map;const s=t=>{if("std"==(t=t.toLowerCase())||"core"==t)return;if(!mt[t])throw Error("The '"+t+"' module cannot be found.");let e=mt[t].deps;if(null==e?void 0:e.length)for(let t of e)s(t);let i=it[t];r.has(t)||r.set(t,!i||i.isEmpty)};for(let e of t)s(e);let a=[];e&&a.push("core"),a.push(...r.keys());const o=[...r.entries()].filter((t=>!t[1])).map((t=>t[0]));await rt(a,(async()=>{const t=[...r.entries()].filter((t=>t[1])).map((t=>t[0]));await nt(o);const n=L(pt),s={};for(let e of t)s[e]=mt[e];const a={engineResourcePaths:n,autoResources:s,names:t};let l=new i;if(e){a.needLoadCore=!0;let t=n.core+vt._workerName;t.startsWith(location.origin)||(t=await fetch(t).then((t=>t.blob())).then((t=>URL.createObjectURL(t)))),st=new Worker(t),st.onerror=t=>{let e=new Error(t.message);l.reject(e)},st.addEventListener("message",(t=>{let e=t.data?t.data:t,i=e.type,n=e.id,r=e.body;switch(i){case"log":ht&&ht(e.message);break;case"task":try{lt[n](r),delete lt[n]}catch(t){throw delete lt[n],t}break;case"event":try{lt[n](r)}catch(t){throw t}break;default:console.log(t)}})),a.bLog=!!ht,a.bd=dt,a.dm=location.origin.startsWith("http")?location.origin:"https://localhost"}else await nt("core");let h=at++;lt[h]=t=>{if(t.success)Object.assign(ft,t.versions),"{}"!==JSON.stringify(t.versions)&&(vt._versions=t.versions),l.resolve(void 0);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),l.reject(e)}},st.postMessage({type:"loadWasm",body:a,id:h}),await l}))};class vt{static get engineResourcePaths(){return pt}static set engineResourcePaths(t){Object.assign(pt,t)}static get bSupportDce4Module(){return this._bSupportDce4Module}static get bSupportIRTModule(){return this._bSupportIRTModule}static get versions(){return this._versions}static get _onLog(){return ht}static set _onLog(t){ct(t)}static get _bDebug(){return dt}static set _bDebug(t){ut(t)}static isModuleLoaded(t){return t=(t=t||"core").toLowerCase(),!!it[t]&&it[t].isFulfilled}static async loadWasm(t){return await _t(t)}static async detectEnvironment(){return await(async()=>({wasm:$,worker:Q,getUserMedia:tt,camera:await et(),browser:J.browser,version:J.version,OS:J.OS}))()}static async getModuleVersion(){return await new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success)return t(i.versions);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"getModuleVersion",id:i})}))}static getVersion(){return`3.4.31(Worker: ${ft.core&&ft.core.worker||"Not Loaded"}, Wasm: ${ft.core&&ft.core.wasm||"Not Loaded"})`}static enableLogging(){K._onLog=console.log,vt._onLog=console.log}static disableLogging(){K._onLog=null,vt._onLog=null}static async cfd(t){return await new Promise(((e,i)=>{let n=ot();lt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cfd",id:n,body:{count:t}})}))}}var yt,wt,Ct,Et,St,bt,Tt,It,xt;vt._bSupportDce4Module=-1,vt._bSupportIRTModule=-1,vt._versions=null,vt._workerName="core.worker.js",vt.browserInfo=J,function(t){t[t.CRIT_ORIGINAL_IMAGE=1]="CRIT_ORIGINAL_IMAGE",t[t.CRIT_BARCODE=2]="CRIT_BARCODE",t[t.CRIT_TEXT_LINE=4]="CRIT_TEXT_LINE",t[t.CRIT_DETECTED_QUAD=8]="CRIT_DETECTED_QUAD",t[t.CRIT_NORMALIZED_IMAGE=16]="CRIT_NORMALIZED_IMAGE",t[t.CRIT_PARSED_RESULT=32]="CRIT_PARSED_RESULT"}(yt||(yt={})),function(t){t[t.CT_NORMAL_INTERSECTED=0]="CT_NORMAL_INTERSECTED",t[t.CT_T_INTERSECTED=1]="CT_T_INTERSECTED",t[t.CT_CROSS_INTERSECTED=2]="CT_CROSS_INTERSECTED",t[t.CT_NOT_INTERSECTED=3]="CT_NOT_INTERSECTED"}(wt||(wt={})),function(t){t[t.EC_OK=0]="EC_OK",t[t.EC_UNKNOWN=-1e4]="EC_UNKNOWN",t[t.EC_NO_MEMORY=-10001]="EC_NO_MEMORY",t[t.EC_NULL_POINTER=-10002]="EC_NULL_POINTER",t[t.EC_LICENSE_INVALID=-10003]="EC_LICENSE_INVALID",t[t.EC_LICENSE_EXPIRED=-10004]="EC_LICENSE_EXPIRED",t[t.EC_FILE_NOT_FOUND=-10005]="EC_FILE_NOT_FOUND",t[t.EC_FILE_TYPE_NOT_SUPPORTED=-10006]="EC_FILE_TYPE_NOT_SUPPORTED",t[t.EC_BPP_NOT_SUPPORTED=-10007]="EC_BPP_NOT_SUPPORTED",t[t.EC_INDEX_INVALID=-10008]="EC_INDEX_INVALID",t[t.EC_CUSTOM_REGION_INVALID=-10010]="EC_CUSTOM_REGION_INVALID",t[t.EC_IMAGE_READ_FAILED=-10012]="EC_IMAGE_READ_FAILED",t[t.EC_TIFF_READ_FAILED=-10013]="EC_TIFF_READ_FAILED",t[t.EC_DIB_BUFFER_INVALID=-10018]="EC_DIB_BUFFER_INVALID",t[t.EC_PDF_READ_FAILED=-10021]="EC_PDF_READ_FAILED",t[t.EC_PDF_DLL_MISSING=-10022]="EC_PDF_DLL_MISSING",t[t.EC_PAGE_NUMBER_INVALID=-10023]="EC_PAGE_NUMBER_INVALID",t[t.EC_CUSTOM_SIZE_INVALID=-10024]="EC_CUSTOM_SIZE_INVALID",t[t.EC_TIMEOUT=-10026]="EC_TIMEOUT",t[t.EC_JSON_PARSE_FAILED=-10030]="EC_JSON_PARSE_FAILED",t[t.EC_JSON_TYPE_INVALID=-10031]="EC_JSON_TYPE_INVALID",t[t.EC_JSON_KEY_INVALID=-10032]="EC_JSON_KEY_INVALID",t[t.EC_JSON_VALUE_INVALID=-10033]="EC_JSON_VALUE_INVALID",t[t.EC_JSON_NAME_KEY_MISSING=-10034]="EC_JSON_NAME_KEY_MISSING",t[t.EC_JSON_NAME_VALUE_DUPLICATED=-10035]="EC_JSON_NAME_VALUE_DUPLICATED",t[t.EC_TEMPLATE_NAME_INVALID=-10036]="EC_TEMPLATE_NAME_INVALID",t[t.EC_JSON_NAME_REFERENCE_INVALID=-10037]="EC_JSON_NAME_REFERENCE_INVALID",t[t.EC_PARAMETER_VALUE_INVALID=-10038]="EC_PARAMETER_VALUE_INVALID",t[t.EC_DOMAIN_NOT_MATCH=-10039]="EC_DOMAIN_NOT_MATCH",t[t.EC_RESERVED_INFO_NOT_MATCH=-10040]="EC_RESERVED_INFO_NOT_MATCH",t[t.EC_LICENSE_KEY_NOT_MATCH=-10043]="EC_LICENSE_KEY_NOT_MATCH",t[t.EC_REQUEST_FAILED=-10044]="EC_REQUEST_FAILED",t[t.EC_LICENSE_INIT_FAILED=-10045]="EC_LICENSE_INIT_FAILED",t[t.EC_SET_MODE_ARGUMENT_ERROR=-10051]="EC_SET_MODE_ARGUMENT_ERROR",t[t.EC_LICENSE_CONTENT_INVALID=-10052]="EC_LICENSE_CONTENT_INVALID",t[t.EC_LICENSE_KEY_INVALID=-10053]="EC_LICENSE_KEY_INVALID",t[t.EC_LICENSE_DEVICE_RUNS_OUT=-10054]="EC_LICENSE_DEVICE_RUNS_OUT",t[t.EC_GET_MODE_ARGUMENT_ERROR=-10055]="EC_GET_MODE_ARGUMENT_ERROR",t[t.EC_IRT_LICENSE_INVALID=-10056]="EC_IRT_LICENSE_INVALID",t[t.EC_FILE_SAVE_FAILED=-10058]="EC_FILE_SAVE_FAILED",t[t.EC_STAGE_TYPE_INVALID=-10059]="EC_STAGE_TYPE_INVALID",t[t.EC_IMAGE_ORIENTATION_INVALID=-10060]="EC_IMAGE_ORIENTATION_INVALID",t[t.EC_CONVERT_COMPLEX_TEMPLATE_ERROR=-10061]="EC_CONVERT_COMPLEX_TEMPLATE_ERROR",t[t.EC_CALL_REJECTED_WHEN_CAPTURING=-10062]="EC_CALL_REJECTED_WHEN_CAPTURING",t[t.EC_NO_IMAGE_SOURCE=-10063]="EC_NO_IMAGE_SOURCE",t[t.EC_READ_DIRECTORY_FAILED=-10064]="EC_READ_DIRECTORY_FAILED",t[t.EC_MODULE_NOT_FOUND=-10065]="EC_MODULE_NOT_FOUND",t[t.EC_MULTI_PAGES_NOT_SUPPORTED=-10066]="EC_MULTI_PAGES_NOT_SUPPORTED",t[t.EC_FILE_ALREADY_EXISTS=-10067]="EC_FILE_ALREADY_EXISTS",t[t.EC_CREATE_FILE_FAILED=-10068]="EC_CREATE_FILE_FAILED",t[t.EC_IMGAE_DATA_INVALID=-10069]="EC_IMGAE_DATA_INVALID",t[t.EC_IMAGE_SIZE_NOT_MATCH=-10070]="EC_IMAGE_SIZE_NOT_MATCH",t[t.EC_IMAGE_PIXEL_FORMAT_NOT_MATCH=-10071]="EC_IMAGE_PIXEL_FORMAT_NOT_MATCH",t[t.EC_SECTION_LEVEL_RESULT_IRREPLACEABLE=-10072]="EC_SECTION_LEVEL_RESULT_IRREPLACEABLE",t[t.EC_AXIS_DEFINITION_INCORRECT=-10073]="EC_AXIS_DEFINITION_INCORRECT",t[t.EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE=-10074]="EC_RESULT_TYPE_MISMATCH_IRREPLACEABLE",t[t.EC_PDF_LIBRARY_LOAD_FAILED=-10075]="EC_PDF_LIBRARY_LOAD_FAILED",t[t.EC_NO_LICENSE=-2e4]="EC_NO_LICENSE",t[t.EC_HANDSHAKE_CODE_INVALID=-20001]="EC_HANDSHAKE_CODE_INVALID",t[t.EC_LICENSE_BUFFER_FAILED=-20002]="EC_LICENSE_BUFFER_FAILED",t[t.EC_LICENSE_SYNC_FAILED=-20003]="EC_LICENSE_SYNC_FAILED",t[t.EC_DEVICE_NOT_MATCH=-20004]="EC_DEVICE_NOT_MATCH",t[t.EC_BIND_DEVICE_FAILED=-20005]="EC_BIND_DEVICE_FAILED",t[t.EC_INSTANCE_COUNT_OVER_LIMIT=-20008]="EC_INSTANCE_COUNT_OVER_LIMIT",t[t.EC_LICENSE_INIT_SEQUENCE_FAILED=-20009]="EC_LICENSE_INIT_SEQUENCE_FAILED",t[t.EC_TRIAL_LICENSE=-20010]="EC_TRIAL_LICENSE",t[t.EC_FAILED_TO_REACH_DLS=-20200]="EC_FAILED_TO_REACH_DLS",t[t.EC_LICENSE_CACHE_USED=-20012]="EC_LICENSE_CACHE_USED",t[t.EC_BARCODE_FORMAT_INVALID=-30009]="EC_BARCODE_FORMAT_INVALID",t[t.EC_QR_LICENSE_INVALID=-30016]="EC_QR_LICENSE_INVALID",t[t.EC_1D_LICENSE_INVALID=-30017]="EC_1D_LICENSE_INVALID",t[t.EC_PDF417_LICENSE_INVALID=-30019]="EC_PDF417_LICENSE_INVALID",t[t.EC_DATAMATRIX_LICENSE_INVALID=-30020]="EC_DATAMATRIX_LICENSE_INVALID",t[t.EC_CUSTOM_MODULESIZE_INVALID=-30025]="EC_CUSTOM_MODULESIZE_INVALID",t[t.EC_AZTEC_LICENSE_INVALID=-30041]="EC_AZTEC_LICENSE_INVALID",t[t.EC_PATCHCODE_LICENSE_INVALID=-30046]="EC_PATCHCODE_LICENSE_INVALID",t[t.EC_POSTALCODE_LICENSE_INVALID=-30047]="EC_POSTALCODE_LICENSE_INVALID",t[t.EC_DPM_LICENSE_INVALID=-30048]="EC_DPM_LICENSE_INVALID",t[t.EC_FRAME_DECODING_THREAD_EXISTS=-30049]="EC_FRAME_DECODING_THREAD_EXISTS",t[t.EC_STOP_DECODING_THREAD_FAILED=-30050]="EC_STOP_DECODING_THREAD_FAILED",t[t.EC_MAXICODE_LICENSE_INVALID=-30057]="EC_MAXICODE_LICENSE_INVALID",t[t.EC_GS1_DATABAR_LICENSE_INVALID=-30058]="EC_GS1_DATABAR_LICENSE_INVALID",t[t.EC_GS1_COMPOSITE_LICENSE_INVALID=-30059]="EC_GS1_COMPOSITE_LICENSE_INVALID",t[t.EC_DOTCODE_LICENSE_INVALID=-30061]="EC_DOTCODE_LICENSE_INVALID",t[t.EC_PHARMACODE_LICENSE_INVALID=-30062]="EC_PHARMACODE_LICENSE_INVALID",t[t.EC_CHARACTER_MODEL_FILE_NOT_FOUND=-40100]="EC_CHARACTER_MODEL_FILE_NOT_FOUND",t[t.EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT=-40101]="EC_TEXT_LINE_GROUP_LAYOUT_CONFLICT",t[t.EC_TEXT_LINE_GROUP_REGEX_CONFLICT=-40102]="EC_TEXT_LINE_GROUP_REGEX_CONFLICT",t[t.EC_QUADRILATERAL_INVALID=-50057]="EC_QUADRILATERAL_INVALID",t[t.EC_PANORAMA_LICENSE_INVALID=-70060]="EC_PANORAMA_LICENSE_INVALID",t[t.EC_RESOURCE_PATH_NOT_EXIST=-90001]="EC_RESOURCE_PATH_NOT_EXIST",t[t.EC_RESOURCE_LOAD_FAILED=-90002]="EC_RESOURCE_LOAD_FAILED",t[t.EC_CODE_SPECIFICATION_NOT_FOUND=-90003]="EC_CODE_SPECIFICATION_NOT_FOUND",t[t.EC_FULL_CODE_EMPTY=-90004]="EC_FULL_CODE_EMPTY",t[t.EC_FULL_CODE_PREPROCESS_FAILED=-90005]="EC_FULL_CODE_PREPROCESS_FAILED",t[t.EC_ZA_DL_LICENSE_INVALID=-90006]="EC_ZA_DL_LICENSE_INVALID",t[t.EC_AAMVA_DL_ID_LICENSE_INVALID=-90007]="EC_AAMVA_DL_ID_LICENSE_INVALID",t[t.EC_AADHAAR_LICENSE_INVALID=-90008]="EC_AADHAAR_LICENSE_INVALID",t[t.EC_MRTD_LICENSE_INVALID=-90009]="EC_MRTD_LICENSE_INVALID",t[t.EC_VIN_LICENSE_INVALID=-90010]="EC_VIN_LICENSE_INVALID",t[t.EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID=-90011]="EC_CUSTOMIZED_CODE_TYPE_LICENSE_INVALID",t[t.EC_LICENSE_WARNING=-10076]="EC_LICENSE_WARNING",t[t.EC_BARCODE_READER_LICENSE_NOT_FOUND=-30063]="EC_BARCODE_READER_LICENSE_NOT_FOUND",t[t.EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND=-40103]="EC_LABEL_RECOGNIZER_LICENSE_NOT_FOUND",t[t.EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND=-50058]="EC_DOCUMENT_NORMALIZER_LICENSE_NOT_FOUND",t[t.EC_CODE_PARSER_LICENSE_NOT_FOUND=-90012]="EC_CODE_PARSER_LICENSE_NOT_FOUND"}(Ct||(Ct={})),function(t){t[t.GEM_SKIP=0]="GEM_SKIP",t[t.GEM_AUTO=1]="GEM_AUTO",t[t.GEM_GENERAL=2]="GEM_GENERAL",t[t.GEM_GRAY_EQUALIZE=4]="GEM_GRAY_EQUALIZE",t[t.GEM_GRAY_SMOOTH=8]="GEM_GRAY_SMOOTH",t[t.GEM_SHARPEN_SMOOTH=16]="GEM_SHARPEN_SMOOTH",t[t.GEM_REV=-2147483648]="GEM_REV"}(Et||(Et={})),function(t){t[t.GTM_SKIP=0]="GTM_SKIP",t[t.GTM_INVERTED=1]="GTM_INVERTED",t[t.GTM_ORIGINAL=2]="GTM_ORIGINAL",t[t.GTM_AUTO=4]="GTM_AUTO",t[t.GTM_REV=-2147483648]="GTM_REV"}(St||(St={})),function(t){t[t.ITT_FILE_IMAGE=0]="ITT_FILE_IMAGE",t[t.ITT_VIDEO_FRAME=1]="ITT_VIDEO_FRAME"}(bt||(bt={})),function(t){t[t.PDFRM_VECTOR=1]="PDFRM_VECTOR",t[t.PDFRM_RASTER=2]="PDFRM_RASTER",t[t.PDFRM_REV=-2147483648]="PDFRM_REV"}(Tt||(Tt={})),function(t){t[t.RDS_RASTERIZED_PAGES=0]="RDS_RASTERIZED_PAGES",t[t.RDS_EXTRACTED_IMAGES=1]="RDS_EXTRACTED_IMAGES"}(It||(It={})),function(t){t[t.CVS_NOT_VERIFIED=0]="CVS_NOT_VERIFIED",t[t.CVS_PASSED=1]="CVS_PASSED",t[t.CVS_FAILED=2]="CVS_FAILED"}(xt||(xt={}));const Ot={IRUT_NULL:BigInt(0),IRUT_COLOUR_IMAGE:BigInt(1),IRUT_SCALED_DOWN_COLOUR_IMAGE:BigInt(2),IRUT_GRAYSCALE_IMAGE:BigInt(4),IRUT_TRANSOFORMED_GRAYSCALE_IMAGE:BigInt(8),IRUT_ENHANCED_GRAYSCALE_IMAGE:BigInt(16),IRUT_PREDETECTED_REGIONS:BigInt(32),IRUT_BINARY_IMAGE:BigInt(64),IRUT_TEXTURE_DETECTION_RESULT:BigInt(128),IRUT_TEXTURE_REMOVED_GRAYSCALE_IMAGE:BigInt(256),IRUT_TEXTURE_REMOVED_BINARY_IMAGE:BigInt(512),IRUT_CONTOURS:BigInt(1024),IRUT_LINE_SEGMENTS:BigInt(2048),IRUT_TEXT_ZONES:BigInt(4096),IRUT_TEXT_REMOVED_BINARY_IMAGE:BigInt(8192),IRUT_CANDIDATE_BARCODE_ZONES:BigInt(16384),IRUT_LOCALIZED_BARCODES:BigInt(32768),IRUT_SCALED_UP_BARCODE_IMAGE:BigInt(65536),IRUT_DEFORMATION_RESISTED_BARCODE_IMAGE:BigInt(1<<17),IRUT_COMPLEMENTED_BARCODE_IMAGE:BigInt(1<<18),IRUT_DECODED_BARCODES:BigInt(1<<19),IRUT_LONG_LINES:BigInt(1<<20),IRUT_CORNERS:BigInt(1<<21),IRUT_CANDIDATE_QUAD_EDGES:BigInt(1<<22),IRUT_DETECTED_QUADS:BigInt(1<<23),IRUT_LOCALIZED_TEXT_LINES:BigInt(1<<24),IRUT_RECOGNIZED_TEXT_LINES:BigInt(1<<25),IRUT_NORMALIZED_IMAGES:BigInt(1<<26),IRUT_SHORT_LINES:BigInt(1<<27),IRUT_RAW_TEXT_LINES:BigInt(1<<28),IRUT_LOGIC_LINES:BigInt(1<<29),IRUT_ALL:BigInt("0xFFFFFFFFFFFFFFFF")};var At,Rt;!function(t){t[t.ROET_PREDETECTED_REGION=0]="ROET_PREDETECTED_REGION",t[t.ROET_LOCALIZED_BARCODE=1]="ROET_LOCALIZED_BARCODE",t[t.ROET_DECODED_BARCODE=2]="ROET_DECODED_BARCODE",t[t.ROET_LOCALIZED_TEXT_LINE=3]="ROET_LOCALIZED_TEXT_LINE",t[t.ROET_RECOGNIZED_TEXT_LINE=4]="ROET_RECOGNIZED_TEXT_LINE",t[t.ROET_DETECTED_QUAD=5]="ROET_DETECTED_QUAD",t[t.ROET_NORMALIZED_IMAGE=6]="ROET_NORMALIZED_IMAGE",t[t.ROET_SOURCE_IMAGE=7]="ROET_SOURCE_IMAGE",t[t.ROET_TARGET_ROI=8]="ROET_TARGET_ROI"}(At||(At={})),function(t){t[t.ST_NULL=0]="ST_NULL",t[t.ST_REGION_PREDETECTION=1]="ST_REGION_PREDETECTION",t[t.ST_BARCODE_LOCALIZATION=2]="ST_BARCODE_LOCALIZATION",t[t.ST_BARCODE_DECODING=3]="ST_BARCODE_DECODING",t[t.ST_TEXT_LINE_LOCALIZATION=4]="ST_TEXT_LINE_LOCALIZATION",t[t.ST_TEXT_LINE_RECOGNITION=5]="ST_TEXT_LINE_RECOGNITION",t[t.ST_DOCUMENT_DETECTION=6]="ST_DOCUMENT_DETECTION",t[t.ST_DOCUMENT_NORMALIZATION=7]="ST_DOCUMENT_NORMALIZATION"}(Rt||(Rt={}));const Dt="undefined"==typeof self,Lt=Dt?{}:self,Mt="function"==typeof importScripts,Ft=(()=>{if(!Mt){if(!Dt&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),Pt=t=>t&&"object"==typeof t&&"function"==typeof t.then,kt=(async()=>{})().constructor;let Nt=class extends kt{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,Pt(t)?e=t:"function"==typeof t&&(e=new kt(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(Pt(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}};const Bt=" is not allowed to change after `createInstance` or `loadWasm` is called.",jt=!Dt&&document.currentScript&&(document.currentScript.getAttribute("data-license")||document.currentScript.getAttribute("data-productKeys")||document.currentScript.getAttribute("data-licenseKey")||document.currentScript.getAttribute("data-handshakeCode")||document.currentScript.getAttribute("data-organizationID"))||"",Vt=(t,e)=>{const i=t;if(i._license!==e){if(!i._pLoad.isEmpty)throw new Error("`license`"+Bt);i._license=e}};!Dt&&document.currentScript&&document.currentScript.getAttribute("data-sessionPassword");const Ut=t=>{if(null==t)t=[];else{t=t instanceof Array?[...t]:[t];for(let e=0;e{e=Ut(e);const i=t;if(i._licenseServer!==e){if(!i._pLoad.isEmpty)throw new Error("`licenseServer`"+Bt);i._licenseServer=e}},Wt=(t,e)=>{e=e||"";const i=t;if(i._deviceFriendlyName!==e){if(!i._pLoad.isEmpty)throw new Error("`deviceFriendlyName`"+Bt);i._deviceFriendlyName=e}};let Yt,zt,Ht,Xt,Zt;"undefined"!=typeof navigator&&(Yt=navigator,zt=Yt.userAgent,Ht=Yt.platform,Xt=Yt.mediaDevices),function(){if(!Dt){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Yt.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:Ht,search:"Win"},Mac:{str:Ht},Linux:{str:Ht}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||zt,a=r.search||e,o=r.verStr||zt,l=r.verSearch||e;if(l instanceof Array||(l=[l]),-1!=s.indexOf(a)){i=e;for(let t of l){let e=o.indexOf(t);if(-1!=e){n=parseFloat(o.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||zt,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=zt.indexOf("Windows NT")&&(r="HarmonyOS"),Zt={browser:i,version:n,OS:r}}Dt&&(Zt={browser:"ssr",version:0,OS:"ssr"})}(),Xt&&Xt.getUserMedia,"Chrome"===Zt.browser&&Zt.version>66||"Safari"===Zt.browser&&Zt.version>13||"OPR"===Zt.browser&&Zt.version>43||"Edge"===Zt.browser&&Zt.version;const qt=()=>(_t("license"),rt("dynamsoft_inited",(async()=>{let{lt:t,l:e,ls:i,sp:n,rmk:r,cv:s}=((t,e=!1)=>{const i=Kt;if(i._pLoad.isEmpty){let n,r,s,a=i._license||"",o=JSON.parse(JSON.stringify(i._licenseServer)),l=i._sessionPassword,h=0;if(a.startsWith("t")||a.startsWith("f"))h=0;else if(0===a.length||a.startsWith("P")||a.startsWith("L")||a.startsWith("Y")||a.startsWith("A"))h=1;else{h=2;const e=a.indexOf(":");-1!=e&&(a=a.substring(e+1));const i=a.indexOf("?");if(-1!=i&&(r=a.substring(i+1),a=a.substring(0,i)),a.startsWith("DLC2"))h=0;else{if(a.startsWith("DLS2")){let e;try{let t=a.substring(4);t=atob(t),e=JSON.parse(t)}catch(t){throw new Error("Format Error: The license string you specified is invalid, please check to make sure it is correct.")}if(a=e.handshakeCode?e.handshakeCode:e.organizationID?e.organizationID:"","number"==typeof a&&(a=JSON.stringify(a)),0===o.length){let t=[];e.mainServerURL&&(t[0]=e.mainServerURL),e.standbyServerURL&&(t[1]=e.standbyServerURL),o=Ut(t)}!l&&e.sessionPassword&&(l=e.sessionPassword),n=e.remark}a&&"200001"!==a&&!a.startsWith("200001-")||(h=1)}}if(h&&(e||(Lt.crypto||(s="Please upgrade your browser to support online key."),Lt.crypto.subtle||(s="Require https to use online key in this browser."))),s)throw new Error(s);return 1===h&&(a="",console.warn("Applying for a public trial license ...")),{lt:h,l:a,ls:o,sp:l,rmk:n,cv:r}}throw new Error("Can't preprocess license again"+Bt)})(),a=new Nt;Kt._pLoad.task=a,(async()=>{try{await Kt._pLoad}catch(t){}})();let o=ot();lt[o]=e=>{if(e.message&&Kt._onAuthMessage){let t=Kt._onAuthMessage(e.message);null!=t&&(e.message=t)}let i,n=!1;if(1===t&&(n=!0),e.success?(ht&&ht("init license success"),e.message&&console.warn(e.message),vt._bSupportIRTModule=e.bSupportIRTModule,vt._bSupportDce4Module=e.bSupportDce4Module,Kt.bPassValidation=!0,[0,-10076].includes(e.initLicenseInfo.errorCode)?[-10076].includes(e.initLicenseInfo.errorCode)&&console.warn(e.initLicenseInfo.errorString):a.reject(new Error(e.initLicenseInfo.errorString))):(i=Error(e.message),e.stack&&(i.stack=e.stack),e.ltsErrorCode&&(i.ltsErrorCode=e.ltsErrorCode),n||111==e.ltsErrorCode&&-1!=e.message.toLowerCase().indexOf("trial license")&&(n=!0)),n){const t=L(vt.engineResourcePaths);(async(t,e,i)=>{if(!t._bNeverShowDialog)try{let n=await fetch(t.engineResourcePath+"dls.license.dialog.html");if(!n.ok)throw Error("Get license dialog fail. Network Error: "+n.statusText);let r=await n.text();if(!r.trim().startsWith("<"))throw Error("Get license dialog fail. Can't get valid HTMLElement.");let s=document.createElement("div");s.innerHTML=r;let a=[];for(let t=0;t{if(t==e.target){o.remove();for(let t of a)t.remove()}}));else if(!h&&t.classList.contains("dls-license-icon-close"))h=t,t.addEventListener("click",(()=>{o.remove();for(let t of a)t.remove()}));else if(!c&&t.classList.contains("dls-license-icon-error"))c=t,"error"!=e&&t.remove();else if(!d&&t.classList.contains("dls-license-icon-warn"))d=t,"warn"!=e&&t.remove();else if(!u&&t.classList.contains("dls-license-msg-content")){u=t;let e=i;for(;e;){let i=e.indexOf("["),n=e.indexOf("]",i),r=e.indexOf("(",n),s=e.indexOf(")",r);if(-1==i||-1==n||-1==r||-1==s){t.appendChild(new Text(e));break}i>0&&t.appendChild(new Text(e.substring(0,i)));let a=document.createElement("a"),o=e.substring(i+1,n);a.innerText=o;let l=e.substring(r+1,s);a.setAttribute("href",l),a.setAttribute("target","_blank"),t.appendChild(a),e=e.substring(s+1)}}document.body.appendChild(o)}catch(e){t._onLog&&t._onLog(e.message||e)}})({_bNeverShowDialog:Kt._bNeverShowDialog,engineResourcePath:t.license,_onLog:ht},e.success?"warn":"error",e.message)}e.success?a.resolve(void 0):a.reject(i)},await nt("core"),st.postMessage({type:"license_dynamsoft",body:{v:"3.4.31",brtk:!!t,bptk:1===t,l:e,os:Zt,fn:Kt.deviceFriendlyName,ls:i,sp:n,rmk:r,cv:s},id:o}),Kt.bCallInitLicense=!0,await a})));let Jt;gt.license={},gt.license.dynamsoft=qt,gt.license.getAR=async()=>{{let t=it.dynamsoft_inited;t&&t.isRejected&&await t}return st?new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success){delete i.success;{let t=Kt.license;t&&(t.startsWith("t")||t.startsWith("f"))&&(i.pk=t)}if(Object.keys(i).length){if(i.lem){let t=Error(i.lem);t.ltsErrorCode=i.lec,delete i.lem,delete i.lec,i.ae=t}t(i)}else t(null)}else{let t=Error(i.message);i.stack&&(t.stack=i.stack),e(t)}},st.postMessage({type:"license_getAR",id:i})})):null};let Kt=class t{static setLicenseServer(e){Gt(t,e)}static get license(){return this._license}static set license(e){Vt(t,e)}static get licenseServer(){return this._licenseServer}static set licenseServer(e){Gt(t,e)}static get deviceFriendlyName(){return this._deviceFriendlyName}static set deviceFriendlyName(e){Wt(t,e)}static initLicense(e,i){if(Vt(t,e),t.bCallInitLicense=!0,"boolean"==typeof i&&i||"object"==typeof i&&i.executeNow)return qt()}static setDeviceFriendlyName(e){Wt(t,e)}static getDeviceFriendlyName(){return t._deviceFriendlyName}static getDeviceUUID(){return(async()=>(await rt("dynamsoft_uuid",(async()=>{await _t();let t=new Nt,e=ot();lt[e]=e=>{if(e.success)t.resolve(e.uuid);else{const i=Error(e.message);e.stack&&(i.stack=e.stack),t.reject(i)}},st.postMessage({type:"license_getDeviceUUID",id:e}),Jt=await t})),Jt))()}};Kt._pLoad=new Nt,Kt.bPassValidation=!1,Kt.bCallInitLicense=!1,Kt._license=jt,Kt._licenseServer=[],Kt._deviceFriendlyName="",vt.engineResourcePaths.license={version:"3.4.31",path:Ft,isInternal:!0},mt.license={wasm:!0,js:!0},gt.license.LicenseManager=Kt;const $t="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,$t)<0&&(vt.engineResourcePaths.std={version:$t,path:(t=>{if(null==t&&(t="./"),Dt||Mt);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(Ft+`../../dynamsoft-capture-vision-std@${$t}/dist/`),isInternal:!0});let Qt=class{static getVersion(){return`3.4.31(Worker: ${ft.license&&ft.license.worker||"Not Loaded"}, Wasm: ${ft.license&&ft.license.wasm||"Not Loaded"})`}};function te(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function ee(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError;const ie=t=>t&&"object"==typeof t&&"function"==typeof t.then,ne=(async()=>{})().constructor;class re extends ne{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,ie(t)?e=t:"function"==typeof t&&(e=new ne(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(ie(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}}class se{constructor(t){this._cvr=t}async getMaxBufferedItems(){return await new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success)return t(i.count);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_getMaxBufferedItems",id:i,instanceID:this._cvr._instanceID})}))}async setMaxBufferedItems(t){return await new Promise(((e,i)=>{let n=ot();lt[n]=async t=>{if(t.success)return e();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_setMaxBufferedItems",id:n,instanceID:this._cvr._instanceID,body:{count:t}})}))}async getBufferedCharacterItemSet(){return await new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success)return t(i.itemSet);{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_getBufferedCharacterItemSet",id:i,instanceID:this._cvr._instanceID})}))}}var ae={onTaskResultsReceived:!1,onTaskResultsReceivedForDce:!1,onPredetectedRegionsReceived:!1,onLocalizedBarcodesReceived:!1,onDecodedBarcodesReceived:!1,onLocalizedTextLinesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onColourImageUnitReceived:!1,onScaledDownColourImageUnitReceived:!1,onGrayscaleImageUnitReceived:!1,onTransformedGrayscaleImageUnitReceived:!1,onEnhancedGrayscaleImageUnitReceived:!1,onBinaryImageUnitReceived:!1,onTextureDetectionResultUnitReceived:!1,onTextureRemovedGrayscaleImageUnitReceived:!1,onTextureRemovedBinaryImageUnitReceived:!1,onContoursUnitReceived:!1,onLineSegmentsUnitReceived:!1,onTextZonesUnitReceived:!1,onTextRemovedBinaryImageUnitReceived:!1,onRawTextLinesReceived:!1,onLongLinesUnitReceived:!1,onCornersUnitReceived:!1,onCandidateQuadEdgesUnitReceived:!1,onCandidateBarcodeZonesUnitReceived:!1,onScaledUpBarcodeImageUnitReceived:!1,onDeformationResistedBarcodeImageUnitReceived:!1,onComplementedBarcodeImageUnitReceived:!1,onShortLinesUnitReceived:!1,onLogicLinesReceived:!1};const oe=t=>{for(let e in t._irrRegistryState)t._irrRegistryState[e]=!1;for(let e of t._intermediateResultReceiverSet)if(e.isDce||e.isFilter)t._irrRegistryState.onTaskResultsReceivedForDce=!0;else for(let i in e)t._irrRegistryState[i]||(t._irrRegistryState[i]=!!e[i])};class le{constructor(t){this._irrRegistryState=ae,this._intermediateResultReceiverSet=new Set,this._cvr=t}async addResultReceiver(t){if("object"!=typeof t)throw new Error("Invalid receiver.");this._intermediateResultReceiverSet.add(t),oe(this);let e=-1,i={};if(!t.isDce&&!t.isFilter){if(!t._observedResultUnitTypes||!t._observedTaskMap)throw new Error("Invalid Intermediate Result Receiver.");e=t._observedResultUnitTypes,t._observedTaskMap.forEach(((t,e)=>{i[e]=t})),t._observedTaskMap.clear()}return await new Promise(((t,n)=>{let r=ot();lt[r]=async e=>{if(e.success)return t();{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,n(t)}},st.postMessage({type:"cvr_setIrrRegistry",id:r,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState,observedResultUnitTypes:e.toString(),observedTaskMap:i}})}))}async removeResultReceiver(t){return this._intermediateResultReceiverSet.delete(t),oe(this),await new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_setIrrRegistry",id:i,instanceID:this._cvr._instanceID,body:{receiverObj:this._irrRegistryState}})}))}getOriginalImage(){return this._cvr._dsImage}}const he="undefined"==typeof self,ce="function"==typeof importScripts,de=(()=>{if(!ce){if(!he&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),ue=t=>{if(null==t&&(t="./"),he||ce);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};var fe;vt.engineResourcePaths.cvr={version:"2.4.33",path:de,isInternal:!0},mt.cvr={js:!0,wasm:!0,deps:["license","dip"]},gt.cvr={};const ge="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,ge)<0&&(vt.engineResourcePaths.std={version:ge,path:ue(de+`../../dynamsoft-capture-vision-std@${ge}/dist/`),isInternal:!0});const me="2.4.31";(!vt.engineResourcePaths.dip||"string"!=typeof vt.engineResourcePaths.dip&&D(vt.engineResourcePaths.dip.version,me)<0)&&(vt.engineResourcePaths.dip={version:me,path:ue(de+`../../dynamsoft-image-processing@${me}/dist/`),isInternal:!0});class pe{static getVersion(){return this._version}}pe._version=`2.4.33(Worker: ${null===(fe=ft.cvr)||void 0===fe?void 0:fe.worker}, Wasm: loading...`;const _e={barcodeResultItems:{type:yt.CRIT_BARCODE,reveiver:"onDecodedBarcodesReceived",isNeedFilter:!0},textLineResultItems:{type:yt.CRIT_TEXT_LINE,reveiver:"onRecognizedTextLinesReceived",isNeedFilter:!0},detectedQuadResultItems:{type:yt.CRIT_DETECTED_QUAD,reveiver:"onDetectedQuadsReceived",isNeedFilter:!1},normalizedImageResultItems:{type:yt.CRIT_NORMALIZED_IMAGE,reveiver:"onNormalizedImagesReceived",isNeedFilter:!1},parsedResultItems:{type:yt.CRIT_PARSED_RESULT,reveiver:"onParsedResultsReceived",isNeedFilter:!1}};var ve,ye,we,Ce,Ee,Se,be,Te,Ie,xe,Oe,Ae,Re;function De(t,e){if(t&&t.location){const i=t.location.points;for(let t of i)t.x=t.x/e,t.y=t.y/e;De(t.referencedItem,e)}}function Le(t){if(t.disposed)throw new Error('"CaptureVisionRouter" instance has been disposed')}!function(t){t[t.ISS_BUFFER_EMPTY=0]="ISS_BUFFER_EMPTY",t[t.ISS_EXHAUSTED=1]="ISS_EXHAUSTED"}(ve||(ve={}));const Me={onTaskResultsReceived:()=>{},isFilter:!0};class Fe{constructor(){this.maxImageSideLength=["iPhone","Android","HarmonyOS"].includes(vt.browserInfo.OS)?2048:4096,this._instanceID=void 0,this._dsImage=null,this._isPauseScan=!0,this._isOutputOriginalImage=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1,this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._minImageCaptureInterval=0,this._averageProcessintTimeArray=[],this._averageFetchImageTimeArray=[],this._currentSettings=null,this._averageTime=999,ye.set(this,null),we.set(this,null),Ce.set(this,null),Ee.set(this,null),Se.set(this,null),be.set(this,new Set),Te.set(this,new Set),Ie.set(this,new Set),xe.set(this,0),Oe.set(this,!1),Ae.set(this,!1),Re.set(this,!1),this._singleFrameModeCallbackBind=this._singleFrameModeCallback.bind(this)}get disposed(){return te(this,Re,"f")}static async createInstance(){if(!gt.license)throw Error("Module `license` is not existed.");await gt.license.dynamsoft(),await _t(["cvr"]);const t=new Fe,e=new re;let i=ot();return lt[i]=async i=>{var n;if(i.success)t._instanceID=i.instanceID,t._currentSettings=JSON.parse(JSON.parse(i.outputSettings).data),pe._version=`2.4.33(Worker: ${null===(n=ft.cvr)||void 0===n?void 0:n.worker}, Wasm: ${i.version})`,ee(t,Ae,!0),ee(t,Ee,t.getIntermediateResultManager()),ee(t,Ae,!1),e.resolve(t);else{const t=Error(i.message);i.stack&&(t.stack=i.stack),e.reject(t)}},st.postMessage({type:"cvr_createInstance",id:i}),e}async _singleFrameModeCallback(t){for(let e of te(this,be,"f"))this._isOutputOriginalImage&&e.onOriginalImageResultReceived&&e.onOriginalImageResultReceived({imageData:t});const e={bytes:new Uint8Array(t.bytes),width:t.width,height:t.height,stride:t.stride,format:t.format,tag:t.tag};this._templateName||(this._templateName=this._currentSettings.CaptureVisionTemplates[0].Name);const i=await this.capture(e,this._templateName);i.originalImageTag=t.tag;const n={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of te(this,be,"f"))if(t.isDce)t.onCapturedResultReceived(i,{isDetectVerifyOpen:!1,isNormalizeVerifyOpen:!1,isBarcodeVerifyOpen:!1,isLabelVerifyOpen:!1});else{for(let e in _e){const r=e,s=_e[r];t[s.reveiver]&&i[r]&&t[s.reveiver](Object.assign(Object.assign({},n),{[r]:i[r]}))}t.onCapturedResultReceived&&t.onCapturedResultReceived(i)}}setInput(t){if(Le(this),t){if(ee(this,ye,t),t.isCameraEnhancer){te(this,Ee,"f")&&(te(this,ye,"f")._intermediateResultReceiver.isDce=!0,te(this,Ee,"f").addResultReceiver(te(this,ye,"f")._intermediateResultReceiver));const t=te(this,ye,"f").getCameraView();if(t){const e=t._capturedResultReceiver;e.isDce=!0,te(this,be,"f").add(e)}}}else ee(this,ye,null)}getInput(){return te(this,ye,"f")}addImageSourceStateListener(t){if(Le(this),"object"!=typeof t)return console.warn("Invalid ISA state listener.");t&&Object.keys(t)&&te(this,Te,"f").add(t)}removeImageSourceStateListener(t){return Le(this),te(this,Te,"f").delete(t)}addResultReceiver(t){if(Le(this),"object"!=typeof t)throw new Error("Invalid receiver.");t&&Object.keys(t).length&&(te(this,be,"f").add(t),this._setCrrRegistry())}removeResultReceiver(t){Le(this),te(this,be,"f").delete(t),this._setCrrRegistry()}async _setCrrRegistry(){const t={onCapturedResultReceived:!1,onDecodedBarcodesReceived:!1,onRecognizedTextLinesReceived:!1,onDetectedQuadsReceived:!1,onNormalizedImagesReceived:!1,onParsedResultsReceived:!1};for(let e of te(this,be,"f"))e.isDce||(t.onCapturedResultReceived=!!e.onCapturedResultReceived,t.onDecodedBarcodesReceived=!!e.onDecodedBarcodesReceived,t.onRecognizedTextLinesReceived=!!e.onRecognizedTextLinesReceived,t.onDetectedQuadsReceived=!!e.onDetectedQuadsReceived,t.onNormalizedImagesReceived=!!e.onNormalizedImagesReceived,t.onParsedResultsReceived=!!e.onParsedResultsReceived);const e=new re;let i=ot();return lt[i]=async t=>{if(t.success)e.resolve();else{let i=new Error(t.message);i.stack=t.stack+"\n"+i.stack,e.reject()}},st.postMessage({type:"cvr_setCrrRegistry",id:i,instanceID:this._instanceID,body:{receiver:JSON.stringify(t)}}),e}async addResultFilter(t){if(Le(this),!t||"object"!=typeof t||!Object.keys(t).length)return console.warn("Invalid filter.");te(this,Ie,"f").add(t),t._dynamsoft(),await this._handleFilterUpdate()}async removeResultFilter(t){Le(this),te(this,Ie,"f").delete(t),await this._handleFilterUpdate()}async _handleFilterUpdate(){if(te(this,Ee,"f").removeResultReceiver(Me),0===te(this,Ie,"f").size){this._isOpenBarcodeVerify=!1,this._isOpenLabelVerify=!1,this._isOpenDetectVerify=!1,this._isOpenNormalizeVerify=!1;const t={[yt.CRIT_BARCODE]:!1,[yt.CRIT_TEXT_LINE]:!1,[yt.CRIT_DETECTED_QUAD]:!1,[yt.CRIT_NORMALIZED_IMAGE]:!1},e={[yt.CRIT_BARCODE]:!1,[yt.CRIT_TEXT_LINE]:!1,[yt.CRIT_DETECTED_QUAD]:!1,[yt.CRIT_NORMALIZED_IMAGE]:!1};return await Pe(this,t),void await ke(this,e)}for(let t of te(this,Ie,"f")){if(this._isOpenBarcodeVerify=t.isResultCrossVerificationEnabled(yt.CRIT_BARCODE),this._isOpenLabelVerify=t.isResultCrossVerificationEnabled(yt.CRIT_TEXT_LINE),this._isOpenDetectVerify=t.isResultCrossVerificationEnabled(yt.CRIT_DETECTED_QUAD),this._isOpenNormalizeVerify=t.isResultCrossVerificationEnabled(yt.CRIT_NORMALIZED_IMAGE),t.isLatestOverlappingEnabled(yt.CRIT_BARCODE)){[...te(this,Ee,"f")._intermediateResultReceiverSet.values()].find((t=>t.isFilter))||te(this,Ee,"f").addResultReceiver(Me)}await Pe(this,t.verificationEnabled),await ke(this,t.duplicateFilterEnabled),await Ne(this,t.duplicateForgetTime)}}async startCapturing(t){var e,i;if(Le(this),!this._isPauseScan)return;if(!te(this,ye,"f"))throw new Error("'ImageSourceAdapter' is not set. call 'setInput' before 'startCapturing'");t||(t=Fe._defaultTemplate);const n=await this.containsTask(t);await _t(n);for(let t of te(this,Ie,"f"))await this.addResultFilter(t);if(n.includes("dlr")&&!(null===(e=gt.dlr)||void 0===e?void 0:e.bLoadConfusableCharsData)){const t=L(vt.engineResourcePaths);await(null===(i=gt.dlr)||void 0===i?void 0:i.loadRecognitionData("ConfusableChars",t.dlr))}if(te(this,ye,"f").isCameraEnhancer&&(n.includes("ddn")?te(this,ye,"f").setPixelFormat(o.IPF_ABGR_8888):te(this,ye,"f").setPixelFormat(o.IPF_GRAYSCALED)),void 0!==te(this,ye,"f").singleFrameMode&&"disabled"!==te(this,ye,"f").singleFrameMode)return this._templateName=t,void te(this,ye,"f").on("singleFrameAcquired",this._singleFrameModeCallbackBind);return te(this,ye,"f").getColourChannelUsageType()===a.CCUT_AUTO&&te(this,ye,"f").setColourChannelUsageType(n.includes("ddn")?a.CCUT_FULL_CHANNEL:a.CCUT_Y_CHANNEL_ONLY),te(this,Ce,"f")&&te(this,Ce,"f").isPending?te(this,Ce,"f"):(ee(this,Ce,new re(((e,i)=>{if(this.disposed)return;let n=ot();lt[n]=async n=>{if(te(this,Ce,"f")&&!te(this,Ce,"f").isFulfilled){if(!n.success){let t=new Error(n.message);return t.stack=n.stack+"\n"+t.stack,i(t)}this._isPauseScan=!1,this._isOutputOriginalImage=n.isOutputOriginalImage,this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((async()=>{-1!==this._minImageCaptureInterval&&te(this,ye,"f").startFetching(),this._loopReadVideo(t),e()}),0)}},st.postMessage({type:"cvr_startCapturing",id:n,instanceID:this._instanceID,body:{templateName:t}})}))),await te(this,Ce,"f"))}stopCapturing(){Le(this),te(this,ye,"f")&&(te(this,ye,"f").isCameraEnhancer&&void 0!==te(this,ye,"f").singleFrameMode&&"disabled"!==te(this,ye,"f").singleFrameMode?te(this,ye,"f").off("singleFrameAcquired",this._singleFrameModeCallbackBind):(!async function(t){let e=ot();const i=new re;lt[e]=async t=>{if(t.success)return i.resolve();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i.reject(e)}},st.postMessage({type:"cvr_clearVerifyList",id:e,instanceID:t._instanceID})}(this),te(this,ye,"f").stopFetching(),this._averageProcessintTimeArray=[],this._averageTime=999,this._isPauseScan=!0,ee(this,Ce,null),te(this,ye,"f").setColourChannelUsageType(a.CCUT_AUTO)))}async containsTask(t){return Le(this),await new Promise(((e,i)=>{let n=ot();lt[n]=async t=>{if(t.success)return e(JSON.parse(t.tasks));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_containsTask",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async _loopReadVideo(t){if(this.disposed||this._isPauseScan)return;if(ee(this,Oe,!0),te(this,ye,"f").isBufferEmpty())if(te(this,ye,"f").hasNextImageToFetch())for(let t of te(this,Te,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ve.ISS_BUFFER_EMPTY);else if(!te(this,ye,"f").hasNextImageToFetch())for(let t of te(this,Te,"f"))t.onImageSourceStateReceived&&t.onImageSourceStateReceived(ve.ISS_EXHAUSTED);if(-1===this._minImageCaptureInterval||te(this,ye,"f").isBufferEmpty())try{te(this,ye,"f").isBufferEmpty()&&Fe._onLog&&Fe._onLog("buffer is empty so fetch image"),Fe._onLog&&Fe._onLog(`DCE: start fetching a frame: ${Date.now()}`),this._dsImage=te(this,ye,"f").fetchImage(),Fe._onLog&&Fe._onLog(`DCE: finish fetching a frame: ${Date.now()}`),te(this,ye,"f").setImageFetchInterval(this._averageTime)}catch(e){return void this._reRunCurrnetFunc(t)}else if(te(this,ye,"f").setImageFetchInterval(this._averageTime-(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0)),this._dsImage=te(this,ye,"f").getImage(),this._dsImage.tag&&Date.now()-this._dsImage.tag.timeStamp>200)return void this._reRunCurrnetFunc(t);if(!this._dsImage)return void this._reRunCurrnetFunc(t);for(let t of te(this,be,"f"))this._isOutputOriginalImage&&t.onOriginalImageResultReceived&&t.onOriginalImageResultReceived({imageData:this._dsImage});const e=Date.now();this._captureDsimage(this._dsImage,t).then((async i=>{if(Fe._onLog&&Fe._onLog("no js handle time: "+(Date.now()-e)),this._isPauseScan)return void this._reRunCurrnetFunc(t);i.originalImageTag=this._dsImage.tag?this._dsImage.tag:null;const n={originalImageHashId:i.originalImageHashId,originalImageTag:i.originalImageTag,errorCode:i.errorCode,errorString:i.errorString};for(let t of te(this,be,"f"))if(t.isDce){const e=Date.now();if(t.onCapturedResultReceived(i,{isDetectVerifyOpen:this._isOpenDetectVerify,isNormalizeVerifyOpen:this._isOpenNormalizeVerify,isBarcodeVerifyOpen:this._isOpenBarcodeVerify,isLabelVerifyOpen:this._isOpenLabelVerify}),Fe._onLog){const t=Date.now()-e;t>10&&Fe._onLog(`draw result time: ${t}`)}}else{for(let e in _e){const r=e,s=_e[r];t[s.reveiver],t[s.reveiver]&&i[r]&&t[s.reveiver](Object.assign(Object.assign({},n),{[r]:i[r].filter((t=>!s.isNeedFilter||!t.isFilter))})),i[r]&&(i[r]=i[r].filter((t=>!s.isNeedFilter||!t.isFilter)))}t.onCapturedResultReceived&&(i.items=i.items.filter((t=>[yt.CRIT_DETECTED_QUAD,yt.CRIT_NORMALIZED_IMAGE].includes(t.type)||!t.isFilter)),t.onCapturedResultReceived(i))}const r=Date.now();if(this._minImageCaptureInterval>-1&&(5===this._averageProcessintTimeArray.length&&this._averageProcessintTimeArray.shift(),5===this._averageFetchImageTimeArray.length&&this._averageFetchImageTimeArray.shift(),this._averageProcessintTimeArray.push(Date.now()-e),this._averageFetchImageTimeArray.push(this._dsImage&&this._dsImage.tag?this._dsImage.tag.timeSpent:0),this._averageTime=Math.min(...this._averageProcessintTimeArray)-Math.max(...this._averageFetchImageTimeArray),this._averageTime=this._averageTime>0?this._averageTime:0,Fe._onLog&&(Fe._onLog(`minImageCaptureInterval: ${this._minImageCaptureInterval}`),Fe._onLog(`averageProcessintTimeArray: ${this._averageProcessintTimeArray}`),Fe._onLog(`averageFetchImageTimeArray: ${this._averageFetchImageTimeArray}`),Fe._onLog(`averageTime: ${this._averageTime}`))),Fe._onLog){const t=Date.now()-r;t>10&&Fe._onLog(`fetch image calculate time: ${t}`)}Fe._onLog&&Fe._onLog(`time finish decode: ${Date.now()}`),Fe._onLog&&Fe._onLog("main time: "+(Date.now()-e)),Fe._onLog&&Fe._onLog("===================================================="),this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._minImageCaptureInterval>0&&this._minImageCaptureInterval>=this._averageTime?this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),this._minImageCaptureInterval-this._averageTime):this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,0))})).catch((e=>{te(this,ye,"f").stopFetching(),e.errorCode&&0===e.errorCode&&(this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{te(this,ye,"f").startFetching(),this._loopReadVideo(t)}),Math.max(this._minImageCaptureInterval,1e3))),"platform error"!==e.message&&setTimeout((()=>{throw e}),0)}))}_reRunCurrnetFunc(t){this._loopReadVideoTimeoutId&&clearTimeout(this._loopReadVideoTimeoutId),this._loopReadVideoTimeoutId=setTimeout((()=>{this._loopReadVideo(t)}),0)}async capture(t,e){var i,n;Le(this),e||(e=Fe._defaultTemplate);const r=await this.containsTask(e);if(await _t(r),r.includes("dlr")&&!(null===(i=gt.dlr)||void 0===i?void 0:i.bLoadConfusableCharsData)){const t=L(vt.engineResourcePaths);await(null===(n=gt.dlr)||void 0===n?void 0:n.loadRecognitionData("ConfusableChars",t.dlr))}let s;if(ee(this,Oe,!1),C(t))s=await this._captureDsimage(t,e);else if("string"==typeof t)s="data:image/"==t.substring(0,11)?await this._captureBase64(t,e):await this._captureUrl(t,e);else if(t instanceof Blob)s=await this._captureBlob(t,e);else if(t instanceof HTMLImageElement)s=await this._captureImage(t,e);else if(t instanceof HTMLCanvasElement)s=await this._captureCanvas(t,e);else{if(!(t instanceof HTMLVideoElement))throw new TypeError("'capture(imageOrFile, templateName)': Type of 'imageOrFile' should be 'DSImageData', 'Url', 'Base64', 'Blob', 'HTMLImageElement', 'HTMLCanvasElement', 'HTMLVideoElement'.");s=await this._captureVideo(t,e)}return s}async _captureDsimage(t,e){return await this._captureInWorker(t,e)}async _captureUrl(t,e){let i=await A(t,"blob");return await this._captureBlob(i,e)}async _captureBase64(t,e){t=t.substring(t.indexOf(",")+1);let i=atob(t),n=i.length,r=new Uint8Array(n);for(;n--;)r[n]=i.charCodeAt(n);return await this._captureBlob(new Blob([r]),e)}async _captureBlob(t,e){let i=null,n=null;if("undefined"!=typeof createImageBitmap)try{i=await createImageBitmap(t)}catch(t){}i||(n=await async function(t){return await new Promise(((e,i)=>{let n=URL.createObjectURL(t),r=new Image;r.src=n,r.onload=()=>{URL.revokeObjectURL(r.dbrObjUrl),e(r)},r.onerror=t=>{i(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}}))}(t));let r=await this._captureImage(i||n,e);return i&&i.close(),r}async _captureImage(t,e){let i,n,r=t instanceof HTMLImageElement?t.naturalWidth:t.width,s=t instanceof HTMLImageElement?t.naturalHeight:t.height,a=Math.max(r,s);a>this.maxImageSideLength?(ee(this,xe,this.maxImageSideLength/a),i=Math.round(r*te(this,xe,"f")),n=Math.round(s*te(this,xe,"f"))):(i=r,n=s),te(this,we,"f")||ee(this,we,document.createElement("canvas"));const o=te(this,we,"f");o.width===i&&o.height===n||(o.width=i,o.height=n),o.ctx2d||(o.ctx2d=o.getContext("2d",{willReadFrequently:!0}));return o.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),t.dbrObjUrl&&URL.revokeObjectURL(t.dbrObjUrl),await this._captureCanvas(o,e)}async _captureCanvas(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";if([t.width,t.height].includes(0))throw Error("The width or height of the 'canvas' is 0.");const i=t.ctx2d||t.getContext("2d",{willReadFrequently:!0}),n={bytes:Uint8Array.from(i.getImageData(0,0,t.width,t.height).data),width:t.width,height:t.height,stride:4*t.width,format:10};return await this._captureInWorker(n,e)}async _captureVideo(t,e){if(t.crossOrigin&&"anonymous"!=t.crossOrigin)throw"cors";let i,n,r=t.videoWidth,s=t.videoHeight,a=Math.max(r,s);a>this.maxImageSideLength?(ee(this,xe,this.maxImageSideLength/a),i=Math.round(r*te(this,xe,"f")),n=Math.round(s*te(this,xe,"f"))):(i=r,n=s),te(this,we,"f")||ee(this,we,document.createElement("canvas"));const o=te(this,we,"f");o.width===i&&o.height===n||(o.width=i,o.height=n),o.ctx2d||(o.ctx2d=o.getContext("2d",{willReadFrequently:!0}));return o.ctx2d.drawImage(t,0,0,r,s,0,0,i,n),await this._captureCanvas(o,e)}async _captureInWorker(t,e){const{bytes:i,width:n,height:r,stride:s,format:a}=t;let o=ot();const l=new re;return lt[o]=async e=>{var i,n;if(!e.success){let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,l.reject(t)}{const r=Date.now();Fe._onLog&&(Fe._onLog(`get result time from worker: ${r}`),Fe._onLog("worker to main time consume: "+(r-e.workerReturnMsgTime)));try{const r=e.captureResult;if(0!==r.errorCode){let t=new Error(r.errorString);return t.errorCode=r.errorCode,l.reject(t)}t.bytes=e.bytes;for(let e of r.items)0!==te(this,xe,"f")&&De(e,te(this,xe,"f")),e.type===yt.CRIT_ORIGINAL_IMAGE?e.imageData=t:e.type===yt.CRIT_NORMALIZED_IMAGE?null===(i=gt.ddn)||void 0===i||i.handleNormalizedImageResultItem(e):e.type===yt.CRIT_PARSED_RESULT&&(null===(n=gt.dcp)||void 0===n||n.handleParsedResultItem(e));if(te(this,Oe,"f"))for(let t of te(this,Ie,"f"))t.onDecodedBarcodesReceived(r),t.onRecognizedTextLinesReceived(r),t.onDetectedQuadsReceived(r),t.onNormalizedImagesReceived(r);for(let t in _e){const e=t,i=r.items.filter((t=>t.type===_e[e].type));i.length&&(r[t]=i)}if(!this._isPauseScan||!te(this,Oe,"f")){const e=r.intermediateResult;if(e){let i=0;for(let n of te(this,Ee,"f")._intermediateResultReceiverSet){i++;for(let r of e){if("onTaskResultsReceived"===r.info.callbackName){for(let e of r.intermediateResultUnits)e.originalImageTag=t.tag?t.tag:null;n[r.info.callbackName]&&n[r.info.callbackName]({intermediateResultUnits:r.intermediateResultUnits},r.info)}else n[r.info.callbackName]&&n[r.info.callbackName](r.result,r.info);i===te(this,Ee,"f")._intermediateResultReceiverSet.size&&delete r.info.callbackName}}}}return r&&r.hasOwnProperty("intermediateResult")&&delete r.intermediateResult,ee(this,xe,0),l.resolve(r)}catch(t){return l.reject(t)}}},Fe._onLog&&Fe._onLog(`send buffer to worker: ${Date.now()}`),st.postMessage({type:"cvr_capture",id:o,instanceID:this._instanceID,body:{bytes:i,width:n,height:r,stride:s,format:a,templateName:e||"",isScanner:te(this,Oe,"f")}},[i.buffer]),l}async initSettings(t){return Le(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?t.trimStart().startsWith("{")||(t=await A(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise(((e,i)=>{let n=ot();lt[n]=async n=>{if(n.success){const r=JSON.parse(n.response);if(0!==r.errorCode){let t=new Error(r.errorString?r.errorString:"Init Settings Failed.");return t.errorCode=r.errorCode,i(t)}const s=JSON.parse(t);this._currentSettings=s;let a=[],o=s.CaptureVisionTemplates;for(let t=0;t{let n=ot();lt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,i(t)}return e(JSON.parse(n.data))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_outputSettings",id:n,instanceID:this._instanceID,body:{templateName:t||"*"}})}))}async outputSettingsToFile(t,e,i){const n=await this.outputSettings(t),r=new Blob([JSON.stringify(n,null,2,(function(t,e){return e instanceof Array?JSON.stringify(e):e}),2)],{type:"application/json"});if(i){const t=document.createElement("a");t.href=URL.createObjectURL(r),e.endsWith(".json")&&(e=e.replace(".json","")),t.download=`${e}.json`,t.onclick=()=>{setTimeout((()=>{URL.revokeObjectURL(t.href)}),500)},t.click()}return r}async getTemplateNames(){return Le(this),await new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,e(t)}return t(JSON.parse(n.data))}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_getTemplateNames",id:i,instanceID:this._instanceID})}))}async getSimplifiedSettings(t){Le(this),t||(t=this._currentSettings.CaptureVisionTemplates[0].Name);const e=await this.containsTask(t);return await _t(e),await new Promise(((e,i)=>{let n=ot();lt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString);return t.errorCode=n.errorCode,i(t)}const r=JSON.parse(n.data,((t,e)=>"barcodeFormatIds"===t?BigInt(e):e));return r.minImageCaptureInterval=this._minImageCaptureInterval,e(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_getSimplifiedSettings",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async updateSettings(t,e){Le(this);const i=await this.containsTask(t);return await _t(i),await new Promise(((i,n)=>{let r=ot();lt[r]=async t=>{if(t.success){const r=JSON.parse(t.response);if(e.minImageCaptureInterval&&e.minImageCaptureInterval>=-1&&(this._minImageCaptureInterval=e.minImageCaptureInterval),this._isOutputOriginalImage=t.isOutputOriginalImage,0!==r.errorCode){let t=new Error(r.errorString?r.errorString:"Update Settings Failed.");return t.errorCode=r.errorCode,n(t)}return this._currentSettings=await this.outputSettings("*"),i(r)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},st.postMessage({type:"cvr_updateSettings",id:r,instanceID:this._instanceID,body:{settings:e,templateName:t}})}))}async resetSettings(){return Le(this),await new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success){const n=JSON.parse(i.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Reset Settings Failed.");return t.errorCode=n.errorCode,e(t)}return this._currentSettings=await this.outputSettings("*"),t(n)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_resetSettings",id:i,instanceID:this._instanceID})}))}getBufferedItemsManager(){return te(this,Se,"f")||ee(this,Se,new se(this)),te(this,Se,"f")}getIntermediateResultManager(){if(Le(this),!te(this,Ae,"f")&&0!==vt.bSupportIRTModule)throw new Error("The current license does not support the use of intermediate results.");return te(this,Ee,"f")||ee(this,Ee,new le(this)),te(this,Ee,"f")}async parseRequiredResources(t){return Le(this),await new Promise(((e,i)=>{let n=ot();lt[n]=async t=>{if(t.success)return e(JSON.parse(t.resources));{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"cvr_parseRequiredResources",id:n,instanceID:this._instanceID,body:{templateName:t}})}))}async dispose(){Le(this),te(this,Ce,"f")&&this.stopCapturing(),ee(this,ye,null),te(this,be,"f").clear(),te(this,Te,"f").clear(),te(this,Ie,"f").clear(),te(this,Ee,"f")._intermediateResultReceiverSet.clear(),ee(this,Re,!0);let t=ot();lt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},st.postMessage({type:"cvr_dispose",id:t,instanceID:this._instanceID})}_getInternalData(){return{isa:te(this,ye,"f"),promiseStartScan:te(this,Ce,"f"),intermediateResultManager:te(this,Ee,"f"),bufferdItemsManager:te(this,Se,"f"),resultReceiverSet:te(this,be,"f"),isaStateListenerSet:te(this,Te,"f"),resultFilterSet:te(this,Ie,"f"),compressRate:te(this,xe,"f"),canvas:te(this,we,"f"),isScanner:te(this,Oe,"f"),innerUseTag:te(this,Ae,"f"),isDestroyed:te(this,Re,"f")}}async _getWasmFilterState(){return await new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success){const e=JSON.parse(i.response);return t(e)}{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"cvr_getWasmFilterState",id:i,instanceID:this._instanceID})}))}}async function Pe(t,e){return Le(t),await new Promise(((i,n)=>{let r=ot();lt[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},st.postMessage({type:"cvr_enableResultCrossVerification",id:r,instanceID:t._instanceID,body:{verificationEnabled:e}})}))}async function ke(t,e){return Le(t),await new Promise(((i,n)=>{let r=ot();lt[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},st.postMessage({type:"cvr_enableResultDeduplication",id:r,instanceID:t._instanceID,body:{duplicateFilterEnabled:e}})}))}async function Ne(t,e){return Le(t),await new Promise(((i,n)=>{let r=ot();lt[r]=async t=>{if(t.success)return i(t.result);{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},st.postMessage({type:"cvr_setDuplicateForgetTime",id:r,instanceID:t._instanceID,body:{duplicateForgetTime:e}})}))}ye=new WeakMap,we=new WeakMap,Ce=new WeakMap,Ee=new WeakMap,Se=new WeakMap,be=new WeakMap,Te=new WeakMap,Ie=new WeakMap,xe=new WeakMap,Oe=new WeakMap,Ae=new WeakMap,Re=new WeakMap,Fe._defaultTemplate="Default";class Be{constructor(){this.onCapturedResultReceived=null,this.onOriginalImageResultReceived=null}}class je{constructor(){this._observedResultUnitTypes=Ot.IRUT_ALL,this._observedTaskMap=new Map,this._parameters={setObservedResultUnitTypes:t=>{this._observedResultUnitTypes=t},getObservedResultUnitTypes:()=>this._observedResultUnitTypes,isResultUnitTypeObserved:t=>!!(t&this._observedResultUnitTypes),addObservedTask:t=>{this._observedTaskMap.set(t,!0)},removeObservedTask:t=>{this._observedTaskMap.set(t,!1)},isTaskObserved:t=>0===this._observedTaskMap.size||!!this._observedTaskMap.get(t)},this.onTaskResultsReceived=null,this.onPredetectedRegionsReceived=null,this.onColourImageUnitReceived=null,this.onScaledDownColourImageUnitReceived=null,this.onGrayscaleImageUnitReceived=null,this.onTransformedGrayscaleImageUnitReceived=null,this.onEnhancedGrayscaleImageUnitReceived=null,this.onBinaryImageUnitReceived=null,this.onTextureDetectionResultUnitReceived=null,this.onTextureRemovedGrayscaleImageUnitReceived=null,this.onTextureRemovedBinaryImageUnitReceived=null,this.onContoursUnitReceived=null,this.onLineSegmentsUnitReceived=null,this.onTextZonesUnitReceived=null,this.onTextRemovedBinaryImageUnitReceived=null,this.onShortLinesUnitReceived=null}getObservationParameters(){return this._parameters}}var Ve;!function(t){t.PT_DEFAULT="Default",t.PT_READ_BARCODES="ReadBarcodes_Default",t.PT_RECOGNIZE_TEXT_LINES="RecognizeTextLines_Default",t.PT_DETECT_DOCUMENT_BOUNDARIES="DetectDocumentBoundaries_Default",t.PT_DETECT_AND_NORMALIZE_DOCUMENT="DetectAndNormalizeDocument_Default",t.PT_NORMALIZE_DOCUMENT="NormalizeDocument_Default",t.PT_READ_BARCODES_SPEED_FIRST="ReadBarcodes_SpeedFirst",t.PT_READ_BARCODES_READ_RATE_FIRST="ReadBarcodes_ReadRateFirst",t.PT_READ_BARCODES_BALANCE="ReadBarcodes_Balance",t.PT_READ_SINGLE_BARCODE="ReadBarcodes_Balanced",t.PT_READ_DENSE_BARCODES="ReadDenseBarcodes",t.PT_READ_DISTANT_BARCODES="ReadDistantBarcodes",t.PT_RECOGNIZE_NUMBERS="RecognizeNumbers",t.PT_RECOGNIZE_LETTERS="RecognizeLetters",t.PT_RECOGNIZE_NUMBERS_AND_LETTERS="RecognizeNumbersAndLetters",t.PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS="RecognizeNumbersAndUppercaseLetters",t.PT_RECOGNIZE_UPPERCASE_LETTERS="RecognizeUppercaseLetters"}(Ve||(Ve={}));const Ue="undefined"==typeof self,Ge="function"==typeof importScripts,We=(()=>{if(!Ge){if(!Ue&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})();vt.engineResourcePaths.dce={version:"4.1.1",path:We,isInternal:!0},mt.dce={wasm:!1,js:!1},gt.dce={};let Ye,ze,He,Xe,Ze,qe=class{static getVersion(){return"4.1.1"}};function Je(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function Ke(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r?r.value=i:e.set(t,i),i}"function"==typeof SuppressedError&&SuppressedError,"undefined"!=typeof navigator&&(Ye=navigator,ze=Ye.userAgent,He=Ye.platform,Xe=Ye.mediaDevices),function(){if(!Ue){const t={Edge:{search:"Edg",verSearch:"Edg"},OPR:null,Chrome:null,Safari:{str:Ye.vendor,search:"Apple",verSearch:["Version","iPhone OS","CPU OS"]},Firefox:null,Explorer:{search:"MSIE",verSearch:"MSIE"}},e={HarmonyOS:null,Android:null,iPhone:null,iPad:null,Windows:{str:He,search:"Win"},Mac:{str:He},Linux:{str:He}};let i="unknownBrowser",n=0,r="unknownOS";for(let e in t){const r=t[e]||{};let s=r.str||ze,a=r.search||e,o=r.verStr||ze,l=r.verSearch||e;if(l instanceof Array||(l=[l]),-1!=s.indexOf(a)){i=e;for(let t of l){let e=o.indexOf(t);if(-1!=e){n=parseFloat(o.substring(e+t.length+1));break}}break}}for(let t in e){const i=e[t]||{};let n=i.str||ze,s=i.search||t;if(-1!=n.indexOf(s)){r=t;break}}"Linux"==r&&-1!=ze.indexOf("Windows NT")&&(r="HarmonyOS"),Ze={browser:i,version:n,OS:r}}Ue&&(Ze={browser:"ssr",version:0,OS:"ssr"})}();const $e="undefined"!=typeof WebAssembly&&ze&&!(/Safari/.test(ze)&&!/Chrome/.test(ze)&&/\(.+\s11_2_([2-6]).*\)/.test(ze)),Qe=!("undefined"==typeof Worker),ti=!(!Xe||!Xe.getUserMedia),ei=async()=>{let t=!1;if(ti)try{(await Xe.getUserMedia({video:!0})).getTracks().forEach((t=>{t.stop()})),t=!0}catch(t){}return t};"Chrome"===Ze.browser&&Ze.version>66||"Safari"===Ze.browser&&Ze.version>13||"OPR"===Ze.browser&&Ze.version>43||"Edge"===Ze.browser&&Ze.version;var ii={653:(t,e,i)=>{var n,r,s,a,o,l,h,c,d,u,f,g,m,p,_,v,y,w,C,E,S,b=b||{version:"5.2.1"};if(e.fabric=b,"undefined"!=typeof document&&"undefined"!=typeof window)document instanceof("undefined"!=typeof HTMLDocument?HTMLDocument:Document)?b.document=document:b.document=document.implementation.createHTMLDocument(""),b.window=window;else{var T=new(i(192).JSDOM)(decodeURIComponent("%3C!DOCTYPE%20html%3E%3Chtml%3E%3Chead%3E%3C%2Fhead%3E%3Cbody%3E%3C%2Fbody%3E%3C%2Fhtml%3E"),{features:{FetchExternalResources:["img"]},resources:"usable"}).window;b.document=T.document,b.jsdomImplForWrapper=i(898).implForWrapper,b.nodeCanvas=i(245).Canvas,b.window=T,DOMParser=b.window.DOMParser}function I(t,e){var i=t.canvas,n=e.targetCanvas,r=n.getContext("2d");r.translate(0,n.height),r.scale(1,-1);var s=i.height-n.height;r.drawImage(i,0,s,n.width,n.height,0,0,n.width,n.height)}function x(t,e){var i=e.targetCanvas.getContext("2d"),n=e.destinationWidth,r=e.destinationHeight,s=n*r*4,a=new Uint8Array(this.imageBuffer,0,s),o=new Uint8ClampedArray(this.imageBuffer,0,s);t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,a);var l=new ImageData(o,n,r);i.putImageData(l,0,0)}b.isTouchSupported="ontouchstart"in b.window||"ontouchstart"in b.document||b.window&&b.window.navigator&&b.window.navigator.maxTouchPoints>0,b.isLikelyNode="undefined"!=typeof Buffer&&"undefined"==typeof window,b.SHARED_ATTRIBUTES=["display","transform","fill","fill-opacity","fill-rule","opacity","stroke","stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"],b.DPI=96,b.reNum="(?:[-+]?(?:\\d+|\\d*\\.\\d+)(?:[eE][-+]?\\d+)?)",b.commaWsp="(?:\\s+,?\\s*|,\\s*)",b.rePathCommand=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:[eE][-+]?\d+)?)/gi,b.reNonWord=/[ \n\.,;!\?\-]/,b.fontPaths={},b.iMatrix=[1,0,0,1,0,0],b.svgNS="http://www.w3.org/2000/svg",b.perfLimitSizeTotal=2097152,b.maxCacheSideLimit=4096,b.minCacheSideLimit=256,b.charWidthsCache={},b.textureSize=2048,b.disableStyleCopyPaste=!1,b.enableGLFiltering=!0,b.devicePixelRatio=b.window.devicePixelRatio||b.window.webkitDevicePixelRatio||b.window.mozDevicePixelRatio||1,b.browserShadowBlurConstant=1,b.arcToSegmentsCache={},b.boundsOfCurveCache={},b.cachesBoundsOfCurve=!0,b.forceGLPutImageData=!1,b.initFilterBackend=function(){return b.enableGLFiltering&&b.isWebglSupported&&b.isWebglSupported(b.textureSize)?(console.log("max texture size: "+b.maxTextureSize),new b.WebglFilterBackend({tileSize:b.textureSize})):b.Canvas2dFilterBackend?new b.Canvas2dFilterBackend:void 0},"undefined"!=typeof document&&"undefined"!=typeof window&&(window.fabric=b),function(){function t(t,e){if(this.__eventListeners[t]){var i=this.__eventListeners[t];e?i[i.indexOf(e)]=!1:b.util.array.fill(i,!1)}}function e(t,e){var i=function(){e.apply(this,arguments),this.off(t,i)}.bind(this);this.on(t,i)}b.Observable={fire:function(t,e){if(!this.__eventListeners)return this;var i=this.__eventListeners[t];if(!i)return this;for(var n=0,r=i.length;n-1||!!e&&this._objects.some((function(e){return"function"==typeof e.contains&&e.contains(t,!0)}))},complexity:function(){return this._objects.reduce((function(t,e){return t+(e.complexity?e.complexity():0)}),0)}},b.CommonMethods={_setOptions:function(t){for(var e in t)this.set(e,t[e])},_initGradient:function(t,e){!t||!t.colorStops||t instanceof b.Gradient||this.set(e,new b.Gradient(t))},_initPattern:function(t,e,i){!t||!t.source||t instanceof b.Pattern?i&&i():this.set(e,new b.Pattern(t,i))},_setObject:function(t){for(var e in t)this._set(e,t[e])},set:function(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this},_set:function(t,e){this[t]=e},toggle:function(t){var e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this},get:function(t){return this[t]}},n=e,r=Math.sqrt,s=Math.atan2,a=Math.pow,o=Math.PI/180,l=Math.PI/2,b.util={cos:function(t){if(0===t)return 1;switch(t<0&&(t=-t),t/l){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin:function(t){if(0===t)return 0;var e=1;switch(t<0&&(e=-1),t/l){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(t)},removeFromArray:function(t,e){var i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},getRandomInt:function(t,e){return Math.floor(Math.random()*(e-t+1))+t},degreesToRadians:function(t){return t*o},radiansToDegrees:function(t){return t/o},rotatePoint:function(t,e,i){var n=new b.Point(t.x-e.x,t.y-e.y),r=b.util.rotateVector(n,i);return new b.Point(r.x,r.y).addEquals(e)},rotateVector:function(t,e){var i=b.util.sin(e),n=b.util.cos(e);return{x:t.x*n-t.y*i,y:t.x*i+t.y*n}},createVector:function(t,e){return new b.Point(e.x-t.x,e.y-t.y)},calcAngleBetweenVectors:function(t,e){return Math.acos((t.x*e.x+t.y*e.y)/(Math.hypot(t.x,t.y)*Math.hypot(e.x,e.y)))},getHatVector:function(t){return new b.Point(t.x,t.y).multiply(1/Math.hypot(t.x,t.y))},getBisector:function(t,e,i){var n=b.util.createVector(t,e),r=b.util.createVector(t,i),s=b.util.calcAngleBetweenVectors(n,r),a=s*(0===b.util.calcAngleBetweenVectors(b.util.rotateVector(n,s),r)?1:-1)/2;return{vector:b.util.getHatVector(b.util.rotateVector(n,a)),angle:s}},projectStrokeOnPoints:function(t,e,i){var n=[],r=e.strokeWidth/2,s=e.strokeUniform?new b.Point(1/e.scaleX,1/e.scaleY):new b.Point(1,1),a=function(t){var e=r/Math.hypot(t.x,t.y);return new b.Point(t.x*e*s.x,t.y*e*s.y)};return t.length<=1||t.forEach((function(o,l){var h,c,d=new b.Point(o.x,o.y);0===l?(c=t[l+1],h=i?a(b.util.createVector(c,d)).addEquals(d):t[t.length-1]):l===t.length-1?(h=t[l-1],c=i?a(b.util.createVector(h,d)).addEquals(d):t[0]):(h=t[l-1],c=t[l+1]);var u,f,g=b.util.getBisector(d,h,c),m=g.vector,p=g.angle;if("miter"===e.strokeLineJoin&&(u=-r/Math.sin(p/2),f=new b.Point(m.x*u*s.x,m.y*u*s.y),Math.hypot(f.x,f.y)/r<=e.strokeMiterLimit))return n.push(d.add(f)),void n.push(d.subtract(f));u=-r*Math.SQRT2,f=new b.Point(m.x*u*s.x,m.y*u*s.y),n.push(d.add(f)),n.push(d.subtract(f))})),n},transformPoint:function(t,e,i){return i?new b.Point(e[0]*t.x+e[2]*t.y,e[1]*t.x+e[3]*t.y):new b.Point(e[0]*t.x+e[2]*t.y+e[4],e[1]*t.x+e[3]*t.y+e[5])},makeBoundingBoxFromPoints:function(t,e){if(e)for(var i=0;i0&&(e>n?e-=n:e=0,i>n?i-=n:i=0);var r,s=!0,a=t.getImageData(e,i,2*n||1,2*n||1),o=a.data.length;for(r=3;r=r?s-r:2*Math.PI-(r-s)}function s(t,e,i){for(var s=i[1],a=i[2],o=i[3],l=i[4],h=i[5],c=function(t,e,i,s,a,o,l){var h=Math.PI,c=l*h/180,d=b.util.sin(c),u=b.util.cos(c),f=0,g=0,m=-u*t*.5-d*e*.5,p=-u*e*.5+d*t*.5,_=(i=Math.abs(i))*i,v=(s=Math.abs(s))*s,y=p*p,w=m*m,C=_*v-_*y-v*w,E=0;if(C<0){var S=Math.sqrt(1-C/(_*v));i*=S,s*=S}else E=(a===o?-1:1)*Math.sqrt(C/(_*y+v*w));var T=E*i*p/s,I=-E*s*m/i,x=u*T-d*I+.5*t,O=d*T+u*I+.5*e,A=r(1,0,(m-T)/i,(p-I)/s),R=r((m-T)/i,(p-I)/s,(-m-T)/i,(-p-I)/s);0===o&&R>0?R-=2*h:1===o&&R<0&&(R+=2*h);for(var D=Math.ceil(Math.abs(R/h*2)),L=[],M=R/D,F=8/3*Math.sin(M/4)*Math.sin(M/4)/Math.sin(M/2),P=A+M,k=0;kE)for(var T=1,I=m.length;T2;for(e=e||0,h&&(o=t[2].xt[i-2].x?1:r.x===t[i-2].x?0:-1,l=r.y>t[i-2].y?1:r.y===t[i-2].y?0:-1),n.push(["L",r.x+o*e,r.y+l*e]),n},b.util.getPathSegmentsInfo=u,b.util.getBoundsOfCurve=function(e,i,n,r,s,a,o,l){var h;if(b.cachesBoundsOfCurve&&(h=t.call(arguments),b.boundsOfCurveCache[h]))return b.boundsOfCurveCache[h];var c,d,u,f,g,m,p,_,v=Math.sqrt,y=Math.min,w=Math.max,C=Math.abs,E=[],S=[[],[]];d=6*e-12*n+6*s,c=-3*e+9*n-9*s+3*o,u=3*n-3*e;for(var T=0;T<2;++T)if(T>0&&(d=6*i-12*r+6*a,c=-3*i+9*r-9*a+3*l,u=3*r-3*i),C(c)<1e-12){if(C(d)<1e-12)continue;0<(f=-u/d)&&f<1&&E.push(f)}else(p=d*d-4*u*c)<0||(0<(g=(-d+(_=v(p)))/(2*c))&&g<1&&E.push(g),0<(m=(-d-_)/(2*c))&&m<1&&E.push(m));for(var I,x,O,A=E.length,R=A;A--;)I=(O=1-(f=E[A]))*O*O*e+3*O*O*f*n+3*O*f*f*s+f*f*f*o,S[0][A]=I,x=O*O*O*i+3*O*O*f*r+3*O*f*f*a+f*f*f*l,S[1][A]=x;S[0][R]=e,S[1][R]=i,S[0][R+1]=o,S[1][R+1]=l;var D=[{x:y.apply(null,S[0]),y:y.apply(null,S[1])},{x:w.apply(null,S[0]),y:w.apply(null,S[1])}];return b.cachesBoundsOfCurve&&(b.boundsOfCurveCache[h]=D),D},b.util.getPointOnPath=function(t,e,i){i||(i=u(t));for(var n=0;e-i[n].length>0&&n1e-4;)i=l(s),r=s,(n=a(h.x,h.y,i.x,i.y))+o>e?(s-=c,c/=2):(h=i,s+=c,o+=n);return i.angle=d(r),i}(s,e)}},b.util.transformPath=function(t,e,i){return i&&(e=b.util.multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map((function(t){for(var i=t.slice(0),n={},r=1;r=e}))}}}(),function(){function t(e,i,n){if(n)if(!b.isLikelyNode&&i instanceof Element)e=i;else if(i instanceof Array){e=[];for(var r=0,s=i.length;r57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";var n=t.charCodeAt(e+1);if(56320>n||n>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";var r=t.charCodeAt(e-1);if(55296>r||r>56319)throw"Low surrogate without preceding high surrogate";return!1}b.util.string={camelize:function(t){return t.replace(/-+(.)?/g,(function(t,e){return e?e.toUpperCase():""}))},capitalize:function(t,e){return t.charAt(0).toUpperCase()+(e?t.slice(1):t.slice(1).toLowerCase())},escapeXml:function(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">")},graphemeSplit:function(e){var i,n=0,r=[];for(n=0;n-1?t.prototype[r]=function(t){return function(){var i=this.constructor.superclass;this.constructor.superclass=n;var r=e[t].apply(this,arguments);if(this.constructor.superclass=i,"initialize"!==t)return r}}(r):t.prototype[r]=e[r],i&&(e.toString!==Object.prototype.toString&&(t.prototype.toString=e.toString),e.valueOf!==Object.prototype.valueOf&&(t.prototype.valueOf=e.valueOf))};function r(){}function s(e){for(var i=null,n=this;n.constructor.superclass;){var r=n.constructor.superclass.prototype[e];if(n[e]!==r){i=r;break}n=n.constructor.superclass.prototype}return i?arguments.length>1?i.apply(this,t.call(arguments,1)):i.call(this):console.log("tried to callSuper "+e+", method not found in prototype chain",this)}b.util.createClass=function(){var i=null,a=t.call(arguments,0);function o(){this.initialize.apply(this,arguments)}"function"==typeof a[0]&&(i=a.shift()),o.superclass=i,o.subclasses=[],i&&(r.prototype=i.prototype,o.prototype=new r,i.subclasses.push(o));for(var l=0,h=a.length;l-1||"touch"===t.pointerType},u="string"==typeof(d=b.document.createElement("div")).style.opacity,f="string"==typeof d.style.filter,g=/alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,m=function(t){return t},u?m=function(t,e){return t.style.opacity=e,t}:f&&(m=function(t,e){var i=t.style;return t.currentStyle&&!t.currentStyle.hasLayout&&(i.zoom=1),g.test(i.filter)?(e=e>=.9999?"":"alpha(opacity="+100*e+")",i.filter=i.filter.replace(g,e)):i.filter+=" alpha(opacity="+100*e+")",t}),b.util.setStyle=function(t,e){var i=t.style;if(!i)return t;if("string"==typeof e)return t.style.cssText+=";"+e,e.indexOf("opacity")>-1?m(t,e.match(/opacity:\s*(\d?\.?\d*)/)[1]):t;for(var n in e)"opacity"===n?m(t,e[n]):i["float"===n||"cssFloat"===n?void 0===i.styleFloat?"cssFloat":"styleFloat":n]=e[n];return t},function(){var t,e,i,n,r=Array.prototype.slice,s=function(t){return r.call(t,0)};try{t=s(b.document.childNodes)instanceof Array}catch(t){}function a(t,e){var i=b.document.createElement(t);for(var n in e)"class"===n?i.className=e[n]:"for"===n?i.htmlFor=e[n]:i.setAttribute(n,e[n]);return i}function o(t){for(var e=0,i=0,n=b.document.documentElement,r=b.document.body||{scrollLeft:0,scrollTop:0};t&&(t.parentNode||t.host)&&((t=t.parentNode||t.host)===b.document?(e=r.scrollLeft||n.scrollLeft||0,i=r.scrollTop||n.scrollTop||0):(e+=t.scrollLeft||0,i+=t.scrollTop||0),1!==t.nodeType||"fixed"!==t.style.position););return{left:e,top:i}}t||(s=function(t){for(var e=new Array(t.length),i=t.length;i--;)e[i]=t[i];return e}),e=b.document.defaultView&&b.document.defaultView.getComputedStyle?function(t,e){var i=b.document.defaultView.getComputedStyle(t,null);return i?i[e]:void 0}:function(t,e){var i=t.style[e];return!i&&t.currentStyle&&(i=t.currentStyle[e]),i},i=b.document.documentElement.style,n="userSelect"in i?"userSelect":"MozUserSelect"in i?"MozUserSelect":"WebkitUserSelect"in i?"WebkitUserSelect":"KhtmlUserSelect"in i?"KhtmlUserSelect":"",b.util.makeElementUnselectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=b.util.falseFunction),n?t.style[n]="none":"string"==typeof t.unselectable&&(t.unselectable="on"),t},b.util.makeElementSelectable=function(t){return void 0!==t.onselectstart&&(t.onselectstart=null),n?t.style[n]="":"string"==typeof t.unselectable&&(t.unselectable=""),t},b.util.setImageSmoothing=function(t,e){t.imageSmoothingEnabled=t.imageSmoothingEnabled||t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled||t.oImageSmoothingEnabled,t.imageSmoothingEnabled=e},b.util.getById=function(t){return"string"==typeof t?b.document.getElementById(t):t},b.util.toArray=s,b.util.addClass=function(t,e){t&&-1===(" "+t.className+" ").indexOf(" "+e+" ")&&(t.className+=(t.className?" ":"")+e)},b.util.makeElement=a,b.util.wrapElement=function(t,e,i){return"string"==typeof e&&(e=a(e,i)),t.parentNode&&t.parentNode.replaceChild(e,t),e.appendChild(t),e},b.util.getScrollLeftTop=o,b.util.getElementOffset=function(t){var i,n,r=t&&t.ownerDocument,s={left:0,top:0},a={left:0,top:0},l={borderLeftWidth:"left",borderTopWidth:"top",paddingLeft:"left",paddingTop:"top"};if(!r)return a;for(var h in l)a[l[h]]+=parseInt(e(t,h),10)||0;return i=r.documentElement,void 0!==t.getBoundingClientRect&&(s=t.getBoundingClientRect()),n=o(t),{left:s.left+n.left-(i.clientLeft||0)+a.left,top:s.top+n.top-(i.clientTop||0)+a.top}},b.util.getNodeCanvas=function(t){var e=b.jsdomImplForWrapper(t);return e._canvas||e._image},b.util.cleanUpJsdomNode=function(t){if(b.isLikelyNode){var e=b.jsdomImplForWrapper(t);e&&(e._image=null,e._canvas=null,e._currentSrc=null,e._attributes=null,e._classList=null)}}}(),function(){function t(){}b.util.request=function(e,i){i||(i={});var n=i.method?i.method.toUpperCase():"GET",r=i.onComplete||function(){},s=new b.window.XMLHttpRequest,a=i.body||i.parameters;return s.onreadystatechange=function(){4===s.readyState&&(r(s),s.onreadystatechange=t)},"GET"===n&&(a=null,"string"==typeof i.parameters&&(e=function(t,e){return t+(/\?/.test(t)?"&":"?")+e}(e,i.parameters))),s.open(n,e,!0),"POST"!==n&&"PUT"!==n||s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.send(a),s}}(),b.log=console.log,b.warn=console.warn,function(){var t=b.util.object.extend,e=b.util.object.clone,i=[];function n(){return!1}function r(t,e,i,n){return-i*Math.cos(t/n*(Math.PI/2))+i+e}b.util.object.extend(i,{cancelAll:function(){var t=this.splice(0);return t.forEach((function(t){t.cancel()})),t},cancelByCanvas:function(t){if(!t)return[];var e=this.filter((function(e){return"object"==typeof e.target&&e.target.canvas===t}));return e.forEach((function(t){t.cancel()})),e},cancelByTarget:function(t){var e=this.findAnimationsByTarget(t);return e.forEach((function(t){t.cancel()})),e},findAnimationIndex:function(t){return this.indexOf(this.findAnimation(t))},findAnimation:function(t){return this.find((function(e){return e.cancel===t}))},findAnimationsByTarget:function(t){return t?this.filter((function(e){return e.target===t})):[]}});var s=b.window.requestAnimationFrame||b.window.webkitRequestAnimationFrame||b.window.mozRequestAnimationFrame||b.window.oRequestAnimationFrame||b.window.msRequestAnimationFrame||function(t){return b.window.setTimeout(t,1e3/60)},a=b.window.cancelAnimationFrame||b.window.clearTimeout;function o(){return s.apply(b.window,arguments)}b.util.animate=function(i){i||(i={});var s,a=!1,l=function(){var t=b.runningAnimations.indexOf(s);return t>-1&&b.runningAnimations.splice(t,1)[0]};return s=t(e(i),{cancel:function(){return a=!0,l()},currentValue:"startValue"in i?i.startValue:0,completionRate:0,durationRate:0}),b.runningAnimations.push(s),o((function(t){var e,h=t||+new Date,c=i.duration||500,d=h+c,u=i.onChange||n,f=i.abort||n,g=i.onComplete||n,m=i.easing||r,p="startValue"in i&&i.startValue.length>0,_="startValue"in i?i.startValue:0,v="endValue"in i?i.endValue:100,y=i.byValue||(p?_.map((function(t,e){return v[e]-_[e]})):v-_);i.onStart&&i.onStart(),function t(i){var n=(e=i||+new Date)>d?c:e-h,r=n/c,w=p?_.map((function(t,e){return m(n,_[e],y[e],c)})):m(n,_,y,c),C=p?Math.abs((w[0]-_[0])/y[0]):Math.abs((w-_)/y);if(s.currentValue=p?w.slice():w,s.completionRate=C,s.durationRate=r,!a){if(!f(w,C,r))return e>d?(s.currentValue=p?v.slice():v,s.completionRate=1,s.durationRate=1,u(p?v.slice():v,1,1),g(v,1,1),void l()):(u(w,C,r),void o(t));l()}}(h)})),s.cancel},b.util.requestAnimFrame=o,b.util.cancelAnimFrame=function(){return a.apply(b.window,arguments)},b.runningAnimations=i}(),function(){function t(t,e,i){var n="rgba("+parseInt(t[0]+i*(e[0]-t[0]),10)+","+parseInt(t[1]+i*(e[1]-t[1]),10)+","+parseInt(t[2]+i*(e[2]-t[2]),10);return(n+=","+(t&&e?parseFloat(t[3]+i*(e[3]-t[3])):1))+")"}b.util.animateColor=function(e,i,n,r){var s=new b.Color(e).getSource(),a=new b.Color(i).getSource(),o=r.onComplete,l=r.onChange;return r=r||{},b.util.animate(b.util.object.extend(r,{duration:n||500,startValue:s,endValue:a,byValue:a,easing:function(e,i,n,s){return t(i,n,r.colorEasing?r.colorEasing(e,s):1-Math.cos(e/s*(Math.PI/2)))},onComplete:function(e,i,n){if(o)return o(t(a,a,0),i,n)},onChange:function(e,i,n){if(l){if(Array.isArray(e))return l(t(e,e,0),i,n);l(e,i,n)}}}))}}(),function(){function t(t,e,i,n){return t-1&&c>-1&&c-1)&&(i="stroke")}else{if("href"===t||"xlink:href"===t||"font"===t)return i;if("imageSmoothing"===t)return"optimizeQuality"===i;o=l?i.map(s):s(i,r)}}else i="";return!l&&isNaN(o)?i:o}function f(t){return new RegExp("^("+t.join("|")+")\\b","i")}function g(t,e){var i,n,r,s,a=[];for(r=0,s=e.length;r1;)l.shift(),h=e.util.multiplyTransformMatrices(h,l[0]);return h}}();var v=new RegExp("^\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*,?\\s*("+e.reNum+"+)\\s*$");function y(t){if(!e.svgViewBoxElementsRegEx.test(t.nodeName))return{};var i,n,r,a,o,l,h=t.getAttribute("viewBox"),c=1,d=1,u=t.getAttribute("width"),f=t.getAttribute("height"),g=t.getAttribute("x")||0,m=t.getAttribute("y")||0,p=t.getAttribute("preserveAspectRatio")||"",_=!h||!(h=h.match(v)),y=!u||!f||"100%"===u||"100%"===f,w=_&&y,C={},E="",S=0,b=0;if(C.width=0,C.height=0,C.toBeParsed=w,_&&(g||m)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") ",o=(t.getAttribute("transform")||"")+E,t.setAttribute("transform",o),t.removeAttribute("x"),t.removeAttribute("y")),w)return C;if(_)return C.width=s(u),C.height=s(f),C;if(i=-parseFloat(h[1]),n=-parseFloat(h[2]),r=parseFloat(h[3]),a=parseFloat(h[4]),C.minX=i,C.minY=n,C.viewBoxWidth=r,C.viewBoxHeight=a,y?(C.width=r,C.height=a):(C.width=s(u),C.height=s(f),c=C.width/r,d=C.height/a),"none"!==(p=e.util.parsePreserveAspectRatioAttribute(p)).alignX&&("meet"===p.meetOrSlice&&(d=c=c>d?d:c),"slice"===p.meetOrSlice&&(d=c=c>d?c:d),S=C.width-r*c,b=C.height-a*c,"Mid"===p.alignX&&(S/=2),"Mid"===p.alignY&&(b/=2),"Min"===p.alignX&&(S=0),"Min"===p.alignY&&(b=0)),1===c&&1===d&&0===i&&0===n&&0===g&&0===m)return C;if((g||m)&&"#document"!==t.parentNode.nodeName&&(E=" translate("+s(g)+" "+s(m)+") "),o=E+" matrix("+c+" 0 0 "+d+" "+(i*c+S)+" "+(n*d+b)+") ","svg"===t.nodeName){for(l=t.ownerDocument.createElementNS(e.svgNS,"g");t.firstChild;)l.appendChild(t.firstChild);t.appendChild(l)}else(l=t).removeAttribute("x"),l.removeAttribute("y"),o=l.getAttribute("transform")+o;return l.setAttribute("transform",o),C}function w(t,e){var i="xlink:href",n=_(t,e.getAttribute(i).slice(1));if(n&&n.getAttribute(i)&&w(t,n),["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"].forEach((function(t){n&&!e.hasAttribute(t)&&n.hasAttribute(t)&&e.setAttribute(t,n.getAttribute(t))})),!e.children.length)for(var r=n.cloneNode(!0);r.firstChild;)e.appendChild(r.firstChild);e.removeAttribute(i)}e.parseSVGDocument=function(t,i,r,s){if(t){!function(t){for(var i=g(t,["use","svg:use"]),n=0;i.length&&nt.x&&this.y>t.y},gte:function(t){return this.x>=t.x&&this.y>=t.y},lerp:function(t,e){return void 0===e&&(e=.5),e=Math.max(Math.min(1,e),0),new i(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)},distanceFrom:function(t){var e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)},midPointFrom:function(t){return this.lerp(t)},min:function(t){return new i(Math.min(this.x,t.x),Math.min(this.y,t.y))},max:function(t){return new i(Math.max(this.x,t.x),Math.max(this.y,t.y))},toString:function(){return this.x+","+this.y},setXY:function(t,e){return this.x=t,this.y=e,this},setX:function(t){return this.x=t,this},setY:function(t){return this.y=t,this},setFromPoint:function(t){return this.x=t.x,this.y=t.y,this},swap:function(t){var e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i},clone:function(){return new i(this.x,this.y)}})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){this.status=t,this.points=[]}e.Intersection?e.warn("fabric.Intersection is already defined"):(e.Intersection=i,e.Intersection.prototype={constructor:i,appendPoint:function(t){return this.points.push(t),this},appendPoints:function(t){return this.points=this.points.concat(t),this}},e.Intersection.intersectLineLine=function(t,n,r,s){var a,o=(s.x-r.x)*(t.y-r.y)-(s.y-r.y)*(t.x-r.x),l=(n.x-t.x)*(t.y-r.y)-(n.y-t.y)*(t.x-r.x),h=(s.y-r.y)*(n.x-t.x)-(s.x-r.x)*(n.y-t.y);if(0!==h){var c=o/h,d=l/h;0<=c&&c<=1&&0<=d&&d<=1?(a=new i("Intersection")).appendPoint(new e.Point(t.x+c*(n.x-t.x),t.y+c*(n.y-t.y))):a=new i}else a=new i(0===o||0===l?"Coincident":"Parallel");return a},e.Intersection.intersectLinePolygon=function(t,e,n){var r,s,a,o,l=new i,h=n.length;for(o=0;o0&&(l.status="Intersection"),l},e.Intersection.intersectPolygonPolygon=function(t,e){var n,r=new i,s=t.length;for(n=0;n0&&(r.status="Intersection"),r},e.Intersection.intersectPolygonRectangle=function(t,n,r){var s=n.min(r),a=n.max(r),o=new e.Point(a.x,s.y),l=new e.Point(s.x,a.y),h=i.intersectLinePolygon(s,o,t),c=i.intersectLinePolygon(o,a,t),d=i.intersectLinePolygon(a,l,t),u=i.intersectLinePolygon(l,s,t),f=new i;return f.appendPoints(h.points),f.appendPoints(c.points),f.appendPoints(d.points),f.appendPoints(u.points),f.points.length>0&&(f.status="Intersection"),f})}(e),function(t){var e=t.fabric||(t.fabric={});function i(t){t?this._tryParsingColor(t):this.setSource([0,0,0,1])}function n(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}e.Color?e.warn("fabric.Color is already defined."):(e.Color=i,e.Color.prototype={_tryParsingColor:function(t){var e;t in i.colorNameMap&&(t=i.colorNameMap[t]),"transparent"===t&&(e=[255,255,255,0]),e||(e=i.sourceFromHex(t)),e||(e=i.sourceFromRgb(t)),e||(e=i.sourceFromHsl(t)),e||(e=[0,0,0,1]),e&&this.setSource(e)},_rgbToHsl:function(t,i,n){t/=255,i/=255,n/=255;var r,s,a,o=e.util.array.max([t,i,n]),l=e.util.array.min([t,i,n]);if(a=(o+l)/2,o===l)r=s=0;else{var h=o-l;switch(s=a>.5?h/(2-o-l):h/(o+l),o){case t:r=(i-n)/h+(i0)-(t<0)||+t};function f(t,e){var i=t.angle+d(Math.atan2(e.y,e.x))+360;return Math.round(i%360/45)}function g(t,i){var n=i.transform.target,r=n.canvas,s=e.util.object.clone(i);s.target=n,r&&r.fire("object:"+t,s),n.fire(t,i)}function m(t,e){var i=e.canvas,n=t[i.uniScaleKey];return i.uniformScaling&&!n||!i.uniformScaling&&n}function p(t){return t.originX===h&&t.originY===h}function _(t,e,i){var n=t.lockScalingX,r=t.lockScalingY;return!((!n||!r)&&(e||!n&&!r||!i)&&(!n||"x"!==e)&&(!r||"y"!==e))}function v(t,e,i,n){return{e:t,transform:e,pointer:{x:i,y:n}}}function y(t){return function(e,i,n,r){var s=i.target,a=s.getCenterPoint(),o=s.translateToOriginPoint(a,i.originX,i.originY),l=t(e,i,n,r);return s.setPositionByOrigin(o,i.originX,i.originY),l}}function w(t,e){return function(i,n,r,s){var a=e(i,n,r,s);return a&&g(t,v(i,n,r,s)),a}}function C(t,i,n,r,s){var a=t.target,o=a.controls[t.corner],l=a.canvas.getZoom(),h=a.padding/l,c=a.toLocalPoint(new e.Point(r,s),i,n);return c.x>=h&&(c.x-=h),c.x<=-h&&(c.x+=h),c.y>=h&&(c.y-=h),c.y<=h&&(c.y+=h),c.x-=o.offsetX,c.y-=o.offsetY,c}function E(t){return t.flipX!==t.flipY}function S(t,e,i,n,r){if(0!==t[e]){var s=r/t._getTransformedDimensions()[n]*t[i];t.set(i,s)}}function b(t,e,i,n){var r,h=e.target,c=h._getTransformedDimensions(0,h.skewY),u=C(e,e.originX,e.originY,i,n),f=Math.abs(2*u.x)-c.x,g=h.skewX;f<2?r=0:(r=d(Math.atan2(f/h.scaleX,c.y/h.scaleY)),e.originX===s&&e.originY===l&&(r=-r),e.originX===o&&e.originY===a&&(r=-r),E(h)&&(r=-r));var m=g!==r;if(m){var p=h._getTransformedDimensions().y;h.set("skewX",r),S(h,"skewY","scaleY","y",p)}return m}function T(t,e,i,n){var r,h=e.target,c=h._getTransformedDimensions(h.skewX,0),u=C(e,e.originX,e.originY,i,n),f=Math.abs(2*u.y)-c.y,g=h.skewY;f<2?r=0:(r=d(Math.atan2(f/h.scaleY,c.x/h.scaleX)),e.originX===s&&e.originY===l&&(r=-r),e.originX===o&&e.originY===a&&(r=-r),E(h)&&(r=-r));var m=g!==r;if(m){var p=h._getTransformedDimensions().x;h.set("skewY",r),S(h,"skewX","scaleX","x",p)}return m}function I(t,e,i,n,r){r=r||{};var s,a,o,l,h,d,f=e.target,g=f.lockScalingX,v=f.lockScalingY,y=r.by,w=m(t,f),E=_(f,y,w),S=e.gestureScale;if(E)return!1;if(S)a=e.scaleX*S,o=e.scaleY*S;else{if(s=C(e,e.originX,e.originY,i,n),h="y"!==y?u(s.x):1,d="x"!==y?u(s.y):1,e.signX||(e.signX=h),e.signY||(e.signY=d),f.lockScalingFlip&&(e.signX!==h||e.signY!==d))return!1;if(l=f._getTransformedDimensions(),w&&!y){var b=Math.abs(s.x)+Math.abs(s.y),T=e.original,I=b/(Math.abs(l.x*T.scaleX/f.scaleX)+Math.abs(l.y*T.scaleY/f.scaleY));a=T.scaleX*I,o=T.scaleY*I}else a=Math.abs(s.x*f.scaleX/l.x),o=Math.abs(s.y*f.scaleY/l.y);p(e)&&(a*=2,o*=2),e.signX!==h&&"y"!==y&&(e.originX=c[e.originX],a*=-1,e.signX=h),e.signY!==d&&"x"!==y&&(e.originY=c[e.originY],o*=-1,e.signY=d)}var x=f.scaleX,O=f.scaleY;return y?("x"===y&&f.set("scaleX",a),"y"===y&&f.set("scaleY",o)):(!g&&f.set("scaleX",a),!v&&f.set("scaleY",o)),x!==f.scaleX||O!==f.scaleY}r.scaleCursorStyleHandler=function(t,e,n){var r=m(t,n),s="";if(0!==e.x&&0===e.y?s="x":0===e.x&&0!==e.y&&(s="y"),_(n,s,r))return"not-allowed";var a=f(n,e);return i[a]+"-resize"},r.skewCursorStyleHandler=function(t,e,i){var r="not-allowed";if(0!==e.x&&i.lockSkewingY)return r;if(0!==e.y&&i.lockSkewingX)return r;var s=f(i,e)%4;return n[s]+"-resize"},r.scaleSkewCursorStyleHandler=function(t,e,i){return t[i.canvas.altActionKey]?r.skewCursorStyleHandler(t,e,i):r.scaleCursorStyleHandler(t,e,i)},r.rotationWithSnapping=w("rotating",y((function(t,e,i,n){var r=e,s=r.target,a=s.translateToOriginPoint(s.getCenterPoint(),r.originX,r.originY);if(s.lockRotation)return!1;var o,l=Math.atan2(r.ey-a.y,r.ex-a.x),h=Math.atan2(n-a.y,i-a.x),c=d(h-l+r.theta);if(s.snapAngle>0){var u=s.snapAngle,f=s.snapThreshold||u,g=Math.ceil(c/u)*u,m=Math.floor(c/u)*u;Math.abs(c-m)0?s:o:(c>0&&(r=d===a?s:o),c<0&&(r=d===a?o:s),E(l)&&(r=r===s?o:s)),e.originX=r,w("skewing",y(b))(t,e,i,n))},r.skewHandlerY=function(t,e,i,n){var r,o=e.target,c=o.skewY,d=e.originX;return!o.lockSkewingY&&(0===c?r=C(e,h,h,i,n).y>0?a:l:(c>0&&(r=d===s?a:l),c<0&&(r=d===s?l:a),E(o)&&(r=r===a?l:a)),e.originY=r,w("skewing",y(T))(t,e,i,n))},r.dragHandler=function(t,e,i,n){var r=e.target,s=i-e.offsetX,a=n-e.offsetY,o=!r.get("lockMovementX")&&r.left!==s,l=!r.get("lockMovementY")&&r.top!==a;return o&&r.set("left",s),l&&r.set("top",a),(o||l)&&g("moving",v(t,e,i,n)),o||l},r.scaleOrSkewActionName=function(t,e,i){var n=t[i.canvas.altActionKey];return 0===e.x?n?"skewX":"scaleY":0===e.y?n?"skewY":"scaleX":void 0},r.rotationStyleHandler=function(t,e,i){return i.lockRotation?"not-allowed":e.cursorStyle},r.fireEvent=g,r.wrapWithFixedAnchor=y,r.wrapWithFireEvent=w,r.getLocalPoint=C,e.controlsUtils=r}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians,n=e.controlsUtils;n.renderCircleControl=function(t,e,i,n,r){n=n||{};var s,a=this.sizeX||n.cornerSize||r.cornerSize,o=this.sizeY||n.cornerSize||r.cornerSize,l=void 0!==n.transparentCorners?n.transparentCorners:r.transparentCorners,h=l?"stroke":"fill",c=!l&&(n.cornerStrokeColor||r.cornerStrokeColor),d=e,u=i;t.save(),t.fillStyle=n.cornerColor||r.cornerColor,t.strokeStyle=n.cornerStrokeColor||r.cornerStrokeColor,a>o?(s=a,t.scale(1,o/a),u=i*a/o):o>a?(s=o,t.scale(a/o,1),d=e*o/a):s=a,t.lineWidth=1,t.beginPath(),t.arc(d,u,s/2,0,2*Math.PI,!1),t[h](),c&&t.stroke(),t.restore()},n.renderSquareControl=function(t,e,n,r,s){r=r||{};var a=this.sizeX||r.cornerSize||s.cornerSize,o=this.sizeY||r.cornerSize||s.cornerSize,l=void 0!==r.transparentCorners?r.transparentCorners:s.transparentCorners,h=l?"stroke":"fill",c=!l&&(r.cornerStrokeColor||s.cornerStrokeColor),d=a/2,u=o/2;t.save(),t.fillStyle=r.cornerColor||s.cornerColor,t.strokeStyle=r.cornerStrokeColor||s.cornerStrokeColor,t.lineWidth=1,t.translate(e,n),t.rotate(i(s.angle)),t[h+"Rect"](-d,-u,a,o),c&&t.strokeRect(-d,-u,a,o),t.restore()}}(e),function(t){var e=t.fabric||(t.fabric={});e.Control=function(t){for(var e in t)this[e]=t[e]},e.Control.prototype={visible:!0,actionName:"scale",angle:0,x:0,y:0,offsetX:0,offsetY:0,sizeX:null,sizeY:null,touchSizeX:null,touchSizeY:null,cursorStyle:"crosshair",withConnection:!1,actionHandler:function(){},mouseDownHandler:function(){},mouseUpHandler:function(){},getActionHandler:function(){return this.actionHandler},getMouseDownHandler:function(){return this.mouseDownHandler},getMouseUpHandler:function(){return this.mouseUpHandler},cursorStyleHandler:function(t,e){return e.cursorStyle},getActionName:function(t,e){return e.actionName},getVisibility:function(t,e){var i=t._controlsVisibility;return i&&void 0!==i[e]?i[e]:this.visible},setVisibility:function(t){this.visible=t},positionHandler:function(t,i){return e.util.transformPoint({x:this.x*t.x+this.offsetX,y:this.y*t.y+this.offsetY},i)},calcCornerCoords:function(t,i,n,r,s){var a,o,l,h,c=s?this.touchSizeX:this.sizeX,d=s?this.touchSizeY:this.sizeY;if(c&&d&&c!==d){var u=Math.atan2(d,c),f=Math.sqrt(c*c+d*d)/2,g=u-e.util.degreesToRadians(t),m=Math.PI/2-u-e.util.degreesToRadians(t);a=f*e.util.cos(g),o=f*e.util.sin(g),l=f*e.util.cos(m),h=f*e.util.sin(m)}else f=.7071067812*(c&&d?c:i),g=e.util.degreesToRadians(45-t),a=l=f*e.util.cos(g),o=h=f*e.util.sin(g);return{tl:{x:n-h,y:r-l},tr:{x:n+a,y:r-o},bl:{x:n-a,y:r+o},br:{x:n+h,y:r+l}}},render:function(t,i,n,r,s){"circle"===((r=r||{}).cornerStyle||s.cornerStyle)?e.controlsUtils.renderCircleControl.call(this,t,i,n,r,s):e.controlsUtils.renderSquareControl.call(this,t,i,n,r,s)}}}(e),function(){function t(t,e){var i,n,r,s,a=t.getAttribute("style"),o=t.getAttribute("offset")||0;if(o=(o=parseFloat(o)/(/%$/.test(o)?100:1))<0?0:o>1?1:o,a){var l=a.split(/\s*;\s*/);for(""===l[l.length-1]&&l.pop(),s=l.length;s--;){var h=l[s].split(/\s*:\s*/),c=h[0].trim(),d=h[1].trim();"stop-color"===c?i=d:"stop-opacity"===c&&(r=d)}}return i||(i=t.getAttribute("stop-color")||"rgb(0,0,0)"),r||(r=t.getAttribute("stop-opacity")),n=(i=new b.Color(i)).getAlpha(),r=isNaN(parseFloat(r))?1:parseFloat(r),r*=n*e,{offset:o,color:i.toRgb(),opacity:r}}var e=b.util.object.clone;b.Gradient=b.util.createClass({offsetX:0,offsetY:0,gradientTransform:null,gradientUnits:"pixels",type:"linear",initialize:function(t){t||(t={}),t.coords||(t.coords={});var e,i=this;Object.keys(t).forEach((function(e){i[e]=t[e]})),this.id?this.id+="_"+b.Object.__uid++:this.id=b.Object.__uid++,e={x1:t.coords.x1||0,y1:t.coords.y1||0,x2:t.coords.x2||0,y2:t.coords.y2||0},"radial"===this.type&&(e.r1=t.coords.r1||0,e.r2=t.coords.r2||0),this.coords=e,this.colorStops=t.colorStops.slice()},addColorStop:function(t){for(var e in t){var i=new b.Color(t[e]);this.colorStops.push({offset:parseFloat(e),color:i.toRgb(),opacity:i.getAlpha()})}return this},toObject:function(t){var e={type:this.type,coords:this.coords,colorStops:this.colorStops,offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?this.gradientTransform.concat():this.gradientTransform};return b.util.populateWithProperties(this,e,t),e},toSVG:function(t,i){var n,r,s,a,o=e(this.coords,!0),l=(i=i||{},e(this.colorStops,!0)),h=o.r1>o.r2,c=this.gradientTransform?this.gradientTransform.concat():b.iMatrix.concat(),d=-this.offsetX,u=-this.offsetY,f=!!i.additionalTransform,g="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox";if(l.sort((function(t,e){return t.offset-e.offset})),"objectBoundingBox"===g?(d/=t.width,u/=t.height):(d+=t.width/2,u+=t.height/2),"path"===t.type&&"percentage"!==this.gradientUnits&&(d-=t.pathOffset.x,u-=t.pathOffset.y),c[4]-=d,c[5]-=u,a='id="SVGID_'+this.id+'" gradientUnits="'+g+'"',a+=' gradientTransform="'+(f?i.additionalTransform+" ":"")+b.util.matrixToSVG(c)+'" ',"linear"===this.type?s=["\n']:"radial"===this.type&&(s=["\n']),"radial"===this.type){if(h)for((l=l.concat()).reverse(),n=0,r=l.length;n0){var p=m/Math.max(o.r1,o.r2);for(n=0,r=l.length;n\n')}return s.push("linear"===this.type?"\n":"\n"),s.join("")},toLive:function(t){var e,i,n,r=b.util.object.clone(this.coords);if(this.type){for("linear"===this.type?e=t.createLinearGradient(r.x1,r.y1,r.x2,r.y2):"radial"===this.type&&(e=t.createRadialGradient(r.x1,r.y1,r.r1,r.x2,r.y2,r.r2)),i=0,n=this.colorStops.length;i1?1:s,isNaN(s)&&(s=1);var a,o,l,h,c=e.getElementsByTagName("stop"),d="userSpaceOnUse"===e.getAttribute("gradientUnits")?"pixels":"percentage",u=e.getAttribute("gradientTransform")||"",f=[],g=0,m=0;for("linearGradient"===e.nodeName||"LINEARGRADIENT"===e.nodeName?(a="linear",o=function(t){return{x1:t.getAttribute("x1")||0,y1:t.getAttribute("y1")||0,x2:t.getAttribute("x2")||"100%",y2:t.getAttribute("y2")||0}}(e)):(a="radial",o=function(t){return{x1:t.getAttribute("fx")||t.getAttribute("cx")||"50%",y1:t.getAttribute("fy")||t.getAttribute("cy")||"50%",r1:0,x2:t.getAttribute("cx")||"50%",y2:t.getAttribute("cy")||"50%",r2:t.getAttribute("r")||"50%"}}(e)),l=c.length;l--;)f.push(t(c[l],s));return h=b.parseTransformAttribute(u),function(t,e,i,n){var r,s;Object.keys(e).forEach((function(t){"Infinity"===(r=e[t])?s=1:"-Infinity"===r?s=0:(s=parseFloat(e[t],10),"string"==typeof r&&/^(\d+\.\d+)%|(\d+)%$/.test(r)&&(s*=.01,"pixels"===n&&("x1"!==t&&"x2"!==t&&"r2"!==t||(s*=i.viewBoxWidth||i.width),"y1"!==t&&"y2"!==t||(s*=i.viewBoxHeight||i.height)))),e[t]=s}))}(0,o,r,d),"pixels"===d&&(g=-i.left,m=-i.top),new b.Gradient({id:e.getAttribute("id"),type:a,coords:o,colorStops:f,gradientUnits:d,gradientTransform:h,offsetX:g,offsetY:m})}})}(),_=b.util.toFixed,b.Pattern=b.util.createClass({repeat:"repeat",offsetX:0,offsetY:0,crossOrigin:"",patternTransform:null,initialize:function(t,e){if(t||(t={}),this.id=b.Object.__uid++,this.setOptions(t),!t.source||t.source&&"string"!=typeof t.source)e&&e(this);else{var i=this;this.source=b.util.createImage(),b.util.loadImage(t.source,(function(t,n){i.source=t,e&&e(i,n)}),null,this.crossOrigin)}},toObject:function(t){var e,i,n=b.Object.NUM_FRACTION_DIGITS;return"string"==typeof this.source.src?e=this.source.src:"object"==typeof this.source&&this.source.toDataURL&&(e=this.source.toDataURL()),i={type:"pattern",source:e,repeat:this.repeat,crossOrigin:this.crossOrigin,offsetX:_(this.offsetX,n),offsetY:_(this.offsetY,n),patternTransform:this.patternTransform?this.patternTransform.concat():null},b.util.populateWithProperties(this,i,t),i},toSVG:function(t){var e="function"==typeof this.source?this.source():this.source,i=e.width/t.width,n=e.height/t.height,r=this.offsetX/t.width,s=this.offsetY/t.height,a="";return"repeat-x"!==this.repeat&&"no-repeat"!==this.repeat||(n=1,s&&(n+=Math.abs(s))),"repeat-y"!==this.repeat&&"no-repeat"!==this.repeat||(i=1,r&&(i+=Math.abs(r))),e.src?a=e.src:e.toDataURL&&(a=e.toDataURL()),'\n\n\n'},setOptions:function(t){for(var e in t)this[e]=t[e]},toLive:function(t){var e=this.source;if(!e)return"";if(void 0!==e.src){if(!e.complete)return"";if(0===e.naturalWidth||0===e.naturalHeight)return""}return t.createPattern(e,this.repeat)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.toFixed;e.Shadow?e.warn("fabric.Shadow is already defined."):(e.Shadow=e.util.createClass({color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1,initialize:function(t){for(var i in"string"==typeof t&&(t=this._parseShadow(t)),t)this[i]=t[i];this.id=e.Object.__uid++},_parseShadow:function(t){var i=t.trim(),n=e.Shadow.reOffsetsAndBlur.exec(i)||[];return{color:(i.replace(e.Shadow.reOffsetsAndBlur,"")||"rgb(0,0,0)").trim(),offsetX:parseFloat(n[1],10)||0,offsetY:parseFloat(n[2],10)||0,blur:parseFloat(n[3],10)||0}},toString:function(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")},toSVG:function(t){var n=40,r=40,s=e.Object.NUM_FRACTION_DIGITS,a=e.util.rotateVector({x:this.offsetX,y:this.offsetY},e.util.degreesToRadians(-t.angle)),o=new e.Color(this.color);return t.width&&t.height&&(n=100*i((Math.abs(a.x)+this.blur)/t.width,s)+20,r=100*i((Math.abs(a.y)+this.blur)/t.height,s)+20),t.flipX&&(a.x*=-1),t.flipY&&(a.y*=-1),'\n\t\n\t\n\t\n\t\n\t\n\t\t\n\t\t\n\t\n\n'},toObject:function(){if(this.includeDefaultValues)return{color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling};var t={},i=e.Shadow.prototype;return["color","blur","offsetX","offsetY","affectStroke","nonScaling"].forEach((function(e){this[e]!==i[e]&&(t[e]=this[e])}),this),t}}),e.Shadow.reOffsetsAndBlur=/(?:\s|^)(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(-?\d+(?:\.\d*)?(?:px)?(?:\s?|$))?(\d+(?:\.\d*)?(?:px)?)?(?:\s?|$)(?:$|\s)/)}(e),function(){if(b.StaticCanvas)b.warn("fabric.StaticCanvas is already defined.");else{var t=b.util.object.extend,e=b.util.getElementOffset,i=b.util.removeFromArray,n=b.util.toFixed,r=b.util.transformPoint,s=b.util.invertTransform,a=b.util.getNodeCanvas,o=b.util.createCanvasElement,l=new Error("Could not initialize `canvas` element");b.StaticCanvas=b.util.createClass(b.CommonMethods,{initialize:function(t,e){e||(e={}),this.renderAndResetBound=this.renderAndReset.bind(this),this.requestRenderAllBound=this.requestRenderAll.bind(this),this._initStatic(t,e)},backgroundColor:"",backgroundImage:null,overlayColor:"",overlayImage:null,includeDefaultValues:!0,stateful:!1,renderOnAddRemove:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,imageSmoothingEnabled:!0,viewportTransform:b.iMatrix.concat(),backgroundVpt:!0,overlayVpt:!0,enableRetinaScaling:!0,vptCoords:{},skipOffscreen:!0,clipPath:void 0,_initStatic:function(t,e){var i=this.requestRenderAllBound;this._objects=[],this._createLowerCanvas(t),this._initOptions(e),this.interactive||this._initRetinaScaling(),e.overlayImage&&this.setOverlayImage(e.overlayImage,i),e.backgroundImage&&this.setBackgroundImage(e.backgroundImage,i),e.backgroundColor&&this.setBackgroundColor(e.backgroundColor,i),e.overlayColor&&this.setOverlayColor(e.overlayColor,i),this.calcOffset()},_isRetinaScaling:function(){return b.devicePixelRatio>1&&this.enableRetinaScaling},getRetinaScaling:function(){return this._isRetinaScaling()?Math.max(1,b.devicePixelRatio):1},_initRetinaScaling:function(){if(this._isRetinaScaling()){var t=b.devicePixelRatio;this.__initRetinaScaling(t,this.lowerCanvasEl,this.contextContainer),this.upperCanvasEl&&this.__initRetinaScaling(t,this.upperCanvasEl,this.contextTop)}},__initRetinaScaling:function(t,e,i){e.setAttribute("width",this.width*t),e.setAttribute("height",this.height*t),i.scale(t,t)},calcOffset:function(){return this._offset=e(this.lowerCanvasEl),this},setOverlayImage:function(t,e,i){return this.__setBgOverlayImage("overlayImage",t,e,i)},setBackgroundImage:function(t,e,i){return this.__setBgOverlayImage("backgroundImage",t,e,i)},setOverlayColor:function(t,e){return this.__setBgOverlayColor("overlayColor",t,e)},setBackgroundColor:function(t,e){return this.__setBgOverlayColor("backgroundColor",t,e)},__setBgOverlayImage:function(t,e,i,n){return"string"==typeof e?b.util.loadImage(e,(function(e,r){if(e){var s=new b.Image(e,n);this[t]=s,s.canvas=this}i&&i(e,r)}),this,n&&n.crossOrigin):(n&&e.setOptions(n),this[t]=e,e&&(e.canvas=this),i&&i(e,!1)),this},__setBgOverlayColor:function(t,e,i){return this[t]=e,this._initGradient(e,t),this._initPattern(e,t,i),this},_createCanvasElement:function(){var t=o();if(!t)throw l;if(t.style||(t.style={}),void 0===t.getContext)throw l;return t},_initOptions:function(t){var e=this.lowerCanvasEl;this._setOptions(t),this.width=this.width||parseInt(e.width,10)||0,this.height=this.height||parseInt(e.height,10)||0,this.lowerCanvasEl.style&&(e.width=this.width,e.height=this.height,e.style.width=this.width+"px",e.style.height=this.height+"px",this.viewportTransform=this.viewportTransform.slice())},_createLowerCanvas:function(t){t&&t.getContext?this.lowerCanvasEl=t:this.lowerCanvasEl=b.util.getById(t)||this._createCanvasElement(),b.util.addClass(this.lowerCanvasEl,"lower-canvas"),this._originalCanvasStyle=this.lowerCanvasEl.style,this.interactive&&this._applyCanvasStyle(this.lowerCanvasEl),this.contextContainer=this.lowerCanvasEl.getContext("2d")},getWidth:function(){return this.width},getHeight:function(){return this.height},setWidth:function(t,e){return this.setDimensions({width:t},e)},setHeight:function(t,e){return this.setDimensions({height:t},e)},setDimensions:function(t,e){var i;for(var n in e=e||{},t)i=t[n],e.cssOnly||(this._setBackstoreDimension(n,t[n]),i+="px",this.hasLostContext=!0),e.backstoreOnly||this._setCssDimension(n,i);return this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop),this._initRetinaScaling(),this.calcOffset(),e.cssOnly||this.requestRenderAll(),this},_setBackstoreDimension:function(t,e){return this.lowerCanvasEl[t]=e,this.upperCanvasEl&&(this.upperCanvasEl[t]=e),this.cacheCanvasEl&&(this.cacheCanvasEl[t]=e),this[t]=e,this},_setCssDimension:function(t,e){return this.lowerCanvasEl.style[t]=e,this.upperCanvasEl&&(this.upperCanvasEl.style[t]=e),this.wrapperEl&&(this.wrapperEl.style[t]=e),this},getZoom:function(){return this.viewportTransform[0]},setViewportTransform:function(t){var e,i,n,r=this._activeObject,s=this.backgroundImage,a=this.overlayImage;for(this.viewportTransform=t,i=0,n=this._objects.length;i\n'),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push(""),i.join("")},_setSVGPreamble:function(t,e){e.suppressPreamble||t.push('\n','\n')},_setSVGHeader:function(t,e){var i,r=e.width||this.width,s=e.height||this.height,a='viewBox="0 0 '+this.width+" "+this.height+'" ',o=b.Object.NUM_FRACTION_DIGITS;e.viewBox?a='viewBox="'+e.viewBox.x+" "+e.viewBox.y+" "+e.viewBox.width+" "+e.viewBox.height+'" ':this.svgViewportTransformation&&(i=this.viewportTransform,a='viewBox="'+n(-i[4]/i[0],o)+" "+n(-i[5]/i[3],o)+" "+n(this.width/i[0],o)+" "+n(this.height/i[3],o)+'" '),t.push("\n',"Created with Fabric.js ",b.version,"\n","\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"\n")},createSVGClipPathMarkup:function(t){var e=this.clipPath;return e?(e.clipPathId="CLIPPATH_"+b.Object.__uid++,'\n'+this.clipPath.toClipPathSVG(t.reviver)+"\n"):""},createSVGRefElementsMarkup:function(){var t=this;return["background","overlay"].map((function(e){var i=t[e+"Color"];if(i&&i.toLive){var n=t[e+"Vpt"],r=t.viewportTransform,s={width:t.width/(n?r[0]:1),height:t.height/(n?r[3]:1)};return i.toSVG(s,{additionalTransform:n?b.util.matrixToSVG(r):""})}})).join("")},createSVGFontFacesMarkup:function(){var t,e,i,n,r,s,a,o,l="",h={},c=b.fontPaths,d=[];for(this._objects.forEach((function t(e){d.push(e),e._objects&&e._objects.forEach(t)})),a=0,o=d.length;a',"\n",l,"","\n"].join("")),l},_setSVGObjects:function(t,e){var i,n,r,s=this._objects;for(n=0,r=s.length;n\n")}else t.push('\n")},sendToBack:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(e=(r=s._objects).length;e--;)n=r[e],i(this._objects,n),this._objects.unshift(n);else i(this._objects,t),this._objects.unshift(t);return this.renderOnAddRemove&&this.requestRenderAll(),this},bringToFront:function(t){if(!t)return this;var e,n,r,s=this._activeObject;if(t===s&&"activeSelection"===t.type)for(r=s._objects,e=0;e0+h&&(a=s-1,i(this._objects,r),this._objects.splice(a,0,r)),h++;else 0!==(s=this._objects.indexOf(t))&&(a=this._findNewLowerIndex(t,s,e),i(this._objects,t),this._objects.splice(a,0,t));return this.renderOnAddRemove&&this.requestRenderAll(),this},_findNewLowerIndex:function(t,e,i){var n,r;if(i){for(n=e,r=e-1;r>=0;--r)if(t.intersectsWithObject(this._objects[r])||t.isContainedWithinObject(this._objects[r])||this._objects[r].isContainedWithinObject(t)){n=r;break}}else n=e-1;return n},bringForward:function(t,e){if(!t)return this;var n,r,s,a,o,l=this._activeObject,h=0;if(t===l&&"activeSelection"===t.type)for(n=(o=l._objects).length;n--;)r=o[n],(s=this._objects.indexOf(r))"}}),t(b.StaticCanvas.prototype,b.Observable),t(b.StaticCanvas.prototype,b.Collection),t(b.StaticCanvas.prototype,b.DataURLExporter),t(b.StaticCanvas,{EMPTY_JSON:'{"objects": [], "background": "white"}',supports:function(t){var e=o();if(!e||!e.getContext)return null;var i=e.getContext("2d");return i&&"setLineDash"===t?void 0!==i.setLineDash:null}}),b.StaticCanvas.prototype.toJSON=b.StaticCanvas.prototype.toObject,b.isLikelyNode&&(b.StaticCanvas.prototype.createPNGStream=function(){var t=a(this.lowerCanvasEl);return t&&t.createPNGStream()},b.StaticCanvas.prototype.createJPEGStream=function(t){var e=a(this.lowerCanvasEl);return e&&e.createJPEGStream(t)})}}(),b.BaseBrush=b.util.createClass({color:"rgb(0, 0, 0)",width:1,shadow:null,strokeLineCap:"round",strokeLineJoin:"round",strokeMiterLimit:10,strokeDashArray:null,limitedToCanvasSize:!1,_setBrushStyles:function(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])},_saveAndTransform:function(t){var e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])},_setShadow:function(){if(this.shadow){var t=this.canvas,e=this.shadow,i=t.contextTop,n=t.getZoom();t&&t._isRetinaScaling()&&(n*=b.devicePixelRatio),i.shadowColor=e.color,i.shadowBlur=e.blur*n,i.shadowOffsetX=e.offsetX*n,i.shadowOffsetY=e.offsetY*n}},needsFullRender:function(){return new b.Color(this.color).getAlpha()<1||!!this.shadow},_resetShadow:function(){var t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0},_isOutSideCanvas:function(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}),b.PencilBrush=b.util.createClass(b.BaseBrush,{decimate:.4,drawStraightLine:!1,straightLineKey:"shiftKey",initialize:function(t){this.canvas=t,this._points=[]},needsFullRender:function(){return this.callSuper("needsFullRender")||this._hasStraightLine},_drawSegment:function(t,e,i){var n=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,n.x,n.y),n},onMouseDown:function(t,e){this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],this._prepareForDrawing(t),this._captureDrawingPath(t),this._render())},onMouseMove:function(t,e){if(this.canvas._isMainEvent(e.e)&&(this.drawStraightLine=e.e[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._captureDrawingPath(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{var i=this._points,n=i.length,r=this.canvas.contextTop;this._saveAndTransform(r),this.oldEnd&&(r.beginPath(),r.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=this._drawSegment(r,i[n-2],i[n-1],!0),r.stroke(),r.restore()}},onMouseUp:function(t){return!this.canvas._isMainEvent(t.e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)},_prepareForDrawing:function(t){var e=new b.Point(t.x,t.y);this._reset(),this._addPoint(e),this.canvas.contextTop.moveTo(e.x,e.y)},_addPoint:function(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1])||(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),0))},_reset:function(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1},_captureDrawingPath:function(t){var e=new b.Point(t.x,t.y);return this._addPoint(e)},_render:function(t){var e,i,n=this._points[0],r=this._points[1];if(t=t||this.canvas.contextTop,this._saveAndTransform(t),t.beginPath(),2===this._points.length&&n.x===r.x&&n.y===r.y){var s=this.width/1e3;n=new b.Point(n.x,n.y),r=new b.Point(r.x,r.y),n.x-=s,r.x+=s}for(t.moveTo(n.x,n.y),e=1,i=this._points.length;e=r&&(a=t[i],o.push(a));return o.push(t[s]),o},_finalizeAndAddPath:function(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));var t=this.convertPointsToSVGPath(this._points);if(this._isEmptySVGPath(t))this.canvas.requestRenderAll();else{var e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}}),b.CircleBrush=b.util.createClass(b.BaseBrush,{width:10,initialize:function(t){this.canvas=t,this.points=[]},drawDot:function(t){var e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()},dot:function(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()},onMouseDown:function(t){this.points.length=0,this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)},_render:function(){var t,e,i=this.canvas.contextTop,n=this.points;for(this._saveAndTransform(i),t=0,e=n.length;t0&&!this.preserveObjectStacking){e=[],i=[];for(var r=0,s=this._objects.length;r1&&(this._activeObject._objects=i),e.push.apply(e,i)}else e=this._objects;return e},renderAll:function(){!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1);var t=this.contextContainer;return this.renderCanvas(t,this._chooseObjectsToRender()),this},renderTopLayer:function(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()},renderTop:function(){var t=this.contextTop;return this.clearContext(t),this.renderTopLayer(t),this.fire("after:render"),this},_normalizePointer:function(t,e){var i=t.calcTransformMatrix(),n=b.util.invertTransform(i),r=this.restorePointerVpt(e);return b.util.transformPoint(r,n)},isTargetTransparent:function(t,e,i){if(t.shouldCache()&&t._cacheCanvas&&t!==this._activeObject){var n=this._normalizePointer(t,{x:e,y:i}),r=Math.max(t.cacheTranslationX+n.x*t.zoomX,0),s=Math.max(t.cacheTranslationY+n.y*t.zoomY,0);return b.util.isTransparent(t._cacheContext,Math.round(r),Math.round(s),this.targetFindTolerance)}var a=this.contextCache,o=t.selectionBackgroundColor,l=this.viewportTransform;return t.selectionBackgroundColor="",this.clearContext(a),a.save(),a.transform(l[0],l[1],l[2],l[3],l[4],l[5]),t.render(a),a.restore(),t.selectionBackgroundColor=o,b.util.isTransparent(a,e,i,this.targetFindTolerance)},_isSelectionKeyPressed:function(t){return Array.isArray(this.selectionKey)?!!this.selectionKey.find((function(e){return!0===t[e]})):t[this.selectionKey]},_shouldClearSelection:function(t,e){var i=this.getActiveObjects(),n=this._activeObject;return!e||e&&n&&i.length>1&&-1===i.indexOf(e)&&n!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&n&&n!==e},_shouldCenterTransform:function(t,e,i){var n;if(t)return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?n=this.centeredScaling||t.centeredScaling:"rotate"===e&&(n=this.centeredRotation||t.centeredRotation),n?!i:i},_getOriginFromCorner:function(t,e){var i={x:t.originX,y:t.originY};return"ml"===e||"tl"===e||"bl"===e?i.x="right":"mr"!==e&&"tr"!==e&&"br"!==e||(i.x="left"),"tl"===e||"mt"===e||"tr"===e?i.y="bottom":"bl"!==e&&"mb"!==e&&"br"!==e||(i.y="top"),i},_getActionFromCorner:function(t,e,i,n){if(!e||!t)return"drag";var r=n.controls[e];return r.getActionName(i,r,n)},_setupCurrentTransform:function(t,i,n){if(i){var r=this.getPointer(t),s=i.__corner,a=i.controls[s],o=n&&s?a.getActionHandler(t,i,a):b.controlsUtils.dragHandler,l=this._getActionFromCorner(n,s,t,i),h=this._getOriginFromCorner(i,s),c=t[this.centeredKey],d={target:i,action:l,actionHandler:o,corner:s,scaleX:i.scaleX,scaleY:i.scaleY,skewX:i.skewX,skewY:i.skewY,offsetX:r.x-i.left,offsetY:r.y-i.top,originX:h.x,originY:h.y,ex:r.x,ey:r.y,lastX:r.x,lastY:r.y,theta:e(i.angle),width:i.width*i.scaleX,shiftKey:t.shiftKey,altKey:c,original:b.util.saveObjectTransform(i)};this._shouldCenterTransform(i,l,c)&&(d.originX="center",d.originY="center"),d.original.originX=h.x,d.original.originY=h.y,this._currentTransform=d,this._beforeTransform(t)}},setCursor:function(t){this.upperCanvasEl.style.cursor=t},_drawSelection:function(t){var e=this._groupSelector,i=new b.Point(e.ex,e.ey),n=b.util.transformPoint(i,this.viewportTransform),r=new b.Point(e.ex+e.left,e.ey+e.top),s=b.util.transformPoint(r,this.viewportTransform),a=Math.min(n.x,s.x),o=Math.min(n.y,s.y),l=Math.max(n.x,s.x),h=Math.max(n.y,s.y),c=this.selectionLineWidth/2;this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(a,o,l-a,h-o)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,a+=c,o+=c,l-=c,h-=c,b.Object.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(a,o,l-a,h-o))},findTarget:function(t,e){if(!this.skipTargetFind){var n,r,s=this.getPointer(t,!0),a=this._activeObject,o=this.getActiveObjects(),l=i(t),h=o.length>1&&!e||1===o.length;if(this.targets=[],h&&a._findTargetCorner(s,l))return a;if(o.length>1&&!e&&a===this._searchPossibleTargets([a],s))return a;if(1===o.length&&a===this._searchPossibleTargets([a],s)){if(!this.preserveObjectStacking)return a;n=a,r=this.targets,this.targets=[]}var c=this._searchPossibleTargets(this._objects,s);return t[this.altSelectionKey]&&c&&n&&c!==n&&(c=n,this.targets=r),c}},_checkTarget:function(t,e,i){if(e&&e.visible&&e.evented&&e.containsPoint(t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;if(!this.isTargetTransparent(e,i.x,i.y))return!0}},_searchPossibleTargets:function(t,e){for(var i,n,r=t.length;r--;){var s=t[r],a=s.group?this._normalizePointer(s.group,e):e;if(this._checkTarget(a,s,e)){(i=t[r]).subTargetCheck&&i instanceof b.Group&&(n=this._searchPossibleTargets(i._objects,e))&&this.targets.push(n);break}}return i},restorePointerVpt:function(t){return b.util.transformPoint(t,b.util.invertTransform(this.viewportTransform))},getPointer:function(e,i){if(this._absolutePointer&&!i)return this._absolutePointer;if(this._pointer&&i)return this._pointer;var n,r=t(e),s=this.upperCanvasEl,a=s.getBoundingClientRect(),o=a.width||0,l=a.height||0;o&&l||("top"in a&&"bottom"in a&&(l=Math.abs(a.top-a.bottom)),"right"in a&&"left"in a&&(o=Math.abs(a.right-a.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,i||(r=this.restorePointerVpt(r));var h=this.getRetinaScaling();return 1!==h&&(r.x/=h,r.y/=h),n=0===o||0===l?{width:1,height:1}:{width:s.width/o,height:s.height/l},{x:r.x*n.width,y:r.y*n.height}},_createUpperCanvas:function(){var t=this.lowerCanvasEl.className.replace(/\s*lower-canvas\s*/,""),e=this.lowerCanvasEl,i=this.upperCanvasEl;i?i.className="":(i=this._createCanvasElement(),this.upperCanvasEl=i),b.util.addClass(i,"upper-canvas "+t),this.wrapperEl.appendChild(i),this._copyCanvasStyle(e,i),this._applyCanvasStyle(i),this.contextTop=i.getContext("2d")},getTopContext:function(){return this.contextTop},_createCacheCanvas:function(){this.cacheCanvasEl=this._createCanvasElement(),this.cacheCanvasEl.setAttribute("width",this.width),this.cacheCanvasEl.setAttribute("height",this.height),this.contextCache=this.cacheCanvasEl.getContext("2d")},_initWrapperElement:function(){this.wrapperEl=b.util.wrapElement(this.lowerCanvasEl,"div",{class:this.containerClass}),b.util.setStyle(this.wrapperEl,{width:this.width+"px",height:this.height+"px",position:"relative"}),b.util.makeElementUnselectable(this.wrapperEl)},_applyCanvasStyle:function(t){var e=this.width||t.width,i=this.height||t.height;b.util.setStyle(t,{position:"absolute",width:e+"px",height:i+"px",left:0,top:0,"touch-action":this.allowTouchScrolling?"manipulation":"none","-ms-touch-action":this.allowTouchScrolling?"manipulation":"none"}),t.width=e,t.height=i,b.util.makeElementUnselectable(t)},_copyCanvasStyle:function(t,e){e.style.cssText=t.style.cssText},getSelectionContext:function(){return this.contextTop},getSelectionElement:function(){return this.upperCanvasEl},getActiveObject:function(){return this._activeObject},getActiveObjects:function(){var t=this._activeObject;return t?"activeSelection"===t.type&&t._objects?t._objects.slice(0):[t]:[]},_onObjectRemoved:function(t){t===this._activeObject&&(this.fire("before:selection:cleared",{target:t}),this._discardActiveObject(),this.fire("selection:cleared",{target:t}),t.fire("deselected")),t===this._hoveredTarget&&(this._hoveredTarget=null,this._hoveredTargets=[]),this.callSuper("_onObjectRemoved",t)},_fireSelectionEvents:function(t,e){var i=!1,n=this.getActiveObjects(),r=[],s=[];t.forEach((function(t){-1===n.indexOf(t)&&(i=!0,t.fire("deselected",{e,target:t}),s.push(t))})),n.forEach((function(n){-1===t.indexOf(n)&&(i=!0,n.fire("selected",{e,target:n}),r.push(n))})),t.length>0&&n.length>0?i&&this.fire("selection:updated",{e,selected:r,deselected:s}):n.length>0?this.fire("selection:created",{e,selected:r}):t.length>0&&this.fire("selection:cleared",{e,deselected:s})},setActiveObject:function(t,e){var i=this.getActiveObjects();return this._setActiveObject(t,e),this._fireSelectionEvents(i,e),this},_setActiveObject:function(t,e){return this._activeObject!==t&&!!this._discardActiveObject(e,t)&&!t.onSelect({e})&&(this._activeObject=t,!0)},_discardActiveObject:function(t,e){var i=this._activeObject;if(i){if(i.onDeselect({e:t,object:e}))return!1;this._activeObject=null}return!0},discardActiveObject:function(t){var e=this.getActiveObjects(),i=this.getActiveObject();return e.length&&this.fire("before:selection:cleared",{target:i,e:t}),this._discardActiveObject(t),this._fireSelectionEvents(e,t),this},dispose:function(){var t=this.wrapperEl;return this.removeListeners(),t.removeChild(this.upperCanvasEl),t.removeChild(this.lowerCanvasEl),this.contextCache=null,this.contextTop=null,["upperCanvasEl","cacheCanvasEl"].forEach(function(t){b.util.cleanUpJsdomNode(this[t]),this[t]=void 0}.bind(this)),t.parentNode&&t.parentNode.replaceChild(this.lowerCanvasEl,this.wrapperEl),delete this.wrapperEl,b.StaticCanvas.prototype.dispose.call(this),this},clear:function(){return this.discardActiveObject(),this.clearContext(this.contextTop),this.callSuper("clear")},drawControls:function(t){var e=this._activeObject;e&&e._renderControls(t)},_toObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(t),r=this.callSuper("_toObject",t,e,i);return this._unwindGroupTransformOnObject(t,n),r},_realizeGroupTransformOnObject:function(t){if(t.group&&"activeSelection"===t.group.type&&this._activeObject===t.group){var e={};return["angle","flipX","flipY","left","scaleX","scaleY","skewX","skewY","top"].forEach((function(i){e[i]=t[i]})),b.util.addTransformToObject(t,this._activeObject.calcOwnMatrix()),e}return null},_unwindGroupTransformOnObject:function(t,e){e&&t.set(e)},_setSVGObject:function(t,e,i){var n=this._realizeGroupTransformOnObject(e);this.callSuper("_setSVGObject",t,e,i),this._unwindGroupTransformOnObject(e,n)},setViewportTransform:function(t){this.renderOnAddRemove&&this._activeObject&&this._activeObject.isEditing&&this._activeObject.clearContextTop(),b.StaticCanvas.prototype.setViewportTransform.call(this,t)}}),b.StaticCanvas)"prototype"!==n&&(b.Canvas[n]=b.StaticCanvas[n])}(),function(){var t=b.util.addListener,e=b.util.removeListener,i={passive:!1};function n(t,e){return t.button&&t.button===e-1}b.util.object.extend(b.Canvas.prototype,{mainTouchId:null,_initEventListeners:function(){this.removeListeners(),this._bindEvents(),this.addOrRemove(t,"add")},_getEventPrefix:function(){return this.enablePointerEvents?"pointer":"mouse"},addOrRemove:function(t,e){var n=this.upperCanvasEl,r=this._getEventPrefix();t(b.window,"resize",this._onResize),t(n,r+"down",this._onMouseDown),t(n,r+"move",this._onMouseMove,i),t(n,r+"out",this._onMouseOut),t(n,r+"enter",this._onMouseEnter),t(n,"wheel",this._onMouseWheel),t(n,"contextmenu",this._onContextMenu),t(n,"dblclick",this._onDoubleClick),t(n,"dragover",this._onDragOver),t(n,"dragenter",this._onDragEnter),t(n,"dragleave",this._onDragLeave),t(n,"drop",this._onDrop),this.enablePointerEvents||t(n,"touchstart",this._onTouchStart,i),"undefined"!=typeof eventjs&&e in eventjs&&(eventjs[e](n,"gesture",this._onGesture),eventjs[e](n,"drag",this._onDrag),eventjs[e](n,"orientation",this._onOrientationChange),eventjs[e](n,"shake",this._onShake),eventjs[e](n,"longpress",this._onLongPress))},removeListeners:function(){this.addOrRemove(e,"remove");var t=this._getEventPrefix();e(b.document,t+"up",this._onMouseUp),e(b.document,"touchend",this._onTouchEnd,i),e(b.document,t+"move",this._onMouseMove,i),e(b.document,"touchmove",this._onMouseMove,i)},_bindEvents:function(){this.eventsBound||(this._onMouseDown=this._onMouseDown.bind(this),this._onTouchStart=this._onTouchStart.bind(this),this._onMouseMove=this._onMouseMove.bind(this),this._onMouseUp=this._onMouseUp.bind(this),this._onTouchEnd=this._onTouchEnd.bind(this),this._onResize=this._onResize.bind(this),this._onGesture=this._onGesture.bind(this),this._onDrag=this._onDrag.bind(this),this._onShake=this._onShake.bind(this),this._onLongPress=this._onLongPress.bind(this),this._onOrientationChange=this._onOrientationChange.bind(this),this._onMouseWheel=this._onMouseWheel.bind(this),this._onMouseOut=this._onMouseOut.bind(this),this._onMouseEnter=this._onMouseEnter.bind(this),this._onContextMenu=this._onContextMenu.bind(this),this._onDoubleClick=this._onDoubleClick.bind(this),this._onDragOver=this._onDragOver.bind(this),this._onDragEnter=this._simpleEventHandler.bind(this,"dragenter"),this._onDragLeave=this._simpleEventHandler.bind(this,"dragleave"),this._onDrop=this._onDrop.bind(this),this.eventsBound=!0)},_onGesture:function(t,e){this.__onTransformGesture&&this.__onTransformGesture(t,e)},_onDrag:function(t,e){this.__onDrag&&this.__onDrag(t,e)},_onMouseWheel:function(t){this.__onMouseWheel(t)},_onMouseOut:function(t){var e=this._hoveredTarget;this.fire("mouse:out",{target:e,e:t}),this._hoveredTarget=null,e&&e.fire("mouseout",{e:t});var i=this;this._hoveredTargets.forEach((function(n){i.fire("mouse:out",{target:e,e:t}),n&&e.fire("mouseout",{e:t})})),this._hoveredTargets=[],this._iTextInstances&&this._iTextInstances.forEach((function(t){t.isEditing&&t.hiddenTextarea.focus()}))},_onMouseEnter:function(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",{target:null,e:t}),this._hoveredTarget=null,this._hoveredTargets=[])},_onOrientationChange:function(t,e){this.__onOrientationChange&&this.__onOrientationChange(t,e)},_onShake:function(t,e){this.__onShake&&this.__onShake(t,e)},_onLongPress:function(t,e){this.__onLongPress&&this.__onLongPress(t,e)},_onDragOver:function(t){t.preventDefault();var e=this._simpleEventHandler("dragover",t);this._fireEnterLeaveEvents(e,t)},_onDrop:function(t){return this._simpleEventHandler("drop:before",t),this._simpleEventHandler("drop",t)},_onContextMenu:function(t){return this.stopContextMenu&&(t.stopPropagation(),t.preventDefault()),!1},_onDoubleClick:function(t){this._cacheTransformEventData(t),this._handleEvent(t,"dblclick"),this._resetTransformEventData(t)},getPointerId:function(t){var e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1},_isMainEvent:function(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)},_onTouchStart:function(n){n.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(n)),this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();t(b.document,"touchend",this._onTouchEnd,i),t(b.document,"touchmove",this._onMouseMove,i),e(r,s+"down",this._onMouseDown)},_onMouseDown:function(n){this.__onMouseDown(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();e(r,s+"move",this._onMouseMove,i),t(b.document,s+"up",this._onMouseUp),t(b.document,s+"move",this._onMouseMove,i)},_onTouchEnd:function(n){if(!(n.touches.length>0)){this.__onMouseUp(n),this._resetTransformEventData(),this.mainTouchId=null;var r=this._getEventPrefix();e(b.document,"touchend",this._onTouchEnd,i),e(b.document,"touchmove",this._onMouseMove,i);var s=this;this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((function(){t(s.upperCanvasEl,r+"down",s._onMouseDown),s._willAddMouseDown=0}),400)}},_onMouseUp:function(n){this.__onMouseUp(n),this._resetTransformEventData();var r=this.upperCanvasEl,s=this._getEventPrefix();this._isMainEvent(n)&&(e(b.document,s+"up",this._onMouseUp),e(b.document,s+"move",this._onMouseMove,i),t(r,s+"move",this._onMouseMove,i))},_onMouseMove:function(t){!this.allowTouchScrolling&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)},_onResize:function(){this.calcOffset()},_shouldRender:function(t){var e=this._activeObject;return!!(!!e!=!!t||e&&t&&e!==t)||(e&&e.isEditing,!1)},__onMouseUp:function(t){var e,i=this._currentTransform,r=this._groupSelector,s=!1,a=!r||0===r.left&&0===r.top;if(this._cacheTransformEventData(t),e=this._target,this._handleEvent(t,"up:before"),n(t,3))this.fireRightClick&&this._handleEvent(t,"up",3,a);else{if(n(t,2))return this.fireMiddleClick&&this._handleEvent(t,"up",2,a),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)this._onMouseUpInDrawingMode(t);else if(this._isMainEvent(t)){if(i&&(this._finalizeCurrentTransform(t),s=i.actionPerformed),!a){var o=e===this._activeObject;this._maybeGroupObjects(t),s||(s=this._shouldRender(e)||!o&&e===this._activeObject)}var l,h;if(e){if(l=e._findTargetCorner(this.getPointer(t,!0),b.util.isTouchEvent(t)),e.selectable&&e!==this._activeObject&&"up"===e.activeOn)this.setActiveObject(e,t),s=!0;else{var c=e.controls[l],d=c&&c.getMouseUpHandler(t,e,c);d&&d(t,i,(h=this.getPointer(t)).x,h.y)}e.isMoving=!1}if(i&&(i.target!==e||i.corner!==l)){var u=i.target&&i.target.controls[i.corner],f=u&&u.getMouseUpHandler(t,e,c);h=h||this.getPointer(t),f&&f(t,i,h.x,h.y)}this._setCursorFromEvent(t,e),this._handleEvent(t,"up",1,a),this._groupSelector=null,this._currentTransform=null,e&&(e.__corner=0),s?this.requestRenderAll():a||this.renderTop()}}},_simpleEventHandler:function(t,e){var i=this.findTarget(e),n=this.targets,r={e,target:i,subTargets:n};if(this.fire(t,r),i&&i.fire(t,r),!n)return i;for(var s=0;s1&&(e=new b.ActiveSelection(i.reverse(),{canvas:this}),this.setActiveObject(e,t))},_collectObjects:function(t){for(var e,i=[],n=this._groupSelector.ex,r=this._groupSelector.ey,s=n+this._groupSelector.left,a=r+this._groupSelector.top,o=new b.Point(v(n,s),v(r,a)),l=new b.Point(y(n,s),y(r,a)),h=!this.selectionFullyContained,c=n===s&&r===a,d=this._objects.length;d--&&!((e=this._objects[d])&&e.selectable&&e.visible&&(h&&e.intersectsWithRect(o,l,!0)||e.isContainedWithinRect(o,l,!0)||h&&e.containsPoint(o,null,!0)||h&&e.containsPoint(l,null,!0))&&(i.push(e),c)););return i.length>1&&(i=i.filter((function(e){return!e.onSelect({e:t})}))),i},_maybeGroupObjects:function(t){this.selection&&this._groupSelector&&this._groupSelectedObjects(t),this.setCursor(this.defaultCursor),this._groupSelector=null}}),b.util.object.extend(b.StaticCanvas.prototype,{toDataURL:function(t){t||(t={});var e=t.format||"png",i=t.quality||1,n=(t.multiplier||1)*(t.enableRetinaScaling?this.getRetinaScaling():1),r=this.toCanvasElement(n,t);return b.util.toDataURL(r,e,i)},toCanvasElement:function(t,e){t=t||1;var i=((e=e||{}).width||this.width)*t,n=(e.height||this.height)*t,r=this.getZoom(),s=this.width,a=this.height,o=r*t,l=this.viewportTransform,h=(l[4]-(e.left||0))*t,c=(l[5]-(e.top||0))*t,d=this.interactive,u=[o,0,0,o,h,c],f=this.enableRetinaScaling,g=b.util.createCanvasElement(),m=this.contextTop;return g.width=i,g.height=n,this.contextTop=null,this.enableRetinaScaling=!1,this.interactive=!1,this.viewportTransform=u,this.width=i,this.height=n,this.calcViewportBoundaries(),this.renderCanvas(g.getContext("2d"),this._objects),this.viewportTransform=l,this.width=s,this.height=a,this.calcViewportBoundaries(),this.interactive=d,this.enableRetinaScaling=f,this.contextTop=m,g}}),b.util.object.extend(b.StaticCanvas.prototype,{loadFromJSON:function(t,e,i){if(t){var n="string"==typeof t?JSON.parse(t):b.util.object.clone(t),r=this,s=n.clipPath,a=this.renderOnAddRemove;return this.renderOnAddRemove=!1,delete n.clipPath,this._enlivenObjects(n.objects,(function(t){r.clear(),r._setBgOverlay(n,(function(){s?r._enlivenObjects([s],(function(i){r.clipPath=i[0],r.__setupCanvas.call(r,n,t,a,e)})):r.__setupCanvas.call(r,n,t,a,e)}))}),i),this}},__setupCanvas:function(t,e,i,n){var r=this;e.forEach((function(t,e){r.insertAt(t,e)})),this.renderOnAddRemove=i,delete t.objects,delete t.backgroundImage,delete t.overlayImage,delete t.background,delete t.overlay,this._setOptions(t),this.renderAll(),n&&n()},_setBgOverlay:function(t,e){var i={backgroundColor:!1,overlayColor:!1,backgroundImage:!1,overlayImage:!1};if(t.backgroundImage||t.overlayImage||t.background||t.overlay){var n=function(){i.backgroundImage&&i.overlayImage&&i.backgroundColor&&i.overlayColor&&e&&e()};this.__setBgOverlay("backgroundImage",t.backgroundImage,i,n),this.__setBgOverlay("overlayImage",t.overlayImage,i,n),this.__setBgOverlay("backgroundColor",t.background,i,n),this.__setBgOverlay("overlayColor",t.overlay,i,n)}else e&&e()},__setBgOverlay:function(t,e,i,n){var r=this;if(!e)return i[t]=!0,void(n&&n());"backgroundImage"===t||"overlayImage"===t?b.util.enlivenObjects([e],(function(e){r[t]=e[0],i[t]=!0,n&&n()})):this["set"+b.util.string.capitalize(t,!0)](e,(function(){i[t]=!0,n&&n()}))},_enlivenObjects:function(t,e,i){t&&0!==t.length?b.util.enlivenObjects(t,(function(t){e&&e(t)}),null,i):e&&e([])},_toDataURL:function(t,e){this.clone((function(i){e(i.toDataURL(t))}))},_toDataURLWithMultiplier:function(t,e,i){this.clone((function(n){i(n.toDataURLWithMultiplier(t,e))}))},clone:function(t,e){var i=JSON.stringify(this.toJSON(e));this.cloneWithoutData((function(e){e.loadFromJSON(i,(function(){t&&t(e)}))}))},cloneWithoutData:function(t){var e=b.util.createCanvasElement();e.width=this.width,e.height=this.height;var i=new b.Canvas(e);this.backgroundImage?(i.setBackgroundImage(this.backgroundImage.src,(function(){i.renderAll(),t&&t(i)})),i.backgroundImageOpacity=this.backgroundImageOpacity,i.backgroundImageStretch=this.backgroundImageStretch):t&&t(i)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r=e.util.toFixed,s=e.util.string.capitalize,a=e.util.degreesToRadians,o=!e.isLikelyNode;e.Object||(e.Object=e.util.createClass(e.CommonMethods,{type:"object",originX:"left",originY:"top",top:0,left:0,width:0,height:0,scaleX:1,scaleY:1,flipX:!1,flipY:!1,opacity:1,angle:0,skewX:0,skewY:0,cornerSize:13,touchCornerSize:24,transparentCorners:!0,hoverCursor:null,moveCursor:null,padding:0,borderColor:"rgb(178,204,255)",borderDashArray:null,cornerColor:"rgb(178,204,255)",cornerStrokeColor:null,cornerStyle:"rect",cornerDashArray:null,centeredScaling:!1,centeredRotation:!0,fill:"rgb(0,0,0)",fillRule:"nonzero",globalCompositeOperation:"source-over",backgroundColor:"",selectionBackgroundColor:"",stroke:null,strokeWidth:1,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,shadow:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,minScaleLimit:0,selectable:!0,evented:!0,visible:!0,hasControls:!0,hasBorders:!0,perPixelTargetFind:!1,includeDefaultValues:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,excludeFromExport:!1,objectCaching:o,statefullCache:!1,noScaleCache:!0,strokeUniform:!1,dirty:!0,__corner:0,paintFirst:"fill",activeOn:"down",stateProperties:"top left width height scaleX scaleY flipX flipY originX originY transformMatrix stroke strokeWidth strokeDashArray strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit angle opacity fill globalCompositeOperation shadow visible backgroundColor skewX skewY fillRule paintFirst clipPath strokeUniform".split(" "),cacheProperties:"fill stroke strokeWidth strokeDashArray width height paintFirst strokeUniform strokeLineCap strokeDashOffset strokeLineJoin strokeMiterLimit backgroundColor clipPath".split(" "),colorProperties:"fill stroke backgroundColor".split(" "),clipPath:void 0,inverted:!1,absolutePositioned:!1,initialize:function(t){t&&this.setOptions(t)},_createCacheCanvas:function(){this._cacheProperties={},this._cacheCanvas=e.util.createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0},_limitCacheSize:function(t){var i=e.perfLimitSizeTotal,n=t.width,r=t.height,s=e.maxCacheSideLimit,a=e.minCacheSideLimit;if(n<=s&&r<=s&&n*r<=i)return nc&&(t.zoomX/=n/c,t.width=c,t.capped=!0),r>d&&(t.zoomY/=r/d,t.height=d,t.capped=!0),t},_getCacheCanvasDimensions:function(){var t=this.getTotalObjectScaling(),e=this._getTransformedDimensions(0,0),i=e.x*t.scaleX/this.scaleX,n=e.y*t.scaleY/this.scaleY;return{width:i+2,height:n+2,zoomX:t.scaleX,zoomY:t.scaleY,x:i,y:n}},_updateCacheCanvas:function(){var t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){var i=t._currentTransform.target,n=t._currentTransform.action;if(this===i&&n.slice&&"scale"===n.slice(0,5))return!1}var r,s,a=this._cacheCanvas,o=this._limitCacheSize(this._getCacheCanvasDimensions()),l=e.minCacheSideLimit,h=o.width,c=o.height,d=o.zoomX,u=o.zoomY,f=h!==this.cacheWidth||c!==this.cacheHeight,g=this.zoomX!==d||this.zoomY!==u,m=f||g,p=0,_=0,v=!1;if(f){var y=this._cacheCanvas.width,w=this._cacheCanvas.height,C=h>y||c>w;v=C||(h<.9*y||c<.9*w)&&y>l&&w>l,C&&!o.capped&&(h>l||c>l)&&(p=.1*h,_=.1*c)}return this instanceof e.Text&&this.path&&(m=!0,v=!0,p+=this.getHeightOfLine(0)*this.zoomX,_+=this.getHeightOfLine(0)*this.zoomY),!!m&&(v?(a.width=Math.ceil(h+p),a.height=Math.ceil(c+_)):(this._cacheContext.setTransform(1,0,0,1,0,0),this._cacheContext.clearRect(0,0,a.width,a.height)),r=o.x/2,s=o.y/2,this.cacheTranslationX=Math.round(a.width/2-r)+r,this.cacheTranslationY=Math.round(a.height/2-s)+s,this.cacheWidth=h,this.cacheHeight=c,this._cacheContext.translate(this.cacheTranslationX,this.cacheTranslationY),this._cacheContext.scale(d,u),this.zoomX=d,this.zoomY=u,!0)},setOptions:function(t){this._setOptions(t),this._initGradient(t.fill,"fill"),this._initGradient(t.stroke,"stroke"),this._initPattern(t.fill,"fill"),this._initPattern(t.stroke,"stroke")},transform:function(t){var e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])},toObject:function(t){var i=e.Object.NUM_FRACTION_DIGITS,n={type:this.type,version:e.version,originX:this.originX,originY:this.originY,left:r(this.left,i),top:r(this.top,i),width:r(this.width,i),height:r(this.height,i),fill:this.fill&&this.fill.toObject?this.fill.toObject():this.fill,stroke:this.stroke&&this.stroke.toObject?this.stroke.toObject():this.stroke,strokeWidth:r(this.strokeWidth,i),strokeDashArray:this.strokeDashArray?this.strokeDashArray.concat():this.strokeDashArray,strokeLineCap:this.strokeLineCap,strokeDashOffset:this.strokeDashOffset,strokeLineJoin:this.strokeLineJoin,strokeUniform:this.strokeUniform,strokeMiterLimit:r(this.strokeMiterLimit,i),scaleX:r(this.scaleX,i),scaleY:r(this.scaleY,i),angle:r(this.angle,i),flipX:this.flipX,flipY:this.flipY,opacity:r(this.opacity,i),shadow:this.shadow&&this.shadow.toObject?this.shadow.toObject():this.shadow,visible:this.visible,backgroundColor:this.backgroundColor,fillRule:this.fillRule,paintFirst:this.paintFirst,globalCompositeOperation:this.globalCompositeOperation,skewX:r(this.skewX,i),skewY:r(this.skewY,i)};return this.clipPath&&!this.clipPath.excludeFromExport&&(n.clipPath=this.clipPath.toObject(t),n.clipPath.inverted=this.clipPath.inverted,n.clipPath.absolutePositioned=this.clipPath.absolutePositioned),e.util.populateWithProperties(this,n,t),this.includeDefaultValues||(n=this._removeDefaultValues(n)),n},toDatalessObject:function(t){return this.toObject(t)},_removeDefaultValues:function(t){var i=e.util.getKlass(t.type).prototype;return i.stateProperties.forEach((function(e){"left"!==e&&"top"!==e&&(t[e]===i[e]&&delete t[e],Array.isArray(t[e])&&Array.isArray(i[e])&&0===t[e].length&&0===i[e].length&&delete t[e])})),t},toString:function(){return"#"},getObjectScaling:function(){if(!this.group)return{scaleX:this.scaleX,scaleY:this.scaleY};var t=e.util.qrDecompose(this.calcTransformMatrix());return{scaleX:Math.abs(t.scaleX),scaleY:Math.abs(t.scaleY)}},getTotalObjectScaling:function(){var t=this.getObjectScaling(),e=t.scaleX,i=t.scaleY;if(this.canvas){var n=this.canvas.getZoom(),r=this.canvas.getRetinaScaling();e*=n*r,i*=n*r}return{scaleX:e,scaleY:i}},getObjectOpacity:function(){var t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t},_set:function(t,i){var n="scaleX"===t||"scaleY"===t,r=this[t]!==i,s=!1;return n&&(i=this._constrainScale(i)),"scaleX"===t&&i<0?(this.flipX=!this.flipX,i*=-1):"scaleY"===t&&i<0?(this.flipY=!this.flipY,i*=-1):"shadow"!==t||!i||i instanceof e.Shadow?"dirty"===t&&this.group&&this.group.set("dirty",i):i=new e.Shadow(i),this[t]=i,r&&(s=this.group&&this.group.isOnACache(),this.cacheProperties.indexOf(t)>-1?(this.dirty=!0,s&&this.group.set("dirty",!0)):s&&this.stateProperties.indexOf(t)>-1&&this.group.set("dirty",!0)),this},setOnGroup:function(){},getViewportTransform:function(){return this.canvas&&this.canvas.viewportTransform?this.canvas.viewportTransform:e.iMatrix.concat()},isNotVisible:function(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible},render:function(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t,this),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.dirty=!1,this.drawObject(t),this.objectCaching&&this.statefullCache&&this.saveState({propertySet:"cacheProperties"})),t.restore())},renderCache:function(t){t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&(this.statefullCache&&this.saveState({propertySet:"cacheProperties"}),this.drawObject(this._cacheContext,t.forClipping),this.dirty=!1)},_removeCacheCanvas:function(){this._cacheCanvas=null,this._cacheContext=null,this.cacheWidth=0,this.cacheHeight=0},hasStroke:function(){return this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth},hasFill:function(){return this.fill&&"transparent"!==this.fill},needsItsOwnCache:function(){return!("stroke"!==this.paintFirst||!this.hasFill()||!this.hasStroke()||"object"!=typeof this.shadow)||!!this.clipPath},shouldCache:function(){return this.ownCaching=this.needsItsOwnCache()||this.objectCaching&&(!this.group||!this.group.isOnACache()),this.ownCaching},willDrawShadow:function(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)},drawClipPathOnCache:function(t,i){if(t.save(),i.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",i.absolutePositioned){var n=e.util.invertTransform(this.calcTransformMatrix());t.transform(n[0],n[1],n[2],n[3],n[4],n[5])}i.transform(t),t.scale(1/i.zoomX,1/i.zoomY),t.drawImage(i._cacheCanvas,-i.cacheTranslationX,-i.cacheTranslationY),t.restore()},drawObject:function(t,e){var i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath),this.fill=i,this.stroke=n},_drawClipPath:function(t,e){e&&(e.canvas=this.canvas,e.shouldCache(),e._transformDone=!0,e.renderCache({forClipping:!0}),this.drawClipPathOnCache(t,e))},drawCacheOnCanvas:function(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)},isCacheDirty:function(t){if(this.isNotVisible())return!1;if(this._cacheCanvas&&this._cacheContext&&!t&&this._updateCacheCanvas())return!0;if(this.dirty||this.clipPath&&this.clipPath.absolutePositioned||this.statefullCache&&this.hasStateChanged("cacheProperties")){if(this._cacheCanvas&&this._cacheContext&&!t){var e=this.cacheWidth/this.zoomX,i=this.cacheHeight/this.zoomY;this._cacheContext.clearRect(-e/2,-i/2,e,i)}return!0}return!1},_renderBackground:function(t){if(this.backgroundColor){var e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}},_setOpacity:function(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity},_setStrokeStyles:function(t,e){var i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,i.toLive?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)},_setFillStyles:function(t,e){var i=e.fill;i&&(i.toLive?(t.fillStyle=i.toLive(t,this),this._applyPatternGradientTransform(t,e.fill)):t.fillStyle=i)},_setClippingProperties:function(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"},_setLineDash:function(t,e){e&&0!==e.length&&(1&e.length&&e.push.apply(e,e),t.setLineDash(e))},_renderControls:function(t,i){var n,r,s,o=this.getViewportTransform(),l=this.calcTransformMatrix();r=void 0!==(i=i||{}).hasBorders?i.hasBorders:this.hasBorders,s=void 0!==i.hasControls?i.hasControls:this.hasControls,l=e.util.multiplyTransformMatrices(o,l),n=e.util.qrDecompose(l),t.save(),t.translate(n.translateX,n.translateY),t.lineWidth=1*this.borderScaleFactor,this.group||(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(n.angle-=180),t.rotate(a(this.group?n.angle:this.angle)),i.forActiveSelection||this.group?r&&this.drawBordersInGroup(t,n,i):r&&this.drawBorders(t,i),s&&this.drawControls(t,i),t.restore()},_setShadow:function(t){if(this.shadow){var i,n=this.shadow,r=this.canvas,s=r&&r.viewportTransform[0]||1,a=r&&r.viewportTransform[3]||1;i=n.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),r&&r._isRetinaScaling()&&(s*=e.devicePixelRatio,a*=e.devicePixelRatio),t.shadowColor=n.color,t.shadowBlur=n.blur*e.browserShadowBlurConstant*(s+a)*(i.scaleX+i.scaleY)/4,t.shadowOffsetX=n.offsetX*s*i.scaleX,t.shadowOffsetY=n.offsetY*a*i.scaleY}},_removeShadow:function(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)},_applyPatternGradientTransform:function(t,e){if(!e||!e.toLive)return{offsetX:0,offsetY:0};var i=e.gradientTransform||e.patternTransform,n=-this.width/2+e.offsetX||0,r=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,n,r):t.transform(1,0,0,1,n,r),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:n,offsetY:r}},_renderPaintInOrder:function(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))},_render:function(){},_renderFill:function(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())},_renderStroke:function(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform&&this.group){var e=this.getObjectScaling();t.scale(1/e.scaleX,1/e.scaleY)}else this.strokeUniform&&t.scale(1/this.scaleX,1/this.scaleY);this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}},_applyPatternForTransformedGradient:function(t,i){var n,r=this._limitCacheSize(this._getCacheCanvasDimensions()),s=e.util.createCanvasElement(),a=this.canvas.getRetinaScaling(),o=r.x/this.scaleX/a,l=r.y/this.scaleY/a;s.width=o,s.height=l,(n=s.getContext("2d")).beginPath(),n.moveTo(0,0),n.lineTo(o,0),n.lineTo(o,l),n.lineTo(0,l),n.closePath(),n.translate(o/2,l/2),n.scale(r.zoomX/this.scaleX/a,r.zoomY/this.scaleY/a),this._applyPatternGradientTransform(n,i),n.fillStyle=i.toLive(t),n.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(a*this.scaleX/r.zoomX,a*this.scaleY/r.zoomY),t.strokeStyle=n.createPattern(s,"no-repeat")},_findCenterFromElement:function(){return{x:this.left+this.width/2,y:this.top+this.height/2}},_assignTransformMatrixProps:function(){if(this.transformMatrix){var t=e.util.qrDecompose(this.transformMatrix);this.flipX=!1,this.flipY=!1,this.set("scaleX",t.scaleX),this.set("scaleY",t.scaleY),this.angle=t.angle,this.skewX=t.skewX,this.skewY=0}},_removeTransformMatrix:function(t){var i=this._findCenterFromElement();this.transformMatrix&&(this._assignTransformMatrixProps(),i=e.util.transformPoint(i,this.transformMatrix)),this.transformMatrix=null,t&&(this.scaleX*=t.scaleX,this.scaleY*=t.scaleY,this.cropX=t.cropX,this.cropY=t.cropY,i.x+=t.offsetLeft,i.y+=t.offsetTop,this.width=t.width,this.height=t.height),this.setPositionByOrigin(i,"center","center")},clone:function(t,i){var n=this.toObject(i);this.constructor.fromObject?this.constructor.fromObject(n,t):e.Object._fromObject("Object",n,t)},cloneAsImage:function(t,i){var n=this.toCanvasElement(i);return t&&t(new e.Image(n)),this},toCanvasElement:function(t){t||(t={});var i=e.util,n=i.saveObjectTransform(this),r=this.group,s=this.shadow,a=Math.abs,o=(t.multiplier||1)*(t.enableRetinaScaling?e.devicePixelRatio:1);delete this.group,t.withoutTransform&&i.resetObjectTransform(this),t.withoutShadow&&(this.shadow=null);var l,h,c,d,u=e.util.createCanvasElement(),f=this.getBoundingRect(!0,!0),g=this.shadow,m={x:0,y:0};g&&(h=g.blur,l=g.nonScaling?{scaleX:1,scaleY:1}:this.getObjectScaling(),m.x=2*Math.round(a(g.offsetX)+h)*a(l.scaleX),m.y=2*Math.round(a(g.offsetY)+h)*a(l.scaleY)),c=f.width+m.x,d=f.height+m.y,u.width=Math.ceil(c),u.height=Math.ceil(d);var p=new e.StaticCanvas(u,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1});"jpeg"===t.format&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new e.Point(p.width/2,p.height/2),"center","center");var _=this.canvas;p.add(this);var v=p.toCanvasElement(o||1,t);return this.shadow=s,this.set("canvas",_),r&&(this.group=r),this.set(n).setCoords(),p._objects=[],p.dispose(),p=null,v},toDataURL:function(t){return t||(t={}),e.util.toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)},isType:function(t){return arguments.length>1?Array.from(arguments).includes(this.type):this.type===t},complexity:function(){return 1},toJSON:function(t){return this.toObject(t)},rotate:function(t){var e=("center"!==this.originX||"center"!==this.originY)&&this.centeredRotation;return e&&this._setOriginToCenter(),this.set("angle",t),e&&this._resetOrigin(),this},centerH:function(){return this.canvas&&this.canvas.centerObjectH(this),this},viewportCenterH:function(){return this.canvas&&this.canvas.viewportCenterObjectH(this),this},centerV:function(){return this.canvas&&this.canvas.centerObjectV(this),this},viewportCenterV:function(){return this.canvas&&this.canvas.viewportCenterObjectV(this),this},center:function(){return this.canvas&&this.canvas.centerObject(this),this},viewportCenter:function(){return this.canvas&&this.canvas.viewportCenterObject(this),this},getLocalPointer:function(t,i){i=i||this.canvas.getPointer(t);var n=new e.Point(i.x,i.y),r=this._getLeftTopCoords();return this.angle&&(n=e.util.rotatePoint(n,r,a(-this.angle))),{x:n.x-r.x,y:n.y-r.y}},_setupCompositeOperation:function(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)},dispose:function(){e.runningAnimations&&e.runningAnimations.cancelByTarget(this)}}),e.util.createAccessors&&e.util.createAccessors(e.Object),i(e.Object.prototype,e.Observable),e.Object.NUM_FRACTION_DIGITS=2,e.Object.ENLIVEN_PROPS=["clipPath"],e.Object._fromObject=function(t,i,r,s){var a=e[t];i=n(i,!0),e.util.enlivenPatterns([i.fill,i.stroke],(function(t){void 0!==t[0]&&(i.fill=t[0]),void 0!==t[1]&&(i.stroke=t[1]),e.util.enlivenObjectEnlivables(i,i,(function(){var t=s?new a(i[s],i):new a(i);r&&r(t)}))}))},e.Object.__uid=0)}(e),w=b.util.degreesToRadians,C={left:-.5,center:0,right:.5},E={top:-.5,center:0,bottom:.5},b.util.object.extend(b.Object.prototype,{translateToGivenOrigin:function(t,e,i,n,r){var s,a,o,l=t.x,h=t.y;return"string"==typeof e?e=C[e]:e-=.5,"string"==typeof n?n=C[n]:n-=.5,"string"==typeof i?i=E[i]:i-=.5,"string"==typeof r?r=E[r]:r-=.5,a=r-i,((s=n-e)||a)&&(o=this._getTransformedDimensions(),l=t.x+s*o.x,h=t.y+a*o.y),new b.Point(l,h)},translateToCenterPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,e,i,"center","center");return this.angle?b.util.rotatePoint(n,t,w(this.angle)):n},translateToOriginPoint:function(t,e,i){var n=this.translateToGivenOrigin(t,"center","center",e,i);return this.angle?b.util.rotatePoint(n,t,w(this.angle)):n},getCenterPoint:function(){var t=new b.Point(this.left,this.top);return this.translateToCenterPoint(t,this.originX,this.originY)},getPointByOrigin:function(t,e){var i=this.getCenterPoint();return this.translateToOriginPoint(i,t,e)},toLocalPoint:function(t,e,i){var n,r,s=this.getCenterPoint();return n=void 0!==e&&void 0!==i?this.translateToGivenOrigin(s,"center","center",e,i):new b.Point(this.left,this.top),r=new b.Point(t.x,t.y),this.angle&&(r=b.util.rotatePoint(r,s,-w(this.angle))),r.subtractEquals(n)},setPositionByOrigin:function(t,e,i){var n=this.translateToCenterPoint(t,e,i),r=this.translateToOriginPoint(n,this.originX,this.originY);this.set("left",r.x),this.set("top",r.y)},adjustPosition:function(t){var e,i,n=w(this.angle),r=this.getScaledWidth(),s=b.util.cos(n)*r,a=b.util.sin(n)*r;e="string"==typeof this.originX?C[this.originX]:this.originX-.5,i="string"==typeof t?C[t]:t-.5,this.left+=s*(i-e),this.top+=a*(i-e),this.setCoords(),this.originX=t},_setOriginToCenter:function(){this._originalOriginX=this.originX,this._originalOriginY=this.originY;var t=this.getCenterPoint();this.originX="center",this.originY="center",this.left=t.x,this.top=t.y},_resetOrigin:function(){var t=this.translateToOriginPoint(this.getCenterPoint(),this._originalOriginX,this._originalOriginY);this.originX=this._originalOriginX,this.originY=this._originalOriginY,this.left=t.x,this.top=t.y,this._originalOriginX=null,this._originalOriginY=null},_getLeftTopCoords:function(){return this.translateToOriginPoint(this.getCenterPoint(),"left","top")}}),function(){var t=b.util,e=t.degreesToRadians,i=t.multiplyTransformMatrices,n=t.transformPoint;t.object.extend(b.Object.prototype,{oCoords:null,aCoords:null,lineCoords:null,ownMatrixCache:null,matrixCache:null,controls:{},_getCoords:function(t,e){return e?t?this.calcACoords():this.calcLineCoords():(this.aCoords&&this.lineCoords||this.setCoords(!0),t?this.aCoords:this.lineCoords)},getCoords:function(t,e){return i=this._getCoords(t,e),[new b.Point(i.tl.x,i.tl.y),new b.Point(i.tr.x,i.tr.y),new b.Point(i.br.x,i.br.y),new b.Point(i.bl.x,i.bl.y)];var i},intersectsWithRect:function(t,e,i,n){var r=this.getCoords(i,n);return"Intersection"===b.Intersection.intersectPolygonRectangle(r,t,e).status},intersectsWithObject:function(t,e,i){return"Intersection"===b.Intersection.intersectPolygonPolygon(this.getCoords(e,i),t.getCoords(e,i)).status||t.isContainedWithinObject(this,e,i)||this.isContainedWithinObject(t,e,i)},isContainedWithinObject:function(t,e,i){for(var n=this.getCoords(e,i),r=e?t.aCoords:t.lineCoords,s=0,a=t._getImageLines(r);s<4;s++)if(!t.containsPoint(n[s],a))return!1;return!0},isContainedWithinRect:function(t,e,i,n){var r=this.getBoundingRect(i,n);return r.left>=t.x&&r.left+r.width<=e.x&&r.top>=t.y&&r.top+r.height<=e.y},containsPoint:function(t,e,i,n){var r=this._getCoords(i,n),s=(e=e||this._getImageLines(r),this._findCrossPoints(t,e));return 0!==s&&s%2==1},isOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.getCoords(!0,t).some((function(t){return t.x<=i.x&&t.x>=e.x&&t.y<=i.y&&t.y>=e.y}))||!!this.intersectsWithRect(e,i,!0,t)||this._containsCenterOfCanvas(e,i,t)},_containsCenterOfCanvas:function(t,e,i){var n={x:(t.x+e.x)/2,y:(t.y+e.y)/2};return!!this.containsPoint(n,null,!0,i)},isPartiallyOnScreen:function(t){if(!this.canvas)return!1;var e=this.canvas.vptCoords.tl,i=this.canvas.vptCoords.br;return!!this.intersectsWithRect(e,i,!0,t)||this.getCoords(!0,t).every((function(t){return(t.x>=i.x||t.x<=e.x)&&(t.y>=i.y||t.y<=e.y)}))&&this._containsCenterOfCanvas(e,i,t)},_getImageLines:function(t){return{topline:{o:t.tl,d:t.tr},rightline:{o:t.tr,d:t.br},bottomline:{o:t.br,d:t.bl},leftline:{o:t.bl,d:t.tl}}},_findCrossPoints:function(t,e){var i,n,r,s=0;for(var a in e)if(!((r=e[a]).o.y=t.y&&r.d.y>=t.y||(r.o.x===r.d.x&&r.o.x>=t.x?n=r.o.x:(i=(r.d.y-r.o.y)/(r.d.x-r.o.x),n=-(t.y-0*t.x-(r.o.y-i*r.o.x))/(0-i)),n>=t.x&&(s+=1),2!==s)))break;return s},getBoundingRect:function(e,i){var n=this.getCoords(e,i);return t.makeBoundingBoxFromPoints(n)},getScaledWidth:function(){return this._getTransformedDimensions().x},getScaledHeight:function(){return this._getTransformedDimensions().y},_constrainScale:function(t){return Math.abs(t)\n')}},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})},toClipPathSVG:function(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})},_createBaseClipPathSVGMarkup:function(t,e){var i=(e=e||{}).reviver,n=e.additionalTransform||"",r=[this.getSvgTransform(!0,n),this.getSvgCommons()].join(""),s=t.indexOf("COMMON_PARTS");return t[s]=r,i?i(t.join("")):t.join("")},_createBaseSVGMarkup:function(t,e){var i,n,r=(e=e||{}).noStyle,s=e.reviver,a=r?"":'style="'+this.getSvgStyles()+'" ',o=e.withShadow?'style="'+this.getSvgFilter()+'" ':"",l=this.clipPath,h=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=l&&l.absolutePositioned,d=this.stroke,u=this.fill,f=this.shadow,g=[],m=t.indexOf("COMMON_PARTS"),p=e.additionalTransform;return l&&(l.clipPathId="CLIPPATH_"+b.Object.__uid++,n='\n'+l.toClipPathSVG(s)+"\n"),c&&g.push("\n"),g.push("\n"),i=[a,h,r?"":this.addPaintOrder()," ",p?'transform="'+p+'" ':""].join(""),t[m]=i,u&&u.toLive&&g.push(u.toSVG(this)),d&&d.toLive&&g.push(d.toSVG(this)),f&&g.push(f.toSVG(this)),l&&g.push(n),g.push(t.join("")),g.push("\n"),c&&g.push("\n"),s?s(g.join("")):g.join("")},addPaintOrder:function(){return"fill"!==this.paintFirst?' paint-order="'+this.paintFirst+'" ':""}})}(),function(){var t=b.util.object.extend,e="stateProperties";function i(e,i,n){var r={};n.forEach((function(t){r[t]=e[t]})),t(e[i],r,!0)}function n(t,e,i){if(t===e)return!0;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(var r=0,s=t.length;r=0;l--)if(r=o[l],this.isControlVisible(r)&&(n=this._getImageLines(e?this.oCoords[r].touchCorner:this.oCoords[r].corner),0!==(i=this._findCrossPoints({x:s,y:a},n))&&i%2==1))return this.__corner=r,r;return!1},forEachControl:function(t){for(var e in this.controls)t(this.controls[e],e,this)},_setCornerCoords:function(){var t=this.oCoords;for(var e in t){var i=this.controls[e];t[e].corner=i.calcCornerCoords(this.angle,this.cornerSize,t[e].x,t[e].y,!1),t[e].touchCorner=i.calcCornerCoords(this.angle,this.touchCornerSize,t[e].x,t[e].y,!0)}},drawSelectionBackground:function(e){if(!this.selectionBackgroundColor||this.canvas&&!this.canvas.interactive||this.canvas&&this.canvas._activeObject!==this)return this;e.save();var i=this.getCenterPoint(),n=this._calculateCurrentDimensions(),r=this.canvas.viewportTransform;return e.translate(i.x,i.y),e.scale(1/r[0],1/r[3]),e.rotate(t(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-n.x/2,-n.y/2,n.x,n.y),e.restore(),this},drawBorders:function(t,e){e=e||{};var i=this._calculateCurrentDimensions(),n=this.borderScaleFactor,r=i.x+n,s=i.y+n,a=void 0!==e.hasControls?e.hasControls:this.hasControls,o=!1;return t.save(),t.strokeStyle=e.borderColor||this.borderColor,this._setLineDash(t,e.borderDashArray||this.borderDashArray),t.strokeRect(-r/2,-s/2,r,s),a&&(t.beginPath(),this.forEachControl((function(e,i,n){e.withConnection&&e.getVisibility(n,i)&&(o=!0,t.moveTo(e.x*r,e.y*s),t.lineTo(e.x*r+e.offsetX,e.y*s+e.offsetY))})),o&&t.stroke()),t.restore(),this},drawBordersInGroup:function(t,e,i){i=i||{};var n=b.util.sizeAfterTransform(this.width,this.height,e),r=this.strokeWidth,s=this.strokeUniform,a=this.borderScaleFactor,o=n.x+r*(s?this.canvas.getZoom():e.scaleX)+a,l=n.y+r*(s?this.canvas.getZoom():e.scaleY)+a;return t.save(),this._setLineDash(t,i.borderDashArray||this.borderDashArray),t.strokeStyle=i.borderColor||this.borderColor,t.strokeRect(-o/2,-l/2,o,l),t.restore(),this},drawControls:function(t,e){e=e||{},t.save();var i,n,r=this.canvas.getRetinaScaling();return t.setTransform(r,0,0,r,0,0),t.strokeStyle=t.fillStyle=e.cornerColor||this.cornerColor,this.transparentCorners||(t.strokeStyle=e.cornerStrokeColor||this.cornerStrokeColor),this._setLineDash(t,e.cornerDashArray||this.cornerDashArray),this.setCoords(),this.group&&(i=this.group.calcTransformMatrix()),this.forEachControl((function(r,s,a){n=a.oCoords[s],r.getVisibility(a,s)&&(i&&(n=b.util.transformPoint(n,i)),r.render(t,n.x,n.y,e,a))})),t.restore(),this},isControlVisible:function(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)},setControlVisible:function(t,e){return this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e,this},setControlsVisibility:function(t){for(var e in t||(t={}),t)this.setControlVisible(e,t[e]);return this},onDeselect:function(){},onSelect:function(){}})}(),b.util.object.extend(b.StaticCanvas.prototype,{FX_DURATION:500,fxCenterObjectH:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.left,endValue:this.getCenterPoint().x,duration:this.FX_DURATION,onChange:function(e){t.set("left",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxCenterObjectV:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.top,endValue:this.getCenterPoint().y,duration:this.FX_DURATION,onChange:function(e){t.set("top",e),s.requestRenderAll(),r()},onComplete:function(){t.setCoords(),n()}})},fxRemove:function(t,e){var i=function(){},n=(e=e||{}).onComplete||i,r=e.onChange||i,s=this;return b.util.animate({target:this,startValue:t.opacity,endValue:0,duration:this.FX_DURATION,onChange:function(e){t.set("opacity",e),s.requestRenderAll(),r()},onComplete:function(){s.remove(t),n()}})}}),b.util.object.extend(b.Object.prototype,{animate:function(){if(arguments[0]&&"object"==typeof arguments[0]){var t,e,i=[],n=[];for(t in arguments[0])i.push(t);for(var r=0,s=i.length;r-1||r&&s.colorProperties.indexOf(r[1])>-1,o=r?this.get(r[0])[r[1]]:this.get(t);"from"in i||(i.from=o),a||(e=~e.indexOf("=")?o+parseFloat(e.replace("=","")):parseFloat(e));var l={target:this,startValue:i.from,endValue:e,byValue:i.by,easing:i.easing,duration:i.duration,abort:i.abort&&function(t,e,n){return i.abort.call(s,t,e,n)},onChange:function(e,a,o){r?s[r[0]][r[1]]=e:s.set(t,e),n||i.onChange&&i.onChange(e,a,o)},onComplete:function(t,e,r){n||(s.setCoords(),i.onComplete&&i.onComplete(t,e,r))}};return a?b.util.animateColor(l.startValue,l.endValue,l.duration,l):b.util.animate(l)}}),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.object.clone,r={x1:1,x2:1,y1:1,y2:1};function s(t,e){var i=t.origin,n=t.axis1,r=t.axis2,s=t.dimension,a=e.nearest,o=e.center,l=e.farthest;return function(){switch(this.get(i)){case a:return Math.min(this.get(n),this.get(r));case o:return Math.min(this.get(n),this.get(r))+.5*this.get(s);case l:return Math.max(this.get(n),this.get(r))}}}e.Line?e.warn("fabric.Line is already defined"):(e.Line=e.util.createClass(e.Object,{type:"line",x1:0,y1:0,x2:0,y2:0,cacheProperties:e.Object.prototype.cacheProperties.concat("x1","x2","y1","y2"),initialize:function(t,e){t||(t=[0,0,0,0]),this.callSuper("initialize",e),this.set("x1",t[0]),this.set("y1",t[1]),this.set("x2",t[2]),this.set("y2",t[3]),this._setWidthHeight(e)},_setWidthHeight:function(t){t||(t={}),this.width=Math.abs(this.x2-this.x1),this.height=Math.abs(this.y2-this.y1),this.left="left"in t?t.left:this._getLeftToOriginX(),this.top="top"in t?t.top:this._getTopToOriginY()},_set:function(t,e){return this.callSuper("_set",t,e),void 0!==r[t]&&this._setWidthHeight(),this},_getLeftToOriginX:s({origin:"originX",axis1:"x1",axis2:"x2",dimension:"width"},{nearest:"left",center:"center",farthest:"right"}),_getTopToOriginY:s({origin:"originY",axis1:"y1",axis2:"y2",dimension:"height"},{nearest:"top",center:"center",farthest:"bottom"}),_render:function(t){t.beginPath();var e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;var i=t.strokeStyle;t.strokeStyle=this.stroke||t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=i},_findCenterFromElement:function(){return{x:(this.x1+this.x2)/2,y:(this.y1+this.y2)/2}},toObject:function(t){return i(this.callSuper("toObject",t),this.calcLinePoints())},_getNonTransformedDimensions:function(){var t=this.callSuper("_getNonTransformedDimensions");return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t},calcLinePoints:function(){var t=this.x1<=this.x2?-1:1,e=this.y1<=this.y2?-1:1,i=t*this.width*.5,n=e*this.height*.5;return{x1:i,x2:t*this.width*-.5,y1:n,y2:e*this.height*-.5}},_toSVG:function(){var t=this.calcLinePoints();return["\n']}}),e.Line.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x1 y1 x2 y2".split(" ")),e.Line.fromElement=function(t,n,r){r=r||{};var s=e.parseAttributes(t,e.Line.ATTRIBUTE_NAMES),a=[s.x1||0,s.y1||0,s.x2||0,s.y2||0];n(new e.Line(a,i(s,r)))},e.Line.fromObject=function(t,i){var r=n(t,!0);r.points=[t.x1,t.y1,t.x2,t.y2],e.Object._fromObject("Line",r,(function(t){delete t.points,i&&i(t)}),"points")})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.degreesToRadians;e.Circle?e.warn("fabric.Circle is already defined."):(e.Circle=e.util.createClass(e.Object,{type:"circle",radius:0,startAngle:0,endAngle:360,cacheProperties:e.Object.prototype.cacheProperties.concat("radius","startAngle","endAngle"),_set:function(t,e){return this.callSuper("_set",t,e),"radius"===t&&this.setRadius(e),this},toObject:function(t){return this.callSuper("toObject",["radius","startAngle","endAngle"].concat(t))},_toSVG:function(){var t,n=(this.endAngle-this.startAngle)%360;if(0===n)t=["\n'];else{var r=i(this.startAngle),s=i(this.endAngle),a=this.radius;t=['180?"1":"0")+" 1"," "+e.util.cos(s)*a+" "+e.util.sin(s)*a,'" ',"COMMON_PARTS"," />\n"]}return t},_render:function(t){t.beginPath(),t.arc(0,0,this.radius,i(this.startAngle),i(this.endAngle),!1),this._renderPaintInOrder(t)},getRadiusX:function(){return this.get("radius")*this.get("scaleX")},getRadiusY:function(){return this.get("radius")*this.get("scaleY")},setRadius:function(t){return this.radius=t,this.set("width",2*t).set("height",2*t)}}),e.Circle.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy r".split(" ")),e.Circle.fromElement=function(t,i){var n,r=e.parseAttributes(t,e.Circle.ATTRIBUTE_NAMES);if(!("radius"in(n=r)&&n.radius>=0))throw new Error("value of `r` attribute is required and can not be negative");r.left=(r.left||0)-r.radius,r.top=(r.top||0)-r.radius,i(new e.Circle(r))},e.Circle.fromObject=function(t,i){e.Object._fromObject("Circle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={});e.Triangle?e.warn("fabric.Triangle is already defined"):(e.Triangle=e.util.createClass(e.Object,{type:"triangle",width:100,height:100,_render:function(t){var e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)},_toSVG:function(){var t=this.width/2,e=this.height/2;return["']}}),e.Triangle.fromObject=function(t,i){return e.Object._fromObject("Triangle",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=2*Math.PI;e.Ellipse?e.warn("fabric.Ellipse is already defined."):(e.Ellipse=e.util.createClass(e.Object,{type:"ellipse",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this.set("rx",t&&t.rx||0),this.set("ry",t&&t.ry||0)},_set:function(t,e){switch(this.callSuper("_set",t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this},getRx:function(){return this.get("rx")*this.get("scaleX")},getRy:function(){return this.get("ry")*this.get("scaleY")},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']},_render:function(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,i,!1),t.restore(),this._renderPaintInOrder(t)}}),e.Ellipse.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("cx cy rx ry".split(" ")),e.Ellipse.fromElement=function(t,i){var n=e.parseAttributes(t,e.Ellipse.ATTRIBUTE_NAMES);n.left=(n.left||0)-n.rx,n.top=(n.top||0)-n.ry,i(new e.Ellipse(n))},e.Ellipse.fromObject=function(t,i){e.Object._fromObject("Ellipse",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend;e.Rect?e.warn("fabric.Rect is already defined"):(e.Rect=e.util.createClass(e.Object,{stateProperties:e.Object.prototype.stateProperties.concat("rx","ry"),type:"rect",rx:0,ry:0,cacheProperties:e.Object.prototype.cacheProperties.concat("rx","ry"),initialize:function(t){this.callSuper("initialize",t),this._initRxRy()},_initRxRy:function(){this.rx&&!this.ry?this.ry=this.rx:this.ry&&!this.rx&&(this.rx=this.ry)},_render:function(t){var e=this.rx?Math.min(this.rx,this.width/2):0,i=this.ry?Math.min(this.ry,this.height/2):0,n=this.width,r=this.height,s=-this.width/2,a=-this.height/2,o=0!==e||0!==i,l=.4477152502;t.beginPath(),t.moveTo(s+e,a),t.lineTo(s+n-e,a),o&&t.bezierCurveTo(s+n-l*e,a,s+n,a+l*i,s+n,a+i),t.lineTo(s+n,a+r-i),o&&t.bezierCurveTo(s+n,a+r-l*i,s+n-l*e,a+r,s+n-e,a+r),t.lineTo(s+e,a+r),o&&t.bezierCurveTo(s+l*e,a+r,s,a+r-l*i,s,a+r-i),t.lineTo(s,a+i),o&&t.bezierCurveTo(s,a+l*i,s+l*e,a,s+e,a),t.closePath(),this._renderPaintInOrder(t)},toObject:function(t){return this.callSuper("toObject",["rx","ry"].concat(t))},_toSVG:function(){return["\n']}}),e.Rect.ATTRIBUTE_NAMES=e.SHARED_ATTRIBUTES.concat("x y rx ry width height".split(" ")),e.Rect.fromElement=function(t,n,r){if(!t)return n(null);r=r||{};var s=e.parseAttributes(t,e.Rect.ATTRIBUTE_NAMES);s.left=s.left||0,s.top=s.top||0,s.height=s.height||0,s.width=s.width||0;var a=new e.Rect(i(r?e.util.object.clone(r):{},s));a.visible=a.visible&&a.width>0&&a.height>0,n(a)},e.Rect.fromObject=function(t,i){return e.Object._fromObject("Rect",t,i)})}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.util.object.extend,n=e.util.array.min,r=e.util.array.max,s=e.util.toFixed,a=e.util.projectStrokeOnPoints;e.Polyline?e.warn("fabric.Polyline is already defined"):(e.Polyline=e.util.createClass(e.Object,{type:"polyline",points:null,exactBoundingBox:!1,cacheProperties:e.Object.prototype.cacheProperties.concat("points"),initialize:function(t,e){e=e||{},this.points=t||[],this.callSuper("initialize",e),this._setPositionDimensions(e)},_projectStrokeOnPoints:function(){return a(this.points,this,!0)},_setPositionDimensions:function(t){var e,i=this._calcDimensions(t),n=this.exactBoundingBox?this.strokeWidth:0;this.width=i.width-n,this.height=i.height-n,t.fromSVG||(e=this.translateToGivenOrigin({x:i.left-this.strokeWidth/2+n/2,y:i.top-this.strokeWidth/2+n/2},"left","top",this.originX,this.originY)),void 0===t.left&&(this.left=t.fromSVG?i.left:e.x),void 0===t.top&&(this.top=t.fromSVG?i.top:e.y),this.pathOffset={x:i.left+this.width/2+n/2,y:i.top+this.height/2+n/2}},_calcDimensions:function(){var t=this.exactBoundingBox?this._projectStrokeOnPoints():this.points,e=n(t,"x")||0,i=n(t,"y")||0;return{left:e,top:i,width:(r(t,"x")||0)-e,height:(r(t,"y")||0)-i}},toObject:function(t){return i(this.callSuper("toObject",t),{points:this.points.concat()})},_toSVG:function(){for(var t=[],i=this.pathOffset.x,n=this.pathOffset.y,r=e.Object.NUM_FRACTION_DIGITS,a=0,o=this.points.length;a\n']},commonRender:function(t){var e,i=this.points.length,n=this.pathOffset.x,r=this.pathOffset.y;if(!i||isNaN(this.points[i-1].y))return!1;t.beginPath(),t.moveTo(this.points[0].x-n,this.points[0].y-r);for(var s=0;s"},toObject:function(t){return r(this.callSuper("toObject",t),{path:this.path.map((function(t){return t.slice()}))})},toDatalessObject:function(t){var e=this.toObject(["sourcePath"].concat(t));return e.sourcePath&&delete e.path,e},_toSVG:function(){return["\n"]},_getOffsetTransform:function(){var t=e.Object.NUM_FRACTION_DIGITS;return" translate("+a(-this.pathOffset.x,t)+", "+a(-this.pathOffset.y,t)+")"},toClipPathSVG:function(t){var e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},toSVG:function(t){var e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})},complexity:function(){return this.path.length},_calcDimensions:function(){for(var t,r,s=[],a=[],o=0,l=0,h=0,c=0,d=0,u=this.path.length;d"},addWithUpdate:function(t){var i=!!this.group;return this._restoreObjectsState(),e.util.resetObjectTransform(this),t&&(i&&e.util.removeTransformFromObject(t,this.group.calcTransformMatrix()),this._objects.push(t),t.group=this,t._set("canvas",this.canvas)),this._calcBounds(),this._updateObjectsCoords(),this.dirty=!0,i?this.group.addWithUpdate():this.setCoords(),this},removeWithUpdate:function(t){return this._restoreObjectsState(),e.util.resetObjectTransform(this),this.remove(t),this._calcBounds(),this._updateObjectsCoords(),this.setCoords(),this.dirty=!0,this},_onObjectAdded:function(t){this.dirty=!0,t.group=this,t._set("canvas",this.canvas)},_onObjectRemoved:function(t){this.dirty=!0,delete t.group},_set:function(t,i){var n=this._objects.length;if(this.useSetOnGroup)for(;n--;)this._objects[n].setOnGroup(t,i);if("canvas"===t)for(;n--;)this._objects[n]._set(t,i);e.Object.prototype._set.call(this,t,i)},toObject:function(t){var i=this.includeDefaultValues,n=this._objects.filter((function(t){return!t.excludeFromExport})).map((function(e){var n=e.includeDefaultValues;e.includeDefaultValues=i;var r=e.toObject(t);return e.includeDefaultValues=n,r})),r=e.Object.prototype.toObject.call(this,t);return r.objects=n,r},toDatalessObject:function(t){var i,n=this.sourcePath;if(n)i=n;else{var r=this.includeDefaultValues;i=this._objects.map((function(e){var i=e.includeDefaultValues;e.includeDefaultValues=r;var n=e.toDatalessObject(t);return e.includeDefaultValues=i,n}))}var s=e.Object.prototype.toDatalessObject.call(this,t);return s.objects=i,s},render:function(t){this._transformDone=!0,this.callSuper("render",t),this._transformDone=!1},shouldCache:function(){var t=e.Object.prototype.shouldCache.call(this);if(t)for(var i=0,n=this._objects.length;i\n"],i=0,n=this._objects.length;i\n"),e},getSvgStyles:function(){var t=void 0!==this.opacity&&1!==this.opacity?"opacity: "+this.opacity+";":"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")},toClipPathSVG:function(t){for(var e=[],i=0,n=this._objects.length;i"},shouldCache:function(){return!1},isOnACache:function(){return!1},_renderControls:function(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.callSuper("_renderControls",t,e),void 0===(i=i||{}).hasControls&&(i.hasControls=!1),i.forActiveSelection=!0;for(var n=0,r=this._objects.length;n\n','\t\n',"\n"),a=' clip-path="url(#imageCrop_'+l+')" '}if(this.imageSmoothing||(o='" image-rendering="optimizeSpeed'),i.push("\t\n"),this.stroke||this.strokeDashArray){var h=this.fill;this.fill=null,t=["\t\n'],this.fill=h}return"fill"!==this.paintFirst?e.concat(t,i):e.concat(i,t)},getSrc:function(t){var e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src"):e.src:this.src||""},setSrc:function(t,e,i){return b.util.loadImage(t,(function(t,n){this.setElement(t,i),this._setWidthHeight(),e&&e(this,n)}),this,i&&i.crossOrigin),this},toString:function(){return'#'},applyResizeFilters:function(){var t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),n=i.scaleX,r=i.scaleY,s=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||n>e&&r>e)return this._element=s,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=n,void(this._lastScaleY=r);b.filterBackend||(b.filterBackend=b.initFilterBackend());var a=b.util.createCanvasElement(),o=this._filteredEl?this.cacheKey+"_filtered":this.cacheKey,l=s.width,h=s.height;a.width=l,a.height=h,this._element=a,this._lastScaleX=t.scaleX=n,this._lastScaleY=t.scaleY=r,b.filterBackend.applyFilters([t],s,l,h,this._element,o),this._filterScalingX=a.width/this._originalElement.width,this._filterScalingY=a.height/this._originalElement.height},applyFilters:function(t){if(t=(t=t||this.filters||[]).filter((function(t){return t&&!t.isNeutralState()})),this.set("dirty",!0),this.removeTexture(this.cacheKey+"_filtered"),0===t.length)return this._element=this._originalElement,this._filteredEl=null,this._filterScalingX=1,this._filterScalingY=1,this;var e=this._originalElement,i=e.naturalWidth||e.width,n=e.naturalHeight||e.height;if(this._element===this._originalElement){var r=b.util.createCanvasElement();r.width=i,r.height=n,this._element=r,this._filteredEl=r}else this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,n),this._lastScaleX=1,this._lastScaleY=1;return b.filterBackend||(b.filterBackend=b.initFilterBackend()),b.filterBackend.applyFilters(t,this._originalElement,i,n,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height),this},_render:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)},drawCacheOnCanvas:function(t){b.util.setImageSmoothing(t,this.imageSmoothing),b.Object.prototype.drawCacheOnCanvas.call(this,t)},shouldCache:function(){return this.needsItsOwnCache()},_renderFill:function(t){var e=this._element;if(e){var i=this._filterScalingX,n=this._filterScalingY,r=this.width,s=this.height,a=Math.min,o=Math.max,l=o(this.cropX,0),h=o(this.cropY,0),c=e.naturalWidth||e.width,d=e.naturalHeight||e.height,u=l*i,f=h*n,g=a(r*i,c-u),m=a(s*n,d-f),p=-r/2,_=-s/2,v=a(r,c/i-l),y=a(s,d/n-h);e&&t.drawImage(e,u,f,g,m,p,_,v,y)}},_needsResize:function(){var t=this.getTotalObjectScaling();return t.scaleX!==this._lastScaleX||t.scaleY!==this._lastScaleY},_resetWidthHeight:function(){this.set(this.getOriginalSize())},_initElement:function(t,e){this.setElement(b.util.getById(t),e),b.util.addClass(this.getElement(),b.Image.CSS_CANVAS)},_initConfig:function(t){t||(t={}),this.setOptions(t),this._setWidthHeight(t)},_initFilters:function(t,e){t&&t.length?b.util.enlivenObjects(t,(function(t){e&&e(t)}),"fabric.Image.filters"):e&&e()},_setWidthHeight:function(t){t||(t={});var e=this.getElement();this.width=t.width||e.naturalWidth||e.width||0,this.height=t.height||e.naturalHeight||e.height||0},parsePreserveAspectRatioAttribute:function(){var t,e=b.util.parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),i=this._element.width,n=this._element.height,r=1,s=1,a=0,o=0,l=0,h=0,c=this.width,d=this.height,u={width:c,height:d};return!e||"none"===e.alignX&&"none"===e.alignY?(r=c/i,s=d/n):("meet"===e.meetOrSlice&&(t=(c-i*(r=s=b.util.findScaleToFit(this._element,u)))/2,"Min"===e.alignX&&(a=-t),"Max"===e.alignX&&(a=t),t=(d-n*s)/2,"Min"===e.alignY&&(o=-t),"Max"===e.alignY&&(o=t)),"slice"===e.meetOrSlice&&(t=i-c/(r=s=b.util.findScaleToCover(this._element,u)),"Mid"===e.alignX&&(l=t/2),"Max"===e.alignX&&(l=t),t=n-d/s,"Mid"===e.alignY&&(h=t/2),"Max"===e.alignY&&(h=t),i=c/r,n=d/s)),{width:i,height:n,scaleX:r,scaleY:s,offsetLeft:a,offsetTop:o,cropX:l,cropY:h}}}),b.Image.CSS_CANVAS="canvas-img",b.Image.prototype.getSvgSrc=b.Image.prototype.getSrc,b.Image.fromObject=function(t,e){var i=b.util.object.clone(t);b.util.loadImage(i.src,(function(t,n){n?e&&e(null,!0):b.Image.prototype._initFilters.call(i,i.filters,(function(n){i.filters=n||[],b.Image.prototype._initFilters.call(i,[i.resizeFilter],(function(n){i.resizeFilter=n[0],b.util.enlivenObjectEnlivables(i,i,(function(){var n=new b.Image(t,i);e(n,!1)}))}))}))}),null,i.crossOrigin)},b.Image.fromURL=function(t,e,i){b.util.loadImage(t,(function(t,n){e&&e(new b.Image(t,i),n)}),null,i&&i.crossOrigin)},b.Image.ATTRIBUTE_NAMES=b.SHARED_ATTRIBUTES.concat("x y width height preserveAspectRatio xlink:href crossOrigin image-rendering".split(" ")),b.Image.fromElement=function(t,i,n){var r=b.parseAttributes(t,b.Image.ATTRIBUTE_NAMES);b.Image.fromURL(r["xlink:href"],i,e(n?b.util.object.clone(n):{},r))})}(e),b.util.object.extend(b.Object.prototype,{_getAngleValueForStraighten:function(){var t=this.angle%360;return t>0?90*Math.round((t-1)/90):90*Math.round(t/90)},straighten:function(){return this.rotate(this._getAngleValueForStraighten())},fxStraighten:function(t){var e=function(){},i=(t=t||{}).onComplete||e,n=t.onChange||e,r=this;return b.util.animate({target:this,startValue:this.get("angle"),endValue:this._getAngleValueForStraighten(),duration:this.FX_DURATION,onChange:function(t){r.rotate(t),n()},onComplete:function(){r.setCoords(),i()}})}}),b.util.object.extend(b.StaticCanvas.prototype,{straightenObject:function(t){return t.straighten(),this.requestRenderAll(),this},fxStraightenObject:function(t){return t.fxStraighten({onChange:this.requestRenderAllBound})}}),function(){function t(t,e){var i="precision "+e+" float;\nvoid main(){}",n=t.createShader(t.FRAGMENT_SHADER);return t.shaderSource(n,i),t.compileShader(n),!!t.getShaderParameter(n,t.COMPILE_STATUS)}function e(t){t&&t.tileSize&&(this.tileSize=t.tileSize),this.setupGLContext(this.tileSize,this.tileSize),this.captureGPUInfo()}b.isWebglSupported=function(e){if(b.isLikelyNode)return!1;e=e||b.WebglFilterBackend.prototype.tileSize;var i=document.createElement("canvas"),n=i.getContext("webgl")||i.getContext("experimental-webgl"),r=!1;if(n){b.maxTextureSize=n.getParameter(n.MAX_TEXTURE_SIZE),r=b.maxTextureSize>=e;for(var s=["highp","mediump","lowp"],a=0;a<3;a++)if(t(n,s[a])){b.webGlPrecision=s[a];break}}return this.isSupported=r,r},b.WebglFilterBackend=e,e.prototype={tileSize:2048,resources:{},setupGLContext:function(t,e){this.dispose(),this.createWebGLCanvas(t,e),this.aPosition=new Float32Array([0,0,0,1,1,0,1,1]),this.chooseFastestCopyGLTo2DMethod(t,e)},chooseFastestCopyGLTo2DMethod:function(t,e){var i,n=void 0!==window.performance;try{new ImageData(1,1),i=!0}catch(t){i=!1}var r="undefined"!=typeof ArrayBuffer,s="undefined"!=typeof Uint8ClampedArray;if(n&&i&&r&&s){var a=b.util.createCanvasElement(),o=new ArrayBuffer(t*e*4);if(b.forceGLPutImageData)return this.imageBuffer=o,void(this.copyGLTo2D=x);var l,h,c={imageBuffer:o,destinationWidth:t,destinationHeight:e,targetCanvas:a};a.width=t,a.height=e,l=window.performance.now(),I.call(c,this.gl,c),h=window.performance.now()-l,l=window.performance.now(),x.call(c,this.gl,c),h>window.performance.now()-l?(this.imageBuffer=o,this.copyGLTo2D=x):this.copyGLTo2D=I}},createWebGLCanvas:function(t,e){var i=b.util.createCanvasElement();i.width=t,i.height=e;var n={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},r=i.getContext("webgl",n);r||(r=i.getContext("experimental-webgl",n)),r&&(r.clearColor(0,0,0,0),this.canvas=i,this.gl=r)},applyFilters:function(t,e,i,n,r,s){var a,o=this.gl;s&&(a=this.getCachedTexture(s,e));var l={originalWidth:e.width||e.originalWidth,originalHeight:e.height||e.originalHeight,sourceWidth:i,sourceHeight:n,destinationWidth:i,destinationHeight:n,context:o,sourceTexture:this.createTexture(o,i,n,!a&&e),targetTexture:this.createTexture(o,i,n),originalTexture:a||this.createTexture(o,i,n,!a&&e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:r},h=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,h),t.forEach((function(t){t&&t.applyTo(l)})),function(t){var e=t.targetCanvas,i=e.width,n=e.height,r=t.destinationWidth,s=t.destinationHeight;i===r&&n===s||(e.width=r,e.height=s)}(l),this.copyGLTo2D(o,l),o.bindTexture(o.TEXTURE_2D,null),o.deleteTexture(l.sourceTexture),o.deleteTexture(l.targetTexture),o.deleteFramebuffer(h),r.getContext("2d").setTransform(1,0,0,1,0,0),l},dispose:function(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()},clearWebGLCaches:function(){this.programCache={},this.textureCache={}},createTexture:function(t,e,i,n){var r=t.createTexture();return t.bindTexture(t.TEXTURE_2D,r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),n?t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,n):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e,i,0,t.RGBA,t.UNSIGNED_BYTE,null),r},getCachedTexture:function(t,e){if(this.textureCache[t])return this.textureCache[t];var i=this.createTexture(this.gl,e.width,e.height,e);return this.textureCache[t]=i,i},evictCachesForKey:function(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])},copyGLTo2D:I,captureGPUInfo:function(){if(this.gpuInfo)return this.gpuInfo;var t=this.gl,e={renderer:"",vendor:""};if(!t)return e;var i=t.getExtension("WEBGL_debug_renderer_info");if(i){var n=t.getParameter(i.UNMASKED_RENDERER_WEBGL),r=t.getParameter(i.UNMASKED_VENDOR_WEBGL);n&&(e.renderer=n.toLowerCase()),r&&(e.vendor=r.toLowerCase())}return this.gpuInfo=e,e}}}(),function(){var t=function(){};function e(){}b.Canvas2dFilterBackend=e,e.prototype={evictCachesForKey:t,dispose:t,clearWebGLCaches:t,resources:{},applyFilters:function(t,e,i,n,r){var s=r.getContext("2d");s.drawImage(e,0,0,i,n);var a={sourceWidth:i,sourceHeight:n,imageData:s.getImageData(0,0,i,n),originalEl:e,originalImageData:s.getImageData(0,0,i,n),canvasEl:r,ctx:s,filterBackend:this};return t.forEach((function(t){t.applyTo(a)})),a.imageData.width===i&&a.imageData.height===n||(r.width=a.imageData.width,r.height=a.imageData.height),s.putImageData(a.imageData,0,0),a}}}(),b.Image=b.Image||{},b.Image.filters=b.Image.filters||{},b.Image.filters.BaseFilter=b.util.createClass({type:"BaseFilter",vertexSource:"attribute vec2 aPosition;\nvarying vec2 vTexCoord;\nvoid main() {\nvTexCoord = aPosition;\ngl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n}",fragmentSource:"precision highp float;\nvarying vec2 vTexCoord;\nuniform sampler2D uTexture;\nvoid main() {\ngl_FragColor = texture2D(uTexture, vTexCoord);\n}",initialize:function(t){t&&this.setOptions(t)},setOptions:function(t){for(var e in t)this[e]=t[e]},createProgram:function(t,e,i){e=e||this.fragmentSource,i=i||this.vertexSource,"highp"!==b.webGlPrecision&&(e=e.replace(/precision highp float/g,"precision "+b.webGlPrecision+" float"));var n=t.createShader(t.VERTEX_SHADER);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Error("Vertex shader compile error for "+this.type+": "+t.getShaderInfoLog(n));var r=t.createShader(t.FRAGMENT_SHADER);if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Error("Fragment shader compile error for "+this.type+": "+t.getShaderInfoLog(r));var s=t.createProgram();if(t.attachShader(s,n),t.attachShader(s,r),t.linkProgram(s),!t.getProgramParameter(s,t.LINK_STATUS))throw new Error('Shader link error for "${this.type}" '+t.getProgramInfoLog(s));var a=this.getAttributeLocations(t,s),o=this.getUniformLocations(t,s)||{};return o.uStepW=t.getUniformLocation(s,"uStepW"),o.uStepH=t.getUniformLocation(s,"uStepH"),{program:s,attributeLocations:a,uniformLocations:o}},getAttributeLocations:function(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}},getUniformLocations:function(){return{}},sendAttributeData:function(t,e,i){var n=e.aPosition,r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r),t.enableVertexAttribArray(n),t.vertexAttribPointer(n,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)},_setupFrameBuffer:function(t){var e,i,n=t.context;t.passes>1?(e=t.destinationWidth,i=t.destinationHeight,t.sourceWidth===e&&t.sourceHeight===i||(n.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(n,e,i)),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t.targetTexture,0)):(n.bindFramebuffer(n.FRAMEBUFFER,null),n.finish())},_swapTextures:function(t){t.passes--,t.pass++;var e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e},isNeutralState:function(){var t=this.mainParameter,e=b.Image.filters[this.type].prototype;if(t){if(Array.isArray(e[t])){for(var i=e[t].length;i--;)if(this[t][i]!==e[t][i])return!1;return!0}return e[t]===this[t]}return!1},applyTo:function(t){t.webgl?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)},retrieveShader:function(t){return t.programCache.hasOwnProperty(this.type)||(t.programCache[this.type]=this.createProgram(t.context)),t.programCache[this.type]},applyToWebGL:function(t){var e=t.context,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)},bindAdditionalTexture:function(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)},unbindAdditionalTexture:function(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)},getMainParameter:function(){return this[this.mainParameter]},setMainParameter:function(t){this[this.mainParameter]=t},sendUniformData:function(){},createHelpLayer:function(t){if(!t.helpLayer){var e=document.createElement("canvas");e.width=t.sourceWidth,e.height=t.sourceHeight,t.helpLayer=e}},toObject:function(){var t={type:this.type},e=this.mainParameter;return e&&(t[e]=this[e]),t},toJSON:function(){return this.toObject()}}),b.Image.filters.BaseFilter.fromObject=function(t,e){var i=new b.Image.filters[t.type](t);return e&&e(i),i},function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.ColorMatrix=n(i.BaseFilter,{type:"ColorMatrix",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nuniform mat4 uColorMatrix;\nuniform vec4 uConstants;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\ncolor *= uColorMatrix;\ncolor += uConstants;\ngl_FragColor = color;\n}",matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],mainParameter:"matrix",colorsOnly:!0,initialize:function(t){this.callSuper("initialize",t),this.matrix=this.matrix.slice(0)},applyTo2d:function(t){var e,i,n,r,s,a=t.imageData.data,o=a.length,l=this.matrix,h=this.colorsOnly;for(s=0;s=w||a<0||a>=y||(l=4*(o*y+a),h=p[f*_+u],e+=m[l]*h,i+=m[l+1]*h,n+=m[l+2]*h,S||(r+=m[l+3]*h));E[s]=e,E[s+1]=i,E[s+2]=n,E[s+3]=S?m[s+3]:r}t.imageData=C},getUniformLocations:function(t,e){return{uMatrix:t.getUniformLocation(e,"uMatrix"),uOpaque:t.getUniformLocation(e,"uOpaque"),uHalfSize:t.getUniformLocation(e,"uHalfSize"),uSize:t.getUniformLocation(e,"uSize")}},sendUniformData:function(t,e){t.uniform1fv(e.uMatrix,this.matrix)},toObject:function(){return i(this.callSuper("toObject"),{opaque:this.opaque,matrix:this.matrix})}}),e.Image.filters.Convolute.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Grayscale=n(i.BaseFilter,{type:"Grayscale",fragmentSource:{average:"precision highp float;\nuniform sampler2D uTexture;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat average = (color.r + color.b + color.g) / 3.0;\ngl_FragColor = vec4(average, average, average, color.a);\n}",lightness:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\ngl_FragColor = vec4(average, average, average, col.a);\n}",luminosity:"precision highp float;\nuniform sampler2D uTexture;\nuniform int uMode;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 col = texture2D(uTexture, vTexCoord);\nfloat average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\ngl_FragColor = vec4(average, average, average, col.a);\n}"},mode:"average",mainParameter:"mode",applyTo2d:function(t){var e,i,n=t.imageData.data,r=n.length,s=this.mode;for(e=0;eh[0]&&r>h[1]&&s>h[2]&&n 0.0) {\n"+this.fragmentSource[t]+"}\n}"},retrieveShader:function(t){var e,i=this.type+"_"+this.mode;return t.programCache.hasOwnProperty(i)||(e=this.buildSource(this.mode),t.programCache[i]=this.createProgram(t.context,e)),t.programCache[i]},applyTo2d:function(t){var i,n,r,s,a,o,l,h=t.imageData.data,c=h.length,d=1-this.alpha;i=(l=new e.Color(this.color).getSource())[0]*this.alpha,n=l[1]*this.alpha,r=l[2]*this.alpha;for(var u=0;u=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;var i=(e*=Math.PI)/t;return o(e)/e*o(i)/i}},applyTo2d:function(t){var e=t.imageData,i=this.scaleX,n=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/n;var r,s=e.width,o=e.height,l=a(s*i),h=a(o*n);"sliceHack"===this.resizeType?r=this.sliceByTwo(t,s,o,l,h):"hermite"===this.resizeType?r=this.hermiteFastResize(t,s,o,l,h):"bilinear"===this.resizeType?r=this.bilinearFiltering(t,s,o,l,h):"lanczos"===this.resizeType&&(r=this.lanczosResize(t,s,o,l,h)),t.imageData=r},sliceByTwo:function(t,i,r,s,a){var o,l,h=t.imageData,c=.5,d=!1,u=!1,f=i*c,g=r*c,m=e.filterBackend.resources,p=0,_=0,v=i,y=0;for(m.sliceByTwo||(m.sliceByTwo=document.createElement("canvas")),((o=m.sliceByTwo).width<1.5*i||o.height=e)){L=n(1e3*s(b-C.x)),w[L]||(w[L]={});for(var F=E.y-y;F<=E.y+y;F++)F<0||F>=a||(M=n(1e3*s(F-C.y)),w[L][M]||(w[L][M]=f(r(i(L*p,2)+i(M*_,2))/1e3)),(T=w[L][M])>0&&(x+=T,O+=T*c[I=4*(F*e+b)],A+=T*c[I+1],R+=T*c[I+2],D+=T*c[I+3]))}u[I=4*(S*o+l)]=O/x,u[I+1]=A/x,u[I+2]=R/x,u[I+3]=D/x}return++l1&&M<-1||(y=2*M*M*M-3*M*M+1)>0&&(T+=y*f[3+(L=4*(D+x*e))],C+=y,f[L+3]<255&&(y=y*f[L+3]/250),E+=y*f[L],S+=y*f[L+1],b+=y*f[L+2],w+=y)}m[v]=E/w,m[v+1]=S/w,m[v+2]=b/w,m[v+3]=T/C}return g},toObject:function(){return{type:this.type,scaleX:this.scaleX,scaleY:this.scaleY,resizeType:this.resizeType,lanczosLobes:this.lanczosLobes}}}),e.Image.filters.Resize.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Contrast=n(i.BaseFilter,{type:"Contrast",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform float uContrast;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nfloat contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\ncolor.rgb = contrastF * (color.rgb - 0.5) + 0.5;\ngl_FragColor = color;\n}",contrast:0,mainParameter:"contrast",applyTo2d:function(t){if(0!==this.contrast){var e,i=t.imageData.data,n=i.length,r=Math.floor(255*this.contrast),s=259*(r+255)/(255*(259-r));for(e=0;e1&&(e=1/this.aspectRatio):this.aspectRatio<1&&(e=this.aspectRatio),t=e*this.blur*.12,this.horizontal?i[0]=t:i[1]=t,i}}),i.Blur.fromObject=e.Image.filters.BaseFilter.fromObject}(e),function(t){var e=t.fabric||(t.fabric={}),i=e.Image.filters,n=e.util.createClass;i.Gamma=n(i.BaseFilter,{type:"Gamma",fragmentSource:"precision highp float;\nuniform sampler2D uTexture;\nuniform vec3 uGamma;\nvarying vec2 vTexCoord;\nvoid main() {\nvec4 color = texture2D(uTexture, vTexCoord);\nvec3 correction = (1.0 / uGamma);\ncolor.r = pow(color.r, correction.r);\ncolor.g = pow(color.g, correction.g);\ncolor.b = pow(color.b, correction.b);\ngl_FragColor = color;\ngl_FragColor.rgb *= color.a;\n}",gamma:[1,1,1],mainParameter:"gamma",initialize:function(t){this.gamma=[1,1,1],i.BaseFilter.prototype.initialize.call(this,t)},applyTo2d:function(t){var e,i=t.imageData.data,n=this.gamma,r=i.length,s=1/n[0],a=1/n[1],o=1/n[2];for(this.rVals||(this.rVals=new Uint8Array(256),this.gVals=new Uint8Array(256),this.bVals=new Uint8Array(256)),e=0,r=256;e'},_getCacheCanvasDimensions:function(){var t=this.callSuper("_getCacheCanvasDimensions"),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t},_render:function(t){var e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")},_renderText:function(t){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))},_setTextStyles:function(t,e,i){if(t.textBaseline="alphabetical",this.path)switch(this.pathAlign){case"center":t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline="bottom"}t.font=this._getFontDeclaration(e,i)},calcTextWidth:function(){for(var t=this.getLineWidth(0),e=1,i=this._textLines.length;et&&(t=n)}return t},_renderTextLine:function(t,e,i,n,r,s){this._renderChars(t,e,i,n,r,s)},_renderTextLinesBackground:function(t){if(this.textBackgroundColor||this.styleHas("textBackgroundColor")){for(var e,i,n,r,s,a,o,l=t.fillStyle,h=this._getLeftOffset(),c=this._getTopOffset(),d=0,u=0,f=this.path,g=0,m=this._textLines.length;g=0:io?d%=o:d<0&&(d+=o),this._setGraphemeOnPath(d,s,a),d+=s.kernedWidth}return{width:l,numOfSpaces:0}},_setGraphemeOnPath:function(t,i,n){var r=t+i.kernedWidth/2,s=this.path,a=e.util.getPointOnPath(s.path,r,s.segmentsInfo);i.renderLeft=a.x-n.x,i.renderTop=a.y-n.y,i.angle=a.angle+("right"===this.pathSide?Math.PI:0)},_getGraphemeBox:function(t,e,i,n,r){var s,a=this.getCompleteStyleDeclaration(e,i),o=n?this.getCompleteStyleDeclaration(e,i-1):{},l=this._measureChar(t,a,n,o),h=l.kernedWidth,c=l.width;0!==this.charSpacing&&(c+=s=this._getWidthOfCharSpacing(),h+=s);var d={width:c,left:0,height:a.fontSize,kernedWidth:h,deltaY:a.deltaY};if(i>0&&!r){var u=this.__charBounds[e][i-1];d.left=u.left+u.width+l.kernedWidth-l.width}return d},getHeightOfLine:function(t){if(this.__lineHeights[t])return this.__lineHeights[t];for(var e=this._textLines[t],i=this.getHeightOfChar(t,0),n=1,r=e.length;n0){var x=v+s+d;"rtl"===this.direction&&(x=this.width-x-u),h&&_&&(t.fillStyle=_,t.fillRect(x,c+E*n+a,u,this.fontSize/15)),d=f.left,u=f.width,h=g,_=p,n=r,a=o}else u+=f.kernedWidth;x=v+s+d,"rtl"===this.direction&&(x=this.width-x-u),t.fillStyle=p,g&&p&&t.fillRect(x,c+E*n+a,u-C,this.fontSize/15),y+=i}else y+=i;this._removeShadow(t)}},_getFontDeclaration:function(t,i){var n=t||this,r=this.fontFamily,s=e.Text.genericFonts.indexOf(r.toLowerCase())>-1,a=void 0===r||r.indexOf("'")>-1||r.indexOf(",")>-1||r.indexOf('"')>-1||s?n.fontFamily:'"'+n.fontFamily+'"';return[e.isLikelyNode?n.fontWeight:n.fontStyle,e.isLikelyNode?n.fontStyle:n.fontWeight,i?this.CACHE_FONT_SIZE+"px":n.fontSize+"px",a].join(" ")},render:function(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._shouldClearDimensionCache()&&this.initDimensions(),this.callSuper("render",t)))},_splitTextIntoLines:function(t){for(var i=t.split(this._reNewline),n=new Array(i.length),r=["\n"],s=[],a=0;a-1&&(t.underline=!0),t.textDecoration.indexOf("line-through")>-1&&(t.linethrough=!0),t.textDecoration.indexOf("overline")>-1&&(t.overline=!0),delete t.textDecoration)}b.IText=b.util.createClass(b.Text,b.Observable,{type:"i-text",selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,_reSpace:/\s|\n/,_currentCursorOpacity:0,_selectionDirection:null,_abortCursorAnimation:!1,__widthOfSpace:[],inCompositionMode:!1,initialize:function(t,e){this.callSuper("initialize",t,e),this.initBehavior()},setSelectionStart:function(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)},setSelectionEnd:function(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)},_updateAndFire:function(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()},_fireSelectionChanged:function(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})},initDimensions:function(){this.isEditing&&this.initDelayedCursor(),this.clearContextTop(),this.callSuper("initDimensions")},render:function(t){this.clearContextTop(),this.callSuper("render",t),this.cursorOffsetCache={},this.renderCursorOrSelection()},_render:function(t){this.callSuper("_render",t)},clearContextTop:function(t){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var e=this.canvas.contextTop,i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e),this._clearTextArea(e),t||e.restore()}},renderCursorOrSelection:function(){if(this.isEditing&&this.canvas&&this.canvas.contextTop){var t=this._getCursorBoundaries(),e=this.canvas.contextTop;this.clearContextTop(!0),this.selectionStart===this.selectionEnd?this.renderCursor(t,e):this.renderSelection(t,e),e.restore()}},_clearTextArea:function(t){var e=this.width+4,i=this.height+4;t.clearRect(-e/2,-i/2,e,i)},_getCursorBoundaries:function(t){void 0===t&&(t=this.selectionStart);var e=this._getLeftOffset(),i=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t);return{left:e,top:i,leftOffset:n.left,topOffset:n.top}},_getCursorBoundariesOffsets:function(t){if(this.cursorOffsetCache&&"top"in this.cursorOffsetCache)return this.cursorOffsetCache;var e,i,n,r,s=0,a=0,o=this.get2DCursorLocation(t);n=o.charIndex,i=o.lineIndex;for(var l=0;l0?a:0)},"rtl"===this.direction&&(r.left*=-1),this.cursorOffsetCache=r,this.cursorOffsetCache},renderCursor:function(t,e){var i=this.get2DCursorLocation(),n=i.lineIndex,r=i.charIndex>0?i.charIndex-1:0,s=this.getValueOfPropertyAt(n,r,"fontSize"),a=this.scaleX*this.canvas.getZoom(),o=this.cursorWidth/a,l=t.topOffset,h=this.getValueOfPropertyAt(n,r,"deltaY");l+=(1-this._fontSizeFraction)*this.getHeightOfLine(n)/this.lineHeight-s*(1-this._fontSizeFraction),this.inCompositionMode&&this.renderSelection(t,e),e.fillStyle=this.cursorColor||this.getValueOfPropertyAt(n,r,"fill"),e.globalAlpha=this.__isMousedown?1:this._currentCursorOpacity,e.fillRect(t.left+t.leftOffset-o/2,l+t.top+h,o,s)},renderSelection:function(t,e){for(var i=this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,n=this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd,r=-1!==this.textAlign.indexOf("justify"),s=this.get2DCursorLocation(i),a=this.get2DCursorLocation(n),o=s.lineIndex,l=a.lineIndex,h=s.charIndex<0?0:s.charIndex,c=a.charIndex<0?0:a.charIndex,d=o;d<=l;d++){var u,f=this._getLineLeftOffset(d)||0,g=this.getHeightOfLine(d),m=0,p=0;if(d===o&&(m=this.__charBounds[o][h].left),d>=o&&d1)&&(g/=this.lineHeight);var v=t.left+f+m,y=p-m,w=g,C=0;this.inCompositionMode?(e.fillStyle=this.compositionColor||"black",w=1,C=g):e.fillStyle=this.selectionColor,"rtl"===this.direction&&(v=this.width-v-y),e.fillRect(v,t.top+t.topOffset+C,y,w),t.topOffset+=u}},getCurrentCharFontSize:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")},getCurrentCharColor:function(){var t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fill")},_getCurrentCharIndex:function(){var t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}}),b.IText.fromObject=function(e,i){if(t(e),e.styles)for(var n in e.styles)for(var r in e.styles[n])t(e.styles[n][r]);b.Object._fromObject("IText",e,i,"text")}}(),S=b.util.object.clone,b.util.object.extend(b.IText.prototype,{initBehavior:function(){this.initAddedHandler(),this.initRemovedHandler(),this.initCursorSelectionHandlers(),this.initDoubleClickSimulation(),this.mouseMoveHandler=this.mouseMoveHandler.bind(this)},onDeselect:function(){this.isEditing&&this.exitEditing(),this.selected=!1},initAddedHandler:function(){var t=this;this.on("added",(function(){var e=t.canvas;e&&(e._hasITextHandlers||(e._hasITextHandlers=!0,t._initCanvasHandlers(e)),e._iTextInstances=e._iTextInstances||[],e._iTextInstances.push(t))}))},initRemovedHandler:function(){var t=this;this.on("removed",(function(){var e=t.canvas;e&&(e._iTextInstances=e._iTextInstances||[],b.util.removeFromArray(e._iTextInstances,t),0===e._iTextInstances.length&&(e._hasITextHandlers=!1,t._removeCanvasHandlers(e)))}))},_initCanvasHandlers:function(t){t._mouseUpITextHandler=function(){t._iTextInstances&&t._iTextInstances.forEach((function(t){t.__isMousedown=!1}))},t.on("mouse:up",t._mouseUpITextHandler)},_removeCanvasHandlers:function(t){t.off("mouse:up",t._mouseUpITextHandler)},_tick:function(){this._currentTickState=this._animateCursor(this,1,this.cursorDuration,"_onTickComplete")},_animateCursor:function(t,e,i,n){var r;return r={isAborted:!1,abort:function(){this.isAborted=!0}},t.animate("_currentCursorOpacity",e,{duration:i,onComplete:function(){r.isAborted||t[n]()},onChange:function(){t.canvas&&t.selectionStart===t.selectionEnd&&t.renderCursorOrSelection()},abort:function(){return r.isAborted}}),r},_onTickComplete:function(){var t=this;this._cursorTimeout1&&clearTimeout(this._cursorTimeout1),this._cursorTimeout1=setTimeout((function(){t._currentTickCompleteState=t._animateCursor(t,0,this.cursorDuration/2,"_tick")}),100)},initDelayedCursor:function(t){var e=this,i=t?0:this.cursorDelay;this.abortCursorAnimation(),this._currentCursorOpacity=1,this._cursorTimeout2=setTimeout((function(){e._tick()}),i)},abortCursorAnimation:function(){var t=this._currentTickState||this._currentTickCompleteState,e=this.canvas;this._currentTickState&&this._currentTickState.abort(),this._currentTickCompleteState&&this._currentTickCompleteState.abort(),clearTimeout(this._cursorTimeout1),clearTimeout(this._cursorTimeout2),this._currentCursorOpacity=0,t&&e&&e.clearContext(e.contextTop||e.contextContainer)},selectAll:function(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this},getSelectedText:function(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")},findWordBoundaryLeft:function(t){var e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e},findWordBoundaryRight:function(t){var e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i-1;)e++,i--;return t-e},findLineBoundaryRight:function(t){for(var e=0,i=t;!/\n/.test(this._text[i])&&i0&&nthis.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=e):(this.selectionStart=e,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(this.restartCursorIfNeeded(),this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}},_setEditingProps:function(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0},fromStringToGraphemeSelection:function(t,e,i){var n=i.slice(0,t),r=b.util.string.graphemeSplit(n).length;if(t===e)return{selectionStart:r,selectionEnd:r};var s=i.slice(t,e);return{selectionStart:r,selectionEnd:r+b.util.string.graphemeSplit(s).length}},fromGraphemeToStringSelection:function(t,e,i){var n=i.slice(0,t).join("").length;return t===e?{selectionStart:n,selectionEnd:n}:{selectionStart:n,selectionEnd:n+i.slice(t,e).join("").length}},_updateTextarea:function(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){var t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}},updateFromTextArea:function(){if(this.hiddenTextarea){this.cursorOffsetCache={},this.text=this.hiddenTextarea.value,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords());var t=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value);this.selectionEnd=this.selectionStart=t.selectionEnd,this.inCompositionMode||(this.selectionStart=t.selectionStart),this.updateTextareaPosition()}},updateTextareaPosition:function(){if(this.selectionStart===this.selectionEnd){var t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}},_calcTextareaPosition:function(){if(!this.canvas)return{x:1,y:1};var t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),n=i.lineIndex,r=i.charIndex,s=this.getValueOfPropertyAt(n,r,"fontSize")*this.lineHeight,a=e.leftOffset,o=this.calcTransformMatrix(),l={x:e.left+a,y:e.top+e.topOffset+s},h=this.canvas.getRetinaScaling(),c=this.canvas.upperCanvasEl,d=c.width/h,u=c.height/h,f=d-s,g=u-s,m=c.clientWidth/d,p=c.clientHeight/u;return l=b.util.transformPoint(l,o),(l=b.util.transformPoint(l,this.canvas.viewportTransform)).x*=m,l.y*=p,l.x<0&&(l.x=0),l.x>f&&(l.x=f),l.y<0&&(l.y=0),l.y>g&&(l.y=g),l.x+=this.canvas._offset.left,l.y+=this.canvas._offset.top,{left:l.x+"px",top:l.y+"px",fontSize:s+"px",charHeight:s}},_saveEditingProps:function(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}},_restoreEditingProps:function(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor))},exitEditing:function(){var t=this._textBeforeEdit!==this.text,e=this.hiddenTextarea;return this.selected=!1,this.isEditing=!1,this.selectionEnd=this.selectionStart,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this._restoreEditingProps(),this._currentCursorOpacity=0,this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.off("mouse:move",this.mouseMoveHandler),this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this},_removeExtraneousStyles:function(){for(var t in this.styles)this._textLines[t]||delete this.styles[t]},removeStyleFromTo:function(t,e){var i,n,r=this.get2DCursorLocation(t,!0),s=this.get2DCursorLocation(e,!0),a=r.lineIndex,o=r.charIndex,l=s.lineIndex,h=s.charIndex;if(a!==l){if(this.styles[a])for(i=o;i=h&&(n[c-u]=n[d],delete n[d])}},shiftLineStyles:function(t,e){var i=S(this.styles);for(var n in this.styles){var r=parseInt(n,10);r>t&&(this.styles[r+e]=i[r],i[r-e]||delete this.styles[r])}},restartCursorIfNeeded:function(){this._currentTickState&&!this._currentTickState.isAborted&&this._currentTickCompleteState&&!this._currentTickCompleteState.isAborted||this.initDelayedCursor()},insertNewlineStyleObject:function(t,e,i,n){var r,s={},a=!1,o=this._unwrappedTextLines[t].length===e;for(var l in i||(i=1),this.shiftLineStyles(t,i),this.styles[t]&&(r=this.styles[t][0===e?e:e-1]),this.styles[t]){var h=parseInt(l,10);h>=e&&(a=!0,s[h-e]=this.styles[t][l],o&&0===e||delete this.styles[t][l])}var c=!1;for(a&&!o&&(this.styles[t+i]=s,c=!0),c&&i--;i>0;)n&&n[i-1]?this.styles[t+i]={0:S(n[i-1])}:r?this.styles[t+i]={0:S(r)}:delete this.styles[t+i],i--;this._forceClearCache=!0},insertCharStyleObject:function(t,e,i,n){this.styles||(this.styles={});var r=this.styles[t],s=r?S(r):{};for(var a in i||(i=1),s){var o=parseInt(a,10);o>=e&&(r[o+i]=s[o],s[o-i]||delete r[o])}if(this._forceClearCache=!0,n)for(;i--;)Object.keys(n[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]=S(n[i]));else if(r)for(var l=r[e?e-1:1];l&&i--;)this.styles[t][e+i]=S(l)},insertNewStyleBlock:function(t,e,i){for(var n=this.get2DCursorLocation(e,!0),r=[0],s=0,a=0;a0&&(this.insertCharStyleObject(n.lineIndex,n.charIndex,r[0],i),i=i&&i.slice(r[0]+1)),s&&this.insertNewlineStyleObject(n.lineIndex,n.charIndex+r[0],s),a=1;a0?this.insertCharStyleObject(n.lineIndex+a,0,r[a],i):i&&this.styles[n.lineIndex+a]&&i[0]&&(this.styles[n.lineIndex+a][0]=i[0]),i=i&&i.slice(r[a]+1);r[a]>0&&this.insertCharStyleObject(n.lineIndex+a,0,r[a],i)},setSelectionStartEndWithShift:function(t,e,i){i<=t?(e===t?this._selectionDirection="left":"right"===this._selectionDirection&&(this._selectionDirection="left",this.selectionEnd=t),this.selectionStart=i):i>t&&it?this.selectionStart=t:this.selectionStart<0&&(this.selectionStart=0),this.selectionEnd>t?this.selectionEnd=t:this.selectionEnd<0&&(this.selectionEnd=0)}}),b.util.object.extend(b.IText.prototype,{initDoubleClickSimulation:function(){this.__lastClickTime=+new Date,this.__lastLastClickTime=+new Date,this.__lastPointer={},this.on("mousedown",this.onMouseDown)},onMouseDown:function(t){if(this.canvas){this.__newClickTime=+new Date;var e=t.pointer;this.isTripleClick(e)&&(this.fire("tripleclick",t),this._stopEvent(t.e)),this.__lastLastClickTime=this.__lastClickTime,this.__lastClickTime=this.__newClickTime,this.__lastPointer=e,this.__lastIsEditing=this.isEditing,this.__lastSelected=this.selected}},isTripleClick:function(t){return this.__newClickTime-this.__lastClickTime<500&&this.__lastClickTime-this.__lastLastClickTime<500&&this.__lastPointer.x===t.x&&this.__lastPointer.y===t.y},_stopEvent:function(t){t.preventDefault&&t.preventDefault(),t.stopPropagation&&t.stopPropagation()},initCursorSelectionHandlers:function(){this.initMousedownHandler(),this.initMouseupHandler(),this.initClicks()},doubleClickHandler:function(t){this.isEditing&&this.selectWord(this.getSelectionStartFromPointer(t.e))},tripleClickHandler:function(t){this.isEditing&&this.selectLine(this.getSelectionStartFromPointer(t.e))},initClicks:function(){this.on("mousedblclick",this.doubleClickHandler),this.on("tripleclick",this.tripleClickHandler)},_mouseDownHandler:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.__isMousedown=!0,this.selected&&(this.inCompositionMode=!1,this.setCursorByClick(t.e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()))},_mouseDownHandlerBefore:function(t){!this.canvas||!this.editable||t.e.button&&1!==t.e.button||(this.selected=this===this.canvas._activeObject)},initMousedownHandler:function(){this.on("mousedown",this._mouseDownHandler),this.on("mousedown:before",this._mouseDownHandlerBefore)},initMouseupHandler:function(){this.on("mouseup",this.mouseUpHandler)},mouseUpHandler:function(t){if(this.__isMousedown=!1,!(!this.editable||this.group||t.transform&&t.transform.actionPerformed||t.e.button&&1!==t.e.button)){if(this.canvas){var e=this.canvas._activeObject;if(e&&e!==this)return}this.__lastSelected&&!this.__corner?(this.selected=!1,this.__lastSelected=!1,this.enterEditing(t.e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection()):this.selected=!0}},setCursorByClick:function(t){var e=this.getSelectionStartFromPointer(t),i=this.selectionStart,n=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,n,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())},getSelectionStartFromPointer:function(t){for(var e,i=this.getLocalPointer(t),n=0,r=0,s=0,a=0,o=0,l=0,h=this._textLines.length;l0&&(a+=this._textLines[l-1].length+this.missingNewlineOffset(l-1));r=this._getLineLeftOffset(o)*this.scaleX,e=this._textLines[o],"rtl"===this.direction&&(i.x=this.width*this.scaleX-i.x+r);for(var c=0,d=e.length;cs||a<0?0:1);return this.flipX&&(o=r-o),o>this._text.length&&(o=this._text.length),o}}),b.util.object.extend(b.IText.prototype,{initHiddenTextarea:function(){this.hiddenTextarea=b.document.createElement("textarea"),this.hiddenTextarea.setAttribute("autocapitalize","off"),this.hiddenTextarea.setAttribute("autocorrect","off"),this.hiddenTextarea.setAttribute("autocomplete","off"),this.hiddenTextarea.setAttribute("spellcheck","false"),this.hiddenTextarea.setAttribute("data-fabric-hiddentextarea",""),this.hiddenTextarea.setAttribute("wrap","off");var t=this._calcTextareaPosition();this.hiddenTextarea.style.cssText="position: absolute; top: "+t.top+"; left: "+t.left+"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; paddingーtop: "+t.fontSize+";",this.hiddenTextareaContainer?this.hiddenTextareaContainer.appendChild(this.hiddenTextarea):b.document.body.appendChild(this.hiddenTextarea),b.util.addListener(this.hiddenTextarea,"keydown",this.onKeyDown.bind(this)),b.util.addListener(this.hiddenTextarea,"keyup",this.onKeyUp.bind(this)),b.util.addListener(this.hiddenTextarea,"input",this.onInput.bind(this)),b.util.addListener(this.hiddenTextarea,"copy",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"cut",this.copy.bind(this)),b.util.addListener(this.hiddenTextarea,"paste",this.paste.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionstart",this.onCompositionStart.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionupdate",this.onCompositionUpdate.bind(this)),b.util.addListener(this.hiddenTextarea,"compositionend",this.onCompositionEnd.bind(this)),!this._clickHandlerInitialized&&this.canvas&&(b.util.addListener(this.canvas.upperCanvasEl,"click",this.onClick.bind(this)),this._clickHandlerInitialized=!0)},keysMap:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorRight",36:"moveCursorLeft",37:"moveCursorLeft",38:"moveCursorUp",39:"moveCursorRight",40:"moveCursorDown"},keysMapRtl:{9:"exitEditing",27:"exitEditing",33:"moveCursorUp",34:"moveCursorDown",35:"moveCursorLeft",36:"moveCursorRight",37:"moveCursorRight",38:"moveCursorUp",39:"moveCursorLeft",40:"moveCursorDown"},ctrlKeysMapUp:{67:"copy",88:"cut"},ctrlKeysMapDown:{65:"selectAll"},onClick:function(){this.hiddenTextarea&&this.hiddenTextarea.focus()},onKeyDown:function(t){if(this.isEditing){var e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}},onKeyUp:function(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())},onInput:function(t){var e=this.fromPaste;if(this.fromPaste=!1,t&&t.stopPropagation(),this.isEditing){var i,n,r,s,a,o=this._splitTextIntoLines(this.hiddenTextarea.value).graphemeText,l=this._text.length,h=o.length,c=h-l,d=this.selectionStart,u=this.selectionEnd,f=d!==u;if(""===this.hiddenTextarea.value)return this.styles={},this.updateFromTextArea(),this.fire("changed"),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll()));var g=this.fromStringToGraphemeSelection(this.hiddenTextarea.selectionStart,this.hiddenTextarea.selectionEnd,this.hiddenTextarea.value),m=d>g.selectionStart;f?(i=this._text.slice(d,u),c+=u-d):h0&&(n+=(i=this.__charBounds[t][e-1]).left+i.width),n},getDownCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(r===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;var s=n.charIndex,a=this._getWidthBeforeCursor(r,s),o=this._getIndexOnLine(r+1,a);return this._textLines[r].slice(s).length+o+1+this.missingNewlineOffset(r)},_getSelectionForOffset:function(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart},getUpCursorOffset:function(t,e){var i=this._getSelectionForOffset(t,e),n=this.get2DCursorLocation(i),r=n.lineIndex;if(0===r||t.metaKey||33===t.keyCode)return-i;var s=n.charIndex,a=this._getWidthBeforeCursor(r,s),o=this._getIndexOnLine(r-1,a),l=this._textLines[r].slice(0,s),h=this.missingNewlineOffset(r-1);return-this._textLines[r-1].length+o-l.length+(1-h)},_getIndexOnLine:function(t,e){for(var i,n,r=this._textLines[t],s=this._getLineLeftOffset(t),a=0,o=0,l=r.length;oe){n=!0;var h=s-i,c=s,d=Math.abs(h-e);a=Math.abs(c-e)=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)},moveCursorUp:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)},_moveCursorUpOrDown:function(t,e){var i=this["get"+t+"CursorOffset"](e,"right"===this._selectionDirection);e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i&&(this.setSelectionInBoundaries(),this.abortCursorAnimation(),this._currentCursorOpacity=1,this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorWithShift:function(t){var e="left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t},moveCursorWithoutShift:function(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t},moveCursorLeft:function(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)},_move:function(t,e,i){var n;if(t.altKey)n=this["findWordBoundary"+i](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;n=this["findLineBoundary"+i](this[e])}if(void 0!==typeof n&&this[e]!==n)return this[e]=n,!0},_moveLeft:function(t,e){return this._move(t,e,"Left")},_moveRight:function(t,e){return this._move(t,e,"Right")},moveCursorLeftWithoutShift:function(t){var e=!0;return this._selectionDirection="left",this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e},moveCursorLeftWithShift:function(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection="left",this._moveLeft(t,"selectionStart")):void 0},moveCursorRight:function(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)},_moveCursorLeftOrRight:function(t,e){var i="moveCursor"+t+"With";this._currentCursorOpacity=1,e.shiftKey?i+="Shift":i+="outShift",this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())},moveCursorRightWithShift:function(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection="right",this._moveRight(t,"selectionEnd")):void 0},moveCursorRightWithoutShift:function(t){var e=!0;return this._selectionDirection="right",this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e},removeChars:function(t,e){void 0===e&&(e=t+1),this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()},insertChars:function(t,e,i,n){void 0===n&&(n=i),n>i&&this.removeStyleFromTo(i,n);var r=b.util.string.graphemeSplit(t);this.insertNewStyleBlock(r,i,e),this._text=[].concat(this._text.slice(0,i),r,this._text.slice(n)),this.text=this._text.join(""),this.set("dirty",!0),this._shouldClearDimensionCache()&&(this.initDimensions(),this.setCoords()),this._removeExtraneousStyles()}}),function(){var t=b.util.toFixed,e=/ +/g;b.util.object.extend(b.Text.prototype,{_toSVG:function(){var t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)},toSVG:function(t){return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0})},_getSVGLeftTopOffsets:function(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}},_wrapSVGTextAndBg:function(t){var e=this.getSvgTextDecoration(this);return[t.textBgRects.join(""),'\t\t",t.textSpans.join(""),"\n"]},_getSVGTextAndBg:function(t,e){var i,n=[],r=[],s=t;this._setSVGBg(r);for(var a=0,o=this._textLines.length;a",b.util.string.escapeXml(i),""].join("")},_setSVGTextLineText:function(t,e,i,n){var r,s,a,o,l,h=this.getHeightOfLine(e),c=-1!==this.textAlign.indexOf("justify"),d="",u=0,f=this._textLines[e];n+=h*(1-this._fontSizeFraction)/this.lineHeight;for(var g=0,m=f.length-1;g<=m;g++)l=g===m||this.charSpacing,d+=f[g],a=this.__charBounds[e][g],0===u?(i+=a.kernedWidth-a.width,u+=a.width):u+=a.kernedWidth,c&&!l&&this._reSpaceAndTab.test(f[g])&&(l=!0),l||(r=r||this.getCompleteStyleDeclaration(e,g),s=this.getCompleteStyleDeclaration(e,g+1),l=this._hasStyleChangedForSvg(r,s)),l&&(o=this._getStyleDeclaration(e,g)||{},t.push(this._createTextCharSpan(d,o,i,n)),d="",r=s,i+=u,u=0)},_pushTextBgRect:function(e,i,n,r,s,a){var o=b.Object.NUM_FRACTION_DIGITS;e.push("\t\t\n')},_setSVGTextLineBg:function(t,e,i,n){for(var r,s,a=this._textLines[e],o=this.getHeightOfLine(e)/this.lineHeight,l=0,h=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),d=0,u=a.length;dthis.width&&this._set("width",this.dynamicMinWidth),-1!==this.textAlign.indexOf("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight(),this.saveState({propertySet:"_dimensionAffectingProps"}))},_generateStyleMap:function(t){for(var e=0,i=0,n=0,r={},s=0;s0?(i=0,n++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[n])&&s>0&&(i++,n++),r[s]={line:e,offset:i},n+=t.graphemeLines[s].length,i+=t.graphemeLines[s].length;return r},styleHas:function(t,i){if(this._styleMap&&!this.isWrapping){var n=this._styleMap[i];n&&(i=n.line)}return e.Text.prototype.styleHas.call(this,t,i)},isEmptyStyles:function(t){if(!this.styles)return!0;var e,i,n=0,r=!1,s=this._styleMap[t],a=this._styleMap[t+1];for(var o in s&&(t=s.line,n=s.offset),a&&(r=a.line===t,e=a.offset),i=void 0===t?this.styles:{line:this.styles[t]})for(var l in i[o])if(l>=n&&(!r||ln&&!p?(o.push(l),l=[],s=f,p=!0):s+=_,p||a||l.push(u),l=l.concat(c),g=a?0:this._measureWord([u],i,d),d++,p=!1,f>m&&(m=f);return v&&o.push(l),m+r>this.dynamicMinWidth&&(this.dynamicMinWidth=m-_+r),o},isEndOfWrapping:function(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line},missingNewlineOffset:function(t){return this.splitByGrapheme?this.isEndOfWrapping(t)?1:0:1},_splitTextIntoLines:function(t){for(var i=e.Text.prototype._splitTextIntoLines.call(this,t),n=this._wrapText(i.lines,this.width),r=new Array(n.length),s=0;s{},898:()=>{},245:()=>{}},ni={};function ri(t){var e=ni[t];if(void 0!==e)return e.exports;var i=ni[t]={exports:{}};return ii[t](i,i.exports,ri),i.exports}ri.d=(t,e)=>{for(var i in e)ri.o(e,i)&&!ri.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:e[i]})},ri.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var si={};(()=>{let t;ri.d(si,{R:()=>t}),t="undefined"!=typeof document&&"undefined"!=typeof window?ri(653).fabric:{version:"5.2.1"}})();var ai,oi,li,hi,ci=si.R;!function(t){t[t.DIMT_RECTANGLE=1]="DIMT_RECTANGLE",t[t.DIMT_QUADRILATERAL=2]="DIMT_QUADRILATERAL",t[t.DIMT_TEXT=4]="DIMT_TEXT",t[t.DIMT_ARC=8]="DIMT_ARC",t[t.DIMT_IMAGE=16]="DIMT_IMAGE",t[t.DIMT_POLYGON=32]="DIMT_POLYGON",t[t.DIMT_LINE=64]="DIMT_LINE",t[t.DIMT_GROUP=128]="DIMT_GROUP"}(ai||(ai={})),function(t){t[t.DIS_DEFAULT=1]="DIS_DEFAULT",t[t.DIS_SELECTED=2]="DIS_SELECTED"}(oi||(oi={})),function(t){t[t.EF_ENHANCED_FOCUS=4]="EF_ENHANCED_FOCUS",t[t.EF_AUTO_ZOOM=16]="EF_AUTO_ZOOM",t[t.EF_TAP_TO_FOCUS=64]="EF_TAP_TO_FOCUS"}(li||(li={})),function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(hi||(hi={}));const di=t=>"number"==typeof t&&!Number.isNaN(t),ui=t=>"string"==typeof t;var fi,gi,mi,pi,_i,vi,yi,wi,Ci,Ei,Si;!function(t){t[t.ARC=0]="ARC",t[t.IMAGE=1]="IMAGE",t[t.LINE=2]="LINE",t[t.POLYGON=3]="POLYGON",t[t.QUAD=4]="QUAD",t[t.RECT=5]="RECT",t[t.TEXT=6]="TEXT",t[t.GROUP=7]="GROUP"}(_i||(_i={})),function(t){t[t.DEFAULT=0]="DEFAULT",t[t.SELECTED=1]="SELECTED"}(vi||(vi={}));class bi{get mediaType(){return new Map([["rect",ai.DIMT_RECTANGLE],["quad",ai.DIMT_QUADRILATERAL],["text",ai.DIMT_TEXT],["arc",ai.DIMT_ARC],["image",ai.DIMT_IMAGE],["polygon",ai.DIMT_POLYGON],["line",ai.DIMT_LINE],["group",ai.DIMT_GROUP]]).get(this._mediaType)}get styleSelector(){switch(Je(this,gi,"f")){case oi.DIS_DEFAULT:return"default";case oi.DIS_SELECTED:return"selected"}}set drawingStyleId(t){this.styleId=t}get drawingStyleId(){return this.styleId}set coordinateBase(t){if(!["view","image"].includes(t))throw new Error("Invalid 'coordinateBase'.");this._drawingLayer&&("image"===Je(this,mi,"f")&&"view"===t?this.updateCoordinateBaseFromImageToView():"view"===Je(this,mi,"f")&&"image"===t&&this.updateCoordinateBaseFromViewToImage()),Ke(this,mi,t)}get coordinateBase(){return Je(this,mi,"f")}get drawingLayerId(){return this._drawingLayerId}constructor(t,e){if(fi.add(this),gi.set(this,void 0),mi.set(this,"image"),this._zIndex=null,this._drawingLayer=null,this._drawingLayerId=null,this._mapState_StyleId=new Map,this.mapEvent_Callbacks=new Map([["selected",new Map],["deselected",new Map],["mousedown",new Map],["mouseup",new Map],["dblclick",new Map],["mouseover",new Map],["mouseout",new Map]]),this.mapNoteName_Content=new Map([]),this.isDrawingItem=!0,null!=e&&!di(e))throw new TypeError("Invalid 'drawingStyleId'.");t&&this._setFabricObject(t),this.setState(oi.DIS_DEFAULT),this.styleId=e}_setFabricObject(t){this._fabricObject=t,this._fabricObject.on("selected",(()=>{this.setState(oi.DIS_SELECTED)})),this._fabricObject.on("deselected",(()=>{this._fabricObject.canvas&&this._fabricObject.canvas.getActiveObjects().includes(this._fabricObject)?this.setState(oi.DIS_SELECTED):this.setState(oi.DIS_DEFAULT),"textbox"===this._fabricObject.type&&(this._fabricObject.isEditing&&this._fabricObject.exitEditing(),this._fabricObject.selected=!1)})),t.getDrawingItem=()=>this}_getFabricObject(){return this._fabricObject}setState(t){Ke(this,gi,t)}getState(){return Je(this,gi,"f")}_on(t,e){if(!e)return;const i=t.toLowerCase(),n=this.mapEvent_Callbacks.get(i);if(!n)throw new Error(`Event '${t}' does not exist.`);let r=n.get(e);r||(r=t=>{const i=t.e;if(!i)return void(e&&e.apply(this,[{targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null}]));const n={targetItem:this,itemClientX:null,itemClientY:null,itemPageX:null,itemPageY:null};if(this._drawingLayer){let t,e,r,s;const a=i.target.getBoundingClientRect();t=a.left,e=a.top,r=t+window.scrollX,s=e+window.scrollY;const{width:o,height:l}=this._drawingLayer.fabricCanvas.lowerCanvasEl.getBoundingClientRect(),h=this._drawingLayer.width,c=this._drawingLayer.height,d=o/l,u=h/c,f=this._drawingLayer._getObjectFit();let g,m,p,_,v=1;if("contain"===f)d0?i-1:n,Oi),actionName:"modifyPolygon",pointIndex:i}),t}),{}),Ke(this,wi,JSON.parse(JSON.stringify(t))),this._mediaType="polygon"}extendSet(t,e){if("vertices"===t){const t=this._fabricObject;if(t.group){const i=t.group;t.points=e.map((t=>({x:t.x-i.left-i.width/2,y:t.y-i.top-i.height/2}))),i.addWithUpdate()}else t.points=e;const i=t.points.length-1;return t.controls=t.points.reduce((function(t,e,n){return t["p"+n]=new ci.Control({positionHandler:Ii,actionHandler:Ai(n>0?n-1:i,Oi),actionName:"modifyPolygon",pointIndex:n}),t}),{}),t._setPositionDimensions({}),!0}}extendGet(t){if("vertices"===t){const t=[],e=this._fabricObject;if(e.selectable&&!e.group)for(let i in e.oCoords)t.push({x:e.oCoords[i].x,y:e.oCoords[i].y});else for(let i of e.points){let n=i.x-e.pathOffset.x,r=i.y-e.pathOffset.y;const s=ci.util.transformPoint({x:n,y:r},e.calcTransformMatrix());t.push({x:s.x,y:s.y})}return t}}updateCoordinateBaseFromImageToView(){const t=this.get("vertices").map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",t)}updateCoordinateBaseFromViewToImage(){const t=this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})));this.set("vertices",t)}setPosition(t){this.setPolygon(t)}getPosition(){return this.getPolygon()}updatePosition(){Je(this,wi,"f")&&this.setPolygon(Je(this,wi,"f"))}setPolygon(t){if(!I(t))throw new TypeError("Invalid 'polygon'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Ke(this,wi,JSON.parse(JSON.stringify(t)))}getPolygon(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Je(this,wi,"f")?JSON.parse(JSON.stringify(Je(this,wi,"f"))):null}}wi=new WeakMap;class Di extends bi{set maintainAspectRatio(t){t&&this.set("scaleY",this.get("scaleX"))}get maintainAspectRatio(){return Je(this,Ei,"f")}constructor(t,e,i,n){if(super(null,n),Ci.set(this,void 0),Ei.set(this,void 0),!O(e))throw new TypeError("Invalid 'rect'.");if(t instanceof HTMLImageElement||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement)this._setFabricObject(new ci.Image(t,{left:e.x,top:e.y}));else{if(!C(t))throw new TypeError("Invalid 'image'.");{const i=document.createElement("canvas");let n;if(i.width=t.width,i.height=t.height,t.format===o.IPF_GRAYSCALED){n=new Uint8ClampedArray(t.width*t.height*4);for(let e=0;e{let e=(t=>t.split("\n").map((t=>t.split("\t"))))(t);return(t=>{for(let e=0;;e++){let i=-1;for(let n=0;ni&&(i=r.length)}if(-1===i)break;for(let n=0;n=t[n].length-1)continue;let r=" ".repeat(i+2-t[n][e].length);t[n][e]=t[n][e].concat(r)}}})(e),(t=>{let e="";for(let i=0;i({x:e.x-t.left-t.width/2,y:e.y-t.top-t.height/2}))),t.addWithUpdate()}else i.points=e;const n=i.points.length-1;return i.controls=i.points.reduce((function(t,e,i){return t["p"+i]=new ci.Control({positionHandler:Ii,actionHandler:Ai(i>0?i-1:n,Oi),actionName:"modifyPolygon",pointIndex:i}),t}),{}),i._setPositionDimensions({}),!0}}extendGet(t){if("startPoint"===t||"endPoint"===t){const e=[],i=this._fabricObject;if(i.selectable&&!i.group)for(let t in i.oCoords)e.push({x:i.oCoords[t].x,y:i.oCoords[t].y});else for(let t of i.points){let n=t.x-i.pathOffset.x,r=t.y-i.pathOffset.y;const s=ci.util.transformPoint({x:n,y:r},i.calcTransformMatrix());e.push({x:s.x,y:s.y})}return"startPoint"===t?e[0]:e[1]}}updateCoordinateBaseFromImageToView(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(e.x),y:this.convertPropFromViewToImage(e.y)})}updateCoordinateBaseFromViewToImage(){const t=this.get("startPoint"),e=this.get("endPoint");this.set("startPoint",{x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)}),this.set("endPoint",{x:this.convertPropFromImageToView(e.x),y:this.convertPropFromImageToView(e.y)})}setPosition(t){this.setLine(t)}getPosition(){return this.getLine()}updatePosition(){Je(this,Fi,"f")&&this.setLine(Je(this,Fi,"f"))}setPolygon(){}getPolygon(){return null}setLine(t){if(!b(t))throw new TypeError("Invalid 'line'.");if(this._drawingLayer){if("view"===this.coordinateBase)this.set("startPoint",{x:this.convertPropFromViewToImage(t.startPoint.x),y:this.convertPropFromViewToImage(t.startPoint.y)}),this.set("endPoint",{x:this.convertPropFromViewToImage(t.endPoint.x),y:this.convertPropFromViewToImage(t.endPoint.y)});else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("startPoint",t.startPoint),this.set("endPoint",t.endPoint)}this._drawingLayer.renderAll()}else Ke(this,Fi,JSON.parse(JSON.stringify(t)))}getLine(){if(this._drawingLayer){if("view"===this.coordinateBase)return{startPoint:{x:this.convertPropFromImageToView(this.get("startPoint").x),y:this.convertPropFromImageToView(this.get("startPoint").y)},endPoint:{x:this.convertPropFromImageToView(this.get("endPoint").x),y:this.convertPropFromImageToView(this.get("endPoint").y)}};if("image"===this.coordinateBase)return{startPoint:this.get("startPoint"),endPoint:this.get("endPoint")};throw new Error("Invalid 'coordinateBase'.")}return Je(this,Fi,"f")?JSON.parse(JSON.stringify(Je(this,Fi,"f"))):null}}Fi=new WeakMap;class Ni extends Ri{constructor(t,e){if(super({points:null==t?void 0:t.points},e),Pi.set(this,void 0),!x(t))throw new TypeError("Invalid 'quad'.");Ke(this,Pi,JSON.parse(JSON.stringify(t))),this._mediaType="quad"}setPosition(t){this.setQuad(t)}getPosition(){return this.getQuad()}updatePosition(){Je(this,Pi,"f")&&this.setQuad(Je(this,Pi,"f"))}setPolygon(){}getPolygon(){return null}setQuad(t){if(!x(t))throw new TypeError("Invalid 'quad'.");if(this._drawingLayer){if("view"===this.coordinateBase){const e=t.points.map((t=>({x:this.convertPropFromViewToImage(t.x),y:this.convertPropFromViewToImage(t.y)})));this.set("vertices",e)}else{if("image"!==this.coordinateBase)throw new Error("Invalid 'coordinateBase'.");this.set("vertices",t.points)}this._drawingLayer.renderAll()}else Ke(this,Pi,JSON.parse(JSON.stringify(t)))}getQuad(){if(this._drawingLayer){if("view"===this.coordinateBase)return{points:this.get("vertices").map((t=>({x:this.convertPropFromImageToView(t.x),y:this.convertPropFromImageToView(t.y)})))};if("image"===this.coordinateBase)return{points:this.get("vertices")};throw new Error("Invalid 'coordinateBase'.")}return Je(this,Pi,"f")?JSON.parse(JSON.stringify(Je(this,Pi,"f"))):null}}Pi=new WeakMap;class Bi extends bi{constructor(t){super(new ci.Group(t.map((t=>t._getFabricObject())))),this._fabricObject.on("selected",(()=>{this.setState(oi.DIS_SELECTED);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("selected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._fabricObject.on("deselected",(()=>{this.setState(oi.DIS_DEFAULT);const t=this._fabricObject._objects;for(let e of t)setTimeout((()=>{e&&e.fire("deselected")}),0);setTimeout((()=>{this._fabricObject&&this._fabricObject.canvas&&(this._fabricObject.dirty=!0,this._fabricObject.canvas.renderAll())}),0)})),this._mediaType="group"}extendSet(t,e){return!1}extendGet(t){}updateCoordinateBaseFromImageToView(){}updateCoordinateBaseFromViewToImage(){}setPosition(){}getPosition(){}updatePosition(){}getChildDrawingItems(){return this._fabricObject._objects.map((t=>t.getDrawingItem()))}setChildDrawingItems(t){if(!t||!t.isDrawingItem)throw TypeError("Illegal drawing item.");this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"add"):this._fabricObject.addWithUpdate(t._getFabricObject())}removeChildItem(t){t&&t.isDrawingItem&&(this._drawingLayer?this._drawingLayer._updateGroupItem(this,t,"remove"):this._fabricObject.removeWithUpdate(t._getFabricObject()))}}const ji=t=>null!==t&&"object"==typeof t&&!Array.isArray(t),Vi=t=>!!ui(t)&&""!==t,Ui=t=>!(!ji(t)||"id"in t&&!di(t.id)||"lineWidth"in t&&!di(t.lineWidth)||"fillStyle"in t&&!Vi(t.fillStyle)||"strokeStyle"in t&&!Vi(t.strokeStyle)||"paintMode"in t&&!["fill","stroke","strokeAndFill"].includes(t.paintMode)||"fontFamily"in t&&!Vi(t.fontFamily)||"fontSize"in t&&!di(t.fontSize));class Gi{static convert(t,e,i){const n={x:0,y:0,width:e,height:i};if(!t)return n;if(O(t))t.isMeasuredInPercentage?(n.x=t.x/100*e,n.y=t.y/100*i,n.width=t.width/100*e,n.height=t.height/100*i):(n.x=t.x,n.y=t.y,n.width=t.width,n.height=t.height);else{if(!E(t))throw TypeError("Invalid region.");t.isMeasuredInPercentage?(n.x=t.left/100*e,n.y=t.top/100*i,n.width=(t.right-t.left)/100*e,n.height=(t.bottom-t.top)/100*i):(n.x=t.left,n.y=t.top,n.width=t.right-t.left,n.height=t.bottom-t.top)}return n.x=Math.round(n.x),n.y=Math.round(n.y),n.width=Math.round(n.width),n.height=Math.round(n.height),n}}var Wi,Yi;class zi{constructor(){Wi.set(this,new Map),Yi.set(this,!1)}get disposed(){return Je(this,Yi,"f")}on(t,e){t=t.toLowerCase();const i=Je(this,Wi,"f").get(t);if(i){if(i.includes(e))return;i.push(e)}else Je(this,Wi,"f").set(t,[e])}off(t,e){t=t.toLowerCase();const i=Je(this,Wi,"f").get(t);if(!i)return;const n=i.indexOf(e);-1!==n&&i.splice(n,1)}offAll(t){t=t.toLowerCase();const e=Je(this,Wi,"f").get(t);e&&(e.length=0)}fire(t,e=[],i={async:!1,copy:!0}){e||(e=[]),t=t.toLowerCase();const n=Je(this,Wi,"f").get(t);if(n&&n.length){i=Object.assign({async:!1,copy:!0},i);for(let r of n){if(!r)continue;let s=[];if(i.copy)for(let i of e){try{i=JSON.parse(JSON.stringify(i))}catch(t){}s.push(i)}else s=e;let a=!1;if(i.async)setTimeout((()=>{this.disposed||n.includes(r)&&r.apply(i.target,s)}),0);else try{a=r.apply(i.target,s)}catch(t){}if(!0===a)break}}}dispose(){Ke(this,Yi,!0)}}function Hi(t,e,i){return(i.x-t.x)*(e.y-t.y)==(e.x-t.x)*(i.y-t.y)&&Math.min(t.x,e.x)<=i.x&&i.x<=Math.max(t.x,e.x)&&Math.min(t.y,e.y)<=i.y&&i.y<=Math.max(t.y,e.y)}function Xi(t){return Math.abs(t)<1e-6?0:t<0?-1:1}function Zi(t,e,i,n){let r=t[0]*(i[1]-e[1])+e[0]*(t[1]-i[1])+i[0]*(e[1]-t[1]),s=t[0]*(n[1]-e[1])+e[0]*(t[1]-n[1])+n[0]*(e[1]-t[1]);return!((r^s)>=0&&0!==r&&0!==s||(r=i[0]*(t[1]-n[1])+n[0]*(i[1]-t[1])+t[0]*(n[1]-i[1]),s=i[0]*(e[1]-n[1])+n[0]*(i[1]-e[1])+e[0]*(n[1]-i[1]),(r^s)>=0&&0!==r&&0!==s))}Wi=new WeakMap,Yi=new WeakMap;const qi=async t=>{if("string"!=typeof t)throw new TypeError("Invalid url.");const e=await fetch(t);if(!e.ok)throw Error("Network Error: "+e.statusText);const i=await e.text();if(!i.trim().startsWith("<"))throw Error("Unable to get valid HTMLElement.");const n=document.createElement("div");if(n.insertAdjacentHTML("beforeend",i),1===n.childElementCount&&n.firstChild instanceof HTMLTemplateElement)return n.firstChild.content;const r=new DocumentFragment;for(let t of n.children)r.append(t);return r};var Ji,Ki,$i,Qi,tn,en,nn,rn,sn,an,on,ln,hn,cn,dn,un,fn,gn,mn,pn,_n,vn,yn,wn,Cn,En,Sn,bn,Tn,In,xn,On,An,Rn;class Dn{static createDrawingStyle(t){if(!Ui(t))throw new Error("Invalid style definition.");let e,i=Dn.USER_START_STYLE_ID;for(;Je(Dn,Ji,"f",Ki).has(i);)i++;e=i;const n=JSON.parse(JSON.stringify(t));n.id=e;for(let t in Je(Dn,Ji,"f",$i))n.hasOwnProperty(t)||(n[t]=Je(Dn,Ji,"f",$i)[t]);return Je(Dn,Ji,"f",Ki).set(e,n),n.id}static _getDrawingStyle(t,e){if("number"!=typeof t)throw new Error("Invalid style id.");const i=Je(Dn,Ji,"f",Ki).get(t);return i?e?JSON.parse(JSON.stringify(i)):i:null}static getDrawingStyle(t){return this._getDrawingStyle(t,!0)}static getAllDrawingStyles(){return JSON.parse(JSON.stringify(Array.from(Je(Dn,Ji,"f",Ki).values())))}static _updateDrawingStyle(t,e){if(!Ui(e))throw new Error("Invalid style definition.");const i=Je(Dn,Ji,"f",Ki).get(t);if(i)for(let t in e)i.hasOwnProperty(t)&&(i[t]=e[t])}static updateDrawingStyle(t,e){this._updateDrawingStyle(t,e)}}Ji=Dn,Dn.STYLE_BLUE_STROKE=1,Dn.STYLE_GREEN_STROKE=2,Dn.STYLE_ORANGE_STROKE=3,Dn.STYLE_YELLOW_STROKE=4,Dn.STYLE_BLUE_STROKE_FILL=5,Dn.STYLE_GREEN_STROKE_FILL=6,Dn.STYLE_ORANGE_STROKE_FILL=7,Dn.STYLE_YELLOW_STROKE_FILL=8,Dn.STYLE_BLUE_STROKE_TRANSPARENT=9,Dn.STYLE_GREEN_STROKE_TRANSPARENT=10,Dn.STYLE_ORANGE_STROKE_TRANSPARENT=11,Dn.USER_START_STYLE_ID=1024,Ki={value:new Map([[Dn.STYLE_BLUE_STROKE,{id:Dn.STYLE_BLUE_STROKE,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_GREEN_STROKE,{id:Dn.STYLE_GREEN_STROKE,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_ORANGE_STROKE,{id:Dn.STYLE_ORANGE_STROKE,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_YELLOW_STROKE,{id:Dn.STYLE_YELLOW_STROKE,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_BLUE_STROKE_FILL,{id:Dn.STYLE_BLUE_STROKE_FILL,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.3)",strokeStyle:"rgba(73, 173, 245, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_GREEN_STROKE_FILL,{id:Dn.STYLE_GREEN_STROKE_FILL,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.3)",strokeStyle:"rgba(73, 245, 73, 0.9)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_ORANGE_STROKE_FILL,{id:Dn.STYLE_ORANGE_STROKE_FILL,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.3)",strokeStyle:"rgba(254, 180, 32, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_YELLOW_STROKE_FILL,{id:Dn.STYLE_YELLOW_STROKE_FILL,lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_BLUE_STROKE_TRANSPARENT,{id:Dn.STYLE_BLUE_STROKE_TRANSPARENT,lineWidth:4,fillStyle:"rgba(73, 173, 245, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_GREEN_STROKE_TRANSPARENT,{id:Dn.STYLE_GREEN_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(73, 245, 73, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}],[Dn.STYLE_ORANGE_STROKE_TRANSPARENT,{id:Dn.STYLE_ORANGE_STROKE_TRANSPARENT,lineWidth:2,fillStyle:"rgba(254, 180, 32, 0.2)",strokeStyle:"transparent",paintMode:"strokeAndFill",fontFamily:"consolas",fontSize:40}]])},$i={value:{lineWidth:2,fillStyle:"rgba(245, 236, 73, 0.3)",strokeStyle:"rgba(245, 236, 73, 1)",paintMode:"stroke",fontFamily:"consolas",fontSize:40}},"undefined"!=typeof document&&"undefined"!=typeof window&&(ci.StaticCanvas.prototype.dispose=function(){return this.isRendering&&(ci.util.cancelAnimFrame(this.isRendering),this.isRendering=0),this.forEachObject((function(t){t.dispose&&t.dispose()})),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose&&this.backgroundImage.dispose(),this.backgroundImage=null,this.overlayImage&&this.overlayImage.dispose&&this.overlayImage.dispose(),this.overlayImage=null,this._iTextInstances=null,this.contextContainer=null,this.lowerCanvasEl.classList.remove("lower-canvas"),delete this._originalCanvasStyle,this.lowerCanvasEl.setAttribute("width",this.width),this.lowerCanvasEl.setAttribute("height",this.height),ci.util.cleanUpJsdomNode(this.lowerCanvasEl),this.lowerCanvasEl=void 0,this},ci.Object.prototype.transparentCorners=!1,ci.Object.prototype.cornerSize=20,ci.Object.prototype.touchCornerSize=100,ci.Object.prototype.cornerColor="rgb(254,142,20)",ci.Object.prototype.cornerStyle="circle",ci.Object.prototype.strokeUniform=!0,ci.Object.prototype.hasBorders=!1,ci.Canvas.prototype.containerClass="",ci.Canvas.prototype.getPointer=function(t,e){if(this._absolutePointer&&!e)return this._absolutePointer;if(this._pointer&&e)return this._pointer;var i,n=this.upperCanvasEl,r=ci.util.getPointer(t,n),s=n.getBoundingClientRect(),a=s.width||0,o=s.height||0;a&&o||("top"in s&&"bottom"in s&&(o=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(a=Math.abs(s.right-s.left))),this.calcOffset(),r.x=r.x-this._offset.left,r.y=r.y-this._offset.top,e||(r=this.restorePointerVpt(r));var l=this.getRetinaScaling();if(1!==l&&(r.x/=l,r.y/=l),0!==a&&0!==o){var h=window.getComputedStyle(n).objectFit,c=n.width,d=n.height,u=a,f=o;i={width:c/u,height:d/f};var g,m,p=c/d,_=u/f;return"contain"===h?p>_?(g=u,m=u/p,{x:r.x*i.width,y:(r.y-(f-m)/2)*i.width}):(g=f*p,m=f,{x:(r.x-(u-g)/2)*i.height,y:r.y*i.height}):"cover"===h?p>_?{x:(c-i.height*u)/2+r.x*i.height,y:r.y*i.height}:{x:r.x*i.width,y:(d-i.width*f)/2+r.y*i.width}:{x:r.x*i.width,y:r.y*i.height}}return i={width:1,height:1},{x:r.x*i.width,y:r.y*i.height}},ci.Canvas.prototype._onTouchStart=function(t){var e=this.findTarget(t);!this.allowTouchScrolling&&t.cancelable&&t.preventDefault&&t.preventDefault(),e&&t.cancelable&&t.preventDefault&&t.preventDefault(),null===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),this._resetTransformEventData();var i=this.upperCanvasEl,n=this._getEventPrefix();ci.util.addListener(ci.document,"touchend",this._onTouchEnd,{passive:!1}),ci.util.addListener(ci.document,"touchmove",this._onMouseMove,{passive:!1}),ci.util.removeListener(i,n+"down",this._onMouseDown)},ci.Textbox.prototype._wrapLine=function(t,e,i,n){const r=t.match(/[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/g),s=!(!r||!r.length);var a=0,o=this.splitByGrapheme||s,l=[],h=[],c=o?ci.util.string.graphemeSplit(t):t.split(this._wordJoiners),d="",u=0,f=o?"":" ",g=0,m=0,p=0,_=!0,v=this._getWidthOfCharSpacing();n=n||0,0===c.length&&c.push([]),i-=n;for(var y=0;yi&&!_?(l.push(h),h=[],a=g,_=!0):a+=v,_||o||h.push(f),h=h.concat(d),m=o?0:this._measureWord([f],e,u),u++,_=!1,g>p&&(p=g);return y&&l.push(h),p+n>this.dynamicMinWidth&&(this.dynamicMinWidth=p-v+n),l});class Ln{get width(){return this.fabricCanvas.width}get height(){return this.fabricCanvas.height}set _allowMultiSelect(t){this.fabricCanvas.selection=t,this.fabricCanvas.renderAll()}get _allowMultiSelect(){return this.fabricCanvas.selection}constructor(t,e,i){if(this.mapType_StateAndStyleId=new Map,this.mode="viewer",this.onSelectionChanged=null,this._arrDrwaingItem=[],this._arrFabricObject=[],this._visible=!0,t.hasOwnProperty("getFabricCanvas"))this.fabricCanvas=t.getFabricCanvas();else{let e=this.fabricCanvas=new ci.Canvas(t,Object.assign(i,{allowTouchScrolling:!0,selection:!1}));e.setDimensions({width:"100%",height:"100%"},{cssOnly:!0}),e.lowerCanvasEl.className="",e.upperCanvasEl.className="",e.on("selection:created",(function(t){const e=t.selected,i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(i,[])}),0)}})),e.on("before:selection:cleared",(function(t){const e=this.getActiveObjects(),i=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!i.includes(e)&&i.push(e)}for(let t of i){const i=[];for(let n of e){const e=n.getDrawingItem();e._drawingLayer===t&&i.push(e)}setTimeout((()=>{const e=[];for(let n of i)t.hasDrawingItem(n)&&e.push(n);e.length>0&&t.onSelectionChanged&&t.onSelectionChanged([],e)}),0)}})),e.on("selection:updated",(function(t){const e=t.selected,i=t.deselected,n=[];for(let t of e){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of i){const e=t.getDrawingItem()._drawingLayer;e&&!n.includes(e)&&n.push(e)}for(let t of n){const n=[],r=[];for(let i of e){const e=i.getDrawingItem();e._drawingLayer===t&&n.push(e)}for(let e of i){const i=e.getDrawingItem();i._drawingLayer===t&&r.push(i)}setTimeout((()=>{t.onSelectionChanged&&t.onSelectionChanged(n,r)}),0)}})),e.wrapperEl.style.position="absolute",t.getFabricCanvas=()=>this.fabricCanvas}let n,r;switch(this.id=e,e){case Ln.DDN_LAYER_ID:n=Dn.getDrawingStyle(Dn.STYLE_BLUE_STROKE),r=Dn.getDrawingStyle(Dn.STYLE_BLUE_STROKE_FILL);break;case Ln.DBR_LAYER_ID:n=Dn.getDrawingStyle(Dn.STYLE_ORANGE_STROKE),r=Dn.getDrawingStyle(Dn.STYLE_ORANGE_STROKE_FILL);break;case Ln.DLR_LAYER_ID:n=Dn.getDrawingStyle(Dn.STYLE_GREEN_STROKE),r=Dn.getDrawingStyle(Dn.STYLE_GREEN_STROKE_FILL);break;default:n=Dn.getDrawingStyle(Dn.STYLE_YELLOW_STROKE),r=Dn.getDrawingStyle(Dn.STYLE_YELLOW_STROKE_FILL)}for(let t of bi.arrMediaTypes)this.mapType_StateAndStyleId.set(t,{default:n.id,selected:r.id})}getId(){return this.id}setVisible(t){if(t){for(let t of this._arrFabricObject)t.visible=!0,t.hasControls=!0;this._visible=!0}else{for(let t of this._arrFabricObject)t.visible=!1,t.hasControls=!1;this._visible=!1}this.fabricCanvas.renderAll()}isVisible(){return this._visible}_getItemCurrentStyle(t){if(t.styleId)return Dn.getDrawingStyle(t.styleId);return Dn.getDrawingStyle(t._mapState_StyleId.get(t.styleSelector))||null}_changeMediaTypeCurStyleInStyleSelector(t,e,i,n){const r=this.getDrawingItems((e=>e._mediaType===t));for(let t of r)t.styleSelector===e&&this._changeItemStyle(t,i,!0);n||this.fabricCanvas.renderAll()}_changeItemStyle(t,e,i){if(!t||!e)return;const n=t._getFabricObject();"number"==typeof t.styleId&&(e=Dn.getDrawingStyle(t.styleId)),n.strokeWidth=e.lineWidth,"fill"===e.paintMode?(n.fill=e.fillStyle,n.stroke=e.fillStyle):"stroke"===e.paintMode?(n.fill="transparent",n.stroke=e.strokeStyle):"strokeAndFill"===e.paintMode&&(n.fill=e.fillStyle,n.stroke=e.strokeStyle),n.fontFamily&&(n.fontFamily=e.fontFamily),n.fontSize&&(n.fontSize=e.fontSize),n.group||(n.dirty=!0),i||this.fabricCanvas.renderAll()}_updateGroupItem(t,e,i){if(!t||!e)return;const n=t.getChildDrawingItems();if("add"===i){if(n.includes(e))return;const i=e._getFabricObject();if(this.fabricCanvas.getObjects().includes(i)){if(!this._arrFabricObject.includes(i))throw new Error("Existed in other drawing layers.");e._zIndex=null}else{let i;if(e.styleId)i=Dn.getDrawingStyle(e.styleId);else{const n=this.mapType_StateAndStyleId.get(e._mediaType);i=Dn.getDrawingStyle(n[t.styleSelector]);const r=()=>{this._changeItemStyle(e,Dn.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).selected),!0)},s=()=>{this._changeItemStyle(e,Dn.getDrawingStyle(this.mapType_StateAndStyleId.get(e._mediaType).default),!0)};e._on("selected",r),e._on("deselected",s),e._funcChangeStyleToSelected=r,e._funcChangeStyleToDefault=s}e._drawingLayer=this,e._drawingLayerId=this.id,this._changeItemStyle(e,i,!0)}t._fabricObject.addWithUpdate(e._getFabricObject())}else{if("remove"!==i)return;if(!n.includes(e))return;e._zIndex=null,e._drawingLayer=null,e._drawingLayerId=null,e._off("selected",e._funcChangeStyleToSelected),e._off("deselected",e._funcChangeStyleToDefault),e._funcChangeStyleToSelected=null,e._funcChangeStyleToDefault=null,t._fabricObject.removeWithUpdate(e._getFabricObject())}this.fabricCanvas.renderAll()}_addDrawingItem(t,e){if(!(t instanceof bi))throw new TypeError("Invalid 'drawingItem'.");if(t._drawingLayer){if(t._drawingLayer==this)return;throw new Error("This drawing item has existed in other layer.")}let i=t._getFabricObject();const n=this.fabricCanvas.getObjects();let r,s;if(n.includes(i)){if(this._arrFabricObject.includes(i))return;throw new Error("Existed in other drawing layers.")}if("group"===t._mediaType){r=t.getChildDrawingItems();for(let t of r)if(t._drawingLayer&&t._drawingLayer!==this)throw new Error("The childItems of DT_Group have existed in other drawing layers.")}if(e&&"object"==typeof e&&!Array.isArray(e))for(let t in e)i.set(t,e[t]);if(r){for(let t of r){const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of bi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Dn.getDrawingStyle(t.styleId);else{s=Dn.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Dn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected),!0)},n=()=>{this._changeItemStyle(t,Dn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default),!0)};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}t._drawingLayer=this,t._drawingLayerId=this.id,this._changeItemStyle(t,s,!0)}i.dirty=!0,this.fabricCanvas.renderAll()}else{const e=this.mapType_StateAndStyleId.get(t._mediaType);for(let i of bi.arrStyleSelectors)t._mapState_StyleId.set(i,e[i]);if(t.styleId)s=Dn.getDrawingStyle(t.styleId);else{s=Dn.getDrawingStyle(e.default);const i=()=>{this._changeItemStyle(t,Dn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).selected))},n=()=>{this._changeItemStyle(t,Dn.getDrawingStyle(this.mapType_StateAndStyleId.get(t._mediaType).default))};t._on("selected",i),t._on("deselected",n),t._funcChangeStyleToSelected=i,t._funcChangeStyleToDefault=n}this._changeItemStyle(t,s)}t._zIndex=this.id,t._drawingLayer=this,t._drawingLayerId=this.id;const a=this._arrFabricObject.length;let o=n.length;if(a)o=n.indexOf(this._arrFabricObject[a-1])+1;else for(let e=0;et.toLowerCase())):e=bi.arrMediaTypes,i?i.forEach((t=>t.toLowerCase())):i=bi.arrStyleSelectors;const n=Dn.getDrawingStyle(t);if(!n)throw new Error(`The 'drawingStyle' with id '${t}' doesn't exist.`);let r;for(let s of e)if(r=this.mapType_StateAndStyleId.get(s),r)for(let e of i){this._changeMediaTypeCurStyleInStyleSelector(s,e,n,!0),r[e]=t;for(let i of this._arrDrwaingItem)i._mediaType===s&&i._mapState_StyleId.set(e,t)}this.fabricCanvas.renderAll()}setDefaultStyle(t,e,i){const n=[];i&ai.DIMT_RECTANGLE&&n.push("rect"),i&ai.DIMT_QUADRILATERAL&&n.push("quad"),i&ai.DIMT_TEXT&&n.push("text"),i&ai.DIMT_ARC&&n.push("arc"),i&ai.DIMT_IMAGE&&n.push("image"),i&ai.DIMT_POLYGON&&n.push("polygon"),i&ai.DIMT_LINE&&n.push("line");const r=[];e&oi.DIS_DEFAULT&&r.push("default"),e&oi.DIS_SELECTED&&r.push("selected"),this._setDefaultStyle(t,n.length?n:null,r.length?r:null)}setMode(t){if("viewer"===(t=t.toLowerCase())){for(let t of this._arrDrwaingItem)t._setEditable(!1);this.fabricCanvas.discardActiveObject(),this.fabricCanvas.renderAll(),this.mode="viewer"}else{if("editor"!==t)throw new RangeError("Invalid value.");for(let t of this._arrDrwaingItem)t._setEditable(!0);this.mode="editor"}this._manager._switchPointerEvent()}getMode(){return this.mode}_setDimensions(t,e){this.fabricCanvas.setDimensions(t,e)}_setObjectFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);this.fabricCanvas.lowerCanvasEl.style.objectFit=t,this.fabricCanvas.upperCanvasEl.style.objectFit=t}_getObjectFit(){return this.fabricCanvas.lowerCanvasEl.style.objectFit}renderAll(){for(let t of this._arrDrwaingItem){const e=this._getItemCurrentStyle(t);this._changeItemStyle(t,e,!0)}this.fabricCanvas.renderAll()}dispose(){this.clearDrawingItems(),1===this._manager._arrDrawingLayer.length&&(this.fabricCanvas.wrapperEl.style.pointerEvents="none",this.fabricCanvas.dispose(),this._arrDrwaingItem.length=0,this._arrFabricObject.length=0)}}Ln.DDN_LAYER_ID=1,Ln.DBR_LAYER_ID=2,Ln.DLR_LAYER_ID=3,Ln.USER_DEFINED_LAYER_BASE_ID=100,Ln.TIP_LAYER_ID=999;class Mn{constructor(){this._arrDrawingLayer=[]}createDrawingLayer(t,e){if(this.getDrawingLayer(e))throw new Error("Existed drawing layer id.");const i=new Ln(t,e,{enableRetinaScaling:!1});return i._manager=this,this._arrDrawingLayer.push(i),this._switchPointerEvent(),i}deleteDrawingLayer(t){const e=this.getDrawingLayer(t);if(!e)return;const i=this._arrDrawingLayer;e.dispose(),i.splice(i.indexOf(e),1),this._switchPointerEvent()}clearDrawingLayers(){for(let t of this._arrDrawingLayer)t.dispose();this._arrDrawingLayer.length=0}getDrawingLayer(t){for(let e of this._arrDrawingLayer)if(e.getId()===t)return e;return null}getAllDrawingLayers(){return Array.from(this._arrDrawingLayer)}getSelectedDrawingItems(){if(!this._arrDrawingLayer.length)return;const t=this._getFabricCanvas().getActiveObjects(),e=[];for(let i of t)e.push(i.getDrawingItem());return e}setDimensions(t,e){this._arrDrawingLayer.length&&this._arrDrawingLayer[0]._setDimensions(t,e)}setObjectFit(t){for(let e of this._arrDrawingLayer)e&&e._setObjectFit(t)}getObjectFit(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0]._getObjectFit():null}setVisible(t){if(!this._arrDrawingLayer.length)return;this._getFabricCanvas().wrapperEl.style.display=t?"block":"none"}_getFabricCanvas(){return this._arrDrawingLayer.length?this._arrDrawingLayer[0].fabricCanvas:null}_switchPointerEvent(){if(this._arrDrawingLayer.length)for(let t of this._arrDrawingLayer)t.getMode()}}class Fn extends Mi{constructor(t,e,i,n,r){super(t,{x:e,y:i,width:n,height:0},r),Qi.set(this,void 0),tn.set(this,void 0),this._fabricObject.paddingTop=15,this._fabricObject.calcTextHeight=function(){for(var t=0,e=0,i=this._textLines.length;e=0&&Ke(this,tn,setTimeout((()=>{this.set("visible",!1),this._drawingLayer&&this._drawingLayer.renderAll()}),Je(this,Qi,"f")))}getDuration(){return Je(this,Qi,"f")}}Qi=new WeakMap,tn=new WeakMap;class Pn{constructor(){en.add(this),nn.set(this,void 0),rn.set(this,void 0),sn.set(this,void 0),an.set(this,!0),this._drawingLayerManager=new Mn}createDrawingLayerBaseCvs(t,e,i="contain"){if("number"!=typeof t||t<=1)throw new Error("Invalid 'width'.");if("number"!=typeof e||e<=1)throw new Error("Invalid 'height'.");if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");const n=document.createElement("canvas");return n.width==t&&n.height==e||(n.width=t,n.height=e),n.style.objectFit=i,n}_createDrawingLayer(t,e,i,n){if(!this._layerBaseCvs){let r;try{r=this.getContentDimensions()}catch(t){if("Invalid content dimensions."!==(t.message||t))throw t}e||(e=(null==r?void 0:r.width)||1280),i||(i=(null==r?void 0:r.height)||720),n||(n=(null==r?void 0:r.objectFit)||"contain"),this._layerBaseCvs=this.createDrawingLayerBaseCvs(e,i,n)}const r=this._layerBaseCvs,s=this._drawingLayerManager.createDrawingLayer(r,t);return this._innerComponent.getElement("drawing-layer")||this._innerComponent.setElement("drawing-layer",r.parentElement),s}createDrawingLayer(){let t;for(let e=Ln.USER_DEFINED_LAYER_BASE_ID;;e++)if(!this._drawingLayerManager.getDrawingLayer(e)&&e!==Ln.TIP_LAYER_ID){t=e;break}return this._createDrawingLayer(t)}deleteDrawingLayer(t){var e;this._drawingLayerManager.deleteDrawingLayer(t),this._drawingLayerManager.getAllDrawingLayers().length||(null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null)}deleteUserDefinedDrawingLayer(t){if("number"!=typeof t)throw new TypeError("Invalid id.");if(tt.getId()>=0&&t.getId()!==Ln.TIP_LAYER_ID))}updateDrawingLayers(t){((t,e,i)=>{if(!(t<=1||e<=1)){if(!["contain","cover"].includes(i))throw new Error("Unsupported 'objectFit'.");this._drawingLayerManager.setDimensions({width:t,height:e},{backstoreOnly:!0}),this._drawingLayerManager.setObjectFit(i)}})(t.width,t.height,t.objectFit)}getSelectedDrawingItems(){return this._drawingLayerManager.getSelectedDrawingItems()}setTipConfig(t){if(!(ji(e=t)&&T(e.topLeftPoint)&&di(e.width))||e.width<=0||!di(e.duration)||"coordinateBase"in e&&!["view","image"].includes(e.coordinateBase))throw new Error("Invalid tip config.");var e;Ke(this,nn,JSON.parse(JSON.stringify(t))),Je(this,nn,"f").coordinateBase||(Je(this,nn,"f").coordinateBase="view"),Ke(this,sn,t.duration),Je(this,en,"m",cn).call(this)}getTipConfig(){return Je(this,nn,"f")?Je(this,nn,"f"):null}setTipVisible(t){if("boolean"!=typeof t)throw new TypeError("Invalid value.");this._tip&&(this._tip.set("visible",t),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll()),Ke(this,an,t)}isTipVisible(){return Je(this,an,"f")}updateTipMessage(t){if(!Je(this,nn,"f"))throw new Error("Tip config is not set.");this._tipStyleId||(this._tipStyleId=Dn.createDrawingStyle({fillStyle:"#FFFFFF",paintMode:"fill",fontFamily:"Open Sans",fontSize:40})),this._drawingLayerOfTip||(this._drawingLayerOfTip=this._drawingLayerManager.getDrawingLayer(Ln.TIP_LAYER_ID)||this._createDrawingLayer(Ln.TIP_LAYER_ID)),this._tip?this._tip.set("text",t):this._tip=Je(this,en,"m",on).call(this,t,Je(this,nn,"f").topLeftPoint.x,Je(this,nn,"f").topLeftPoint.y,Je(this,nn,"f").width,Je(this,nn,"f").coordinateBase,this._tipStyleId),Je(this,en,"m",ln).call(this,this._tip,this._drawingLayerOfTip),this._tip.set("visible",Je(this,an,"f")),this._drawingLayerOfTip&&this._drawingLayerOfTip.renderAll(),Je(this,rn,"f")&&clearTimeout(Je(this,rn,"f")),Je(this,sn,"f")>=0&&Ke(this,rn,setTimeout((()=>{Je(this,en,"m",hn).call(this)}),Je(this,sn,"f")))}}nn=new WeakMap,rn=new WeakMap,sn=new WeakMap,an=new WeakMap,en=new WeakSet,on=function(t,e,i,n,r,s){const a=new Fn(t,e,i,n,s);return a.coordinateBase=r,a},ln=function(t,e){e.hasDrawingItem(t)||e.addDrawingItems([t])},hn=function(){this._tip&&this._drawingLayerOfTip.removeDrawingItems([this._tip])},cn=function(){if(!this._tip)return;const t=Je(this,nn,"f");this._tip.coordinateBase=t.coordinateBase,this._tip.setTextRect({x:t.topLeftPoint.x,y:t.topLeftPoint.y,width:t.width,height:0}),this._tip.set("width",this._tip.get("width")),this._tip._drawingLayer&&this._tip._drawingLayer.renderAll()};class kn extends HTMLElement{constructor(){super(),dn.set(this,void 0);const t=new DocumentFragment,e=document.createElement("div");e.setAttribute("class","wrapper"),t.appendChild(e),Ke(this,dn,e);const i=document.createElement("slot");i.setAttribute("name","single-frame-input-container"),e.append(i);const n=document.createElement("slot");n.setAttribute("name","content"),e.append(n);const r=document.createElement("slot");r.setAttribute("name","drawing-layer"),e.append(r);const s=document.createElement("style");s.textContent='\n.wrapper {\n position: relative;\n width: 100%;\n height: 100%;\n}\n::slotted(canvas[slot="content"]) {\n object-fit: contain;\n pointer-events: none;\n}\n::slotted(div[slot="single-frame-input-container"]) {\n width: 1px;\n height: 1px;\n overflow: hidden;\n pointer-events: none;\n}\n::slotted(*) {\n position: absolute;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n}\n ',t.appendChild(s),this.attachShadow({mode:"open"}).appendChild(t)}getWrapper(){return Je(this,dn,"f")}setElement(t,e){if(!(e instanceof HTMLElement))throw new TypeError("Invalid 'el'.");if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");this.removeElement(t),e.setAttribute("slot",t),this.appendChild(e)}getElement(t){if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");return this.querySelector(`[slot="${t}"]`)}removeElement(t){var e;if(!["content","single-frame-input-container","drawing-layer"].includes(t))throw new TypeError("Invalid 'slot'.");null===(e=this.querySelectorAll(`[slot="${t}"]`))||void 0===e||e.forEach((t=>t.remove()))}}dn=new WeakMap,customElements.get("dce-component")||customElements.define("dce-component",kn);class Nn extends Pn{static get engineResourcePath(){return L(vt.engineResourcePaths).dce}static set defaultUIElementURL(t){Nn._defaultUIElementURL=t}static get defaultUIElementURL(){var t;return null===(t=Nn._defaultUIElementURL)||void 0===t?void 0:t.replace("@engineResourcePath/",Nn.engineResourcePath)}static async createInstance(t){const e=new Nn;return"string"==typeof t&&(t=t.replace("@engineResourcePath/",Nn.engineResourcePath)),await e.setUIElement(t||Nn.defaultUIElementURL),e}static _transformCoordinates(t,e,i,n,r,s,a){const o=s/n,l=a/r;t.x=Math.round(t.x/o+e),t.y=Math.round(t.y/l+i)}set _singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(t!==Je(this,Cn,"f")){if(Ke(this,Cn,t),Je(this,un,"m",bn).call(this))Ke(this,pn,null),this._videoContainer=null,this._innerComponent.removeElement("content"),this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block");else if(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none"),!Je(this,pn,"f")){const t=document.createElement("video");t.style.position="absolute",t.style.left="0",t.style.top="0",t.style.width="100%",t.style.height="100%",t.style.objectFit=this.getVideoFit(),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(Ze.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ke(this,pn,t);const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}Je(this,un,"m",bn).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading())}}get _singleFrameMode(){return Je(this,Cn,"f")}get disposed(){return Je(this,Sn,"f")}constructor(){super(),un.add(this),fn.set(this,void 0),gn.set(this,void 0),mn.set(this,void 0),this.containerClassName="dce-video-container",pn.set(this,void 0),this.videoFit="contain",this._hideDefaultSelection=!1,this._divScanArea=null,this._divScanLight=null,this._bgLoading=null,this._selCam=null,this._bgCamera=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,_n.set(this,null),this.regionMaskFillStyle="rgba(0,0,0,0.5)",this.regionMaskStrokeStyle="rgb(254,142,20)",this.regionMaskLineWidth=6,vn.set(this,!1),yn.set(this,!1),wn.set(this,{width:0,height:0}),this._updateLayersTimeout=500,this._videoResizeListener=()=>{Je(this,un,"m",An).call(this),this._updateLayersTimeoutId&&clearTimeout(this._updateLayersTimeoutId),this._updateLayersTimeoutId=setTimeout((()=>{this.disposed||(this.eventHandler.fire("videoEl:resized",null,{async:!1}),this.eventHandler.fire("content:updated",null,{async:!1}),this.isScanLaserVisible()&&Je(this,un,"m",On).call(this))}),this._updateLayersTimeout)},this._windowResizeListener=()=>{Nn._onLog&&Nn._onLog("window resize event triggered."),Je(this,wn,"f").width===document.documentElement.clientWidth&&Je(this,wn,"f").height===document.documentElement.clientHeight||(Je(this,wn,"f").width=document.documentElement.clientWidth,Je(this,wn,"f").height=document.documentElement.clientHeight,this._videoResizeListener())},Cn.set(this,"disabled"),this._clickIptSingleFrameMode=()=>{if(!Je(this,un,"m",bn).call(this))return;let t;if(this._singleFrameInputContainer)t=this._singleFrameInputContainer.firstElementChild;else{t=document.createElement("input"),t.setAttribute("type","file"),"camera"===this._singleFrameMode?(t.setAttribute("capture",""),t.setAttribute("accept","image/*")):"image"===this._singleFrameMode&&(t.removeAttribute("capture"),t.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp")),t.addEventListener("change",(async()=>{const e=t.files[0];t.value="";{const t=async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise(((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i},i=(t,e,i,n)=>{t.width==i&&t.height==n||(t.width=i,t.height=n);const r=t.getContext("2d");r.clearRect(0,0,t.width,t.height),r.drawImage(e,0,0)},n=await t(e),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let a=this._cvsSingleFrameMode;const o=null==a?void 0:a.width,l=null==a?void 0:a.height;a||(a=document.createElement("canvas"),this._cvsSingleFrameMode=a),i(a,n,r,s),this._innerComponent.setElement("content",a),o===a.width&&l===a.height||this.eventHandler.fire("content:updated",null,{async:!1})}this._onSingleFrameAcquired&&setTimeout((()=>{this._onSingleFrameAcquired(this._cvsSingleFrameMode)}),0)})),t.style.position="absolute",t.style.top="-9999px",t.style.backgroundColor="transparent",t.style.color="transparent";const e=document.createElement("div");e.append(t),this._innerComponent.setElement("single-frame-input-container",e),this._singleFrameInputContainer=e}null==t||t.click()},En.set(this,[]),this._capturedResultReceiver={onCapturedResultReceived:(t,e)=>{var i,n,r,s;if(this.disposed)return;if(this.clearAllInnerDrawingItems(),!t)return;const a=t.originalImageTag;if(!a)return;const o=t.items;if(!(null==o?void 0:o.length))return;const l=(null===(i=a.cropRegion)||void 0===i?void 0:i.left)||0,h=(null===(n=a.cropRegion)||void 0===n?void 0:n.top)||0,c=(null===(r=a.cropRegion)||void 0===r?void 0:r.right)?a.cropRegion.right-l:a.originalWidth,d=(null===(s=a.cropRegion)||void 0===s?void 0:s.bottom)?a.cropRegion.bottom-h:a.originalHeight,u=a.currentWidth,f=a.currentHeight,g=(t,e,i,n,r,s,a,o,l=[],h)=>{e.forEach((t=>Nn._transformCoordinates(t,i,n,r,s,a,o)));const c=new Ni({points:[{x:e[0].x,y:e[0].y},{x:e[1].x,y:e[1].y},{x:e[2].x,y:e[2].y},{x:e[3].x,y:e[3].y}]},h);for(let t of l)c.addNote(t);t.addDrawingItems([c]),Je(this,En,"f").push(c)};let m,p;for(let t of o)switch(t.type){case yt.CRIT_ORIGINAL_IMAGE:break;case yt.CRIT_BARCODE:m=this.getDrawingLayer(Ln.DBR_LAYER_ID),p=[{name:"format",content:t.formatString},{name:"text",content:t.text}],(null==e?void 0:e.isBarcodeVerifyOpen)?t.verified?g(m,t.location.points,l,h,c,d,u,f,p):g(m,t.location.points,l,h,c,d,u,f,p,Dn.STYLE_ORANGE_STROKE_TRANSPARENT):g(m,t.location.points,l,h,c,d,u,f,p);break;case yt.CRIT_TEXT_LINE:m=this.getDrawingLayer(Ln.DLR_LAYER_ID),p=[{name:"text",content:t.text}],e.isLabelVerifyOpen?t.verified?g(m,t.location.points,l,h,c,d,u,f,p):g(m,t.location.points,l,h,c,d,u,f,p,Dn.STYLE_GREEN_STROKE_TRANSPARENT):g(m,t.location.points,l,h,c,d,u,f,p);break;case yt.CRIT_DETECTED_QUAD:m=this.getDrawingLayer(Ln.DDN_LAYER_ID),(null==e?void 0:e.isDetectVerifyOpen)?t.crossVerificationStatus===xt.CVS_PASSED?g(m,t.location.points,l,h,c,d,u,f,[]):g(m,t.location.points,l,h,c,d,u,f,[],Dn.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,l,h,c,d,u,f,[]);break;case yt.CRIT_NORMALIZED_IMAGE:m=this.getDrawingLayer(Ln.DDN_LAYER_ID),(null==e?void 0:e.isNormalizeVerifyOpen)?t.crossVerificationStatus===xt.CVS_PASSED?g(m,t.location.points,l,h,c,d,u,f,[]):g(m,t.location.points,l,h,c,d,u,f,[],Dn.STYLE_BLUE_STROKE_TRANSPARENT):g(m,t.location.points,l,h,c,d,u,f,[]);break;case yt.CRIT_PARSED_RESULT:break;default:throw new Error("Illegal item type.")}}},Sn.set(this,!1),this.eventHandler=new zi,this.eventHandler.on("content:updated",(()=>{Je(this,fn,"f")&&clearTimeout(Je(this,fn,"f")),Ke(this,fn,setTimeout((()=>{if(this.disposed)return;let t;this._updateVideoContainer();try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateDrawingLayers(t),this.updateConvertedRegion(t)}),0))})),this.eventHandler.on("videoEl:resized",(()=>{Je(this,gn,"f")&&clearTimeout(Je(this,gn,"f")),Ke(this,gn,setTimeout((()=>{this.disposed||this._updateVideoContainer()}),0))}))}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await qi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i.cloneNode(!0))}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){var t,e;if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;let i=this.UIElement;i=i.shadowRoot||i;let n=(null===(t=i.classList)||void 0===t?void 0:t.contains(this.containerClassName))?i:i.querySelector(`.${this.containerClassName}`);if(!n)throw Error(`Can not find the element with class '${this.containerClassName}'.`);if(this._innerComponent=document.createElement("dce-component"),n.appendChild(this._innerComponent),Je(this,un,"m",bn).call(this));else{const t=document.createElement("video");Object.assign(t.style,{position:"absolute",left:"0",top:"0",width:"100%",height:"100%",objectFit:this.getVideoFit()}),t.setAttribute("autoplay","true"),t.setAttribute("playsinline","true"),t.setAttribute("muted","true"),["iPhone","iPad","Mac"].includes(Ze.OS)&&t.setAttribute("poster","data:image/gif;base64,R0lGODlhAQABAIEAAAAAAAAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAgEAAEEBAA7"),Ke(this,pn,t);const e=document.createElement("div");e.append(t),e.style.overflow="hidden",this._videoContainer=e,this._innerComponent.setElement("content",e)}if(this._selRsl=i.querySelector(".dce-sel-resolution"),this._selMinLtr=i.querySelector(".dlr-sel-minletter"),this._divScanArea=i.querySelector(".dce-scanarea"),this._divScanLight=i.querySelector(".dce-scanlight"),this._bgLoading=i.querySelector(".dce-bg-loading"),this._bgCamera=i.querySelector(".dce-bg-camera"),this._selCam=i.querySelector(".dce-sel-camera"),this._optGotRsl=i.querySelector(".dce-opt-gotResolution"),this._btnClose=i.querySelector(".dce-btn-close"),this._optGotMinLtr=i.querySelector(".dlr-opt-gotMinLtr"),this._selRsl&&(this._hideDefaultSelection||Je(this,un,"m",bn).call(this)||this._selRsl.options.length||(this._selRsl.innerHTML=['','','',''].join(""),this._optGotRsl=this._selRsl.options[0])),this._selMinLtr&&(this._hideDefaultSelection||Je(this,un,"m",bn).call(this)||this._selMinLtr.options.length||(this._selMinLtr.innerHTML=['','','','','','','','','','',''].join(""),this._optGotMinLtr=this._selMinLtr.options[0])),this.isScanLaserVisible()||Je(this,un,"m",An).call(this),Je(this,un,"m",bn).call(this)&&(this._innerComponent&&(this._innerComponent.addEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.setAttribute("title","Take a photo")),this._bgCamera&&(this._bgCamera.style.display="block")),Je(this,un,"m",bn).call(this)||this._hideDefaultSelection?(this._selCam&&(this._selCam.style.display="none"),this._selRsl&&(this._selRsl.style.display="none"),this._selMinLtr&&(this._selMinLtr.style.display="none")):(this._selCam&&(this._selCam.style.display="block"),this._selRsl&&(this._selRsl.style.display="block"),this._selMinLtr&&(this._selMinLtr.style.display="block"),this._stopLoading()),window.ResizeObserver){this._resizeObserver||(this._resizeObserver=new ResizeObserver((t=>{var e;Nn._onLog&&Nn._onLog("resize observer triggered.");for(let i of t)i.target===(null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper())&&this._videoResizeListener()})));const t=null===(e=this._innerComponent)||void 0===e?void 0:e.getWrapper();t&&this._resizeObserver.observe(t)}Je(this,wn,"f").width=document.documentElement.clientWidth,Je(this,wn,"f").height=document.documentElement.clientHeight,window.addEventListener("resize",this._windowResizeListener)}_unbindUI(){var t,e,i,n;Je(this,un,"m",bn).call(this)?(this._innerComponent&&(this._innerComponent.removeEventListener("click",this._clickIptSingleFrameMode),this._innerComponent.removeAttribute("title")),this._bgCamera&&(this._bgCamera.style.display="none")):this._stopLoading(),Je(this,un,"m",An).call(this),null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,this._drawingLayerOfMask=null,this._drawingLayerOfTip=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null,Ke(this,pn,null),null===(n=this._videoContainer)||void 0===n||n.remove(),this._videoContainer=null,this._selCam=null,this._selRsl=null,this._optGotRsl=null,this._btnClose=null,this._selMinLtr=null,this._optGotMinLtr=null,this._divScanArea=null,this._divScanLight=null,this._singleFrameInputContainer&&(this._singleFrameInputContainer.remove(),this._singleFrameInputContainer=null),window.ResizeObserver&&this._resizeObserver&&this._resizeObserver.disconnect(),window.removeEventListener("resize",this._windowResizeListener)}_startLoading(){this._bgLoading&&(this._bgLoading.style.display="",this._bgLoading.style.animationPlayState="")}_stopLoading(){this._bgLoading&&(this._bgLoading.style.display="none",this._bgLoading.style.animationPlayState="paused")}_renderCamerasInfo(t,e){if(this._selCam){let i;this._selCam.textContent="";for(let n of e){const e=document.createElement("option");e.value=n.deviceId,e.innerText=n.label,this._selCam.append(e),n.deviceId&&t&&t.deviceId==n.deviceId&&(i=e)}this._selCam.value=i?i.value:""}let i=this.UIElement;if(i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=i.querySelector(".dce-mn-cameras");if(t){t.textContent="";for(let i of e){const e=document.createElement("div");e.classList.add("dce-mn-camera-option"),e.setAttribute("data-davice-id",i.deviceId),e.textContent=i.label,t.append(e)}}}}_renderResolutionInfo(t){this._optGotRsl&&(this._optGotRsl.setAttribute("data-width",t.width),this._optGotRsl.setAttribute("data-height",t.height),this._optGotRsl.innerText="got "+t.width+"x"+t.height,this._selRsl&&this._optGotRsl.parentNode==this._selRsl&&(this._selRsl.value="got"));{let e=this.UIElement;e=(null==e?void 0:e.shadowRoot)||e;let i=null==e?void 0:e.querySelector(".dce-mn-resolution-box");if(i){let e="";if(t&&t.width&&t.height){let i=Math.max(t.width,t.height),n=Math.min(t.width,t.height);e=n<=1080?n+"P":i<3e3?"2K":Math.round(i/1e3)+"K"}i.textContent=e}}}getVideoElement(){return Je(this,pn,"f")}isVideoLoaded(){return!(!Je(this,pn,"f")||!this.cameraEnhancer)&&this.cameraEnhancer.isOpen()}setVideoFit(t){if(t=t.toLowerCase(),!["contain","cover"].includes(t))throw new Error(`Unsupported value '${t}'.`);if(this.videoFit=t,!Je(this,pn,"f"))return;if(Je(this,pn,"f").style.objectFit=t,Je(this,un,"m",bn).call(this))return;let e;this._updateVideoContainer();try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Je(this,un,"m",Rn).call(this,e,this.getConvertedRegion()),this.updateDrawingLayers(e)}getVideoFit(){return this.videoFit}getContentDimensions(){var t,e,i,n;let r,s,a;if(Je(this,un,"m",bn).call(this)?(r=null===(i=this._cvsSingleFrameMode)||void 0===i?void 0:i.width,s=null===(n=this._cvsSingleFrameMode)||void 0===n?void 0:n.height,a="contain"):(r=null===(t=Je(this,pn,"f"))||void 0===t?void 0:t.videoWidth,s=null===(e=Je(this,pn,"f"))||void 0===e?void 0:e.videoHeight,a=this.getVideoFit()),!r||!s)throw new Error("Invalid content dimensions.");return{width:r,height:s,objectFit:a}}updateConvertedRegion(t){const e=Gi.convert(this.scanRegion,t.width,t.height);Ke(this,_n,e),Je(this,mn,"f")&&clearTimeout(Je(this,mn,"f")),Ke(this,mn,setTimeout((()=>{let t;try{t=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}Je(this,un,"m",Tn).call(this,t,e),Je(this,un,"m",Rn).call(this,t,e)}),0))}getConvertedRegion(){return Je(this,_n,"f")}setScanRegion(t){if(null!=t&&!E(t)&&!O(t))throw TypeError("Invalid 'region'.");let e;this.scanRegion=t?JSON.parse(JSON.stringify(t)):null;try{e=this.getContentDimensions()}catch(t){if("Invalid content dimensions."===(t.message||t))return;throw t}this.updateConvertedRegion(e)}getScanRegion(){return JSON.parse(JSON.stringify(this.scanRegion))}getVisibleRegionOfVideo(t){if(!this.isVideoLoaded())throw new Error("The video is not loaded.");const e=Je(this,pn,"f").videoWidth,i=Je(this,pn,"f").videoHeight,n=this.getVideoFit(),{width:r,height:s}=this._innerComponent.getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");let a;const o={x:0,y:0,width:e,height:i,isMeasuredInPercentage:!1};if("cover"===n&&(r/s1){const t=Je(this,pn,"f").videoWidth,e=Je(this,pn,"f").videoHeight,{width:n,height:r}=this._innerComponent.getBoundingClientRect(),s=t/e;if(n/rt.remove())),Je(this,En,"f").length=0}dispose(){this._unbindUI(),Ke(this,Sn,!0)}}function Bn(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}function jn(t,e,i,n,r){if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,i),i}fn=new WeakMap,gn=new WeakMap,mn=new WeakMap,pn=new WeakMap,_n=new WeakMap,vn=new WeakMap,yn=new WeakMap,wn=new WeakMap,Cn=new WeakMap,En=new WeakMap,Sn=new WeakMap,un=new WeakSet,bn=function(){return"disabled"!==this._singleFrameMode},Tn=function(t,e){!e||0===e.x&&0===e.y&&e.width===t.width&&e.height===t.height?this.clearScanRegionMask():this.setScanRegionMask(e.x,e.y,e.width,e.height)},In=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!0)},xn=function(){this._drawingLayerOfMask&&this._drawingLayerOfMask.setVisible(!1)},On=function(){this._divScanLight&&"none"==this._divScanLight.style.display&&(this._divScanLight.style.display="block")},An=function(){this._divScanLight&&(this._divScanLight.style.display="none")},Rn=function(t,e){if(!this._divScanArea)return;if(!this._innerComponent.getElement("content"))return;const{width:i,height:n,objectFit:r}=t;e||(e={x:0,y:0,width:i,height:n});const{width:s,height:a}=this._innerComponent.getBoundingClientRect();if(s<=0||a<=0)return;const o=s/a,l=i/n;let h,c,d,u,f=1;if("contain"===r)o66||"Safari"===zn.browser&&zn.version>13||"OPR"===zn.browser&&zn.version>43||"Edge"===zn.browser&&zn.version,"function"==typeof SuppressedError&&SuppressedError;class Zn{static multiply(t,e){const i=[];for(let n=0;n<3;n++){const r=e.slice(3*n,3*n+3);for(let e=0;e<3;e++){const n=[t[e],t[e+3],t[e+6]].reduce(((t,e,i)=>t+e*r[i]),0);i.push(n)}}return i}static identity(){return[1,0,0,0,1,0,0,0,1]}static translate(t,e,i){return Zn.multiply(t,[1,0,0,0,1,0,e,i,1])}static rotate(t,e){var i=Math.cos(e),n=Math.sin(e);return Zn.multiply(t,[i,-n,0,n,i,0,0,0,1])}static scale(t,e,i){return Zn.multiply(t,[e,0,0,0,i,0,0,0,1])}}var qn,Jn,Kn,$n,Qn,tr,er,ir,nr,rr,sr,ar,or,lr,hr,cr,dr,ur,fr,gr,mr,pr,_r,vr,yr,wr,Cr,Er,Sr,br,Tr,Ir,xr,Or,Ar,Rr,Dr,Lr,Mr,Fr,Pr,kr,Nr,Br,jr,Vr,Ur,Gr,Wr,Yr;!function(t){t.GREY="grey",t.GREY32="grey32",t.RGBA="rgba",t.RBGA="rbga",t.GRBA="grba",t.GBRA="gbra",t.BRGA="brga",t.BGRA="bgra"}(qn||(qn={}));class zr{static get version(){return"1.1.3"}static get webGLSupported(){return void 0===zr._webGLSupported&&(zr._webGLSupported=!!document.createElement("canvas").getContext("webgl")),zr._webGLSupported}get disposed(){return Hn(this,er,"f")}constructor(){Jn.set(this,qn.RGBA),Kn.set(this,null),$n.set(this,null),Qn.set(this,null),this.useWebGLByDefault=!0,this._reusedCvs=null,this._reusedWebGLCvs=null,tr.set(this,null),er.set(this,!1)}drawImage(t,e,i,n,r,s){if(this.disposed)throw Error("The 'ImageDataGetter' instance has been disposed.");if(!i||!n)throw new Error("Invalid 'sourceWidth' or 'sourceHeight'.");if((null==s?void 0:s.bUseWebGL)&&!zr.webGLSupported)throw new Error("Your browser or machine may not support WebGL.");if(e instanceof HTMLVideoElement&&4!==e.readyState||e instanceof HTMLImageElement&&!e.complete)throw new Error("The source is not loaded.");let a;zr._onLog&&(a=Date.now(),zr._onLog("drawImage(), START: "+a));let o=0,l=0,h=i,c=n,d=0,u=0,f=i,g=n;r&&(r.sx&&(o=Math.round(r.sx)),r.sy&&(l=Math.round(r.sy)),r.sWidth&&(h=Math.round(r.sWidth)),r.sHeight&&(c=Math.round(r.sHeight)),r.dx&&(d=Math.round(r.dx)),r.dy&&(u=Math.round(r.dy)),r.dWidth&&(f=Math.round(r.dWidth)),r.dHeight&&(g=Math.round(r.dHeight)));let m,p=qn.RGBA;if((null==s?void 0:s.pixelFormat)&&(p=s.pixelFormat),(null==s?void 0:s.bufferContainer)&&(m=s.bufferContainer,m.length<4*f*g))throw new Error("Unexpected size of the 'bufferContainer'.");const _=t;if(!zr.webGLSupported||!(this.useWebGLByDefault&&null==(null==s?void 0:s.bUseWebGL)||(null==s?void 0:s.bUseWebGL))){zr._onLog&&zr._onLog("drawImage() in context2d."),_.ctx2d||(_.ctx2d=_.getContext("2d",{willReadFrequently:!0}));const t=_.ctx2d;if(!t)throw new Error("Unable to get 'CanvasRenderingContext2D' from canvas.");return(_.width{const e=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,e),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW);const i=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([0,0,0,1,1,0,1,0,0,1,1,1]),t.STATIC_DRAW),{positions:e,texCoords:i}},i=t=>{const e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e},n=(t,e)=>{const i=t.createProgram();if(e.forEach((e=>t.attachShader(i,e))),t.linkProgram(i),!t.getProgramParameter(i,t.LINK_STATUS)){const e=new Error(`An error occured linking the program: ${t.getProgramInfoLog(i)}.`);throw e.name="WebGLError",e}return t.useProgram(i),i},r=(t,e,i)=>{const n=t.createShader(e);if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){const e=new Error(`An error occured compiling the shader: ${t.getShaderInfoLog(n)}.`);throw e.name="WebGLError",e}return n},s="\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\n\nuniform mat3 u_matrix;\nuniform mat3 u_textureMatrix;\n\nvarying vec2 v_texCoord;\nvoid main(void) {\ngl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1.0);\nv_texCoord = vec4((u_textureMatrix * vec3(a_texCoord, 1)).xy, 0, 1.0).xy;\n}";let a="rgb";["rgba","rbga","grba","gbra","brga","bgra"].includes(p)&&(a=p.slice(0,3));const o=`\nprecision mediump float;\nvarying vec2 v_texCoord;\nuniform sampler2D u_image;\nuniform float uColorFactor;\n\nvoid main() {\nvec4 sample = texture2D(u_image, v_texCoord);\nfloat grey = 0.3 * sample.r + 0.59 * sample.g + 0.11 * sample.b;\ngl_FragColor = vec4(sample.${a} * (1.0 - uColorFactor) + (grey * uColorFactor), sample.a);\n}`,l=n(t,[r(t,t.VERTEX_SHADER,s),r(t,t.FRAGMENT_SHADER,o)]);Xn(this,$n,{program:l,attribLocations:{vertexPosition:t.getAttribLocation(l,"a_position"),texPosition:t.getAttribLocation(l,"a_texCoord")},uniformLocations:{uSampler:t.getUniformLocation(l,"u_image"),uColorFactor:t.getUniformLocation(l,"uColorFactor"),uMatrix:t.getUniformLocation(l,"u_matrix"),uTextureMatrix:t.getUniformLocation(l,"u_textureMatrix")}}),Xn(this,Qn,e(t)),Xn(this,Kn,i(t)),Xn(this,Jn,p)}const r=(t,e,i)=>{t.bindBuffer(t.ARRAY_BUFFER,e),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0)},s=(t,e,i)=>{const n=t.RGBA,r=t.RGBA,s=t.UNSIGNED_BYTE;t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,n,r,s,i)},v=(t,e,s,a)=>{t.clearColor(0,0,0,1),t.clearDepth(1),t.enable(t.DEPTH_TEST),t.depthFunc(t.LEQUAL),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),r(t,s.positions,e.attribLocations.vertexPosition),r(t,s.texCoords,e.attribLocations.texPosition),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,a),t.uniform1i(e.uniformLocations.uSampler,0),t.uniform1f(e.uniformLocations.uColorFactor,[qn.GREY,qn.GREY32].includes(p)?1:0);let m,_,v=Zn.translate(Zn.identity(),-1,-1);v=Zn.scale(v,2,2),v=Zn.scale(v,1/t.canvas.width,1/t.canvas.height),m=Zn.translate(v,d,u),m=Zn.scale(m,f,g),t.uniformMatrix3fv(e.uniformLocations.uMatrix,!1,m),_=Zn.translate(Zn.identity(),o/i,l/n),_=Zn.scale(_,h/i,c/n),t.uniformMatrix3fv(e.uniformLocations.uTextureMatrix,!1,_),t.drawArrays(t.TRIANGLES,0,6)};s(t,Hn(this,Kn,"f"),e),v(t,Hn(this,$n,"f"),Hn(this,Qn,"f"),Hn(this,Kn,"f"));const y=m||new Uint8Array(4*f*g);if(t.readPixels(d,u,f,g,t.RGBA,t.UNSIGNED_BYTE,y),255!==y[3]){zr._onLog&&zr._onLog("Incorrect WebGL drawing .");const t=new Error("WebGL error: incorrect drawing.");throw t.name="WebGLError",t}return zr._onLog&&zr._onLog("drawImage() in WebGL end. Costs: "+(Date.now()-a)),{context:t,pixelFormat:p===qn.GREY?qn.GREY32:p,bUseWebGL:!0}}catch(a){if(this.forceLoseContext(),null==(null==s?void 0:s.bUseWebGL))return zr._onLog&&zr._onLog("'drawImage()' in WebGL failed, try again in context2d."),this.useWebGLByDefault=!1,this.drawImage(t,e,i,n,r,Object.assign({},s,{bUseWebGL:!1}));throw a.name="WebGLError",a}}readCvsData(t,e,i){if(!(t instanceof CanvasRenderingContext2D||t instanceof WebGLRenderingContext))throw new Error("Invalid 'context'.");let n,r=0,s=0,a=t.canvas.width,o=t.canvas.height;if(e&&(e.x&&(r=e.x),e.y&&(s=e.y),e.width&&(a=e.width),e.height&&(o=e.height)),(null==i?void 0:i.length)<4*a*o)throw new Error("Unexpected size of the 'bufferContainer'.");if(t instanceof WebGLRenderingContext){const e=t;i?(e.readPixels(r,s,a,o,e.RGBA,e.UNSIGNED_BYTE,i),n=new Uint8Array(i.buffer,0,4*a*o)):(n=new Uint8Array(4*a*o),e.readPixels(r,s,a,o,e.RGBA,e.UNSIGNED_BYTE,n))}else if(t instanceof CanvasRenderingContext2D){let e;e=t.getImageData(r,s,a,o),n=new Uint8Array(e.data.buffer),null==i||i.set(n)}return n}transformPixelFormat(t,e,i,n){let r,s;if(zr._onLog&&(r=Date.now(),zr._onLog("transformPixelFormat(), START: "+r)),e===i)return zr._onLog&&zr._onLog("transformPixelFormat() end. Costs: "+(Date.now()-r)),n?new Uint8Array(t):t;const a=[qn.RGBA,qn.RBGA,qn.GRBA,qn.GBRA,qn.BRGA,qn.BGRA];if(a.includes(e))if(i===qn.GREY){s=new Uint8Array(t.length/4);for(let e=0;el||e.sy+e.sHeight>h)throw new Error("Invalid position.");null===(n=zr._onLog)||void 0===n||n.call(zr,"getImageData(), START: "+(c=Date.now()));const u=Math.round(e.sx),f=Math.round(e.sy),g=Math.round(e.sWidth),m=Math.round(e.sHeight),p=Math.round(e.dWidth),_=Math.round(e.dHeight);let v,y=(null==i?void 0:i.pixelFormat)||qn.RGBA,w=null==i?void 0:i.bufferContainer;if(w&&(qn.GREY===y&&w.length{this.disposed||n.includes(r)&&r.apply(i.target,s)}),0);else try{a=r.apply(i.target,s)}catch(t){}if(!0===a)break}}}dispose(){jn(this,nr,!0)}}ir=new WeakMap,nr=new WeakMap;const Xr=(t,e,i,n)=>{if(!i)return t;let r=e+Math.round((t-e)/i)*i;return n&&(r=Math.min(r,n)),r};class Zr{static get version(){return"2.0.18"}static isStorageAvailable(t){let e;try{e=window[t];const i="__storage_test__";return e.setItem(i,i),e.removeItem(i),!0}catch(t){return t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e&&0!==e.length}}static findBestRearCameraInIOS(t,e){if(!t||!t.length)return null;let i=!1;if((null==e?void 0:e.getMainCamera)&&(i=!0),i){const e=["후면 카메라","背面カメラ","後置鏡頭","后置相机","กล้องด้านหลัง","बैक कैमरा","الكاميرا الخلفية","מצלמה אחורית","камера на задней панели","задня камера","задна камера","артқы камера","πίσω κάμερα","zadní fotoaparát","zadná kamera","tylny aparat","takakamera","stražnja kamera","rückkamera","kamera på baksidan","kamera belakang","kamera bak","hátsó kamera","fotocamera (posteriore)","câmera traseira","câmara traseira","cámara trasera","càmera posterior","caméra arrière","cameră spate","camera mặt sau","camera aan achterzijde","bagsidekamera","back camera","arka kamera"],i=t.find((t=>e.includes(t.label.toLowerCase())));return null==i?void 0:i.deviceId}{const e=["후면","背面","後置","后置","านหลัง","बैक","خلفية","אחורית","задняя","задней","задна","πίσω","zadní","zadná","tylny","trasera","traseira","taka","stražnja","spate","sau","rück","posteriore","posterior","hátsó","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"],i=["트리플","三镜头","三鏡頭","トリプル","สาม","ट्रिपल","ثلاثية","משולשת","үштік","тройная","тройна","потроєна","τριπλή","üçlü","trójobiektywowy","trostruka","trojný","trojitá","trippelt","trippel","triplă","triple","tripla","tiga","kolmois","ba camera"],n=["듀얼 와이드","雙廣角","双广角","デュアル広角","คู่ด้านหลังมุมกว้าง","ड्युअल वाइड","مزدوجة عريضة","כפולה רחבה","қос кең бұрышты","здвоєна ширококутна","двойная широкоугольная","двойна широкоъгълна","διπλή ευρεία","çift geniş","laajakulmainen kaksois","kép rộng mặt sau","kettős, széles látószögű","grande angular dupla","ganda","dwuobiektywowy","dwikamera","dvostruka široka","duální širokoúhlý","duálna širokouhlá","dupla grande-angular","dublă","dubbel vidvinkel","dual-weitwinkel","dual wide","dual con gran angular","dual","double","doppia con grandangolo","doble","dobbelt vidvinkelkamera"],r=t.filter((t=>{const i=t.label.toLowerCase();return e.some((t=>i.includes(t)))}));if(!r.length)return null;const s=r.find((t=>{const e=t.label.toLowerCase();return i.some((t=>e.includes(t)))}));if(s)return s.deviceId;const a=r.find((t=>{const e=t.label.toLowerCase();return n.some((t=>e.includes(t)))}));return a?a.deviceId:r[0].deviceId}}static findBestRearCamera(t,e){if(!t||!t.length)return null;if(["iPhone","iPad","Mac"].includes(zn.OS))return Zr.findBestRearCameraInIOS(t,{getMainCamera:null==e?void 0:e.getMainCameraInIOS});const i=["후","背面","背置","後面","後置","后面","后置","านหลัง","หลัง","बैक","خلفية","אחורית","задняя","задня","задней","задна","πίσω","zadní","zadná","tylny","trás","trasera","traseira","taka","stražnja","spate","sau","rück","rear","posteriore","posterior","hátsó","darrere","belakang","baksidan","bakre","bak","bagside","back","aртқы","arrière","arka","achterzijde"];for(let e of t){const t=e.label.toLowerCase();if(t&&i.some((e=>t.includes(e)))&&/\b0(\b)?/.test(t))return e.deviceId}return["Android","HarmonyOS"].includes(zn.OS)?t[t.length-1].deviceId:null}static findBestCamera(t,e,i){return t&&t.length?"environment"===e?this.findBestRearCamera(t,i):"user"===e?null:e?void 0:null:null}static async playVideo(t,e,i){if(!t)throw new Error("Invalid 'videoEl'.");if(!e)throw new Error("Invalid 'source'.");return new Promise((async(n,r)=>{let s;const a=()=>{t.removeEventListener("loadstart",c),t.removeEventListener("abort",d),t.removeEventListener("play",u),t.removeEventListener("error",f),t.removeEventListener("loadedmetadata",p)};let o=!1;const l=()=>{o=!0,s&&clearTimeout(s),a(),n(t)},h=t=>{s&&clearTimeout(s),a(),r(t)},c=()=>{t.addEventListener("abort",d,{once:!0})},d=()=>{const t=new Error("Video playing was interrupted.");t.name="AbortError",h(t)},u=()=>{l()},f=()=>{h(new Error(`Video error ${t.error.code}: ${t.error.message}.`))};let g;const m=new Promise((t=>{g=t})),p=()=>{g()};if(t.addEventListener("loadstart",c,{once:!0}),t.addEventListener("play",u,{once:!0}),t.addEventListener("error",f,{once:!0}),t.addEventListener("loadedmetadata",p,{once:!0}),"string"==typeof e||e instanceof String?t.src=e:t.srcObject=e,t.autoplay&&await new Promise((t=>{setTimeout(t,1e3)})),!o){i&&(s=setTimeout((()=>{a(),r(new Error("Failed to play video. Timeout."))}),i)),await m;try{await t.play(),l()}catch(t){console.warn("1st play error: "+((null==t?void 0:t.message)||t))}if(!o)try{await t.play(),l()}catch(t){console.warn("2rd play error: "+((null==t?void 0:t.message)||t)),h(t)}}}))}static async testCameraAccess(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))return{ok:!1,errorName:"InsecureContext",errorMessage:"Insecure context."};let n;try{n=t?await navigator.mediaDevices.getUserMedia(t):await navigator.mediaDevices.getUserMedia({video:!0})}catch(t){return{ok:!1,errorName:t.name,errorMessage:t.message}}finally{null==n||n.getTracks().forEach((t=>{t.stop()}))}return{ok:!0}}get state(){if(!Bn(this,_r,"f"))return"closed";if("pending"===Bn(this,_r,"f"))return"opening";if("fulfilled"===Bn(this,_r,"f"))return"opened";throw new Error("Unknown state.")}set ifSaveLastUsedCamera(t){t?Zr.isStorageAvailable("localStorage")?jn(this,fr,!0):(jn(this,fr,!1),console.warn("Local storage is unavailable")):jn(this,fr,!1)}get ifSaveLastUsedCamera(){return Bn(this,fr,"f")}get isVideoPlaying(){return!(!Bn(this,ar,"f")||Bn(this,ar,"f").paused)&&"opened"===this.state}set tapFocusEventBoundEl(t){var e,i,n;if(!(t instanceof HTMLElement)&&null!=t)throw new TypeError("Invalid 'element'.");null===(e=Bn(this,Sr,"f"))||void 0===e||e.removeEventListener("click",Bn(this,Er,"f")),null===(i=Bn(this,Sr,"f"))||void 0===i||i.removeEventListener("touchend",Bn(this,Er,"f")),null===(n=Bn(this,Sr,"f"))||void 0===n||n.removeEventListener("touchmove",Bn(this,Cr,"f")),jn(this,Sr,t),t&&(window.TouchEvent&&["Android","HarmonyOS","iPhone","iPad"].includes(zn.OS)?(t.addEventListener("touchend",Bn(this,Er,"f")),t.addEventListener("touchmove",Bn(this,Cr,"f"))):t.addEventListener("click",Bn(this,Er,"f")))}get tapFocusEventBoundEl(){return Bn(this,Sr,"f")}get disposed(){return Bn(this,Lr,"f")}constructor(t){var e,i;sr.add(this),ar.set(this,null),or.set(this,void 0),lr.set(this,(()=>{"opened"===this.state&&Bn(this,xr,"f").fire("resumed",null,{target:this,async:!1})})),hr.set(this,(()=>{Bn(this,xr,"f").fire("paused",null,{target:this,async:!1})})),cr.set(this,void 0),dr.set(this,void 0),this.cameraOpenTimeout=15e3,this._arrCameras=[],ur.set(this,void 0),fr.set(this,!1),this.ifSkipCameraInspection=!1,this.selectIOSRearMainCameraAsDefault=!1,gr.set(this,void 0),mr.set(this,!0),pr.set(this,void 0),_r.set(this,void 0),vr.set(this,!1),this._focusParameters={maxTimeout:400,minTimeout:300,kTimeout:void 0,oldDistance:null,fds:null,isDoingFocus:0,taskBackToContinous:null,curFocusTaskId:0,focusCancelableTime:1500,defaultFocusAreaSizeRatio:6,focusBackToContinousTime:5e3,tapFocusMinDistance:null,tapFocusMaxDistance:null,focusArea:null,tempBufferContainer:null,defaultTempBufferContainerLenRatio:1/4},yr.set(this,!1),this._focusSupported=!0,this.calculateCoordInVideo=(t,e)=>{let i,n;const r=window.getComputedStyle(Bn(this,ar,"f")).objectFit,s=this.getResolution(),a=Bn(this,ar,"f").getBoundingClientRect(),o=a.left,l=a.top,{width:h,height:c}=Bn(this,ar,"f").getBoundingClientRect();if(h<=0||c<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const d=h/c,u=s.width/s.height;let f=1;if("contain"===r)u>d?(f=h/s.width,i=(t-o)/f,n=(e-l-(c-h/u)/2)/f):(f=c/s.height,n=(e-l)/f,i=(t-o-(h-c*u)/2)/f);else{if("cover"!==r)throw new Error("Unsupported object-fit.");u>d?(f=c/s.height,n=(e-l)/f,i=(t-o+(c*u-h)/2)/f):(f=h/s.width,i=(t-o)/f,n=(e-l+(h/u-c)/2)/f)}return{x:i,y:n}},wr.set(this,!1),Cr.set(this,(()=>{jn(this,wr,!0)})),Er.set(this,(async t=>{var e;if(Bn(this,wr,"f"))return void jn(this,wr,!1);if(!Bn(this,yr,"f"))return;if(!this.isVideoPlaying)return;if(!Bn(this,or,"f"))return;if(!this._focusSupported)return;if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(e=this.getCameraCapabilities())||void 0===e?void 0:e.focusDistance,!this._focusParameters.fds))return void(this._focusSupported=!1);if(null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),1==this._focusParameters.isDoingFocus)return;let i,n;if(this._focusParameters.taskBackToContinous&&(clearTimeout(this._focusParameters.taskBackToContinous),this._focusParameters.taskBackToContinous=null),t instanceof MouseEvent)i=t.clientX,n=t.clientY;else{if(!(t instanceof TouchEvent))throw new Error("Unknown event type.");if(!t.changedTouches.length)return;i=t.changedTouches[0].clientX,n=t.changedTouches[0].clientY}const r=this.getResolution(),s=2*Math.round(Math.min(r.width,r.height)/this._focusParameters.defaultFocusAreaSizeRatio/2);let a;try{a=this.calculateCoordInVideo(i,n)}catch(t){}if(a.x<0||a.x>r.width||a.y<0||a.y>r.height)return;const o={x:a.x+"px",y:a.y+"px"},l=s+"px",h=l;let c;Zr._onLog&&(c=Date.now());try{await Bn(this,sr,"m",Gr).call(this,o,l,h,this._focusParameters.tapFocusMinDistance,this._focusParameters.tapFocusMaxDistance)}catch(t){if(Zr._onLog)throw Zr._onLog(t),t}Zr._onLog&&Zr._onLog(`Tap focus costs: ${Date.now()-c} ms`),this._focusParameters.taskBackToContinous=setTimeout((()=>{var t;Zr._onLog&&Zr._onLog("Back to continuous focus."),null===(t=Bn(this,or,"f"))||void 0===t||t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch((()=>{}))}),this._focusParameters.focusBackToContinousTime),Bn(this,xr,"f").fire("tapfocus",null,{target:this,async:!1})})),Sr.set(this,null),br.set(this,1),Tr.set(this,{x:0,y:0}),this.updateVideoElWhenSoftwareScaled=()=>{if(!Bn(this,ar,"f"))return;const t=Bn(this,br,"f");if(t<1)throw new RangeError("Invalid scale value.");if(1===t)Bn(this,ar,"f").style.transform="";else{const e=window.getComputedStyle(Bn(this,ar,"f")).objectFit,i=Bn(this,ar,"f").videoWidth,n=Bn(this,ar,"f").videoHeight,{width:r,height:s}=Bn(this,ar,"f").getBoundingClientRect();if(r<=0||s<=0)throw new Error("Unable to get video dimensions. Video may not be rendered on the page.");const a=r/s,o=i/n;let l=1;"contain"===e?l=aa?s/(i/t):r/(n/t));const h=l*(1-1/t)*(i/2-Bn(this,Tr,"f").x),c=l*(1-1/t)*(n/2-Bn(this,Tr,"f").y);Bn(this,ar,"f").style.transform=`translate(${h}px, ${c}px) scale(${t})`}},Ir.set(this,(function(){if(!(this.data instanceof Uint8Array||this.data instanceof Uint8ClampedArray))throw new TypeError("Invalid data.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.pixelFormat===qn.GREY){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{var t,e;if("visible"===document.visibilityState){if(Zr._onLog&&Zr._onLog("document visible. video paused: "+(null===(t=Bn(this,ar,"f"))||void 0===t?void 0:t.paused)),"opening"==this.state||"opened"==this.state){let e=!1;if(!this.isVideoPlaying){Zr._onLog&&Zr._onLog("document visible. Not auto resume. 1st resume start.");try{await this.resume(),e=!0}catch(t){Zr._onLog&&Zr._onLog("document visible. 1st resume video failed, try open instead.")}e||await Bn(this,sr,"m",Nr).call(this)}if(await new Promise((t=>setTimeout(t,300))),!this.isVideoPlaying){Zr._onLog&&Zr._onLog("document visible. 1st open failed. 2rd resume start."),e=!1;try{await this.resume(),e=!0}catch(t){Zr._onLog&&Zr._onLog("document visible. 2rd resume video failed, try open instead.")}e||await Bn(this,sr,"m",Nr).call(this)}}}else"hidden"===document.visibilityState&&(Zr._onLog&&Zr._onLog("document hidden. video paused: "+(null===(e=Bn(this,ar,"f"))||void 0===e?void 0:e.paused)),"opening"==this.state||"opened"==this.state&&this.isVideoPlaying&&this.pause())})),Lr.set(this,!1),(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia)||setTimeout((()=>{Zr.onWarning&&Zr.onWarning("The browser is too old or the page is loaded from an insecure origin.")}),0),this.defaultConstraints={video:{facingMode:{ideal:"environment"}}},this.resetMediaStreamConstraints(),t instanceof HTMLVideoElement&&this.setVideoEl(t),jn(this,xr,new Hr),this.imageDataGetter=new zr,document.addEventListener("visibilitychange",Bn(this,Dr,"f"))}setVideoEl(t){if(!(t&&t instanceof HTMLVideoElement))throw new Error("Invalid 'videoEl'.");t.addEventListener("play",Bn(this,lr,"f")),t.addEventListener("pause",Bn(this,hr,"f")),jn(this,ar,t)}getVideoEl(){return Bn(this,ar,"f")}releaseVideoEl(){var t,e;null===(t=Bn(this,ar,"f"))||void 0===t||t.removeEventListener("play",Bn(this,lr,"f")),null===(e=Bn(this,ar,"f"))||void 0===e||e.removeEventListener("pause",Bn(this,hr,"f")),jn(this,ar,null)}isVideoLoaded(){return!!Bn(this,ar,"f")&&4==Bn(this,ar,"f").readyState}async open(){if(Bn(this,pr,"f")&&!Bn(this,mr,"f")){if("pending"===Bn(this,_r,"f"))return Bn(this,pr,"f");if("fulfilled"===Bn(this,_r,"f"))return}Bn(this,xr,"f").fire("before:open",null,{target:this}),await Bn(this,sr,"m",Nr).call(this),Bn(this,xr,"f").fire("played",null,{target:this,async:!1}),Bn(this,xr,"f").fire("opened",null,{target:this,async:!1})}async close(){if("closed"===this.state)return;Bn(this,xr,"f").fire("before:close",null,{target:this});const t=Bn(this,pr,"f");if(Bn(this,sr,"m",jr).call(this),t&&"pending"===Bn(this,_r,"f")){try{await t}catch(t){}if(!1===Bn(this,mr,"f")){const t=new Error("'close()' was interrupted.");throw t.name="AbortError",t}}jn(this,pr,null),jn(this,_r,null),Bn(this,xr,"f").fire("closed",null,{target:this,async:!1})}pause(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");Bn(this,ar,"f").pause()}async resume(){if(!this.isVideoLoaded())throw new Error("Video is not loaded.");if("opened"!==this.state)throw new Error("Camera or video is not open.");await Bn(this,ar,"f").play()}async setCamera(t){if("string"!=typeof t)throw new TypeError("Invalid 'deviceId'.");if("object"!=typeof Bn(this,cr,"f").video&&(Bn(this,cr,"f").video={}),delete Bn(this,cr,"f").video.facingMode,Bn(this,cr,"f").video.deviceId={exact:t},!("closed"===this.state||this.videoSrc||"opening"===this.state&&Bn(this,mr,"f"))){Bn(this,xr,"f").fire("before:camera:change",[],{target:this,async:!1}),await Bn(this,sr,"m",Br).call(this);try{this.resetSoftwareScale()}catch(t){}return Bn(this,dr,"f")}}async switchToFrontCamera(t){if("object"!=typeof Bn(this,cr,"f").video&&(Bn(this,cr,"f").video={}),(null==t?void 0:t.resolution)&&(Bn(this,cr,"f").video.width={ideal:t.resolution.width},Bn(this,cr,"f").video.height={ideal:t.resolution.height}),delete Bn(this,cr,"f").video.deviceId,Bn(this,cr,"f").video.facingMode={exact:"user"},jn(this,ur,null),!("closed"===this.state||this.videoSrc||"opening"===this.state&&Bn(this,mr,"f"))){Bn(this,xr,"f").fire("before:camera:change",[],{target:this,async:!1}),Bn(this,sr,"m",Br).call(this);try{this.resetSoftwareScale()}catch(t){}return Bn(this,dr,"f")}}getCamera(){var t;if(Bn(this,dr,"f"))return Bn(this,dr,"f");{let e=(null===(t=Bn(this,cr,"f").video)||void 0===t?void 0:t.deviceId)||"";if(e){e=e.exact||e.ideal||e;for(let t of this._arrCameras)if(t.deviceId===e)return JSON.parse(JSON.stringify(t))}return{deviceId:"",label:"",_checked:!1}}}async _getCameras(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;if(t){let t=await navigator.mediaDevices.getUserMedia({video:!0});n=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind)),t.getTracks().forEach((t=>{t.stop()}))}else n=(await navigator.mediaDevices.enumerateDevices()).filter((t=>"videoinput"===t.kind));const r=[],s=[];if(this._arrCameras)for(let t of this._arrCameras)t._checked&&s.push(t);for(let t=0;t"videoinput"===t.kind));return i&&i.length&&!i[0].deviceId?this._getCameras(!0):this._getCameras(!1)}async getAllCameras(){return this.getCameras()}async setResolution(t,e,i){if("number"!=typeof t||t<=0)throw new TypeError("Invalid 'width'.");if("number"!=typeof e||e<=0)throw new TypeError("Invalid 'height'.");if("object"!=typeof Bn(this,cr,"f").video&&(Bn(this,cr,"f").video={}),i?(Bn(this,cr,"f").video.width={exact:t},Bn(this,cr,"f").video.height={exact:e}):(Bn(this,cr,"f").video.width={ideal:t},Bn(this,cr,"f").video.height={ideal:e}),"closed"===this.state||this.videoSrc||"opening"===this.state&&Bn(this,mr,"f"))return null;Bn(this,xr,"f").fire("before:resolution:change",[],{target:this,async:!1}),await Bn(this,sr,"m",Br).call(this);try{this.resetSoftwareScale()}catch(t){}const n=this.getResolution();return{width:n.width,height:n.height}}getResolution(){if("opened"===this.state&&this.videoSrc&&Bn(this,ar,"f"))return{width:Bn(this,ar,"f").videoWidth,height:Bn(this,ar,"f").videoHeight};if(Bn(this,or,"f")){const t=Bn(this,or,"f").getSettings();return{width:t.width,height:t.height}}if(this.isVideoLoaded())return{width:Bn(this,ar,"f").videoWidth,height:Bn(this,ar,"f").videoHeight};{const t={width:0,height:0};let e=Bn(this,cr,"f").video.width||0,i=Bn(this,cr,"f").video.height||0;return e&&(t.width=e.exact||e.ideal||e),i&&(t.height=i.exact||i.ideal||i),t}}async getResolutions(t){var e,i,n,r,s,a,o,l,h,c,d;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let u="";const f=(t,e)=>{const i=Bn(this,Ar,"f").get(t);if(!i||!i.length)return!1;for(let t of i)if(t.width===e.width&&t.height===e.height)return!0;return!1};if(this._mediaStream){u=null===(d=Bn(this,dr,"f"))||void 0===d?void 0:d.deviceId;let e=Bn(this,Ar,"f").get(u);if(e&&!t)return JSON.parse(JSON.stringify(e));e=[],Bn(this,Ar,"f").set(u,e),jn(this,vr,!0);try{for(let t of this.detectedResolutions){await Bn(this,or,"f").applyConstraints({width:{ideal:t.width},height:{ideal:t.height}}),Bn(this,sr,"m",Fr).call(this);const i=Bn(this,or,"f").getSettings(),n={width:i.width,height:i.height};f(u,n)||e.push({width:n.width,height:n.height})}}catch(t){throw Bn(this,sr,"m",jr).call(this),jn(this,vr,!1),t}try{await Bn(this,sr,"m",Nr).call(this)}catch(t){if("AbortError"===t.name)return e;throw t}finally{jn(this,vr,!1)}return e}{const e=async(t,e,i)=>{const n={video:{deviceId:{exact:t},width:{ideal:e},height:{ideal:i}}};let r=null;try{r=await navigator.mediaDevices.getUserMedia(n)}catch(t){return null}if(!r)return null;const s=r.getVideoTracks();let a=null;try{const t=s[0].getSettings();a={width:t.width,height:t.height}}catch(t){const e=document.createElement("video");e.srcObject=r,a={width:e.videoWidth,height:e.videoHeight},e.srcObject=null}return s.forEach((t=>{t.stop()})),a};let i=(null===(s=null===(r=null===(n=Bn(this,cr,"f"))||void 0===n?void 0:n.video)||void 0===r?void 0:r.deviceId)||void 0===s?void 0:s.exact)||(null===(l=null===(o=null===(a=Bn(this,cr,"f"))||void 0===a?void 0:a.video)||void 0===o?void 0:o.deviceId)||void 0===l?void 0:l.ideal)||(null===(c=null===(h=Bn(this,cr,"f"))||void 0===h?void 0:h.video)||void 0===c?void 0:c.deviceId);if(!i)return[];let d=Bn(this,Ar,"f").get(i);if(d&&!t)return JSON.parse(JSON.stringify(d));d=[],Bn(this,Ar,"f").set(i,d);for(let t of this.detectedResolutions){const n=await e(i,t.width,t.height);n&&!f(i,n)&&d.push({width:n.width,height:n.height})}return d}}async setMediaStreamConstraints(t,e){if(!(t=>{return null!==t&&"[object Object]"===(e=t,Object.prototype.toString.call(e));var e})(t))throw new TypeError("Invalid 'mediaStreamConstraints'.");jn(this,cr,JSON.parse(JSON.stringify(t))),jn(this,ur,null),e&&Bn(this,sr,"m",Br).call(this)}getMediaStreamConstraints(){return JSON.parse(JSON.stringify(Bn(this,cr,"f")))}resetMediaStreamConstraints(){jn(this,cr,this.defaultConstraints?JSON.parse(JSON.stringify(this.defaultConstraints)):null)}getCameraCapabilities(){if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Bn(this,or,"f").getCapabilities?Bn(this,or,"f").getCapabilities():{}}getCameraSettings(){if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");return Bn(this,or,"f").getSettings()}async turnOnTorch(){if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Bn(this,or,"f").applyConstraints({advanced:[{torch:!0}]})}async turnOffTorch(){if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const t=this.getCameraCapabilities();if(!(null==t?void 0:t.torch))throw Error("Not supported.");await Bn(this,or,"f").applyConstraints({advanced:[{torch:!1}]})}async setColorTemperature(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.colorTemperature;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Xr(t,n.min,n.step,n.max)),await Bn(this,or,"f").applyConstraints({advanced:[{colorTemperature:t,whiteBalanceMode:"manual"}]}),t}getColorTemperature(){return this.getCameraSettings().colorTemperature||0}async setExposureCompensation(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.exposureCompensation;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Xr(t,n.min,n.step,n.max)),await Bn(this,or,"f").applyConstraints({advanced:[{exposureCompensation:t}]}),t}getExposureCompensation(){return this.getCameraSettings().exposureCompensation||0}async setFrameRate(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");let n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.frameRate;if(!n)throw Error("Not supported.");e&&(tn.max&&(t=n.max));const r=this.getResolution();return await Bn(this,or,"f").applyConstraints({width:{ideal:Math.max(r.width,r.height)},frameRate:t}),t}getFrameRate(){return this.getCameraSettings().frameRate}async setFocus(t,e){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const i=this.getCameraCapabilities(),n=null==i?void 0:i.focusMode,r=null==i?void 0:i.focusDistance;if(!n)throw Error("Not supported.");if("string"!=typeof t.mode)throw TypeError("Invalid 'mode'.");const s=t.mode.toLowerCase();if(!n.includes(s))throw Error("Unsupported focus mode.");if("manual"===s){if(!r)throw Error("Manual focus unsupported.");if(t.hasOwnProperty("distance")){let i=t.distance;e&&(ir.max&&(i=r.max),i=Xr(i,r.min,r.step,r.max)),this._focusParameters.focusArea=null,await Bn(this,or,"f").applyConstraints({advanced:[{focusMode:s,focusDistance:i}]})}else{if(!t.area)throw new Error("'distance' or 'area' should be specified in 'manual' mode.");{const e=t.area.centerPoint;let i=t.area.width,n=t.area.height;if(!i||!n){const t=this.getResolution();i||(i=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px"),n||(n=2*Math.round(Math.min(t.width,t.height)/this._focusParameters.defaultFocusAreaSizeRatio/2)+"px")}this._focusParameters.focusArea={centerPoint:{x:e.x,y:e.y},width:i,height:n},await Bn(this,sr,"m",Gr).call(this,e,i,n)}}}else this._focusParameters.focusArea=null,await Bn(this,or,"f").applyConstraints({advanced:[{focusMode:s}]})}getFocus(){const t=this.getCameraSettings(),e=t.focusMode;return e?"manual"===e?this._focusParameters.focusArea?{mode:"manual",area:JSON.parse(JSON.stringify(this._focusParameters.focusArea))}:{mode:"manual",distance:t.focusDistance}:{mode:e}:null}async enableTapToFocus(){jn(this,yr,!0)}disableTapToFocus(){jn(this,yr,!1)}isTapToFocusEnabled(){return Bn(this,yr,"f")}async setZoom(t){if("object"!=typeof t||Array.isArray(t)||null==t)throw new TypeError("Invalid 'settings'.");if("number"!=typeof t.factor)throw new TypeError("Illegal type of 'factor'.");if(t.factor<1)throw new RangeError("Invalid 'factor'.");if("opened"!==this.state)throw new Error("Video is not playing.");t.centerPoint?Bn(this,sr,"m",Wr).call(this,t.centerPoint):this.resetScaleCenter();try{if(Bn(this,sr,"m",Yr).call(this,Bn(this,Tr,"f"))){const e=await this.setHardwareScale(t.factor,!0);let i=this.getHardwareScale();1==i&&1!=e&&(i=e),t.factor>i?this.setSoftwareScale(t.factor/i):this.setSoftwareScale(1)}else await this.setHardwareScale(1),this.setSoftwareScale(t.factor)}catch(e){const i=e.message||e;if("Not supported."!==i&&"Camera is not open."!==i)throw e;this.setSoftwareScale(t.factor)}}getZoom(){if("opened"!==this.state)throw new Error("Video is not playing.");let t=1;try{t=this.getHardwareScale()}catch(t){if("Camera is not open."!==(t.message||t))throw t}return{factor:t*Bn(this,br,"f")}}async resetZoom(){await this.setZoom({factor:1})}async setHardwareScale(t,e){var i;if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if(!Bn(this,or,"f")||"opened"!==this.state)throw new Error("Camera is not open.");const n=null===(i=this.getCameraCapabilities())||void 0===i?void 0:i.zoom;if(!n)throw Error("Not supported.");return e&&(tn.max&&(t=n.max),t=Xr(t,n.min,n.step,n.max)),await Bn(this,or,"f").applyConstraints({advanced:[{zoom:t}]}),t}getHardwareScale(){return this.getCameraSettings().zoom||1}setSoftwareScale(t,e){if("number"!=typeof t)throw new TypeError("Invalid 'value'.");if(t<1)throw new RangeError("Invalid 'value'.");if("opened"!==this.state)throw new Error("Video is not playing.");e&&Bn(this,sr,"m",Wr).call(this,e),jn(this,br,t),this.updateVideoElWhenSoftwareScaled()}getSoftwareScale(){return Bn(this,br,"f")}resetScaleCenter(){if("opened"!==this.state)throw new Error("Video is not playing.");const t=this.getResolution();jn(this,Tr,{x:t.width/2,y:t.height/2})}resetSoftwareScale(){this.setSoftwareScale(1),this.resetScaleCenter()}getFrameData(t){if(this.disposed)throw Error("The 'Camera' instance has been disposed.");if(!this.isVideoLoaded())return null;if(Bn(this,vr,"f"))return null;const e=Date.now();Zr._onLog&&Zr._onLog("getFrameData() START: "+e);const i=Bn(this,ar,"f").videoWidth,n=Bn(this,ar,"f").videoHeight;let r={sx:0,sy:0,sWidth:i,sHeight:n,dWidth:i,dHeight:n};(null==t?void 0:t.position)&&(r=JSON.parse(JSON.stringify(t.position)));let s=qn.RGBA;(null==t?void 0:t.pixelFormat)&&(s=t.pixelFormat);let a=Bn(this,br,"f");(null==t?void 0:t.scale)&&(a=t.scale);let o=Bn(this,Tr,"f");if(null==t?void 0:t.scaleCenter){if("string"!=typeof t.scaleCenter.x||"string"!=typeof t.scaleCenter.y)throw new Error("Invalid scale center.");let e=0,r=0;if(t.scaleCenter.x.endsWith("px"))e=parseFloat(t.scaleCenter.x);else{if(!t.scaleCenter.x.endsWith("%"))throw new Error("Invalid scale center.");e=parseFloat(t.scaleCenter.x)/100*i}if(t.scaleCenter.y.endsWith("px"))r=parseFloat(t.scaleCenter.y);else{if(!t.scaleCenter.y.endsWith("%"))throw new Error("Invalid scale center.");r=parseFloat(t.scaleCenter.y)/100*n}if(isNaN(e)||isNaN(r))throw new Error("Invalid scale center.");o.x=Math.round(e),o.y=Math.round(r)}let l=null;if((null==t?void 0:t.bufferContainer)&&(l=t.bufferContainer),0==i||0==n)return null;1!==a&&(r.sWidth=Math.round(r.sWidth/a),r.sHeight=Math.round(r.sHeight/a),r.sx=Math.round((1-1/a)*o.x+r.sx/a),r.sy=Math.round((1-1/a)*o.y+r.sy/a));const h=this.imageDataGetter.getImageData(Bn(this,ar,"f"),r,{pixelFormat:s,bufferContainer:l});if(!h)return null;const c=Date.now();return Zr._onLog&&Zr._onLog("getFrameData() END: "+c),{data:h.data,width:h.width,height:h.height,pixelFormat:h.pixelFormat,timeSpent:c-e,timeStamp:c,toCanvas:Bn(this,Ir,"f")}}on(t,e){if(!Bn(this,Or,"f").includes(t.toLowerCase()))throw new Error(`Event '${t}' does not exist.`);Bn(this,xr,"f").on(t,e)}off(t,e){Bn(this,xr,"f").off(t,e)}async dispose(){this.tapFocusEventBoundEl=null,await this.close(),this.releaseVideoEl(),Bn(this,xr,"f").dispose(),this.imageDataGetter.dispose(),document.removeEventListener("visibilitychange",Bn(this,Dr,"f")),jn(this,Lr,!0)}}var qr,Jr,Kr,$r,Qr,ts,es,is,ns,rs,ss,as,os,ls,hs,cs,ds,us,fs,gs,ms,ps,_s,vs,ys,ws,Cs,Es,Ss,bs,Ts,Is,xs,Os,As;ar=new WeakMap,or=new WeakMap,lr=new WeakMap,hr=new WeakMap,cr=new WeakMap,dr=new WeakMap,ur=new WeakMap,fr=new WeakMap,gr=new WeakMap,mr=new WeakMap,pr=new WeakMap,_r=new WeakMap,vr=new WeakMap,yr=new WeakMap,wr=new WeakMap,Cr=new WeakMap,Er=new WeakMap,Sr=new WeakMap,br=new WeakMap,Tr=new WeakMap,Ir=new WeakMap,xr=new WeakMap,Or=new WeakMap,Ar=new WeakMap,Rr=new WeakMap,Dr=new WeakMap,Lr=new WeakMap,sr=new WeakSet,Mr=async function(){const t=this.getMediaStreamConstraints();if("boolean"==typeof t.video&&(t.video={}),t.video.deviceId);else if(Bn(this,ur,"f"))delete t.video.facingMode,t.video.deviceId={exact:Bn(this,ur,"f")};else if(this.ifSaveLastUsedCamera&&Zr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")){delete t.video.facingMode,t.video.deviceId={ideal:window.localStorage.getItem("dce_last_camera_id")};const e=JSON.parse(window.localStorage.getItem("dce_last_apply_width")),i=JSON.parse(window.localStorage.getItem("dce_last_apply_height"));e&&i&&(t.video.width=e,t.video.height=i)}else if(this.ifSkipCameraInspection);else{const e=async t=>{let e=null;return"environment"===t&&["Android","HarmonyOS","iPhone","iPad"].includes(zn.OS)?(await this._getCameras(!1),Bn(this,sr,"m",Fr).call(this),e=Zr.findBestCamera(this._arrCameras,"environment",{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})):t||["Android","HarmonyOS","iPhone","iPad"].includes(zn.OS)||(await this._getCameras(!1),Bn(this,sr,"m",Fr).call(this),e=Zr.findBestCamera(this._arrCameras,null,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault})),e};let i=t.video.facingMode;i instanceof Array&&i.length&&(i=i[0]),"object"==typeof i&&(i=i.exact||i.ideal);const n=await e(i);n&&(delete t.video.facingMode,t.video.deviceId={exact:n})}return t},Fr=function(){if(Bn(this,mr,"f")){const t=new Error("The operation was interrupted.");throw t.name="AbortError",t}},Pr=async function(t){var e,i;if(!(null===(i=null===(e=null===window||void 0===window?void 0:window.navigator)||void 0===e?void 0:e.mediaDevices)||void 0===i?void 0:i.getUserMedia))throw new Error("Failed to access the camera because the browser is too old or the page is loaded from an insecure origin.");let n;try{Zr._onLog&&Zr._onLog("======try getUserMedia========");let e=[0,500,1e3,2e3],i=null;const r=async t=>{for(let r of e){r&&(await new Promise((t=>setTimeout(t,r))),Bn(this,sr,"m",Fr).call(this));try{Zr._onLog&&Zr._onLog("ask "+JSON.stringify(t)),n=await navigator.mediaDevices.getUserMedia(t),Bn(this,sr,"m",Fr).call(this);break}catch(t){if("NotFoundError"===t.name||"NotAllowedError"===t.name||"AbortError"===t.name||"OverconstrainedError"===t.name)throw t;i=t,Zr._onLog&&Zr._onLog(t.message||t)}}};if(await r(t),n||"object"!=typeof t.video||(t.video.deviceId&&(delete t.video.deviceId,await r(t)),!n&&t.video.facingMode&&(delete t.video.facingMode,await r(t)),n||!t.video.width&&!t.video.height||(delete t.video.width,delete t.video.height,await r(t))),!n)throw i;return n}catch(t){throw null==n||n.getTracks().forEach((t=>{t.stop()})),"NotFoundError"===t.name&&(DOMException?t=new DOMException("No camera available, please use a device with an accessible camera.",t.name):(t=new Error("No camera available, please use a device with an accessible camera.")).name="NotFoundError"),t}},kr=function(){this._mediaStream&&(this._mediaStream.getTracks().forEach((t=>{t.stop()})),this._mediaStream=null),jn(this,or,null)},Nr=async function(){jn(this,mr,!1);const t=jn(this,gr,Symbol());if(Bn(this,pr,"f")&&"pending"===Bn(this,_r,"f")){try{await Bn(this,pr,"f")}catch(t){}Bn(this,sr,"m",Fr).call(this)}if(t!==Bn(this,gr,"f"))return;const e=jn(this,pr,(async()=>{jn(this,_r,"pending");try{if(this.videoSrc){if(!Bn(this,ar,"f"))throw new Error("'videoEl' should be set.");await Zr.playVideo(Bn(this,ar,"f"),this.videoSrc,this.cameraOpenTimeout),Bn(this,sr,"m",Fr).call(this)}else{let t=await Bn(this,sr,"m",Mr).call(this);Bn(this,sr,"m",kr).call(this);let e=await Bn(this,sr,"m",Pr).call(this,t);await this._getCameras(!1),Bn(this,sr,"m",Fr).call(this);const i=()=>{const t=e.getVideoTracks();let i,n;if(t.length&&(i=t[0]),i){const t=i.getSettings();if(t)for(let e of this._arrCameras)if(t.deviceId===e.deviceId){e._checked=!0,e.label=i.label,n=e;break}}return n},n=Bn(this,cr,"f");if("object"==typeof n.video){let r=n.video.facingMode;if(r instanceof Array&&r.length&&(r=r[0]),"object"==typeof r&&(r=r.exact||r.ideal),!(Bn(this,ur,"f")||this.ifSaveLastUsedCamera&&Zr.isStorageAvailable&&window.localStorage.getItem("dce_last_camera_id")||this.ifSkipCameraInspection||n.video.deviceId)){const n=i(),s=Zr.findBestCamera(this._arrCameras,r,{getMainCameraInIOS:this.selectIOSRearMainCameraAsDefault});s&&s!=(null==n?void 0:n.deviceId)&&(e.getTracks().forEach((t=>{t.stop()})),t.video.deviceId={exact:s},e=await Bn(this,sr,"m",Pr).call(this,t),Bn(this,sr,"m",Fr).call(this))}}const r=i();(null==r?void 0:r.deviceId)&&(jn(this,ur,r&&r.deviceId),this.ifSaveLastUsedCamera&&Zr.isStorageAvailable&&(window.localStorage.setItem("dce_last_camera_id",Bn(this,ur,"f")),"object"==typeof t.video&&t.video.width&&t.video.height&&(window.localStorage.setItem("dce_last_apply_width",JSON.stringify(t.video.width)),window.localStorage.setItem("dce_last_apply_height",JSON.stringify(t.video.height))))),Bn(this,ar,"f")&&(await Zr.playVideo(Bn(this,ar,"f"),e,this.cameraOpenTimeout),Bn(this,sr,"m",Fr).call(this)),this._mediaStream=e;const s=e.getVideoTracks();(null==s?void 0:s.length)&&jn(this,or,s[0]),jn(this,dr,r)}}catch(t){throw Bn(this,sr,"m",jr).call(this),jn(this,_r,null),t}jn(this,_r,"fulfilled")})());return e},Br=async function(){var t;if("closed"===this.state||this.videoSrc)return;const e=null===(t=Bn(this,dr,"f"))||void 0===t?void 0:t.deviceId,i=this.getResolution();await Bn(this,sr,"m",Nr).call(this);const n=this.getResolution();e&&e!==Bn(this,dr,"f").deviceId&&Bn(this,xr,"f").fire("camera:changed",[Bn(this,dr,"f").deviceId,e],{target:this,async:!1}),i.width==n.width&&i.height==n.height||Bn(this,xr,"f").fire("resolution:changed",[{width:n.width,height:n.height},{width:i.width,height:i.height}],{target:this,async:!1}),Bn(this,xr,"f").fire("played",null,{target:this,async:!1})},jr=function(){Bn(this,sr,"m",kr).call(this),jn(this,dr,null),Bn(this,ar,"f")&&(Bn(this,ar,"f").srcObject=null,this.videoSrc&&(Bn(this,ar,"f").pause(),Bn(this,ar,"f").currentTime=0)),jn(this,mr,!0);try{this.resetSoftwareScale()}catch(t){}},Vr=async function t(e,i){const n=t=>{if(!Bn(this,or,"f")||!this.isVideoPlaying||t.focusTaskId!=this._focusParameters.curFocusTaskId){Bn(this,or,"f")&&this.isVideoPlaying||(this._focusParameters.isDoingFocus=0);const e=new Error(`Focus task ${t.focusTaskId} canceled.`);throw e.name="DeprecatedTaskError",e}1===this._focusParameters.isDoingFocus&&Date.now()-t.timeStart>this._focusParameters.focusCancelableTime&&(this._focusParameters.isDoingFocus=-1)};let r;i=Xr(i,this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),await Bn(this,or,"f").applyConstraints({advanced:[{focusMode:"manual",focusDistance:i}]}),n(e),r=null==this._focusParameters.oldDistance?this._focusParameters.kTimeout*Math.max(Math.abs(1/this._focusParameters.fds.min-1/i),Math.abs(1/this._focusParameters.fds.max-1/i))+this._focusParameters.minTimeout:this._focusParameters.kTimeout*Math.abs(1/this._focusParameters.oldDistance-1/i)+this._focusParameters.minTimeout,this._focusParameters.oldDistance=i,await new Promise((t=>{setTimeout(t,r)})),n(e);let s=e.focusL-e.focusW/2,a=e.focusT-e.focusH/2,o=e.focusW,l=e.focusH;const h=this.getResolution();s=Math.round(s),a=Math.round(a),o=Math.round(o),l=Math.round(l),o>h.width&&(o=h.width),l>h.height&&(l=h.height),s<0?s=0:s+o>h.width&&(s=h.width-o),a<0?a=0:a+l>h.height&&(a=h.height-l);const c=4*h.width*h.height*this._focusParameters.defaultTempBufferContainerLenRatio,d=4*o*l;let u=this._focusParameters.tempBufferContainer;if(u){const t=u.length;c>t&&c>=d?u=new Uint8Array(c):d>t&&d>=c&&(u=new Uint8Array(d))}else u=this._focusParameters.tempBufferContainer=new Uint8Array(Math.max(c,d));if(!this.imageDataGetter.getImageData(Bn(this,ar,"f"),{sx:s,sy:a,sWidth:o,sHeight:l,dWidth:o,dHeight:l},{pixelFormat:qn.RGBA,bufferContainer:u}))return Bn(this,sr,"m",t).call(this,e,i);const f=u;let g=0;for(let t=0,e=d-8;to&&od)return await Bn(this,sr,"m",t).call(this,e,a,o,r,s,c,d)}else{let l=await Bn(this,sr,"m",Vr).call(this,e,c);if(o>l)return await Bn(this,sr,"m",t).call(this,e,a,o,r,s,c,l);if(o==l)return await Bn(this,sr,"m",t).call(this,e,a,o,c,l);let d=await Bn(this,sr,"m",Vr).call(this,e,h);if(d>o&&oa.width||l<0||l>a.height)throw new Error("Invalid 'centerPoint'.");let h=0;if(e.endsWith("px"))h=parseFloat(e);else{if(!e.endsWith("%"))throw new Error("Invalid 'width'.");h=parseFloat(e)/100*a.width}if(isNaN(h)||h<0)throw new Error("Invalid 'width'.");let c=0;if(i.endsWith("px"))c=parseFloat(i);else{if(!i.endsWith("%"))throw new Error("Invalid 'height'.");c=parseFloat(i)/100*a.height}if(isNaN(c)||c<0)throw new Error("Invalid 'height'.");if(1!==Bn(this,br,"f")){const t=Bn(this,br,"f"),e=Bn(this,Tr,"f");h/=t,c/=t,o=(1-1/t)*e.x+o/t,l=(1-1/t)*e.y+l/t}if(!this._focusSupported)throw new Error("Manual focus unsupported.");if(!this._focusParameters.fds&&(this._focusParameters.fds=null===(s=this.getCameraCapabilities())||void 0===s?void 0:s.focusDistance,!this._focusParameters.fds))throw this._focusSupported=!1,new Error("Manual focus unsupported.");null==this._focusParameters.kTimeout&&(this._focusParameters.kTimeout=(this._focusParameters.maxTimeout-this._focusParameters.minTimeout)/(1/this._focusParameters.fds.min-1/this._focusParameters.fds.max)),this._focusParameters.isDoingFocus=1;const d={focusL:o,focusT:l,focusW:h,focusH:c,focusTaskId:++this._focusParameters.curFocusTaskId,timeStart:Date.now()},u=async(t,e,i)=>{try{(null==e||ethis._focusParameters.fds.max)&&(i=this._focusParameters.fds.max),this._focusParameters.oldDistance=null;let n=Xr(Math.sqrt(i*(e||this._focusParameters.fds.step)),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),r=Xr(Math.sqrt((e||this._focusParameters.fds.step)*n),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),s=Xr(Math.sqrt(n*i),this._focusParameters.fds.min,this._focusParameters.fds.step,this._focusParameters.fds.max),a=await Bn(this,sr,"m",Vr).call(this,t,s),o=await Bn(this,sr,"m",Vr).call(this,t,r),l=await Bn(this,sr,"m",Vr).call(this,t,n);if(o>l&&la&&o>a){let e=await Bn(this,sr,"m",Vr).call(this,t,i);const r=await Bn(this,sr,"m",Ur).call(this,t,n,l,i,e,s,a);return this._focusParameters.isDoingFocus=0,r}if(o==l&&ll){const e=await Bn(this,sr,"m",Ur).call(this,t,n,l,s,a);return this._focusParameters.isDoingFocus=0,e}return u(t,e,i)}catch(t){if("DeprecatedTaskError"!==t.name)throw t}};return u(d,n,r)},Wr=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");if(!t||"string"!=typeof t.x||"string"!=typeof t.y)throw new Error("Invalid 'center'.");const e=this.getResolution();let i=0,n=0;if(t.x.endsWith("px"))i=parseFloat(t.x);else{if(!t.x.endsWith("%"))throw new Error("Invalid scale center.");i=parseFloat(t.x)/100*e.width}if(t.y.endsWith("px"))n=parseFloat(t.y);else{if(!t.y.endsWith("%"))throw new Error("Invalid scale center.");n=parseFloat(t.y)/100*e.height}if(isNaN(i)||isNaN(n))throw new Error("Invalid scale center.");jn(this,Tr,{x:i,y:n})},Yr=function(t){if("opened"!==this.state)throw new Error("Video is not playing.");const e=this.getResolution();return t&&t.x==e.width/2&&t.y==e.height/2},Zr.browserInfo=zn,Zr.onWarning=null===(rr=null===window||void 0===window?void 0:window.console)||void 0===rr?void 0:rr.warn;class Rs{constructor(t){qr.add(this),Jr.set(this,void 0),Kr.set(this,0),$r.set(this,void 0),Qr.set(this,0),ts.set(this,!1),Ke(this,Jr,t)}startCharging(){Je(this,ts,"f")||(Rs._onLog&&Rs._onLog("start charging."),Je(this,qr,"m",is).call(this),Ke(this,ts,!0))}stopCharging(){Je(this,$r,"f")&&clearTimeout(Je(this,$r,"f")),Je(this,ts,"f")&&(Rs._onLog&&Rs._onLog("stop charging."),Ke(this,Kr,Date.now()-Je(this,Qr,"f")),Ke(this,ts,!1))}}Jr=new WeakMap,Kr=new WeakMap,$r=new WeakMap,Qr=new WeakMap,ts=new WeakMap,qr=new WeakSet,es=function(){vt.cfd(1),Rs._onLog&&Rs._onLog("charge 1.")},is=function t(){0==Je(this,Kr,"f")&&Je(this,qr,"m",es).call(this),Ke(this,Qr,Date.now()),Je(this,$r,"f")&&clearTimeout(Je(this,$r,"f")),Ke(this,$r,setTimeout((()=>{Ke(this,Kr,0),Je(this,qr,"m",t).call(this)}),Je(this,Jr,"f")-Je(this,Kr,"f")))};class Ds{static beep(){if(!this.allowBeep)return;if(!this.beepSoundSource)return;let t,e=Date.now();if(!(e-Je(this,ns,"f",as)<100)){if(Ke(this,ns,e,0,as),Je(this,ns,"f",rs).size&&(t=Je(this,ns,"f",rs).values().next().value,this.beepSoundSource==t.src?(Je(this,ns,"f",rs).delete(t),t.play()):t=null),!t)if(Je(this,ns,"f",ss).size<16){t=new Audio(this.beepSoundSource);let e=null,i=()=>{t.removeEventListener("loadedmetadata",i),t.play(),e=setTimeout((()=>{Je(this,ns,"f",ss).delete(t)}),2e3*t.duration)};t.addEventListener("loadedmetadata",i),t.addEventListener("ended",(()=>{null!=e&&(clearTimeout(e),e=null),t.pause(),t.currentTime=0,Je(this,ns,"f",ss).delete(t),Je(this,ns,"f",rs).add(t)}))}else Je(this,ns,"f",os)||(Ke(this,ns,!0,0,os),console.warn("The requested audio tracks exceed 16 and will not be played."));t&&Je(this,ns,"f",ss).add(t)}}static vibrate(){if(this.allowVibrate){if(!navigator||!navigator.vibrate)throw new Error("Not supported.");navigator.vibrate(Ds.vibrateDuration)}}}ns=Ds,rs={value:new Set},ss={value:new Set},as={value:0},os={value:!1},Ds.allowBeep=!0,Ds.beepSoundSource="data:audio/mpeg;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU4LjI5LjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAABQAAAkAAgICAgICAgICAgICAgICAgICAgKCgoKCgoKCgoKCgoKCgoKCgoKCgwMDAwMDAwMDAwMDAwMDAwMDAwMDg4ODg4ODg4ODg4ODg4ODg4ODg4P//////////////////////////AAAAAExhdmM1OC41NAAAAAAAAAAAAAAAACQEUQAAAAAAAAJAk0uXRQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAANQAbGeUEQAAHZYZ3fASqD4P5TKBgocg+Bw/8+CAYBA4XB9/4EBAEP4nB9+UOf/6gfUCAIKyjgQ/Kf//wfswAAAwQA/+MYxAYOqrbdkZGQAMA7DJLCsQxNOij///////////+tv///3RWiZGBEhsf/FO/+LoCSFs1dFVS/g8f/4Mhv0nhqAieHleLy/+MYxAYOOrbMAY2gABf/////////////////usPJ66R0wI4boY9/8jQYg//g2SPx1M0N3Z0kVJLIs///Uw4aMyvHJJYmPBYG/+MYxAgPMALBucAQAoGgaBoFQVBUFQWDv6gZBUFQVBUGgaBr5YSgqCoKhIGg7+IQVBUFQVBoGga//SsFSoKnf/iVTEFNRTMu/+MYxAYAAANIAAAAADEwMFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV",Ds.allowVibrate=!0,Ds.vibrateDuration=300;const Ls=new Map([[qn.GREY,o.IPF_GRAYSCALED],[qn.RGBA,o.IPF_ABGR_8888]]),Ms="function"==typeof BigInt?{BF_NULL:BigInt(0),BF_ALL:BigInt(0x10000000000000000),BF_DEFAULT:BigInt(4265345023),BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096),BF_CODE_39:BigInt(1),BF_CODE_128:BigInt(2),BF_CODE_93:BigInt(4),BF_CODABAR:BigInt(8),BF_ITF:BigInt(16),BF_EAN_13:BigInt(32),BF_EAN_8:BigInt(64),BF_UPC_A:BigInt(128),BF_UPC_E:BigInt(256),BF_INDUSTRIAL_25:BigInt(512),BF_CODE_39_EXTENDED:BigInt(1024),BF_GS1_DATABAR_OMNIDIRECTIONAL:BigInt(2048),BF_GS1_DATABAR_TRUNCATED:BigInt(4096),BF_GS1_DATABAR_STACKED:BigInt(8192),BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:BigInt(16384),BF_GS1_DATABAR_EXPANDED:BigInt(32768),BF_GS1_DATABAR_EXPANDED_STACKED:BigInt(65536),BF_GS1_DATABAR_LIMITED:BigInt(131072),BF_PATCHCODE:BigInt(262144),BF_CODE_32:BigInt(16777216),BF_PDF417:BigInt(33554432),BF_QR_CODE:BigInt(67108864),BF_DATAMATRIX:BigInt(134217728),BF_AZTEC:BigInt(268435456),BF_MAXICODE:BigInt(536870912),BF_MICRO_QR:BigInt(1073741824),BF_MICRO_PDF417:BigInt(524288),BF_GS1_COMPOSITE:BigInt(2147483648),BF_MSI_CODE:BigInt(1048576),BF_CODE_11:BigInt(2097152),BF_TWO_DIGIT_ADD_ON:BigInt(4194304),BF_FIVE_DIGIT_ADD_ON:BigInt(8388608),BF_MATRIX_25:BigInt(68719476736),BF_POSTALCODE:BigInt(0x3f0000000000000),BF_NONSTANDARD_BARCODE:BigInt(4294967296),BF_USPSINTELLIGENTMAIL:BigInt(4503599627370496),BF_POSTNET:BigInt(9007199254740992),BF_PLANET:BigInt(0x40000000000000),BF_AUSTRALIANPOST:BigInt(0x80000000000000),BF_RM4SCC:BigInt(72057594037927940),BF_KIX:BigInt(0x200000000000000),BF_DOTCODE:BigInt(8589934592),BF_PHARMACODE_ONE_TRACK:BigInt(17179869184),BF_PHARMACODE_TWO_TRACK:BigInt(34359738368),BF_PHARMACODE:BigInt(51539607552)}:{BF_NULL:"0x00",BF_ALL:"0xFFFFFFFFFFFFFFFF",BF_DEFAULT:"0xFE3BFFFF",BF_ONED:"0x003007FF",BF_GS1_DATABAR:"0x0003F800",BF_CODE_39:"0x1",BF_CODE_128:"0x2",BF_CODE_93:"0x4",BF_CODABAR:"0x8",BF_ITF:"0x10",BF_EAN_13:"0x20",BF_EAN_8:"0x40",BF_UPC_A:"0x80",BF_UPC_E:"0x100",BF_INDUSTRIAL_25:"0x200",BF_CODE_39_EXTENDED:"0x400",BF_GS1_DATABAR_OMNIDIRECTIONAL:"0x800",BF_GS1_DATABAR_TRUNCATED:"0x1000",BF_GS1_DATABAR_STACKED:"0x2000",BF_GS1_DATABAR_STACKED_OMNIDIRECTIONAL:"0x4000",BF_GS1_DATABAR_EXPANDED:"0x8000",BF_GS1_DATABAR_EXPANDED_STACKED:"0x10000",BF_GS1_DATABAR_LIMITED:"0x20000",BF_PATCHCODE:"0x00040000",BF_CODE_32:"0x01000000",BF_PDF417:"0x02000000",BF_QR_CODE:"0x04000000",BF_DATAMATRIX:"0x08000000",BF_AZTEC:"0x10000000",BF_MAXICODE:"0x20000000",BF_MICRO_QR:"0x40000000",BF_MICRO_PDF417:"0x00080000",BF_GS1_COMPOSITE:"0x80000000",BF_MSI_CODE:"0x100000",BF_CODE_11:"0x200000",BF_TWO_DIGIT_ADD_ON:"0x400000",BF_FIVE_DIGIT_ADD_ON:"0x800000",BF_MATRIX_25:"0x1000000000",BF_POSTALCODE:"0x3F0000000000000",BF_NONSTANDARD_BARCODE:"0x100000000",BF_USPSINTELLIGENTMAIL:"0x10000000000000",BF_POSTNET:"0x20000000000000",BF_PLANET:"0x40000000000000",BF_AUSTRALIANPOST:"0x80000000000000",BF_RM4SCC:"0x100000000000000",BF_KIX:"0x200000000000000",BF_DOTCODE:"0x200000000",BF_PHARMACODE_ONE_TRACK:"0x400000000",BF_PHARMACODE_TWO_TRACK:"0x800000000",BF_PHARMACODE:"0xC00000000"};class Fs extends K{static set _onLog(t){Ke(Fs,hs,t,0,cs),Zr._onLog=t,Rs._onLog=t}static get _onLog(){return Je(Fs,hs,"f",cs)}static async detectEnvironment(){return await(async()=>({wasm:$e,worker:Qe,getUserMedia:ti,camera:await ei(),browser:Ze.browser,version:Ze.version,OS:Ze.OS}))()}static async testCameraAccess(){const t=await Zr.testCameraAccess();return t.ok?{ok:!0,message:"Successfully accessed the camera."}:"InsecureContext"===t.errorName?{ok:!1,message:"Insecure context."}:"OverconstrainedError"===t.errorName||"NotFoundError"===t.errorName?{ok:!1,message:"No camera detected."}:"NotAllowedError"===t.errorName?{ok:!1,message:"No permission to access camera."}:"AbortError"===t.errorName?{ok:!1,message:"Some problem occurred which prevented the device from being used."}:"NotReadableError"===t.errorName?{ok:!1,message:"A hardware error occurred."}:"SecurityError"===t.errorName?{ok:!1,message:"User media support is disabled."}:{ok:!1,message:t.errorMessage}}static async createInstance(t){var e,i;if(t&&!(t instanceof Nn))throw new TypeError("Invalid view.");if(null===(e=gt.license)||void 0===e?void 0:e.LicenseManager){if(!(null===(i=gt.license)||void 0===i?void 0:i.LicenseManager.bCallInitLicense))throw new Error("License is not set.");await vt.loadWasm(["license"]),await gt.license.dynamsoft()}const n=new Fs(t);return Fs.onWarning&&(location&&"file:"===location.protocol?setTimeout((()=>{Fs.onWarning&&Fs.onWarning({id:1,message:"The page is opened over file:// and Dynamsoft Camera Enhancer may not work properly. Please open the page via https://."})}),0):!1!==window.isSecureContext&&navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||setTimeout((()=>{Fs.onWarning&&Fs.onWarning({id:2,message:"Dynamsoft Camera Enhancer may not work properly in a non-secure context. Please open the page via https://."})}),0)),n}get video(){return this.cameraManager.getVideoEl()}set videoSrc(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraView&&(this.cameraView._hideDefaultSelection=!0),this.cameraManager.videoSrc=t}get videoSrc(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.videoSrc}set ifSaveLastUsedCamera(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSaveLastUsedCamera=t}get ifSaveLastUsedCamera(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSaveLastUsedCamera}set ifSkipCameraInspection(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.ifSkipCameraInspection=t}get ifSkipCameraInspection(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.ifSkipCameraInspection}set cameraOpenTimeout(t){if(!this.cameraManager)throw new Error("Camera manager is null.");this.cameraManager.cameraOpenTimeout=t}get cameraOpenTimeout(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.cameraOpenTimeout}set singleFrameMode(t){if(!["disabled","image","camera"].includes(t))throw new Error("Invalid value.");if(this.isOpen())throw new Error("It is not allowed to change `singleFrameMode` when the camera is open.");Ke(this,fs,t)}get singleFrameMode(){return Je(this,fs,"f")}get _isFetchingStarted(){return Je(this,ys,"f")}get disposed(){return Je(this,bs,"f")}constructor(t){if(super(),ls.add(this),ds.set(this,"closed"),us.set(this,void 0),this.isTorchOn=void 0,fs.set(this,void 0),this._onCameraSelChange=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&await this.selectCamera(this.cameraView._selCam.value)},this._onResolutionSelChange=async()=>{if(!this.isOpen())return;if(!this.cameraView||this.cameraView.disposed)return;let t,e;if(this.cameraView._selRsl&&-1!=this.cameraView._selRsl.selectedIndex){let i=this.cameraView._selRsl.options[this.cameraView._selRsl.selectedIndex];t=parseInt(i.getAttribute("data-width")),e=parseInt(i.getAttribute("data-height"))}await this.setResolution({width:t,height:e})},this._onCloseBtnClick=async()=>{this.isOpen()&&this.cameraView&&!this.cameraView.disposed&&this.close()},gs.set(this,((t,e,i,n)=>{const r=Date.now(),s={sx:n.x,sy:n.y,sWidth:n.width,sHeight:n.height,dWidth:n.width,dHeight:n.height},a=Math.max(s.dWidth,s.dHeight);if(this.canvasSizeLimit&&a>this.canvasSizeLimit){const t=this.canvasSizeLimit/a;s.dWidth>s.dHeight?(s.dWidth=this.canvasSizeLimit,s.dHeight=Math.round(s.dHeight*t)):(s.dWidth=Math.round(s.dWidth*t),s.dHeight=this.canvasSizeLimit)}const l=this.cameraManager.imageDataGetter.getImageData(t,s,{pixelFormat:this.getPixelFormat()===o.IPF_GRAYSCALED?qn.GREY:qn.RGBA});let h=null;if(l){const t=Date.now();let a;a=l.pixelFormat===qn.GREY?l.width:4*l.width;let o=!0;0===s.sx&&0===s.sy&&s.sWidth===e&&s.sHeight===i&&(o=!1),h={bytes:l.data,width:l.width,height:l.height,stride:a,format:Ls.get(l.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:bt.ITT_FILE_IMAGE,isCropped:o,cropRegion:{left:n.x,top:n.y,right:n.x+n.width,bottom:n.y+n.height,isMeasuredInPercentage:!1},originalWidth:e,originalHeight:i,currentWidth:l.width,currentHeight:l.height,timeSpent:t-r,timeStamp:t},toCanvas:Je(this,ms,"f"),isDCEFrame:!0}}return h})),this._onSingleFrameAcquired=t=>{let e;e=this.cameraView?this.cameraView.getConvertedRegion():Gi.convert(Je(this,_s,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height});const i=Je(this,gs,"f").call(this,t,t.width,t.height,e);Je(this,us,"f").fire("singleFrameAcquired",[i],{async:!1,copy:!1})},ms.set(this,(function(){if(!(this.bytes instanceof Uint8Array||this.bytes instanceof Uint8ClampedArray))throw new TypeError("Invalid bytes.");if("number"!=typeof this.width||this.width<=0)throw new Error("Invalid width.");if("number"!=typeof this.height||this.height<=0)throw new Error("Invalid height.");const t=document.createElement("canvas");let e;if(t.width=this.width,t.height=this.height,this.format===o.IPF_GRAYSCALED){e=new Uint8ClampedArray(this.width*this.height*4);for(let t=0;t{if(!this.video)return;const t=this.cameraManager.getSoftwareScale();if(t<1)throw new RangeError("Invalid scale value.");this.cameraView&&!this.cameraView.disposed?(this.video.style.transform=1===t?"":`scale(${t})`,this.cameraView._updateVideoContainer()):this.video.style.transform=1===t?"":`scale(${t})`},["iPhone","iPad","Android","HarmonyOS"].includes(Ze.OS)?this.cameraManager.setResolution(1280,720):this.cameraManager.setResolution(1920,1080),navigator&&navigator.mediaDevices&&navigator.mediaDevices.getUserMedia?this.singleFrameMode="disabled":this.singleFrameMode="image",t&&(this.setCameraView(t),t.cameraEnhancer=this),this._on("before:camera:change",(()=>{Je(this,Ss,"f").stopCharging();const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("camera:changed",(()=>{this.clearBuffer()})),this._on("before:resolution:change",(()=>{const t=this.cameraView;t&&!t.disposed&&(t._startLoading(),t.clearAllInnerDrawingItems())})),this._on("resolution:changed",(()=>{this.clearBuffer(),t.eventHandler.fire("content:updated",null,{async:!1})})),this._on("paused",(()=>{Je(this,Ss,"f").stopCharging();const t=this.cameraView;t&&t.disposed})),this._on("resumed",(()=>{const t=this.cameraView;t&&t.disposed})),this._on("tapfocus",(()=>{Je(this,Cs,"f").tapToFocus&&Je(this,Ss,"f").startCharging()})),this._intermediateResultReceiver={},this._intermediateResultReceiver.onTaskResultsReceived=async(t,e)=>{var i,n,r,s;if(Je(this,ls,"m",Ts).call(this)||!this.isOpen()||this.isPaused())return;const a=t.intermediateResultUnits;Fs._onLog&&(Fs._onLog("intermediateResultUnits:"),Fs._onLog(a));let o=!1,l=!1;for(let t of a){if(t.unitType===Ot.IRUT_DECODED_BARCODES&&t.decodedBarcodes.length){o=!0;break}t.unitType===Ot.IRUT_LOCALIZED_BARCODES&&t.localizedBarcodes.length&&(l=!0)}if(Fs._onLog&&(Fs._onLog("hasLocalizedBarcodes:"),Fs._onLog(l)),Je(this,Cs,"f").autoZoom||Je(this,Cs,"f").enhancedFocus)if(o)Je(this,Es,"f").autoZoomInFrameArray.length=0,Je(this,Es,"f").autoZoomOutFrameCount=0,Je(this,Es,"f").frameArrayInIdealZoom.length=0,Je(this,Es,"f").autoFocusFrameArray.length=0;else{const e=async t=>{await this.setZoom(t),Je(this,Cs,"f").autoZoom&&Je(this,Ss,"f").startCharging()},o=async t=>{await this.setFocus(t),Je(this,Cs,"f").enhancedFocus&&Je(this,Ss,"f").startCharging()};if(l){const l=a[0].originalImageTag,h=(null===(i=l.cropRegion)||void 0===i?void 0:i.left)||0,c=(null===(n=l.cropRegion)||void 0===n?void 0:n.top)||0,d=(null===(r=l.cropRegion)||void 0===r?void 0:r.right)?l.cropRegion.right-h:l.originalWidth,u=(null===(s=l.cropRegion)||void 0===s?void 0:s.bottom)?l.cropRegion.bottom-c:l.originalHeight,f=l.currentWidth,g=l.currentHeight;let m;{let t,e,i,n,r;{const t=this.video.videoWidth*(1-Je(this,Es,"f").autoZoomDetectionArea)/2,e=this.video.videoWidth*(1+Je(this,Es,"f").autoZoomDetectionArea)/2,i=e,n=t,s=this.video.videoHeight*(1-Je(this,Es,"f").autoZoomDetectionArea)/2,a=s,o=this.video.videoHeight*(1+Je(this,Es,"f").autoZoomDetectionArea)/2;r=[{x:t,y:s},{x:e,y:a},{x:i,y:o},{x:n,y:o}]}Fs._onLog&&(Fs._onLog("detectionArea:"),Fs._onLog(r));const s=[];{const t=(t,e)=>{const i=(t,e)=>{if(!t&&!e)throw new Error("Invalid arguments.");return function(t,e,i){let n=!1;const r=t.length;if(r<=2)return!1;for(let s=0;s0!=Xi(o.y-i)>0&&Xi(e-(i-a.y)*(a.x-o.x)/(a.y-o.y)-a.x)<0&&(n=!n)}return n}(e,t.x,t.y)},n=(t,e)=>!!(Zi([t[0],t[1]],[t[2],t[3]],[e[0].x,e[0].y],[e[1].x,e[1].y])||Zi([t[0],t[1]],[t[2],t[3]],[e[1].x,e[1].y],[e[2].x,e[2].y])||Zi([t[0],t[1]],[t[2],t[3]],[e[2].x,e[2].y],[e[3].x,e[3].y])||Zi([t[0],t[1]],[t[2],t[3]],[e[3].x,e[3].y],[e[0].x,e[0].y]));return!!(i({x:t[0].x,y:t[0].y},e)||i({x:t[1].x,y:t[1].y},e)||i({x:t[2].x,y:t[2].y},e)||i({x:t[3].x,y:t[3].y},e))||!!(i({x:e[0].x,y:e[0].y},t)||i({x:e[1].x,y:e[1].y},t)||i({x:e[2].x,y:e[2].y},t)||i({x:e[3].x,y:e[3].y},t))||!!(n([e[0].x,e[0].y,e[1].x,e[1].y],t)||n([e[1].x,e[1].y,e[2].x,e[2].y],t)||n([e[2].x,e[2].y,e[3].x,e[3].y],t)||n([e[3].x,e[3].y,e[0].x,e[0].y],t))};for(let e of a)if(e.unitType===Ot.IRUT_LOCALIZED_BARCODES)for(let i of e.localizedBarcodes){if(!i)continue;const e=i.location.points;e.forEach((t=>{Nn._transformCoordinates(t,h,c,d,u,f,g)})),t(r,e)&&s.push(i)}if(Fs._debug&&this.cameraView){const t=this.__layer||(this.__layer=this.cameraView._createDrawingLayer(99));t.clearDrawingItems();const e=this.__styleId2||(this.__styleId2=Dn.createDrawingStyle({strokeStyle:"red"}));for(let i of a)if(i.unitType===Ot.IRUT_LOCALIZED_BARCODES)for(let n of i.localizedBarcodes){if(!n)continue;const i=n.location.points,r=new Ri({points:i},e);t.addDrawingItems([r])}}}if(Fs._onLog&&(Fs._onLog("intersectedResults:"),Fs._onLog(s)),!s.length)return;let o;if(s.length){let t=s.filter((t=>t.possibleFormats==Ms.BF_QR_CODE||t.possibleFormats==Ms.BF_DATAMATRIX));if(t.length||(t=s.filter((t=>t.possibleFormats==Ms.BF_ONED)),t.length||(t=s)),t.length){const e=t=>{const e=t.location.points,i=(e[0].x+e[1].x+e[2].x+e[3].x)/4,n=(e[0].y+e[1].y+e[2].y+e[3].y)/4;return(i-f/2)*(i-f/2)+(n-g/2)*(n-g/2)};o=t[0];let i=e(o);if(1!=t.length)for(let n=1;n1.1*o.confidence||t[n].confidence>.9*o.confidence&&ri&&s>i&&a>i&&l>i&&m.result.moduleSize{})),Je(this,Es,"f").autoZoomInFrameArray.filter((t=>!0===t)).length>=Je(this,Es,"f").autoZoomInFrameLimit[1]){Je(this,Es,"f").autoZoomInFrameArray.length=0;const i=[(.5-n)/(.5-r),(.5-n)/(.5-s),(.5-n)/(.5-a),(.5-n)/(.5-l)].filter((t=>t>0)),o=Math.min(...i,Je(this,Es,"f").autoZoomInIdealModuleSize/m.result.moduleSize),h=this.getZoomSettings().factor;let c=Math.max(Math.pow(h*o,1/Je(this,Es,"f").autoZoomInMaxTimes),Je(this,Es,"f").autoZoomInMinStep);c=Math.min(c,o);let d=h*c;d=Math.max(Je(this,Es,"f").minValue,d),d=Math.min(Je(this,Es,"f").maxValue,d);try{await e({factor:d})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else if(Je(this,Es,"f").autoZoomInFrameArray.length=0,Je(this,Es,"f").frameArrayInIdealZoom.push(!0),Je(this,Es,"f").frameArrayInIdealZoom.splice(0,Je(this,Es,"f").frameArrayInIdealZoom.length-Je(this,Es,"f").frameLimitInIdealZoom[0]),Je(this,Es,"f").frameArrayInIdealZoom.filter((t=>!0===t)).length>=Je(this,Es,"f").frameLimitInIdealZoom[1]&&(Je(this,Es,"f").frameArrayInIdealZoom.length=0,Je(this,Cs,"f").enhancedFocus)){const e=m.points;try{await o({mode:"manual",area:{centerPoint:{x:(e[0].x+e[2].x)/2+"px",y:(e[0].y+e[2].y)/2+"px"},width:e[2].x-e[0].x+"px",height:e[2].y-e[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}if(!Je(this,Cs,"f").autoZoom&&Je(this,Cs,"f").enhancedFocus&&(Je(this,Es,"f").autoFocusFrameArray.push(!0),Je(this,Es,"f").autoFocusFrameArray.splice(0,Je(this,Es,"f").autoFocusFrameArray.length-Je(this,Es,"f").autoFocusFrameLimit[0]),Je(this,Es,"f").autoFocusFrameArray.filter((t=>!0===t)).length>=Je(this,Es,"f").autoFocusFrameLimit[1])){Je(this,Es,"f").autoFocusFrameArray.length=0;try{const t=m.points;await o({mode:"manual",area:{centerPoint:{x:(t[0].x+t[2].x)/2+"px",y:(t[0].y+t[2].y)/2+"px"},width:t[2].x-t[0].x+"px",height:t[2].y-t[0].y+"px"}})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}}else{if(Je(this,Cs,"f").autoZoom){if(Je(this,Es,"f").autoZoomInFrameArray.push(!1),Je(this,Es,"f").autoZoomInFrameArray.splice(0,Je(this,Es,"f").autoZoomInFrameArray.length-Je(this,Es,"f").autoZoomInFrameLimit[0]),Je(this,Es,"f").autoZoomOutFrameCount++,Je(this,Es,"f").frameArrayInIdealZoom.push(!1),Je(this,Es,"f").frameArrayInIdealZoom.splice(0,Je(this,Es,"f").frameArrayInIdealZoom.length-Je(this,Es,"f").frameLimitInIdealZoom[0]),Je(this,Es,"f").autoZoomOutFrameCount>=Je(this,Es,"f").autoZoomOutFrameLimit){Je(this,Es,"f").autoZoomOutFrameCount=0;const i=this.getZoomSettings().factor;let n=i-Math.max((i-1)*Je(this,Es,"f").autoZoomOutStepRate,Je(this,Es,"f").autoZoomOutMinStep);n=Math.max(Je(this,Es,"f").minValue,n),n=Math.min(Je(this,Es,"f").maxValue,n);try{await e({factor:n})}catch(t){const e=t.message||t;console.warn(e)}this.clearBuffer()}Je(this,Cs,"f").enhancedFocus&&o({mode:"continuous"}).catch((()=>{}))}!Je(this,Cs,"f").autoZoom&&Je(this,Cs,"f").enhancedFocus&&(Je(this,Es,"f").autoFocusFrameArray.length=0,o({mode:"continuous"}).catch((()=>{})))}}},Ke(this,Ss,new Rs(1e4))}setCameraView(t){if(!(t instanceof Nn))throw new TypeError("Invalid view.");if(t.disposed)throw new Error("The camera view has been disposed.");if(this.isOpen())throw new Error("It is not allowed to change camera view when the camera is open.");this.releaseCameraView(),t._singleFrameMode=this.singleFrameMode,t._onSingleFrameAcquired=this._onSingleFrameAcquired,this.videoSrc&&(this.cameraView._hideDefaultSelection=!0),Je(this,ls,"m",Ts).call(this)||this.cameraManager.setVideoEl(t.getVideoElement()),this.cameraView=t,this.addListenerToView()}getCameraView(){return this.cameraView}releaseCameraView(){this.cameraView&&(this.removeListenerFromView(),this.cameraView.disposed||(this.cameraView._singleFrameMode="disabled",this.cameraView._onSingleFrameAcquired=null,this.cameraView._hideDefaultSelection=!1),this.cameraManager.releaseVideoEl(),this.cameraView=null)}addListenerToView(){if(!this.cameraView)return;if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");const t=this.cameraView;Je(this,ls,"m",Ts).call(this)||this.videoSrc||(t._innerComponent&&(this.cameraManager.tapFocusEventBoundEl=t._innerComponent),t._selCam&&t._selCam.addEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.addEventListener("change",this._onResolutionSelChange)),t._btnClose&&t._btnClose.addEventListener("click",this._onCloseBtnClick)}removeListenerFromView(){if(!this.cameraView||this.cameraView.disposed)return;const t=this.cameraView;this.cameraManager.tapFocusEventBoundEl=null,t._selCam&&t._selCam.removeEventListener("change",this._onCameraSelChange),t._selRsl&&t._selRsl.removeEventListener("change",this._onResolutionSelChange),t._btnClose&&t._btnClose.removeEventListener("click",this._onCloseBtnClick)}getCameraState(){return Je(this,ls,"m",Ts).call(this)?Je(this,ds,"f"):new Map([["closed","closed"],["opening","opening"],["opened","open"]]).get(this.cameraManager.state)}isOpen(){return"open"===this.getCameraState()}getVideoEl(){return this.video}async open(){const t=this.cameraView;if(null==t?void 0:t.disposed)throw new Error("'cameraView' has been disposed.");t&&(t._singleFrameMode=this.singleFrameMode,Je(this,ls,"m",Ts).call(this)?t._clickIptSingleFrameMode():(this.cameraManager.setVideoEl(t.getVideoElement()),t._startLoading()));let e={width:0,height:0,deviceId:""};if(Je(this,ls,"m",Ts).call(this));else{try{await this.cameraManager.open()}catch(e){throw t&&t._stopLoading(),"NotFoundError"===e.name?new Error(`No camera devices were detected. Please ensure a camera is connected and recognized by your system. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):"NotAllowedError"===e.name?new Error(`Camera access is blocked. Please check your browser settings or grant permission to use the camera. ${null==e?void 0:e.name}: ${null==e?void 0:e.message}`):e}let i,n=t.getUIElement();if(n=n.shadowRoot||n,i=n.querySelector(".dce-macro-use-mobile-native-like-ui")){let t=n.elTorchAuto=n.querySelector(".dce-mn-torch-auto"),e=n.elTorchOn=n.querySelector(".dce-mn-torch-on"),r=n.elTorchOff=n.querySelector(".dce-mn-torch-off");t&&(e.style.display=null==this.isTorchOn?"":"none"),e&&(e.style.display=1==this.isTorchOn?"":"none"),r&&(r.style.display=0==this.isTorchOn?"":"none");let s=n.elBeepOn=n.querySelector(".dce-mn-beep-on"),a=n.elBeepOff=n.querySelector(".dce-mn-beep-off");s&&(s.style.display=Ds.allowBeep?"":"none"),a&&(a.style.display=Ds.allowBeep?"none":"");let o=n.elVibrateOn=n.querySelector(".dce-mn-vibrate-on"),l=n.elVibrateOff=n.querySelector(".dce-mn-vibrate-off");o&&(o.style.display=Ds.allowVibrate?"":"none"),l&&(l.style.display=Ds.allowVibrate?"none":""),n.elResolutionBox=n.querySelector(".dce-mn-resolution-box");let h,c=n.elZoom=n.querySelector(".dce-mn-zoom");c&&(c.style.display="none",h=n.elZoomSpan=c.querySelector("span"));let d=n.elToast=n.querySelector(".dce-mn-toast"),u=n.elCameraClose=n.querySelector(".dce-mn-camera-close"),f=n.elTakePhoto=n.querySelector(".dce-mn-take-photo"),g=n.elCameraSwitch=n.querySelector(".dce-mn-camera-switch"),m=n.elCameraAndResolutionSettings=n.querySelector(".dce-mn-camera-and-resolution-settings");m&&(m.style.display="none");const p=n.dceMnFs={},_=()=>{this.turnOnTorch()};null==t||t.addEventListener("pointerdown",_);const v=()=>{this.turnOffTorch()};null==e||e.addEventListener("pointerdown",v);const y=()=>{this.turnAutoTorch()};null==r||r.addEventListener("pointerdown",y);const w=()=>{Ds.allowBeep=!Ds.allowBeep,s&&(s.style.display=Ds.allowBeep?"":"none"),a&&(a.style.display=Ds.allowBeep?"none":"")};for(let t of[a,s])null==t||t.addEventListener("pointerdown",w);const C=()=>{Ds.allowVibrate=!Ds.allowVibrate,o&&(o.style.display=Ds.allowVibrate?"":"none"),l&&(l.style.display=Ds.allowVibrate?"none":"")};for(let t of[l,o])null==t||t.addEventListener("pointerdown",C);const E=async t=>{let e,i=t.target;if(e=i.closest(".dce-mn-camera-option"))this.selectCamera(e.getAttribute("data-davice-id"));else if(e=i.closest(".dce-mn-resolution-option")){let t,i=parseInt(e.getAttribute("data-width")),n=parseInt(e.getAttribute("data-height")),r=await this.setResolution({width:i,height:n});{let e=Math.max(r.width,r.height),i=Math.min(r.width,r.height);t=i<=1080?i+"P":e<3e3?"2K":Math.round(e/1e3)+"K"}t!=e.textContent&&T(`Fallback to ${t}`)}else i.closest(".dce-mn-camera-and-resolution-settings")||(i.closest(".dce-mn-resolution-box")?m&&(m.style.display=m.style.display?"":"none"):m&&""===m.style.display&&(m.style.display="none"))};n.addEventListener("click",E);let S=null;p.funcInfoZoomChange=(t,e=3e3)=>{c&&h&&(h.textContent=t.toFixed(1),c.style.display="",null!=S&&(clearTimeout(S),S=null),S=setTimeout((()=>{c.style.display="none",S=null}),e))};let b=null,T=p.funcShowToast=(t,e=3e3)=>{d&&(d.textContent=t,d.style.display="",null!=b&&(clearTimeout(b),b=null),b=setTimeout((()=>{d.style.display="none",b=null}),e))};const I=()=>{this.close()};null==u||u.addEventListener("click",I);const x=()=>{};null==f||f.addEventListener("pointerdown",x);const O=()=>{var t,e;let i,n=this.getVideoSettings(),r=n.video.facingMode,s=null===(e=null===(t=this.cameraManager.getCamera())||void 0===t?void 0:t.label)||void 0===e?void 0:e.toLowerCase(),a=null==s?void 0:s.indexOf("front");-1===a&&(a=null==s?void 0:s.indexOf("前"));let o=null==s?void 0:s.indexOf("back");-1===o&&(o=null==s?void 0:s.indexOf("后")),"number"==typeof a&&-1!==a?i=!0:"number"==typeof o&&-1!==o&&(i=!1),void 0===i&&(i="user"===((null==r?void 0:r.ideal)||(null==r?void 0:r.exact)||r)),n.video.facingMode={ideal:i?"environment":"user"},delete n.video.deviceId,this.updateVideoSettings(n)};null==g||g.addEventListener("pointerdown",O);let A=-1/0,R=1;const D=t=>{let e=Date.now();e-A>1e3&&(R=this.getZoomSettings().factor),R-=t.deltaY/200,R>20&&(R=20),R<1&&(R=1),this.setZoom({factor:R}),A=e};i.addEventListener("wheel",D);const L=new Map;let M=!1;const F=async t=>{var e;for(t.touches.length>=2&&"touchmove"==t.type&&t.preventDefault();t.changedTouches.length>1&&2==t.touches.length;){let i=t.touches[0],n=t.touches[1],r=L.get(i.identifier),s=L.get(n.identifier);if(!r||!s)break;let a=Math.pow(Math.pow(r.x-s.x,2)+Math.pow(r.y-s.y,2),.5),o=Math.pow(Math.pow(i.clientX-n.clientX,2)+Math.pow(i.clientY-n.clientY,2),.5),l=Date.now();if(M||l-A<100)return;l-A>1e3&&(R=this.getZoomSettings().factor),R*=o/a,R>20&&(R=20),R<1&&(R=1);let h=!1;"safari"==(null===(e=null==Ze?void 0:Ze.browser)||void 0===e?void 0:e.toLocaleLowerCase())&&(o/a>1&&R<2?(R=2,h=!0):o/a<1&&R<2&&(R=1,h=!0)),M=!0,h&&T("zooming..."),await this.setZoom({factor:R}),h&&(d.textContent=""),M=!1,A=Date.now();break}L.clear();for(let e of t.touches)L.set(e.identifier,{x:e.clientX,y:e.clientY})};n.addEventListener("touchstart",F),n.addEventListener("touchmove",F),n.addEventListener("touchend",F),n.addEventListener("touchcancel",F),p.unbind=()=>{null==t||t.removeEventListener("pointerdown",_),null==e||e.removeEventListener("pointerdown",v),null==r||r.removeEventListener("pointerdown",y);for(let t of[a,s])null==t||t.removeEventListener("pointerdown",w);for(let t of[l,o])null==t||t.removeEventListener("pointerdown",C);n.removeEventListener("click",E),null==u||u.removeEventListener("click",I),null==f||f.removeEventListener("pointerdown",x),null==g||g.removeEventListener("pointerdown",O),i.removeEventListener("wheel",D),n.removeEventListener("touchstart",F),n.removeEventListener("touchmove",F),n.removeEventListener("touchend",F),n.removeEventListener("touchcancel",F),delete n.dceMnFs,i.style.display="none"},i.style.display="",t&&null==this.isTorchOn&&setTimeout((()=>{this.turnAutoTorch(1e3)}),0)}this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const r=this.getResolution();e.width=r.width,e.height=r.height,e.deviceId=this.getSelectedCamera().deviceId}return Ke(this,ds,"open"),t&&(t._innerComponent.style.display="",Je(this,ls,"m",Ts).call(this)||(t._stopLoading(),t._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),t._renderResolutionInfo({width:e.width,height:e.height}),t.eventHandler.fire("content:updated",null,{async:!1}),t.eventHandler.fire("videoEl:resized",null,{async:!1}))),Je(this,us,"f").fire("opened",null,{target:this,async:!1}),e}close(){var t;const e=this.cameraView;if(null==e?void 0:e.disposed)throw new Error("'cameraView' has been disposed.");if(this.stopFetching(),this.clearBuffer(),Je(this,ls,"m",Ts).call(this));else{this.cameraManager.close();let i=e.getUIElement();i=i.shadowRoot||i,i.querySelector(".dce-macro-use-mobile-native-like-ui")&&(null===(t=i.dceMnFs)||void 0===t||t.unbind())}Ke(this,ds,"closed"),Je(this,Ss,"f").stopCharging(),e&&(e._innerComponent.style.display="none",Je(this,ls,"m",Ts).call(this)&&e._innerComponent.removeElement("content"),e._stopLoading()),Je(this,us,"f").fire("closed",null,{target:this,async:!1})}pause(){if(Je(this,ls,"m",Ts).call(this))throw new Error("'pause()' is invalid in 'singleFrameMode'.");this.cameraManager.pause()}isPaused(){var t;return!Je(this,ls,"m",Ts).call(this)&&!0===(null===(t=this.video)||void 0===t?void 0:t.paused)}async resume(){if(Je(this,ls,"m",Ts).call(this))throw new Error("'resume()' is invalid in 'singleFrameMode'.");await this.cameraManager.resume()}async selectCamera(t){if(!t)throw new Error("Invalid value.");let e;e="string"==typeof t?t:t.deviceId,await this.cameraManager.setCamera(e),this.isTorchOn=!1;const i=this.getResolution(),n=this.cameraView;return n&&!n.disposed&&(n._stopLoading(),n._renderCamerasInfo(this.getSelectedCamera(),this.cameraManager._arrCameras),n._renderResolutionInfo({width:i.width,height:i.height})),{width:i.width,height:i.height,deviceId:this.getSelectedCamera().deviceId}}getSelectedCamera(){return this.cameraManager.getCamera()}async getAllCameras(){return this.cameraManager.getCameras()}async setResolution(t){await this.cameraManager.setResolution(t.width,t.height),this.isTorchOn&&this.turnOnTorch().catch((()=>{}));const e=this.getResolution(),i=this.cameraView;return i&&!i.disposed&&(i._stopLoading(),i._renderResolutionInfo({width:e.width,height:e.height})),{width:e.width,height:e.height,deviceId:this.getSelectedCamera().deviceId}}getResolution(){return this.cameraManager.getResolution()}getAvailableResolutions(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getResolutions()}_on(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Je(this,us,"f").on(t,e):this.cameraManager.on(t,e)}_off(t,e){["opened","closed","singleframeacquired","frameaddedtobuffer"].includes(t.toLowerCase())?Je(this,us,"f").off(t,e):this.cameraManager.off(t,e)}on(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._on(n,e)}off(t,e){const i=t.toLowerCase(),n=new Map([["cameraopen","opened"],["cameraclose","closed"],["camerachange","camera:changed"],["resolutionchange","resolution:changed"],["played","played"],["singleframeacquired","singleFrameAcquired"],["frameaddedtobuffer","frameAddedToBuffer"]]).get(i);if(!n)throw new Error("Invalid event.");this._off(n,e)}getVideoSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getMediaStreamConstraints()}async updateVideoSettings(t){var e;await(null===(e=this.cameraManager)||void 0===e?void 0:e.setMediaStreamConstraints(t,!0))}getCapabilities(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getCameraCapabilities()}getCameraSettings(){return this.cameraManager.getCameraSettings()}async turnOnTorch(){var t,e;if(Je(this,ls,"m",Ts).call(this))throw new Error("'turnOnTorch()' is invalid in 'singleFrameMode'.");try{await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOnTorch())}catch(t){let i=this.cameraView.getUIElement();throw i=i.shadowRoot||i,null===(e=null==i?void 0:i.dceMnFs)||void 0===e||e.funcShowToast("Torch Not Supported"),t}this.isTorchOn=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,i.elTorchAuto&&(i.elTorchAuto.style.display="none"),i.elTorchOn&&(i.elTorchOn.style.display=""),i.elTorchOff&&(i.elTorchOff.style.display="none")}async turnOffTorch(){var t;if(Je(this,ls,"m",Ts).call(this))throw new Error("'turnOffTorch()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.turnOffTorch()),this.isTorchOn=!1;let e=this.cameraView.getUIElement();e=e.shadowRoot||e,e.elTorchAuto&&(e.elTorchAuto.style.display="none"),e.elTorchOn&&(e.elTorchOn.style.display="none"),e.elTorchOff&&(e.elTorchOff.style.display="")}async turnAutoTorch(t=250){if(null!=this._taskid4AutoTorch){if(!(t{var t,r,s;if(this.disposed||e||null!=this.isTorchOn||!this.isOpen())return clearInterval(this._taskid4AutoTorch),void(this._taskid4AutoTorch=null);if(this.isPaused())return;if(++n>10&&this._delay4AutoTorch<1e3)return clearInterval(this._taskid4AutoTorch),this._taskid4AutoTorch=null,void this.turnAutoTorch(1e3);let a;try{a=this.fetchImage()}catch(t){}if(!a||!a.width||!a.height)return;let l=0;if(o.IPF_GRAYSCALED===a.format){for(let t=0;t=this.maxDarkCount4AutoTroch){null===(t=Fs._onLog)||void 0===t||t.call(Fs,`darkCount ${i}`);try{await this.turnOnTorch(),this.isTorchOn=!0;let t=this.cameraView.getUIElement();t=t.shadowRoot||t,null===(r=null==t?void 0:t.dceMnFs)||void 0===r||r.funcShowToast("Torch Auto On")}catch(t){console.warn(t),e=!0;let i=this.cameraView.getUIElement();i=i.shadowRoot||i,null===(s=null==i?void 0:i.dceMnFs)||void 0===s||s.funcShowToast("Torch Not Supported")}}}else i=0};this._taskid4AutoTorch=setInterval(r,t),this.isTorchOn=void 0,r();let s=this.cameraView.getUIElement();s=s.shadowRoot||s,s.elTorchAuto&&(s.elTorchAuto.style.display=""),s.elTorchOn&&(s.elTorchOn.style.display="none"),s.elTorchOff&&(s.elTorchOff.style.display="none")}async setColorTemperature(t){if(Je(this,ls,"m",Ts).call(this))throw new Error("'setColorTemperature()' is invalid in 'singleFrameMode'.");await this.cameraManager.setColorTemperature(t,!0)}getColorTemperature(){return this.cameraManager.getColorTemperature()}async setExposureCompensation(t){var e;if(Je(this,ls,"m",Ts).call(this))throw new Error("'setExposureCompensation()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setExposureCompensation(t,!0))}getExposureCompensation(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getExposureCompensation()}async _setZoom(t){var e,i,n;if(Je(this,ls,"m",Ts).call(this))throw new Error("'setZoom()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setZoom(t));{let e=null===(i=this.cameraView)||void 0===i?void 0:i.getUIElement();e=(null==e?void 0:e.shadowRoot)||e,null===(n=null==e?void 0:e.dceMnFs)||void 0===n||n.funcInfoZoomChange(t.factor)}}async setZoom(t){await this._setZoom(t)}getZoomSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getZoom()}async resetZoom(){var t;if(Je(this,ls,"m",Ts).call(this))throw new Error("'resetZoom()' is invalid in 'singleFrameMode'.");await(null===(t=this.cameraManager)||void 0===t?void 0:t.resetZoom())}async setFrameRate(t){var e;if(Je(this,ls,"m",Ts).call(this))throw new Error("'setFrameRate()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFrameRate(t,!0))}getFrameRate(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFrameRate()}async setFocus(t){var e;if(Je(this,ls,"m",Ts).call(this))throw new Error("'setFocus()' is invalid in 'singleFrameMode'.");await(null===(e=this.cameraManager)||void 0===e?void 0:e.setFocus(t,!0))}getFocusSettings(){var t;return null===(t=this.cameraManager)||void 0===t?void 0:t.getFocus()}setAutoZoomRange(t){Je(this,Es,"f").minValue=t.min,Je(this,Es,"f").maxValue=t.max}getAutoZoomRange(){return{min:Je(this,Es,"f").minValue,max:Je(this,Es,"f").maxValue}}async enableEnhancedFeatures(t){var e,i;if(!(null===(i=null===(e=gt.license)||void 0===e?void 0:e.LicenseManager)||void 0===i?void 0:i.bPassValidation))throw new Error("License is not verified, or license is invalid.");if(0!==vt.bSupportDce4Module)throw new Error("Please set a license containing the DCE module.");t&li.EF_ENHANCED_FOCUS&&(Je(this,Cs,"f").enhancedFocus=!0),t&li.EF_AUTO_ZOOM&&(Je(this,Cs,"f").autoZoom=!0),t&li.EF_TAP_TO_FOCUS&&(Je(this,Cs,"f").tapToFocus=!0,this.cameraManager.enableTapToFocus())}disableEnhancedFeatures(t){t&li.EF_ENHANCED_FOCUS&&(Je(this,Cs,"f").enhancedFocus=!1,this.setFocus({mode:"continuous"}).catch((()=>{}))),t&li.EF_AUTO_ZOOM&&(Je(this,Cs,"f").autoZoom=!1,this.resetZoom().catch((()=>{}))),t&li.EF_TAP_TO_FOCUS&&(Je(this,Cs,"f").tapToFocus=!1,this.cameraManager.disableTapToFocus()),Je(this,ls,"m",xs).call(this)&&Je(this,ls,"m",Is).call(this)||Je(this,Ss,"f").stopCharging()}_setScanRegion(t){if(null!=t&&!E(t)&&!O(t))throw TypeError("Invalid 'region'.");Ke(this,_s,t?JSON.parse(JSON.stringify(t)):null),this.cameraView&&!this.cameraView.disposed&&this.cameraView.setScanRegion(t)}setScanRegion(t){this._setScanRegion(t),this.cameraView&&!this.cameraView.disposed&&(null===t?this.cameraView.setScanRegionMaskVisible(!1):this.cameraView.setScanRegionMaskVisible(!0))}getScanRegion(){return JSON.parse(JSON.stringify(Je(this,_s,"f")))}setErrorListener(t){if(!t)throw new TypeError("Invalid 'listener'");Ke(this,ps,t)}hasNextImageToFetch(){return!("open"!==this.getCameraState()||!this.cameraManager.isVideoLoaded()||Je(this,ls,"m",Ts).call(this))}startFetching(){if(Je(this,ls,"m",Ts).call(this))throw Error("'startFetching()' is unavailable in 'singleFrameMode'.");Je(this,ys,"f")||(Ke(this,ys,!0),Je(this,ls,"m",Os).call(this))}stopFetching(){Je(this,ys,"f")&&(Fs._onLog&&Fs._onLog("DCE: stop fetching loop: "+Date.now()),Je(this,ws,"f")&&clearTimeout(Je(this,ws,"f")),Ke(this,ys,!1))}fetchImage(){if(Je(this,ls,"m",Ts).call(this))throw new Error("'fetchImage()' is unavailable in 'singleFrameMode'.");if(!this.video)throw new Error("The video element does not exist.");if(4!==this.video.readyState)throw new Error("The video is not loaded.");const t=this.getResolution();if(!(null==t?void 0:t.width)||!(null==t?void 0:t.height))throw new Error("The video is not loaded.");let e;if(e=Gi.convert(Je(this,_s,"f"),t.width,t.height),e||(e={x:0,y:0,width:t.width,height:t.height}),e.x>t.width||e.y>t.height)throw new Error("Invalid scan region.");e.x+e.width>t.width&&(e.width=t.width-e.x),e.y+e.height>t.height&&(e.height=t.height-e.y);const i={sx:e.x,sy:e.y,sWidth:e.width,sHeight:e.height,dWidth:e.width,dHeight:e.height},n=Math.max(i.dWidth,i.dHeight);if(this.canvasSizeLimit&&n>this.canvasSizeLimit){const t=this.canvasSizeLimit/n;i.dWidth>i.dHeight?(i.dWidth=this.canvasSizeLimit,i.dHeight=Math.round(i.dHeight*t)):(i.dWidth=Math.round(i.dWidth*t),i.dHeight=this.canvasSizeLimit)}const r=this.cameraManager.getFrameData({position:i,pixelFormat:this.getPixelFormat()===o.IPF_GRAYSCALED?qn.GREY:qn.RGBA});if(!r)return null;let s;s=r.pixelFormat===qn.GREY?r.width:4*r.width;let a=!0;return 0===i.sx&&0===i.sy&&i.sWidth===t.width&&i.sHeight===t.height&&(a=!1),{bytes:r.data,width:r.width,height:r.height,stride:s,format:Ls.get(r.pixelFormat),tag:{imageId:this._imageId==Number.MAX_VALUE?this._imageId=0:++this._imageId,type:bt.ITT_VIDEO_FRAME,isCropped:a,cropRegion:{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height,isMeasuredInPercentage:!1},originalWidth:t.width,originalHeight:t.height,currentWidth:r.width,currentHeight:r.height,timeSpent:r.timeSpent,timeStamp:r.timeStamp},toCanvas:Je(this,ms,"f"),isDCEFrame:!0}}setImageFetchInterval(t){this.fetchInterval=t,Je(this,ys,"f")&&(Je(this,ws,"f")&&clearTimeout(Je(this,ws,"f")),Ke(this,ws,setTimeout((()=>{this.disposed||Je(this,ls,"m",Os).call(this)}),t)))}getImageFetchInterval(){return this.fetchInterval}setPixelFormat(t){Ke(this,vs,t)}getPixelFormat(){return Je(this,vs,"f")}takePhoto(t){if(!this.isOpen())throw new Error("Not open.");if(Je(this,ls,"m",Ts).call(this))throw new Error("'takePhoto()' is unavailable in 'singleFrameMode'.");const e=document.createElement("input");e.setAttribute("type","file"),e.setAttribute("accept",".jpg,.jpeg,.icon,.gif,.svg,.webp,.png,.bmp"),e.setAttribute("capture",""),e.style.position="absolute",e.style.top="-9999px",e.style.backgroundColor="transparent",e.style.color="transparent",e.addEventListener("click",(()=>{const t=this.isOpen();this.close(),window.addEventListener("focus",(()=>{t&&this.open(),e.remove()}),{once:!0})})),e.addEventListener("change",(async()=>{const i=e.files[0],n=await(async t=>{let e=null,i=null;if("undefined"!=typeof createImageBitmap)try{if(e=await createImageBitmap(t),e)return e}catch(t){}var n;return e||(i=await(n=t,new Promise(((t,e)=>{let i=URL.createObjectURL(n),r=new Image;r.src=i,r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=t=>{e(new Error("Can't convert blob to image : "+(t instanceof Event?t.type:t)))}})))),i})(i),r=n instanceof HTMLImageElement?n.naturalWidth:n.width,s=n instanceof HTMLImageElement?n.naturalHeight:n.height;let a=Gi.convert(Je(this,_s,"f"),r,s);a||(a={x:0,y:0,width:r,height:s});const o=Je(this,gs,"f").call(this,n,r,s,a);t&&t(o)})),document.body.appendChild(e),e.click()}convertToPageCoordinates(t){const e=Je(this,ls,"m",As).call(this,t);return{x:e.pageX,y:e.pageY}}convertToClientCoordinates(t){const e=Je(this,ls,"m",As).call(this,t);return{x:e.clientX,y:e.clientY}}convertToScanRegionCoordinates(t){if(!Je(this,_s,"f"))return JSON.parse(JSON.stringify(t));let e,i,n=Je(this,_s,"f").left||Je(this,_s,"f").x||0,r=Je(this,_s,"f").top||Je(this,_s,"f").y||0;if(!Je(this,_s,"f").isMeasuredInPercentage)return{x:t.x-n,y:t.y-r};if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Je(this,ls,"m",Ts).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Je(this,ls,"m",Ts).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");if(Je(this,ls,"m",Ts).call(this)){const t=this.cameraView._innerComponent.getElement("content");e=t.width,i=t.height}else{const t=this.getVideoEl();e=t.videoWidth,i=t.videoHeight}return{x:t.x-Math.round(n*e/100),y:t.y-Math.round(r*i/100)}}dispose(){this.close(),this.cameraManager.dispose(),this.releaseCameraView(),Ke(this,bs,!0)}}var Ps,ks,Ns,Bs,js,Vs,Us,Gs;hs=Fs,ds=new WeakMap,us=new WeakMap,fs=new WeakMap,gs=new WeakMap,ms=new WeakMap,ps=new WeakMap,_s=new WeakMap,vs=new WeakMap,ys=new WeakMap,ws=new WeakMap,Cs=new WeakMap,Es=new WeakMap,Ss=new WeakMap,bs=new WeakMap,ls=new WeakSet,Ts=function(){return"disabled"!==this.singleFrameMode},Is=function(){return!this.videoSrc&&"opened"===this.cameraManager.state},xs=function(){for(let t in Je(this,Cs,"f"))if(1==Je(this,Cs,"f")[t])return!0;return!1},Os=function t(){if(this.disposed)return;if("open"!==this.getCameraState()||!Je(this,ys,"f"))return Je(this,ws,"f")&&clearTimeout(Je(this,ws,"f")),void Ke(this,ws,setTimeout((()=>{this.disposed||Je(this,ls,"m",t).call(this)}),this.fetchInterval));const e=()=>{var t;let e;Fs._onLog&&Fs._onLog("DCE: start fetching a frame into buffer: "+Date.now());try{e=this.fetchImage()}catch(e){const i=e.message||e;if("The video is not loaded."===i)return;if(null===(t=Je(this,ps,"f"))||void 0===t?void 0:t.onErrorReceived)return void setTimeout((()=>{var t;null===(t=Je(this,ps,"f"))||void 0===t||t.onErrorReceived(Ct.EC_IMAGE_READ_FAILED,i)}),0);console.warn(e)}e?(this.addImageToBuffer(e),Fs._onLog&&Fs._onLog("DCE: finish fetching a frame into buffer: "+Date.now()),Je(this,us,"f").fire("frameAddedToBuffer",null,{async:!1})):Fs._onLog&&Fs._onLog("DCE: get a invalid frame, abandon it: "+Date.now())};if(this.getImageCount()>=this.getMaxImageCount())switch(this.getBufferOverflowProtectionMode()){case s.BOPM_BLOCK:break;case s.BOPM_UPDATE:e()}else e();Je(this,ws,"f")&&clearTimeout(Je(this,ws,"f")),Ke(this,ws,setTimeout((()=>{this.disposed||Je(this,ls,"m",t).call(this)}),this.fetchInterval))},As=function(t){if(!this.cameraView)throw new Error("Camera view is not set.");if(this.cameraView.disposed)throw new Error("'cameraView' has been disposed.");if(!this.isOpen())throw new Error("Not open.");if(!Je(this,ls,"m",Ts).call(this)&&!this.cameraManager.isVideoLoaded())throw new Error("Video is not loaded.");if(Je(this,ls,"m",Ts).call(this)&&!this.cameraView._cvsSingleFrameMode)throw new Error("No image is selected.");const e=this.cameraView._innerComponent.getBoundingClientRect(),i=e.left,n=e.top,r=i+window.scrollX,s=n+window.scrollY,{width:a,height:o}=this.cameraView._innerComponent.getBoundingClientRect();if(a<=0||o<=0)throw new Error("Unable to get content dimensions. Camera view may not be rendered on the page.");let l,h,c;if(Je(this,ls,"m",Ts).call(this)){const t=this.cameraView._innerComponent.getElement("content");l=t.width,h=t.height,c="contain"}else{const t=this.getVideoEl();l=t.videoWidth,h=t.videoHeight,c=this.cameraView.getVideoFit()}const d=a/o,u=l/h;let f,g,m,p,_=1;if("contain"===c)d{var e;if(!this.isUseMagnifier)return;if(Je(this,Bs,"f")||Ke(this,Bs,new Ws),!Je(this,Bs,"f").magnifierCanvas)return;document.body.contains(Je(this,Bs,"f").magnifierCanvas)||(Je(this,Bs,"f").magnifierCanvas.style.position="fixed",Je(this,Bs,"f").magnifierCanvas.style.boxSizing="content-box",Je(this,Bs,"f").magnifierCanvas.style.border="2px solid #FFFFFF",document.body.append(Je(this,Bs,"f").magnifierCanvas));const i=this._innerComponent.getElement("content");if(!i)return;if(t.pointer.x<0||t.pointer.x>i.width||t.pointer.y<0||t.pointer.y>i.height)return void Je(this,Vs,"f").call(this);const n=null===(e=this._drawingLayerManager._getFabricCanvas())||void 0===e?void 0:e.lowerCanvasEl;if(!n)return;const r=Math.max(i.clientWidth/5/1.5,i.clientHeight/4/1.5),s=1.5*r,a=[{image:i,width:i.width,height:i.height},{image:n,width:n.width,height:n.height}];Je(this,Bs,"f").update(s,t.pointer,r,a);{let e=0,i=0;t.e instanceof MouseEvent?(e=t.e.clientX,i=t.e.clientY):t.e instanceof TouchEvent&&t.e.changedTouches.length&&(e=t.e.changedTouches[0].clientX,i=t.e.changedTouches[0].clientY),e<1.5*s&&i<1.5*s?(Je(this,Bs,"f").magnifierCanvas.style.left="auto",Je(this,Bs,"f").magnifierCanvas.style.top="0",Je(this,Bs,"f").magnifierCanvas.style.right="0"):(Je(this,Bs,"f").magnifierCanvas.style.left="0",Je(this,Bs,"f").magnifierCanvas.style.top="0",Je(this,Bs,"f").magnifierCanvas.style.right="auto")}Je(this,Bs,"f").show()})),Vs.set(this,(()=>{Je(this,Bs,"f")&&Je(this,Bs,"f").hide()})),Us.set(this,!1)}_setUIElement(t){this.UIElement=t,this._unbindUI(),this._bindUI()}async setUIElement(t){let e;if("string"==typeof t){let i=await qi(t);e=document.createElement("div"),Object.assign(e.style,{width:"100%",height:"100%"}),e.attachShadow({mode:"open"}).appendChild(i)}else e=t;this._setUIElement(e)}getUIElement(){return this.UIElement}_bindUI(){if(!this.UIElement)throw new Error("Need to set 'UIElement'.");if(this._innerComponent)return;const t=this.UIElement;let e=t.classList.contains(this.containerClassName)?t:t.querySelector(`.${this.containerClassName}`);e||(e=document.createElement("div"),e.style.width="100%",e.style.height="100%",e.className=this.containerClassName,t.append(e)),this._innerComponent=document.createElement("dce-component"),e.appendChild(this._innerComponent)}_unbindUI(){var t,e,i;null===(t=this._drawingLayerManager)||void 0===t||t.clearDrawingLayers(),null===(e=this._innerComponent)||void 0===e||e.removeElement("drawing-layer"),this._layerBaseCvs=null,null===(i=this._innerComponent)||void 0===i||i.remove(),this._innerComponent=null}setImage(t,e,i){if(!this._innerComponent)throw new Error("Need to set 'UIElement'.");let n=this._innerComponent.getElement("content");n||(n=document.createElement("canvas"),n.style.objectFit="contain",this._innerComponent.setElement("content",n)),n.width===e&&n.height===i||(n.width=e,n.height=i);const r=n.getContext("2d");r.clearRect(0,0,n.width,n.height),t instanceof Uint8Array||t instanceof Uint8ClampedArray?(t instanceof Uint8Array&&(t=new Uint8ClampedArray(t.buffer)),r.putImageData(new ImageData(t,e,i),0,0)):(t instanceof HTMLCanvasElement||t instanceof HTMLImageElement)&&r.drawImage(t,0,0)}getImage(){return this._innerComponent.getElement("content")}clearImage(){if(!this._innerComponent)return;let t=this._innerComponent.getElement("content");t&&t.getContext("2d").clearRect(0,0,t.width,t.height)}removeImage(){this._innerComponent&&this._innerComponent.removeElement("content")}setOriginalImage(t){if(C(t)){Ke(this,Ns,t);const{width:e,height:i,bytes:n,format:r}=Object.assign({},t);let s;if(r===o.IPF_GRAYSCALED){s=new Uint8ClampedArray(e*i*4);for(let t=0;t{if(!Hs){if(!zs&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),Zs=t=>{if(null==t&&(t="./"),zs||Hs);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};vt.engineResourcePaths.dlr={version:"3.4.32",path:Xs,isInternal:!0},null==vt.engineResourcePaths.dlrData&&(vt.engineResourcePaths.dlrData={version:"1.0.11",path:Zs(Xs+"../../dynamsoft-label-recognizer-data@1.0.11/dist/"),isInternal:!0}),mt.dlr={js:!0,wasm:!0,deps:["license","dip","dnn"]},mt.dnn={wasm:!0,deps:["dip"]};const qs="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,qs)<0&&(vt.engineResourcePaths.std={version:qs,path:Zs(Xs+`../../dynamsoft-capture-vision-std@${qs}/dist/`),isInternal:!0});const Js="2.4.31";(!vt.engineResourcePaths.dip||"string"!=typeof vt.engineResourcePaths.dip&&D(vt.engineResourcePaths.dip.version,Js)<0)&&(vt.engineResourcePaths.dip={version:Js,path:Zs(Xs+`../../dynamsoft-image-processing@${Js}/dist/`),isInternal:!0});const Ks="1.0.20";(!vt.engineResourcePaths.dnn||"string"!=typeof vt.engineResourcePaths.dnn&&D(vt.engineResourcePaths.dnn.version,Ks)<0)&&(vt.engineResourcePaths.dnn={version:Ks,path:Zs(Xs+`../../dynamsoft-capture-vision-dnn@${Ks}/dist/`),isInternal:!0});let $s=!1,Qs=class{static getVersion(){const t=ft.dlr&&ft.dlr.wasm;return`3.4.32(Worker: ${ft.dlr&&ft.dlr.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadRecognitionData(t,e){return await _t("dlr"),await new Promise(((i,n)=>{let r=ot();lt[r]=async t=>{if(t.success){const e=t.result;if(0!==e.errorCode){let t=new Error(e.errorString);return t.errorCode=e.errorCode,n(t)}return e.isModel||($s=!0),i(e)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},e&&!e.endsWith("/")&&(e+="/");const s=L(vt.engineResourcePaths);e||"ConfusableChars"!==t||(e=s.dlr),st.postMessage({type:"dlr_loadData",id:r,body:{dataName:t,dataPath:e||s.dlrData}})}))}};gt.dlr={loadRecognitionData:Qs.loadRecognitionData,get bLoadConfusableCharsData(){return $s}};const ta={filterVINResult:function(t){let e="";if(18===t.characterResults.length){let e=t.characterResults[9].location.points[0].x-t.characterResults[8].location.points[1].x;e<2&&(e=2);let i=t.characterResults[1].location.points[0].x-t.characterResults[0].location.points[1].x,n=t.characterResults[17].location.points[0].x-t.characterResults[16].location.points[1].x,r=2===e?3:e;i-e>=r&&n-e=r&&i-et.characterResults[17].characterHConfidence?t.characterResults.pop():t.characterResults.shift()}else if(19===t.characterResults.length){let e=t.characterResults[10].location.points[0].x-t.characterResults[9].location.points[1].x;e<2&&(e=2);let i,n,r,s=t.characterResults[1].location.points[0].x-t.characterResults[0].location.points[1].x,a=t.characterResults[18].location.points[0].x-t.characterResults[17].location.points[1].x,o=t.characterResults[2].location.points[0].x-t.characterResults[1].location.points[1].x,l=t.characterResults[17].location.points[0].x-t.characterResults[16].location.points[1].x,h=2===e?3:e;if("1"===t.characterResults[1].characterH||"1"===t.characterResults[2].characterH||"1"===t.characterResults[16].characterH||"1"===t.characterResults[17].characterH){for(let e=9;e=(i||h)&&l-e<(n||h))t.characterResults.splice(0,2);else if(l-e>=(n||h)&&o-e<(i||h))t.characterResults.splice(17,2);else if(s>e&&a>e)t.characterResults.pop(),t.characterResults.shift();else{let e=t.characterResults[0].characterHConfidence+t.characterResults[1].characterHConfidence,i=t.characterResults[17].characterHConfidence+t.characterResults[18].characterHConfidence,n=t.characterResults[0].characterHConfidence+t.characterResults[18].characterHConfidence,r=Math.min(e,i,n);r===e?t.characterResults.splice(0,2):r===i?t.characterResults.splice(17,2):r===n&&(t.characterResults.pop(),t.characterResults.shift())}}for(let i of t.characterResults)e+=i.characterH;return e},checkValidVIN:function(t){return!(!t||17!=t.length)&&(t=>{const e=new Map([["A",1],["B",2],["C",3],["D",4],["E",5],["F",6],["G",7],["H",8],["J",1],["K",2],["L",3],["M",4],["N",5],["P",7],["R",9],["S",2],["T",3],["U",4],["V",5],["W",6],["X",7],["Y",8],["Z",9],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9]]),i=[8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2];let n=0;for(let r=0;r{const n=new Map([["<",0],["0",0],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9],["A",10],["B",11],["C",12],["D",13],["E",14],["F",15],["G",16],["H",17],["I",18],["J",19],["K",20],["L",21],["M",22],["N",23],["O",24],["P",25],["Q",26],["R",27],["S",28],["T",29],["U",30],["V",31],["W",32],["X",33],["Y",34],["Z",35]]),r=[7,3,1];let s=0;for(let a=e,o=0;a<=i;a++){let e=n.get(t[a]);e&&(s+=e*r[o%3]),o++}return s%10},i=t.slice(0,10)+t.slice(13,20)+t.slice(21,43),n=e(t,0,8).toString(),r=e(t,13,18).toString(),s=e(t,21,26).toString(),a=e(t,28,41).toString(),o=e(i,0,i.length).toString();return n===t[9]&&r===t[19]&&s===t[27]&&a===t[42]&&o===t[43]},checkValidMRV:function(t){if(!t||44!=t.length&&36!=t.length)return!1;const e=(t,e,i)=>{const n=new Map([["<",0],["0",0],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9],["A",10],["B",11],["C",12],["D",13],["E",14],["F",15],["G",16],["H",17],["I",18],["J",19],["K",20],["L",21],["M",22],["N",23],["O",24],["P",25],["Q",26],["R",27],["S",28],["T",29],["U",30],["V",31],["W",32],["X",33],["Y",34],["Z",35]]),r=[7,3,1];let s=0;for(let a=e,o=0;a<=i;a++){let e=n.get(t[a]);e&&(s+=e*r[o%3]),o++}return s%10},i=e(t,0,8).toString(),n=e(t,13,18).toString(),r=e(t,21,26).toString();return i===t[9]&&n===t[19]&&r===t[27]},checkValidIDCard:function(t,e){if(!t||30!=t.length&&36!=t.length)return!1;const i=(t,e,i)=>{const n=new Map([["<",0],["0",0],["1",1],["2",2],["3",3],["4",4],["5",5],["6",6],["7",7],["8",8],["9",9],["A",10],["B",11],["C",12],["D",13],["E",14],["F",15],["G",16],["H",17],["I",18],["J",19],["K",20],["L",21],["M",22],["N",23],["O",24],["P",25],["Q",26],["R",27],["S",28],["T",29],["U",30],["V",31],["W",32],["X",33],["Y",34],["Z",35]]),r=[7,3,1];let s=0;for(let a=e,o=0;a<=i;a++){let e=n.get(t[a]);e&&(s+=e*r[o%3]),o++}return s%10};if(30===t.length){if(e&&t===e)return i(t,5,13).toString()===t[14];if(e&&t!==e){const n=`${e.substring(5,30)}${t.substring(0,7)}${t.substring(8,15)}${t.substring(18,29)}`;return i(n,0,n.length-1).toString()===t[29]}}else if(36===t.length){const e=i(t,0,8).toString(),n=i(t,13,18).toString(),r=i(t,21,26).toString(),s=`${t.substring(0,10)}${t.substring(13,20)}${t.substring(21,28)}`,a=i(s,0,s.length-1).toString();return e===t[9]&&n===t[19]&&r===t[27]&&a===t[35]}}};var ea,ia,na;function ra(t){delete t.moduleId;const e=JSON.parse(t.jsonString).ResultInfo,i=t.fullCodeString;t.getFieldValue=t=>"fullcodestring"===t.toLowerCase()?i:sa(e,t,"map"),t.getFieldRawValue=t=>sa(e,t,"raw"),t.getFieldMappingStatus=t=>aa(e,t),t.getFieldValidationStatus=t=>oa(e,t),delete t.fullCodeString}function sa(t,e,i){for(let n of t){if(n.FieldName===e)return"raw"===i&&n.RawValue?n.RawValue:n.Value;if(n.ChildFields&&n.ChildFields.length>0){let t;for(let r of n.ChildFields)t=sa(r,e,i);if(void 0!==t)return t}}}function aa(t,e){for(let i of t){if(i.FieldName===e)return i.MappingStatus?Number(ia[i.MappingStatus]):ia.MS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=aa(n,e);if(void 0!==t)return t}}}function oa(t,e){for(let i of t){if(i.FieldName===e&&i.ValidationStatus)return i.ValidationStatus?Number(na[i.ValidationStatus]):na.VS_NONE;if(i.ChildFields&&i.ChildFields.length>0){let t;for(let n of i.ChildFields)t=oa(n,e);if(void 0!==t)return t}}}function la(t){if(t.disposed)throw new Error('"CodeParser" instance has been disposed')}!function(t){t[t.RTLS_LOCALIZED=0]="RTLS_LOCALIZED",t[t.RTLS_RECOGNITION_FAILED=1]="RTLS_RECOGNITION_FAILED",t[t.RTLS_RECOGNITION_SUCCEEDED=2]="RTLS_RECOGNITION_SUCCEEDED"}(ea||(ea={})),lt[-1]=async t=>{Qs.onDataLoadProgressChanged&&Qs.onDataLoadProgressChanged(t.resourcesPath,t.tag,{loaded:t.loaded,total:t.total})},function(t){t[t.MS_NONE=0]="MS_NONE",t[t.MS_SUCCEEDED=1]="MS_SUCCEEDED",t[t.MS_FAILED=2]="MS_FAILED"}(ia||(ia={})),function(t){t[t.VS_NONE=0]="VS_NONE",t[t.VS_SUCCEEDED=1]="VS_SUCCEEDED",t[t.VS_FAILED=2]="VS_FAILED"}(na||(na={}));const ha=t=>t&&"object"==typeof t&&"function"==typeof t.then,ca=(async()=>{})().constructor;let da=class extends ca{get status(){return this._s}get isPending(){return"pending"===this._s}get isFulfilled(){return"fulfilled"===this._s}get isRejected(){return"rejected"===this._s}get task(){return this._task}set task(t){let e;this._task=t,ha(t)?e=t:"function"==typeof t&&(e=new ca(t)),e&&(async()=>{try{const i=await e;t===this._task&&this.resolve(i)}catch(e){t===this._task&&this.reject(e)}})()}get isEmpty(){return null==this._task}constructor(t){let e,i;super(((t,n)=>{e=t,i=n})),this._s="pending",this.resolve=t=>{this.isPending&&(ha(t)?this.task=t:(this._s="fulfilled",e(t)))},this.reject=t=>{this.isPending&&(this._s="rejected",i(t))},this.task=t}},ua=class t{constructor(){this._instanceID=void 0,this.bDestroyed=!1}static async createInstance(){if(!gt.license)throw Error("Module `license` is not existed.");await gt.license.dynamsoft(),await _t("dcp");const e=new t,i=new da;let n=ot();return lt[n]=async t=>{if(t.success)e._instanceID=t.instanceID,i.resolve(e);else{const e=Error(t.message);t.stack&&(e.stack=t.stack),i.reject(e)}},st.postMessage({type:"dcp_createInstance",id:n}),i}async dispose(){la(this);let t=ot();this.bDestroyed=!0,lt[t]=t=>{if(!t.success){let e=new Error(t.message);throw e.stack=t.stack+"\n"+e.stack,e}},st.postMessage({type:"dcp_dispose",id:t,instanceID:this._instanceID})}get disposed(){return this.bDestroyed}async initSettings(t){return la(this),t&&["string","object"].includes(typeof t)?("string"==typeof t?t.trimStart().startsWith("{")||(t=await A(t,"text")):"object"==typeof t&&(t=JSON.stringify(t)),await new Promise(((e,i)=>{let n=ot();lt[n]=async t=>{if(t.success){const n=JSON.parse(t.response);if(0!==n.errorCode){let t=new Error(n.errorString?n.errorString:"Init Settings Failed.");return t.errorCode=n.errorCode,i(t)}return e(n)}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,i(e)}},st.postMessage({type:"dcp_initSettings",id:n,instanceID:this._instanceID,body:{settings:t}})}))):console.error("Invalid settings.")}async resetSettings(){return la(this),await new Promise(((t,e)=>{let i=ot();lt[i]=async i=>{if(i.success)return t();{let t=new Error(i.message);return t.stack=i.stack+"\n"+t.stack,e(t)}},st.postMessage({type:"dcp_resetSettings",id:i,instanceID:this._instanceID})}))}async parse(t,e=""){if(la(this),!t||!(t instanceof Array||t instanceof Uint8Array||"string"==typeof t))throw new Error("`parse` must pass in an Array or Uint8Array or string");return await new Promise(((i,n)=>{let r=ot();t instanceof Array&&(t=Uint8Array.from(t)),"string"==typeof t&&(t=Uint8Array.from(function(t){let e=[];for(let i=0;i{if(t.success){let e=JSON.parse(t.parseResponse);return e.errorCode?n(new Error(e.errorString)):(ra(e),i(e))}{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},st.postMessage({type:"dcp_parse",id:r,instanceID:this._instanceID,body:{source:t,taskSettingName:e}})}))}};const fa="undefined"==typeof self,ga="function"==typeof importScripts,ma=(()=>{if(!ga){if(!fa&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})();vt.engineResourcePaths.dcp={version:"2.4.32",path:ma,isInternal:!0},mt.dcp={js:!0,wasm:!0,deps:["license"]},gt.dcp={handleParsedResultItem:ra};const pa="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,pa)<0&&(vt.engineResourcePaths.std={version:pa,path:(t=>{if(null==t&&(t="./"),fa||ga);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t})(ma+`../../dynamsoft-capture-vision-std@${pa}/dist/`),isInternal:!0});let _a=class{static getVersion(){const t=ft.dcp&&ft.dcp.wasm;return`2.4.32(Worker: ${ft.dcp&&ft.dcp.worker||"Not Loaded"}, Wasm: ${t||"Not Loaded"})`}static async loadSpec(t,e){return await _t("dcp"),await new Promise(((i,n)=>{let r=ot();lt[r]=async t=>{if(t.success)return i();{let e=new Error(t.message);return e.stack=t.stack+"\n"+e.stack,n(e)}},e&&!e.endsWith("/")&&(e+="/");const s=t instanceof Array?t:[t],a=L(vt.engineResourcePaths);st.postMessage({type:"dcp_appendResourceBuffer",id:r,body:{specificationPath:e||a.dcp+"specification/",specificationNames:s}})}))}};const va=async t=>{let e;await new Promise(((i,n)=>{e=new Image,e.onload=()=>i(e),e.onerror=n,e.src=URL.createObjectURL(t)}));const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=e.width,i.height=e.height,n.drawImage(e,0,0),{bytes:Uint8Array.from(n.getImageData(0,0,i.width,i.height).data),width:i.width,height:i.height,stride:4*i.width,format:10}};class ya{async saveToFile(t,e,i){if(!t||!e)return null;if("string"!=typeof e)throw new TypeError("FileName must be of type string.");const n=N(t);return M(n,e,i)}async drawOnImage(t,e,i,n=4294901760,r=1,s){let a;if(t instanceof Blob)a=await va(t);else if("string"==typeof t){let e=await A(t,"blob");a=await va(e)}return await new Promise(((t,o)=>{let l=ot();lt[l]=async e=>{if(e.success)return s&&this.saveToFile(e.image,"test.png",s),t(e.image);{let t=new Error(e.message);return t.stack=e.stack+"\n"+t.stack,o(t)}},st.postMessage({type:"utility_drawOnImage",id:l,body:{dsImage:a,drawingItem:e instanceof Array?e:[e],color:n,thickness:r,type:i}})}))}}const wa="undefined"==typeof self,Ca="function"==typeof importScripts,Ea=(()=>{if(!Ca){if(!wa&&document.currentScript){let t=document.currentScript.src,e=t.indexOf("?");if(-1!=e)t=t.substring(0,e);else{let e=t.indexOf("#");-1!=e&&(t=t.substring(0,e))}return t.substring(0,t.lastIndexOf("/")+1)}return"./"}})(),Sa=t=>{if(null==t&&(t="./"),wa||Ca);else{let e=document.createElement("a");e.href=t,t=e.href}return t.endsWith("/")||(t+="/"),t};vt.engineResourcePaths.utility={version:"1.4.32",path:Ea,isInternal:!0},mt.utility={js:!0,wasm:!0};const ba="1.4.21";"string"!=typeof vt.engineResourcePaths.std&&D(vt.engineResourcePaths.std.version,ba)<0&&(vt.engineResourcePaths.std={version:ba,path:Sa(Ea+`../../dynamsoft-capture-vision-std@${ba}/dist/`),isInternal:!0});const Ta="2.4.31";(!vt.engineResourcePaths.dip||"string"!=typeof vt.engineResourcePaths.dip&&D(vt.engineResourcePaths.dip.version,Ta)<0)&&(vt.engineResourcePaths.dip={version:Ta,path:Sa(Ea+`../../dynamsoft-image-processing@${Ta}/dist/`),isInternal:!0});class Ia{static getVersion(){return`1.4.32(Worker: ${ft.utility&&ft.utility.worker||"Not Loaded"}, Wasm: ${ft.utility&&ft.utility.wasm||"Not Loaded"})`}}function xa(t,e,i,n){if("a"===i&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?n:"a"===i?n.call(t):n?n.value:e.get(t)}var Oa,Aa,Ra,Da,La;function Ma(t,e){let i=!0;for(let a=0;a1)return Math.sqrt((l-a)**2+(h-o)**2);{const t=r+d*(a-r),e=s+d*(o-s);return Math.sqrt((l-t)**2+(h-e)**2)}}function ka(t){const e=[];for(let i=0;i=0&&l<=1&&h>=0&&h<=1?{x:t.x+h*r,y:t.y+h*s}:null}function ja(t){let e=0;for(let i=0;i0}function Ua(t,e){for(let i=0;i<4;i++)if(!Va(t.points[i],t.points[(i+1)%4],e))return!1;return!0}"function"==typeof SuppressedError&&SuppressedError;function Ga(t,e,i,n){const r=t.points,s=e.points;let a=8*i;a=Math.max(a,5);const o=ka(r)[3],l=ka(r)[1],h=ka(s)[3],c=ka(s)[1];let d,u=0;if(d=Math.max(Math.abs(Pa(o,e.points[0])),Math.abs(Pa(o,e.points[3]))),d>u&&(u=d),d=Math.max(Math.abs(Pa(l,e.points[1])),Math.abs(Pa(l,e.points[2]))),d>u&&(u=d),d=Math.max(Math.abs(Pa(h,t.points[0])),Math.abs(Pa(h,t.points[3]))),d>u&&(u=d),d=Math.max(Math.abs(Pa(c,t.points[1])),Math.abs(Pa(c,t.points[2]))),d>u&&(u=d),u>a)return!1;const f=Na(ka(r)[0]),g=Na(ka(r)[2]),m=Na(ka(s)[0]),p=Na(ka(s)[2]),_=Fa(f,p),v=Fa(m,g),y=_>v,w=Math.min(_,v),C=Fa(f,g),E=Fa(m,p);let S=12*i;return S=Math.max(S,5),S=Math.min(S,C),S=Math.min(S,E),!!(w{e.x+=t,e.y+=i})),e.x/=t.length,e.y/=t.length,e}isProbablySameLocationWithOffset(t,e){const i=this.item.location,n=t.location;if(i.area<=0)return!1;if(Math.abs(i.area-n.area)>.4*i.area)return!1;let r=new Array(4).fill(0),s=new Array(4).fill(0),a=0,o=0;for(let t=0;t<4;++t)r[t]=Math.round(100*(n.points[t].x-i.points[t].x))/100,a+=r[t],s[t]=Math.round(100*(n.points[t].y-i.points[t].y))/100,o+=s[t];a/=4,o/=4;for(let t=0;t<4;++t){if(Math.abs(r[t]-a)>this.strictLimit||Math.abs(a)>.8)return!1;if(Math.abs(s[t]-o)>this.strictLimit||Math.abs(o)>.8)return!1}return e.x=a,e.y=o,!0}isLocationOverlap(t,e){if(this.locationArea>e){for(let e=0;e<4;e++)if(Ua(this.location,t.points[e]))return!0;const e=this.getCenterPoint(t.points);if(Ua(this.location,e))return!0}else{for(let e=0;e<4;e++)if(Ua(t,this.location.points[e]))return!0;if(Ua(t,this.getCenterPoint(this.location.points)))return!0}return!1}isMatchedLocationWithOffset(t,e={x:0,y:0}){if(this.isOneD){const i=Object.assign({},t.location);for(let t=0;t<4;t++)i.points[t].x-=e.x,i.points[t].y-=e.y;if(!this.isLocationOverlap(i,t.locationArea))return!1;const n=[this.location.points[0],this.location.points[3]],r=[this.location.points[1],this.location.points[2]];for(let t=0;t<4;t++){const e=i.points[t],s=0===t||3===t?n:r;if(Math.abs(Pa(s,e))>this.locationThreshold)return!1}}else for(let i=0;i<4;i++){const n=t.location.points[i],r=this.location.points[i];if(!(Math.abs(r.x+e.x-n.x)=this.locationThreshold)return!1}return!0}isOverlappedLocationWithOffset(t,e,i=!0){const n=Object.assign({},t.location);for(let t=0;t<4;t++)n.points[t].x-=e.x,n.points[t].y-=e.y;if(!this.isLocationOverlap(n,t.location.area))return!1;if(i){const t=.75;return function(t,e){const i=[];for(let n=0;n<4;n++)for(let r=0;r<4;r++){const s=Ba(t[n],t[(n+1)%4],e[r],e[(r+1)%4]);s&&i.push(s)}return t.forEach((t=>{Ma(e,t)&&i.push(t)})),e.forEach((e=>{Ma(t,e)&&i.push(e)})),ja(function(t){if(t.length<=1)return t;t.sort(((t,e)=>t.x-e.x||t.y-e.y));const e=t.shift();return t.sort(((t,i)=>Math.atan2(t.y-e.y,t.x-e.x)-Math.atan2(i.y-e.y,i.x-e.x))),[e,...t]}(i))}([...this.location.points],n.points)>this.locationArea*t}return!0}}const Ya={BF_ONED:BigInt(3147775),BF_GS1_DATABAR:BigInt(260096)},za={barcode:2,text_line:4,detected_quad:8,normalized_image:16},Ha=t=>Object.values(za).includes(t)||za.hasOwnProperty(t),Xa=(t,e)=>"string"==typeof t?e[za[t]]:e[t],Za=(t,e,i)=>{"string"==typeof t?e[za[t]]=i:e[t]=i},qa=(t,e,i)=>{const n=[8,16].includes(i);if(!n&&t.isResultCrossVerificationEnabled(i))for(let t=0;t{Za(e,this.verificationEnabled,t)})),xa(this,Aa,"f").forEach(((t,e)=>{Za(e,this.duplicateFilterEnabled,t)})),xa(this,Ra,"f").forEach(((t,e)=>{Za(e,this.duplicateForgetTime,t)})),xa(this,Da,"f").forEach(((t,e)=>{Za(e,this.latestOverlappingEnabled,t)})),xa(this,La,"f").forEach(((t,e)=>{Za(e,this.maxOverlappingFrames,t)}))}enableResultCrossVerification(t,e){Ha(t)&&xa(this,Oa,"f").set(t,e)}isResultCrossVerificationEnabled(t){return!!Ha(t)&&Xa(t,this.verificationEnabled)}enableResultDeduplication(t,e){Ha(t)&&(e&&this.enableLatestOverlapping(t,!1),xa(this,Aa,"f").set(t,e))}isResultDeduplicationEnabled(t){return!!Ha(t)&&Xa(t,this.duplicateFilterEnabled)}setDuplicateForgetTime(t,e){Ha(t)&&(e>18e4&&(e=18e4),e<0&&(e=0),xa(this,Ra,"f").set(t,e))}getDuplicateForgetTime(t){return Ha(t)?Xa(t,this.duplicateForgetTime):-1}setMaxOverlappingFrames(t,e){Ha(t)&&xa(this,La,"f").set(t,e)}getMaxOverlappingFrames(t){return Ha(t)?Xa(t,this.maxOverlappingFrames):-1}enableLatestOverlapping(t,e){Ha(t)&&(e&&this.enableResultDeduplication(t,!1),xa(this,Da,"f").set(t,e))}isLatestOverlappingEnabled(t){return!!Ha(t)&&Xa(t,this.latestOverlappingEnabled)}getFilteredResultItemTypes(){let t=0;const e=[yt.CRIT_BARCODE,yt.CRIT_TEXT_LINE,yt.CRIT_DETECTED_QUAD,yt.CRIT_NORMALIZED_IMAGE];for(let i=0;i{if(1!==t.type){const e=(BigInt(t.format)&BigInt(Ya.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Ya.BF_GS1_DATABAR))!=BigInt(0);return new Wa(l,e?1:2,e,t)}})).filter(Boolean);if(this.overlapSet.length>0){const t=new Array(h).fill(new Array(this.overlapSet.length).fill(1));let e=0;for(;e-1!==t)).length;r>p&&(p=r,m=n,g.x=i.x,g.y=i.y)}}if(0===p){for(let e=0;e-1!=t)).length}let i=this.overlapSet.length<=3?p>=1:p>=2;if(!i&&s&&d>0){let t=0;for(let e=0;e=1:t>=3}i||(this.overlapSet=[])}if(0===this.overlapSet.length)this.stabilityCount=0,t.items.forEach(((t,e)=>{if(1!==t.type){const i=Object.assign({},t),n=(BigInt(t.format)&BigInt(Ya.BF_ONED))!=BigInt(0)||(BigInt(t.format)&BigInt(Ya.BF_GS1_DATABAR))!=BigInt(0),s=t.confidence5||Math.abs(g.y)>5)&&(e=!1):e=!1;for(let i=0;i0){for(let t=0;t!(t.overlapCount+this.stabilityCount<=0&&t.crossVerificationFrame<=0)))}f.sort(((t,e)=>e-t)).forEach(((e,i)=>{t.items.splice(e,1)})),u.forEach((e=>{t.items.push(Object.assign(Object.assign({},e),{overlapped:!0}))}))}}onDecodedBarcodesReceived(t){this.latestOverlappingFilter(t),qa(this,t.items,yt.CRIT_BARCODE)}onRecognizedTextLinesReceived(t){qa(this,t.items,yt.CRIT_TEXT_LINE)}onDetectedQuadsReceived(t){qa(this,t.items,yt.CRIT_DETECTED_QUAD)}onNormalizedImagesReceived(t){qa(this,t.items,yt.CRIT_NORMALIZED_IMAGE)}}var Ka,$a,Qa;Oa=new WeakMap,Aa=new WeakMap,Ra=new WeakMap,Da=new WeakMap,La=new WeakMap,function(t){t.Passport="passport",t.TD1="td1",t.TD2="td2",t.PassportAndTD1="passportAndTd1",t.PassportAndTD2="passportAndTd2",t.TD1AndTD2="td1AndTd2",t.All="all"}(Ka||(Ka={})),function(t){t.Passport="passport",t.TD1="td1",t.TD2="td2"}($a||($a={})),function(t){t.Scanner="scanner",t.Result="scan-result"}(Qa||(Qa={}));const to={[Ka.Passport]:"ReadPassport",[Ka.TD1]:"ReadId-TD1",[Ka.TD2]:"ReadId-TD2",[Ka.PassportAndTD1]:"ReadPassportAndId-TD1",[Ka.PassportAndTD2]:"ReadPassportAndId-TD2",[Ka.TD1AndTD2]:"ReadId",[Ka.All]:"ReadPassportAndId"};var eo;function io(t){if("string"==typeof t){const e=document.querySelector(t);if(!e)throw new Error("Element not found");return e}return t instanceof HTMLElement?t:null}!function(t){t[t.RS_SUCCESS=0]="RS_SUCCESS",t[t.RS_CANCELLED=1]="RS_CANCELLED",t[t.RS_FAILED=2]="RS_FAILED"}(eo||(eo={}));function no(t,e){if(!document.getElementById(t)){const i=document.createElement("style");i.id=t,i.textContent=e,document.head.appendChild(i)}}const ro=t=>!t||0===Object.keys(t).length;function so(t){return t?t.charAt(0).toUpperCase()+t.slice(1):""}const ao={"4k":{width:3840,height:2160},"2k":{width:2560,height:1440},"1080p":{width:1920,height:1080},"720p":{width:1280,height:720},"480p":{width:640,height:480}};function oo(t,e={}){const{message:i,spinnerSize:n=32}=e,r=document.createElement("div");r.className="dynamsoft-mrz-loading-screen";const s=document.createElement("div");s.className="dynamsoft-mrz-loading";const a=document.createElement("div");a.className="dynamsoft-mrz-loading-content";const o=`\n \n \n \n `;if(a.innerHTML=o,i){const t=document.createElement("div");t.className="dynamsoft-mrz-loading-message",t.textContent=i,a.appendChild(t)}return s.appendChild(a),r.appendChild(s),t.appendChild(r),{element:r,updateMessage:t=>{let e=s.querySelector(".dynamsoft-mrz-loading-message");null!==t?e?e.textContent=t:(e=document.createElement("div"),e.className="dynamsoft-mrz-loading-message",e.textContent=t,a.appendChild(e)):null==e||e.remove()},hide:()=>{r&&r.parentNode&&(r.classList.add("fade-out"),setTimeout((()=>{var t;null===(t=r.parentNode)||void 0===t||t.removeChild(r)}),200))}}}const lo='\n .dynamsoft-mrz-loading-screen {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: #323234;\n z-index: 998;\n opacity: 1;\n transition: opacity 0.2s ease-out;\n }\n\n .dynamsoft-mrz-loading-screen.fade-out {\n opacity: 0;\n }\n\n .dynamsoft-mrz-loading {\n position: absolute;\n left: 50%;\n top: 50%;\n color: white;\n z-index: 999;\n transform: translate(-50%, -50%);\n }\n\n .dynamsoft-mrz-loading-content {\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 16px;\n }\n\n .dynamsoft-mrz-loading svg {\n animation: spin 1s linear infinite;\n }\n\n .dynamsoft-mrz-loading-message {\n color: white;\n font-family: "Verdana";\n font-size: 14px;\n text-align: center;\n max-width: 200px;\n line-height: 1.4;\n opacity: 0.9;\n }\n\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n';var ho;!function(t){t.InvalidFields="invalidFields",t.DocumentType="documentType",t.DocumentNumber="documentNumber",t.MRZText="mrzText",t.FirstName="firstName",t.LastName="lastName",t.Age="age",t.Sex="sex",t.IssuingState="issuingState",t.IssuingStateRaw="issuingStateRaw",t.Nationality="nationality",t.NationalityRaw="nationalityRaw",t.DateOfBirth="dateOfBirth",t.DateOfExpiry="dateOfExpiry"}(ho||(ho={}));const co={[ho.InvalidFields]:"Invalid Fields",[ho.DocumentType]:"Document Type",[ho.DocumentNumber]:"Document Number",[ho.MRZText]:"MRZ Text",[ho.FirstName]:"Given Name(s)",[ho.LastName]:"Surname",[ho.Age]:"Age",[ho.Sex]:"Sex",[ho.IssuingState]:"Issuing State",[ho.IssuingStateRaw]:"Issuing State (Raw Value)",[ho.Nationality]:"Nationality",[ho.NationalityRaw]:"Nationality State (Raw Value)",[ho.DateOfBirth]:"Date Of Birth (YYYY-MM-DD)",[ho.DateOfExpiry]:"Date Of Expiry (YYYY-MM-DD)"};function uo(t,e,i,n=!1){const r=parseInt(t,10);let s;if(n)s=r>=60?1900+r:2e3+r;else{s=r>(new Date).getFullYear()%100?1900+r:2e3+r}return{year:s,month:parseInt(e,10),day:parseInt(i,10)}}function fo(t){const e=t=>{var e;return 1===(null===(e=`${t}`)||void 0===e?void 0:e.length)?`0${t}`:t};return`${null==t?void 0:t.year}-${e(null==t?void 0:t.month)}${(null==t?void 0:t.day)&&`-${e(null==t?void 0:t.day)}`}`}function go(t){return"D<<"===t?"D":t}function mo(t,e){const i=[],n=t=>e.getFieldValidationStatus(t)===na.VS_FAILED,r=e.codeType,s=function(t){switch(t){case"MRTD_TD1_ID":return $a.TD1;case"MRTD_TD2_ID":case"MRTD_TD2_VISA":case"MRTD_TD2_FRENCH_ID":return $a.TD2;case"MRTD_TD3_PASSPORT":case"MRTD_TD3_VISA":return $a.Passport;default:throw new Error(`Unknown document type: ${t}`)}}(r),a=function(t){switch(t){case"MRTD_TD1_ID":return"ID (TD1)";case"MRTD_TD2_ID":return"ID (TD2)";case"MRTD_TD2_VISA":return"ID (VISA)";case"MRTD_TD2_FRENCH_ID":return"French ID (TD2)";case"MRTD_TD3_PASSPORT":return"Passport (TD3)";case"MRTD_TD3_VISA":return"Visa (TD3)";default:throw new Error(`Unknown document type: ${t}`)}}(r),o=s===$a.Passport&&"MRTD_TD3_PASSPORT"===r?"passportNumber":"documentNumber",l=uo(e.getFieldValue("birthYear"),e.getFieldValue("birthMonth"),e.getFieldValue("birthDay")),h=uo(e.getFieldValue("expiryYear"),e.getFieldValue("expiryMonth"),e.getFieldValue("expiryDay"),!0);["birthYear","birthMonth","birthDay"].forEach((t=>{n(t)&&i.push(ho.DateOfBirth)})),["expiryYear","expiryMonth","expiryDay"].forEach((t=>{n(t)&&i.push(ho.DateOfExpiry)}));const c={[ho.LastName]:e.getFieldValue("primaryIdentifier"),[ho.FirstName]:e.getFieldValue("secondaryIdentifier"),[ho.Nationality]:e.getFieldValue("nationality"),[ho.NationalityRaw]:go(e.getFieldRawValue("nationality")),[ho.DocumentNumber]:e.getFieldValue(o)||e.getFieldValue("longDocumentNumber"),[ho.IssuingState]:e.getFieldValue("issuingState"),[ho.IssuingStateRaw]:go(e.getFieldRawValue("issuingState")),[ho.Sex]:so(e.getFieldValue("sex"))};Object.keys(c).forEach((t=>{let e=!1;switch(t){case ho.FirstName:e=n("secondaryIdentifier");break;case ho.LastName:e=n("primaryIdentifier");break;case ho.DocumentNumber:e=n(o)||n("longDocumentNumber");break;default:e=n(t)}e&&i.push(t)}));const d=function(t){const e=new Date,i=e.getMonth()+1>t.month||e.getMonth()+1===t.month&&e.getDate()>=t.day;return e.getFullYear()-t.year-(i?0:1)}(l);d<1&&i.push(ho.Age);return{[ho.InvalidFields]:i,[ho.FirstName]:c[ho.FirstName],[ho.LastName]:c[ho.LastName],[ho.Age]:d,[ho.DateOfBirth]:l,[ho.Sex]:c[ho.Sex],[ho.Nationality]:c[ho.Nationality],[ho.NationalityRaw]:c[ho.NationalityRaw],[ho.DocumentNumber]:c[ho.DocumentNumber],[ho.DateOfExpiry]:h,[ho.IssuingState]:c[ho.IssuingState],[ho.IssuingStateRaw]:c[ho.IssuingStateRaw],[ho.DocumentType]:so(a),[ho.MRZText]:t}}const po={[$a.TD1]:{width:85.6,height:53.98},[$a.TD2]:{width:105,height:74},[$a.Passport]:{width:125,height:88}};class _o{showScannerLoadingOverlay(t){const e=io(this.config.container);this.loadingScreen=oo(e,{message:t}),e.style.display="block",e.style.position="relative"}hideScannerLoadingOverlay(t=!1){this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,t&&(io(this.config.container).style.display="none"))}constructor(t,e){this.resources=t,this.config=e,this.isSoundFeedbackOn=!1,this.scanModeManager={[$a.Passport]:!0,[$a.TD1]:!0,[$a.TD2]:!0},this.currentScanMode=Ka.All,this.resizeTimer=null,this.capturedResultItems=[],this.originalImageData=null,this.initialized=!1,this.initializedDCE=!1,this.DCE_ELEMENTS={selectCameraBtn:null,uploadImageBtn:null,soundFeedbackBtn:null,closeScannerBtn:null,scanModeSelectContainer:null,passportModeOption:null,td1ModeOption:null,td2ModeOption:null,toast:null},this.loadingScreen=null,this.handleResize=()=>{this.toggleScanGuide(!1),this.resizeTimer&&window.clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout((()=>{this.toggleScanGuide(!0)}),500)}}async initialize(){if(!this.initialized){this.initializeScanModeManager(),this.currentScanMode=this.getScanMode(),no("dynamsoft-mrz-loading-screen-style",lo);try{const{cameraView:t,cameraEnhancer:e,cvRouter:i}=this.resources;if(t.setScanRegionMaskStyle({strokeStyle:"transparent",fillStyle:"transparent",lineWidth:0}),t.setVideoFit("cover"),i.setInput(e),await i.initSettings(this.config.templateFilePath),!0===this.config.enableMultiFrameCrossFilter){const t=new Ja;t.enableResultCrossVerification(yt.CRIT_TEXT_LINE,!0),t.enableResultDeduplication(yt.CRIT_TEXT_LINE,!0),await i.addResultFilter(t)}const n=new Be;n.onCapturedResultReceived=t=>this.handleMRZResult(t),await i.addResultReceiver(n),this.toggleSoundFeedback(!1),!1===this.config.showScanGuide&&this.toggleScanGuide(!1),this.initialized=!0}catch(t){let e=(null==t?void 0:t.message)||t;console.error(e),alert(e),this.closeCamera();const i={status:{code:eo.RS_FAILED,message:"Dynamsoft MRZ Scanner initialize error"}};this.currentScanResolver(i)}}}initializeElements(){var t;const e=io(this.config.container),i=e.children[e.children.length-1];if(!(null==i?void 0:i.shadowRoot))throw new Error("Shadow root not found");if(this.DCE_ELEMENTS={selectCameraBtn:i.shadowRoot.querySelector(".dce-mn-select-camera-icon"),uploadImageBtn:i.shadowRoot.querySelector(".dce-mn-upload-image-icon"),soundFeedbackBtn:i.shadowRoot.querySelector(".dce-mn-sound-feedback"),closeScannerBtn:i.shadowRoot.querySelector(".dce-mn-close"),scanModeSelectContainer:i.shadowRoot.querySelector(".dce-mn-scan-mode-select"),passportModeOption:i.shadowRoot.querySelector(".scan-mode-option-passport"),td1ModeOption:i.shadowRoot.querySelector(".scan-mode-option-td1"),td2ModeOption:i.shadowRoot.querySelector(".scan-mode-option-td2"),toast:i.shadowRoot.querySelector(".dce-mn-toast")},this.setupScanModeSelector(),this.assignDCEClickEvents(),this.DCE_ELEMENTS.toast.style.display="none",!1===this.config.showUploadImage&&(this.DCE_ELEMENTS.uploadImageBtn.style.visibility="hidden"),!1===this.config.showSoundToggle&&(this.DCE_ELEMENTS.soundFeedbackBtn.style.visibility="hidden"),!1===(null===(t=this.config)||void 0===t?void 0:t.showPoweredByDynamsoft)){i.shadowRoot.querySelector(".dce-mn-msg-poweredby").style.display="none"}this.initializedDCE=!0}setupScanModeSelector(){if(!1!==this.config.showFormatSelector)switch(this.currentScanMode){case Ka.PassportAndTD1:this.DCE_ELEMENTS.td2ModeOption.style.display="none";break;case Ka.PassportAndTD2:this.DCE_ELEMENTS.td1ModeOption.style.display="none";break;case Ka.TD1AndTD2:this.DCE_ELEMENTS.passportModeOption.style.display="none";break;case Ka.All:break;default:this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}else this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}assignDCEClickEvents(){if(!Object.values(this.DCE_ELEMENTS).every(Boolean))throw new Error("Camera control elements not found");this.closeCamera=this.closeCamera.bind(this),this.DCE_ELEMENTS.uploadImageBtn.onclick=()=>this.uploadFile(),this.DCE_ELEMENTS.soundFeedbackBtn.onclick=()=>this.toggleSoundFeedback(),this.DCE_ELEMENTS.closeScannerBtn.onclick=()=>this.handleCloseBtn(),this.DCE_ELEMENTS.selectCameraBtn.onclick=t=>{t.stopPropagation(),this.toggleSelectCameraBox()},this.DCE_ELEMENTS.passportModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.passportModeOption.style.display&&await this.toggleScanDocType($a.Passport)},this.DCE_ELEMENTS.td1ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td1ModeOption.style.display&&await this.toggleScanDocType($a.TD1)},this.DCE_ELEMENTS.td2ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td2ModeOption.style.display&&await this.toggleScanDocType($a.TD2)}}handleCloseBtn(){this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:eo.RS_CANCELLED,message:"Cancelled"}})}attachOptionClickListeners(){const t=io(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))return;const i=e.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings");[...e.shadowRoot.querySelectorAll(".dce-mn-camera-option"),...e.shadowRoot.querySelectorAll(".dce-mn-resolution-option")].forEach((t=>{t.addEventListener("click",(async e=>{const n=t.getAttribute("data-davice-id"),r=t.getAttribute("data-height"),s=t.getAttribute("data-width");n?this.resources.cameraEnhancer.selectCamera(n).then((()=>{this.toggleScanGuide()})):r&&s&&this.resources.cameraEnhancer.setResolution({width:parseInt(s),height:parseInt(r)}).then((()=>{this.toggleScanGuide()})),"none"!==i.style.display&&this.toggleSelectCameraBox()}))}))}highlightCameraAndResolutionOption(){const t=io(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))return;const i=e.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings"),n=i.querySelectorAll(".dce-mn-camera-option"),r=i.querySelectorAll(".dce-mn-resolution-option"),s=this.resources.cameraEnhancer.getSelectedCamera(),a=this.resources.cameraEnhancer.getResolution();n.forEach((t=>{const e=t;e.getAttribute("data-davice-id")===(null==s?void 0:s.deviceId)?e.style.border="2px solid #fe814a":e.style.border="none"}));const o={"480p":"480","720p":"720","1080p":"1080","2k":"1440","4k":"2160"},l=function(t){const e=t.width*t.height,i=t.width/t.height;let n="480p",r=Number.MAX_VALUE;for(const[t,s]of Object.entries(ao)){const a=s.width*s.height,o=s.width/s.height,l=.7*Math.abs(a-e)+Math.abs(o-i)*a*.3;l{const e=t,i=e.getAttribute("data-height");e.style.border=i===o[l]?"2px solid #fe814a":"none"}))}toggleSelectCameraBox(){const t=io(this.config.container),e=t.children[t.children.length-1];if(!(null==e?void 0:e.shadowRoot))return;const i=e.shadowRoot.querySelector(".dce-mn-resolution-box");this.highlightCameraAndResolutionOption(),this.attachOptionClickListeners(),i.click()}async relaunch(){}async uploadFile(){var t,e,i,n;const{cvRouter:r}=this.resources,s=document.createElement("input");s.type="file",s.accept=null!==(t=this.config.uploadAcceptedTypes)&&void 0!==t?t:"image/*",s.style.display="none",document.body.appendChild(s);try{this.showScannerLoadingOverlay("Processing file..."),await this.closeCamera(!1);const t=await new Promise(((t,e)=>{s.onchange=i=>{var n;const r=null===(n=i.target.files)||void 0===n?void 0:n[0];r?t(r):e(new Error("No file selected"))},s.addEventListener("cancel",(async()=>{this.hideScannerLoadingOverlay(!1),await this.openCamera(),await this.startCapturing(),this.toggleScanGuide()})),s.click()}));if(!t)return;let a;if(this.config.uploadFileConverter&&!t.type.startsWith("image/"))try{a=await this.config.uploadFileConverter(t)}catch(t){throw new Error(`Error converting file: ${t.message}`)}else{if(!t.type.startsWith("image/"))throw new Error("Unsupported file type. Please provide a converter function for this file type.");a=t}const o=this.config.utilizedTemplateNames[this.currentScanMode];if(!1!==this.config.showScanGuide){const t=await r.getSimplifiedSettings(o);t.roiMeasuredInPercentage=!0,t.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await r.updateSettings(o,t)}const l=await r.capture(a,o);this.capturedResultItems=l.items;const h=this.capturedResultItems.filter((t=>t.type===yt.CRIT_ORIGINAL_IMAGE));if(0===h.length)throw new Error("No image data found in the captured result");const c=h[0].imageData;c.toCanvas=()=>F(c),c.toBlob=async()=>await k("image/png",c),this.originalImageData=c;const d=null==l?void 0:l.textLineResultItems,u=null==l?void 0:l.parsedResultItems;let f={};if(null==d?void 0:d.length){const t=(null===(e=d[0])||void 0===e?void 0:e.text)||"";f=mo(t,u[0])}const g={status:{code:eo.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,data:f,imageData:!0,_imageData:this.originalImageData};null===(n=(i=this.resources).onResultUpdated)||void 0===n||n.call(i,g),this.currentScanResolver(g)}catch(t){let e=(null==t?void 0:t.message)||t;console.error(e),alert(e),this.closeCamera();const i={status:{code:eo.RS_FAILED,message:`Error processing file: ${e}`}};this.currentScanResolver(i)}finally{this.hideScannerLoadingOverlay(!0),document.body.removeChild(s)}}toggleSoundFeedback(t){this.isSoundFeedbackOn=void 0!==t?t:!this.isSoundFeedbackOn;const e=io(this.config.container),i=e.children[e.children.length-1];if(!(null==i?void 0:i.shadowRoot))return;const n=i.shadowRoot.querySelector(".dce-mn-sound-feedback"),r=n.querySelector(".dce-mn-sound-feedback-on");n.querySelector(".dce-mn-sound-feedback-off").style.display=this.isSoundFeedbackOn?"none":"block",r.style.display=this.isSoundFeedbackOn?"block":"none"}calculateScanRegion(t){const{cameraEnhancer:e,cameraView:i}=this.resources;if(!e||!e.isOpen())return;const n=i.getVisibleRegionOfVideo({inPixels:!0});if(!n)return;const r=i.getVideoElement(),s=r.videoWidth,a=r.videoHeight,o=po[t];let l;const h=n.height-80;if(n.width>n.height){l=.75*h/o.height;l*o.width>.9*n.width&&(l=.9*n.width/o.width)}else{l=.9*n.width/o.width;l*o.height>.75*h&&(l=.75*h/o.height)}const c=l*o.width,d=l*o.height,u=(n.width-c)/2,f=(h-d)/2,g=u,m=u+c,p=f,_=f+d,v=(n.x+g)/s*100,y=(n.x+m)/s*100,w=(n.y+p)/a*100,C=(n.y+_)/a*100,E={left:Math.round(v),right:Math.round(y),top:Math.round(w),bottom:Math.round(C),isMeasuredInPercentage:!0};null==i||i.setScanRegionMaskVisible(!0),e.setScanRegion(E)}toggleScanGuide(t){const e=io(this.config.container),i=e.children[e.children.length-1];if(!(null==i?void 0:i.shadowRoot))return;const n=i.shadowRoot.querySelector(".dce-scanguide-passport"),r=i.shadowRoot.querySelector(".dce-scanguide-td1"),s=i.shadowRoot.querySelector(".dce-scanguide-td2");if(!1===t||!1===this.config.showScanGuide)return n.style.display="none",r.style.display="none",void(s.style.display="none");switch(this.currentScanMode){case Ka.All:case Ka.Passport:case Ka.PassportAndTD1:case Ka.PassportAndTD2:n.style.display="block",r.style.display="none",s.style.display="none",this.calculateScanRegion($a.Passport);break;case Ka.TD1:case Ka.TD1AndTD2:n.style.display="none",r.style.display="block",s.style.display="none",this.calculateScanRegion($a.TD1);break;case Ka.TD2:n.style.display="none",r.style.display="none",s.style.display="block",this.calculateScanRegion($a.TD2)}}async openCamera(){try{this.showScannerLoadingOverlay("Initializing camera...");const{cameraEnhancer:t,cameraView:e}=this.resources,i=io(this.config.container);if(i.style.display="block",t.isOpen())t.isPaused()&&await t.resume();else{const n=e.getUIElement();n.parentElement||i.append(n),await t.open()}await t.setResolution({width:2560,height:1440}),!this.initializedDCE&&t.isOpen()&&await this.initializeElements(),window.addEventListener("resize",this.handleResize);const n=i.children[i.children.length-1];if(!(null==n?void 0:n.shadowRoot))throw new Error("Shadow root not found");n.shadowRoot.querySelector(".dce-mn-torch-off").style.display="none",n.shadowRoot.querySelector(".dce-mn-torch-on").style.display="none"}catch(t){let e=(null==t?void 0:t.message)||t;console.error(e),alert(e),this.closeCamera();const i={status:{code:eo.RS_FAILED,message:"MRZ Scanner Open Camera Error"}};this.currentScanResolver(i)}finally{this.hideScannerLoadingOverlay()}}async closeCamera(t=!0){try{window.removeEventListener("resize",this.handleResize),this.resizeTimer&&(window.clearTimeout(this.resizeTimer),this.resizeTimer=null);const{cameraEnhancer:e,cameraView:i}=this.resources,n=io(this.config.container);n.style.display=t?"none":"block",(null==i?void 0:i.getUIElement().parentElement)&&n.removeChild(i.getUIElement()),e.close(),this.stopCapturing()}catch(t){let e=(null==t?void 0:t.message)||t;console.error(`Close Camera error: ${e}`)}}pauseCamera(){const{cameraEnhancer:t}=this.resources;t.pause()}stopCapturing(){const{cameraView:t,cvRouter:e}=this.resources;e.stopCapturing(),t.clearAllInnerDrawingItems()}async handleMRZResult(t){var e;if(this.capturedResultItems=t.items,!(t.items.length<=1))try{const{onResultUpdated:i}=this.resources,n=t.items.filter((t=>t.type===yt.CRIT_ORIGINAL_IMAGE))[0].imageData;n.toCanvas=()=>F(n),n.toBlob=async()=>await k("image/png",n),this.originalImageData=n;const r=null==t?void 0:t.textLineResultItems,s=null==t?void 0:t.parsedResultItems;if(r){this.isSoundFeedbackOn&&Ds.beep();const t=(null===(e=null==r?void 0:r[0])||void 0===e?void 0:e.text)||"",n=mo(t,s[0]);this.closeCamera();const a={status:{code:eo.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,data:n,imageData:!0,_imageData:this.originalImageData};null==i||i(a),this.currentScanResolver(a)}}catch(t){let e=(null==t?void 0:t.message)||t;console.error(e),alert(e),this.closeCamera();const i={status:{code:eo.RS_FAILED,message:"Error capturing image"}};this.currentScanResolver(i)}}initializeScanModeManager(){const{mrzFormatType:t}=this.config;if(this.scanModeManager={[$a.Passport]:!0,[$a.TD1]:!0,[$a.TD2]:!0},!t||Array.isArray(t)&&0===t.length)return;Object.keys(this.scanModeManager).forEach((t=>{this.scanModeManager[t]=!1}));(Array.isArray(t)?t:[t]).forEach((t=>{this.scanModeManager[t]=!0}))}getScanMode(){const t=Object.entries(this.scanModeManager).filter((([t,e])=>e)).map((([t])=>t)).sort().join(",");return{[$a.Passport]:Ka.Passport,[$a.TD1]:Ka.TD1,[$a.TD2]:Ka.TD2,[`${$a.Passport},${$a.TD1}`]:Ka.PassportAndTD1,[`${$a.Passport},${$a.TD2}`]:Ka.PassportAndTD2,[`${$a.TD1},${$a.TD2}`]:Ka.TD1AndTD2,[`${$a.Passport},${$a.TD1},${$a.TD2}`]:Ka.All,"":Ka.All}[t]}DCEShowToast(t,e=3e3){this.DCE_ELEMENTS.toast&&(this.DCE_ELEMENTS.toast.textContent=t,this.DCE_ELEMENTS.toast.style.display="",setTimeout((()=>{this.DCE_ELEMENTS.toast.style.display="none"}),e))}async startCapturing(){const{cvRouter:t,cameraEnhancer:e}=this.resources,i=this.config.utilizedTemplateNames[this.currentScanMode];try{if(!1!==this.config.showScanGuide){const e=await t.getSimplifiedSettings(i);e.roiMeasuredInPercentage=!0,e.roi.points=[{x:0,y:50},{x:100,y:50},{x:100,y:100},{x:0,y:100}],await t.updateSettings(i,e)}await t.startCapturing(i),e.setPixelFormat(o.IPF_ABGR_8888)}catch(t){let e=(null==t?void 0:t.message)||t;console.error("Failed to start capturing:",e),this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:eo.RS_FAILED,message:"Failed to start capturing"}})}}async toggleScanDocType(t){try{if(this.scanModeManager[t]&&0===Object.entries(this.scanModeManager).filter((([e,i])=>i&&e!==t)).length)return console.warn("MRZ Scanner - At least one mode must be enabled"),void this.DCEShowToast("At least one mode must be enabled");this.scanModeManager[t]=!this.scanModeManager[t],this.currentScanMode=this.getScanMode(),this.stopCapturing(),await this.startCapturing(),this.toggleScanGuide(),this.DCE_ELEMENTS.td1ModeOption.classList.toggle("selected",this.scanModeManager[$a.TD1]),this.DCE_ELEMENTS.td2ModeOption.classList.toggle("selected",this.scanModeManager[$a.TD2]),this.DCE_ELEMENTS.passportModeOption.classList.toggle("selected",this.scanModeManager[$a.Passport])}catch(t){let e=(null==t?void 0:t.message)||t;console.error("MRZ Scanner switch scan mode error: ",e),this.closeCamera();const i={status:{code:eo.RS_FAILED,message:"MRZ Scanner switch scan mode error"}};this.currentScanResolver(i)}}async launch(){try{await this.initialize();const{cvRouter:t,cameraEnhancer:e}=this.resources;return new Promise((async t=>{this.currentScanResolver=t,await this.openCamera(),!this.initializedDCE&&e.isOpen()&&await this.initializeElements(),await this.startCapturing(),this.toggleScanGuide()}))}catch(t){let e=(null==t?void 0:t.message)||t;console.error("MRZ Scanner launch error: ",e),this.closeCamera();const i={status:{code:eo.RS_FAILED,message:"MRZ Scanner launch error"}};this.currentScanResolver(i)}}}const vo={rescan:'\n\n\n \n\n\n\n\n\n\n\n',complete:'\n\n\n\n \n\n\n\n\n\n\n\n',failed:'\n \n \n \n\n',info:'\n\n \n \n \n\n'};class yo{constructor(t,e,i){this.resources=t,this.config=e,this.scannerView=i,this.editedFields={}}async launch(){try{return io(this.config.container).textContent="",await this.initialize(),io(this.config.container).style.display="flex",new Promise((t=>{this.currentScanResultViewResolver=t}))}catch(t){let e=(null==t?void 0:t.message)||t;throw console.error(e),e}}async handleRescan(){var t;try{if(!this.scannerView)return void console.error("Scanner View not initialized");this.hideView();const e=await this.scannerView.launch();if((null===(t=null==e?void 0:e.status)||void 0===t?void 0:t.code)===eo.RS_FAILED)return void(this.currentScanResultViewResolver&&this.currentScanResultViewResolver(e));this.resources.onResultUpdated&&((null==e?void 0:e.status.code)===eo.RS_CANCELLED?this.resources.onResultUpdated(this.resources.result):(null==e?void 0:e.status.code)===eo.RS_SUCCESS&&this.resources.onResultUpdated(e)),this.dispose(!0),await this.initialize(),io(this.config.container).style.display="flex"}catch(t){throw console.error("Error in rescan handler:",t),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:eo.RS_FAILED,message:(null==t?void 0:t.message)||t}}),t}}async handleDone(){var t,e;try{(null===(t=this.resources.result)||void 0===t?void 0:t.data)&&!ro(this.editedFields)&&(this.resources.result.data=Object.assign(Object.assign({},this.resources.result.data),this.editedFields),this.resources.onResultUpdated&&this.resources.onResultUpdated(this.resources.result)),(null===(e=this.config)||void 0===e?void 0:e.onDone)&&await this.config.onDone(this.resources.result),this.currentScanResultViewResolver&&this.resources.result&&this.currentScanResultViewResolver(this.resources.result),this.hideView(),this.dispose()}catch(t){throw console.error("Error in done handler:",t),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:eo.RS_FAILED,message:(null==t?void 0:t.message)||t}}),t}}createControls(){var t,e,i,n,r,s,a,o;const{toolbarButtonsConfig:l}=this.config;return function(t){no("dynamsoft-mrz-controls-style","\n .dynamsoft-mrz-controls {\n display: flex;\n height: 6rem;\n background-color: #323234;\n align-items: center;\n font-size: 12px;\n font-family: Verdana;\n color: white;\n width: 100%;\n }\n\n .dynamsoft-mrz-control-btn {\n background-color: #323234;\n color: white;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n height: 100%;\n width: 100%;\n gap: 0.5rem;\n text-align: center;\n user-select: none;\n }\n\n .dynamsoft-mrz-control-btn.hide {\n display: none;\n }\n\n .dynamsoft-mrz-control-btn.disabled {\n opacity: 0.4;\n pointer-events: none;\n cursor: default;\n }\n\n .dynamsoft-mrz-control-icon-wrapper {\n flex: 0.75;\n display: flex;\n align-items: flex-end;\n justify-content: center;\n min-height: 40px;\n }\n\n .dynamsoft-mrz-control-icon img,\n .dynamsoft-mrz-control-icon svg {\n width: 32px;\n height: 32px;\n fill: #fe8e14;\n }\n\n .dynamsoft-mrz-control-text {\n flex: 0.5;\n display: flex;\n align-items: flex-start;\n justify-content: center;\n padding-bottom: 0.5rem;\n }\n\n \n @media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-controls {\n flex-direction: column;\n height: 100%;\n width: 5rem;\n }\n\n .dynamsoft-mrz-control-text {\n padding: 0 0.5rem 0.5rem;\n }\n }\n");const e=document.createElement("div");return e.className="dynamsoft-mrz-controls",t.forEach((t=>{const i=document.createElement("div");i.className=`dynamsoft-mrz-control-btn ${null==t?void 0:t.className}`;const n=document.createElement("div");if(n.className="dynamsoft-mrz-control-icon-wrapper",(r=t.icon).trim().startsWith(""))n.innerHTML=t.icon;else{const e=document.createElement("img");e.src=t.icon,e.alt=t.label,e.width=24,e.height=24,n.appendChild(e)}var r;const s=document.createElement("div");s.className="dynamsoft-mrz-control-text",s.textContent=t.label,t.isDisabled&&i.classList.add("disabled"),t.isHidden&&i.classList.add("hide"),i.appendChild(n),i.appendChild(s),t.onClick&&!t.isDisabled&&i.addEventListener("click",t.onClick),e.appendChild(i)})),e}([{id:"dynamsoft-mrz-scanResult-rescan",icon:(null===(t=null==l?void 0:l.rescan)||void 0===t?void 0:t.icon)||vo.rescan,label:(null===(e=null==l?void 0:l.rescan)||void 0===e?void 0:e.label)||"Re-scan",onClick:()=>this.handleRescan(),className:`${(null===(i=null==l?void 0:l.rescan)||void 0===i?void 0:i.className)||""}`,isHidden:(null===(n=null==l?void 0:l.rescan)||void 0===n?void 0:n.isHidden)||!1,isDisabled:!this.scannerView},{id:"dynamsoft-mrz-scanResult-done",icon:(null===(r=null==l?void 0:l.done)||void 0===r?void 0:r.icon)||vo.complete,label:(null===(s=null==l?void 0:l.done)||void 0===s?void 0:s.label)||"Done",className:`${(null===(a=null==l?void 0:l.done)||void 0===a?void 0:a.className)||""}`,isHidden:(null===(o=null==l?void 0:l.done)||void 0===o?void 0:o.isHidden)||!1,onClick:()=>this.handleDone()}])}handleFieldEdit(t,e){if(t===ho.DateOfBirth||t===ho.DateOfExpiry)try{const[i,n,r]=e.split(/[\/\-\.]/);r&&n&&i&&(this.editedFields[t]={day:parseInt(r,10),month:parseInt(n,10),year:parseInt(i,10)})}catch(t){console.error("Error parsing date",t)}else this.editedFields[t]=e}createMRZDataDisplay(){var t;const e=(null===(t=this.resources.result)||void 0===t?void 0:t.data)||{},i=!!this.config.allowResultEditing,n=e.invalidFields||[],r=document.createElement("div");if(r.className="dynamsoft-mrz-data-container",ro(e)){const t=document.createElement("div");return t.className="dynamsoft-mrz-data-row empty",t.innerText="No MRZ detected. Please try again.",r.appendChild(t),r}if(n.length>0){const t=document.createElement("div");t.className="dynamsoft-mrz-error-notification",t.innerHTML=`\n
${vo.failed}
\n
\n ${i?"Some fields require correction. Please review highlighted fields.":"Some fields contain invalid information. Please rescan the document."}\n
\n `,r.appendChild(t)}else if(0===n.length&&i){const t=document.createElement("div");t.className="dynamsoft-mrz-info-notification",t.innerHTML=`\n
${vo.info}
\n
\n Please review all fields to ensure the information is correct.\n
\n `,r.appendChild(t)}return Object.entries(e).forEach((([t,e])=>{var s;if(t===ho.InvalidFields||!e)return;if(t===ho.MRZText&&!1===(null===(s=this.config)||void 0===s?void 0:s.showMRZText))return;const a=document.createElement("div");a.className="dynamsoft-mrz-data-row";const o=n.includes(t);o&&a.classList.add("invalid-field");const l=[ho.MRZText,ho.DocumentType,ho.IssuingStateRaw,ho.NationalityRaw],h=document.createElement("span");if(h.className="dynamsoft-mrz-data-label",h.innerText=co[t]||t,o){const t=document.createElement("span");if(t.className="dynamsoft-mrz-error-icon",t.innerHTML=vo.failed,h.appendChild(t),i){const t=document.createElement("span");t.className="dynamsoft-mrz-error-hint",t.textContent="Please correct this field",h.appendChild(t)}}const c=document.createElement("div");if(c.className="dynamsoft-mrz-data-value",i&&!l.includes(t)){const i=document.createElement("input");i.className="dynamsoft-mrz-data-input",o&&i.classList.add("invalid"),t===ho.DateOfBirth||t===ho.DateOfExpiry?(i.value=fo(e),i.setAttribute("placeholder","YYYY-MM-DD")):i.value=e,i.addEventListener("input",(e=>{if(this.handleFieldEdit(t,e.target.value),o){i.classList.remove("invalid"),a.classList.remove("invalid-field"),this.editedFields.invalidFields||(this.editedFields.invalidFields=[...n]);const e=this.editedFields.invalidFields.indexOf(t);e>-1&&this.editedFields.invalidFields.splice(e,1)}})),c.appendChild(i)}else t===ho.MRZText?(c.classList.add("code"),c.innerText=e):t===ho.DateOfBirth||t===ho.DateOfExpiry?c.innerText=fo(e):c.innerText=e,o&&c.classList.add("invalid-value");a.appendChild(h),a.appendChild(c),r.appendChild(a)})),r}async initialize(){try{if(!this.resources.result)throw Error("Captured image is missing. Please capture an image first!");if(!this.config.container)throw new Error("Please create a Scan Result View Container element");no("dynamsoft-mrz-result-view-style",wo);const t=document.createElement("div");if(t.className="dynamsoft-mrz-result-view-container",!1!==this.config.showOriginalImage){const e=this.resources.result.originalImageResult,i=document.createElement("div");let n;i.className="dynamsoft-mrz-result-view-image-container",(null==e?void 0:e.toCanvas)&&(n=null==e?void 0:e.toCanvas()),Object.assign(n.style,{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}),i.appendChild(n),t.appendChild(i)}const e=this.createMRZDataDisplay();t.appendChild(e);const i=this.createControls();t.appendChild(i),io(this.config.container).appendChild(t)}catch(t){let e=(null==t?void 0:t.message)||t;console.error(e),alert(e)}}hideView(){io(this.config.container).style.display="none"}dispose(t=!1){io(this.config.container).textContent="",t||(this.currentScanResultViewResolver=void 0)}}const wo="\n .dynamsoft-mrz-result-view-container {\n display: flex;\n width: 100%;\n height: 100%;\n background-color:#575757;\n font-size: 12px;\n flex-direction: column;\n align-items: center;\n }\n\n .dynamsoft-mrz-result-view-image-container {\n width: 100%;\n height: 200px;\n display: flex;\n justify-content: center;\n align-items: center;\n background-color: #323234;\n }\n\n \n.dynamsoft-mrz-data-container {\n font-size: 16px;\n font-family: Verdana;\n color: white;\n overflow: auto;\n width: 100%;\n height: 100%;\n min-height: 0;\n margin: 1rem 0;\n}\n\n.dynamsoft-mrz-data-row {\n padding: 0.5rem 2rem;\n display: flex;\n flex-direction: column;\n gap: 0.5rem;\n transition: background-color 0.3s ease;\n}\n\n.dynamsoft-mrz-data-row.invalid-field {\n background-color: rgba(231, 76, 60, 0.1);\n border-left: 3px solid #e74c3c;\n padding-left: calc(2rem - 3px);\n}\n\n.dynamsoft-mrz-data-label {\n color: #aaa;\n display: flex;\n gap: 0.5rem;\n align-items: end;\n flex-wrap: wrap;\n}\n\n.dynamsoft-mrz-error-notification,\n.dynamsoft-mrz-info-notification {\n color: white;\n padding: 1rem;\n margin: 0.5rem 2rem;\n border-radius: 4px;\n display: flex;\n align-items: center;\n gap: 1rem;\n text-align: start;\n}\n\n.dynamsoft-mrz-error-notification {\n background-color: rgba(231, 76, 60, 0.2);\n}\n\n.dynamsoft-mrz-info-notification {\n background-color: rgba(196, 231, 60, 0.2);\n}\n\n.dynamsoft-mrz-edit-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #aaa;\n}\n\n.dynamsoft-mrz-error-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-info-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: white;\n}\n\n.dynamsoft-mrz-info-message,\n.dynamsoft-mrz-error-message {\n flex: 1;\n}\n\n.dynamsoft-mrz-error-hint {\n font-size: 0.8rem;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-value {\n word-wrap: break-word;\n text-align: start;\n}\n\n.dynamsoft-mrz-data-value.code {\n font-family: monospace;\n}\n\n.dynamsoft-mrz-data-value.invalid-value {\n color: #e74c3c;\n text-decoration: wavy underline #e74c3c;\n text-decoration-skip-ink: none;\n}\n\n.dynamsoft-mrz-data-input {\n width: 100%;\n padding: 5px;\n background-color: rgba(255, 255, 255, 0.1);\n border: 1px solid rgba(255, 255, 255, 0.3);\n color: white;\n border-radius: 4px;\n font-size: 14px;\n transition: all 0.3s ease;\n}\n\n.dynamsoft-mrz-data-input.invalid {\n background-color: rgba(231, 76, 60, 0.1);\n border-color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-input:focus {\n background-color: rgba(255, 255, 255, 0.2);\n border-color: #fe8e14;\n outline: none;\n}\n\n@media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-result-view-container {\n flex-direction: row;\n }\n\n .dynamsoft-mrz-result-view-image-container{\n flex: 1;\n height: 100%;\n }\n\n .dynamsoft-mrz-data-container{\n flex: 1;\n }\n\n .dynamsoft-mrz-data-row:first-of-type {\n padding-top: 2rem;\n }\n\n .dynamsoft-mrz-data-row:last-of-type {\n padding-bottom: 2rem;\n }\n\n .dynamsoft-mrz-data-row.empty {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n padding-top: 0;\n padding-bottom: 0;\n }\n}\n",Co={rootDirectory:"https://cdn.jsdelivr.net/npm/"};class Eo{showLoadingOverlay(t){var e,i;const n=io(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)||io(null===(i=this.config.resultViewConfig)||void 0===i?void 0:i.container);this.loadingScreen=oo(n,{message:t}),n.style.display="block",n.style.position="relative"}hideLoadingOverlay(t=!1){var e,i,n;const r=io(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)||io(null===(i=this.config.resultViewConfig)||void 0===i?void 0:i.container);this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,r.style.display="none",t&&(null===(n=this.config)||void 0===n?void 0:n.container)&&(io(this.config.container).style.display="none"))}constructor(t){this.config=t,this.resources={},this.isInitialized=!1,this.isCapturing=!1,this.loadingScreen=null}async initialize(){if(this.isInitialized)return{resources:this.resources,components:{scannerView:this.scannerView,resultView:this.resultView}};try{if(!this.initializeMRZScannerConfig())return console.error("Failed to initialize mrz scanner config"),{resources:this.resources,components:{}};no("dynamsoft-mrz-loading-screen-style",lo),this.showLoadingOverlay("Loading...");if(!await this.initializeDCVResources())return this.hideLoadingOverlay(!0),console.error("Failed to initialize DCV resources"),{resources:this.resources,components:{}};this.resources.onResultUpdated=t=>{this.resources.result=t};const t={};return this.config.scannerViewConfig&&(this.scannerView=new _o(this.resources,this.config.scannerViewConfig),t.scannerView=this.scannerView,await this.scannerView.initialize()),this.config.resultViewConfig&&(this.resultView=new yo(this.resources,this.config.resultViewConfig,this.scannerView),t.resultView=this.resultView),this.isInitialized=!0,{resources:this.resources,components:t}}catch(t){this.isInitialized=!1;const e=`Initialization Failed: ${(null==t?void 0:t.message)||t}`;return console.error(e),{resources:this.resources,components:{}}}finally{this.hideLoadingOverlay(!0)}}async initializeDCVResources(){var t,e,i;try{return vt.engineResourcePaths=ro(null===(t=this.config)||void 0===t?void 0:t.engineResourcePaths)?Co:this.config.engineResourcePaths,Kt._onAuthMessage=t=>t.replace("(https://www.dynamsoft.com/customer/license/trialLicense?product=unknown&deploymenttype=unknown)","(https://www.dynamsoft.com/customer/license/trialLicense?product=mrz&deploymenttype=web)"),await Kt.initLicense((null===(e=this.config)||void 0===e?void 0:e.license)||"",{executeNow:!0}),vt.loadWasm(["DLR","DCP"]),_a.loadSpec("MRTD_TD3_PASSPORT"),_a.loadSpec("MRTD_TD1_ID"),_a.loadSpec("MRTD_TD2_ID"),Qs.loadRecognitionData("MRZ"),this.resources.cameraView=await Nn.createInstance(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.cameraEnhancerUIPath),this.resources.cameraEnhancer=await Fs.createInstance(this.resources.cameraView),this.resources.cvRouter=await Fe.createInstance(),!0}catch(t){let e=(null==t?void 0:t.message)||t;if(null==e?void 0:e.toLowerCase().includes("license")){const t="The MRZ Scanner license is invalid or has expired. Please contact the site administrator to resolve this issue.";alert(t),console.error(t)}else{const t=`Resource Initialization Failed: ${e}`;alert(t),console.error(t)}return!1}}shouldCreateDefaultContainer(){var t,e;const i=!this.config.container,n=!((null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)||(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container));return i&&n}createDefaultMRZScannerContainer(){const t=document.createElement("div");return t.className="mrz-scanner-main-container",Object.assign(t.style,{height:"100dvh",width:"100%",position:"absolute",left:"0",top:"0",zIndex:"999"}),document.body.append(t),t}checkForTemporaryLicense(t){return!(null==t?void 0:t.length)||(null==t?void 0:t.startsWith("A"))||(null==t?void 0:t.startsWith("L"))||(null==t?void 0:t.startsWith("P"))||(null==t?void 0:t.startsWith("Y"))?"DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9":t}validateViewConfigs(){var t,e,i,n,r,s,a,o;if(!this.config.container){if((null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)&&this.config.showResultView&&!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container)){const t="MRZResultView container is required when showResultView is true";return alert(t),console.error(t),!1}if(!(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.container)&&(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container)&&!this.resources.result){const t="Result is needed to create MRZResultView without a scanner view";return alert(t),console.error(t),!1}}try{if(this.config.container&&!io(this.config.container)){const t="Invalid main container reference";return alert(t),console.error(t),!1}if((null===(r=this.config.scannerViewConfig)||void 0===r?void 0:r.container)&&!io(null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.container)){const t="Invalid scanner view container reference";return alert(t),console.error(t),!1}if((null===(a=this.config.resultViewConfig)||void 0===a?void 0:a.container)&&!io(null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)){const t="Invalid result view container reference";return alert(t),console.error(t),!1}}catch(t){const e=`Error accessing container references: ${t.message}`;return alert(e),console.error(e),!1}return!0}showResultView(){var t,e;return!1!==this.config.showResultView&&(this.config.container?!(void 0!==this.config.showResultView||!(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container)&&!this.config.container)||!!this.config.showResultView:this.config.showResultView&&!!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container))}initializeMRZScannerConfig(){var t,e,i,n,r,s,a;this.config=null!==(t=this.config)&&void 0!==t?t:{};if(!this.validateViewConfigs())return!1;this.shouldCreateDefaultContainer()?this.config.container=this.createDefaultMRZScannerContainer():this.config.container&&(this.config.container=io(this.config.container));const o=this.config.container?this.createViewContainers(io(this.config.container)):{},l={license:this.checkForTemporaryLicense(this.config.license),utilizedTemplateNames:Object.fromEntries(Object.values(Ka).map((t=>{var e;return[t,(null===(e=this.config.utilizedTemplateNames)||void 0===e?void 0:e[t])||to[t]]}))),templateFilePath:(null===(e=this.config)||void 0===e?void 0:e.templateFilePath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.1.0-beta.0514202501/dist/mrz-scanner.template.json"},h=Object.assign(Object.assign({},this.config.scannerViewConfig),{container:o[Qa.Scanner]||io(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.container)||null,cameraEnhancerUIPath:(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.cameraEnhancerUIPath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.1.0-beta.0514202501/dist/mrz-scanner.ui.html",templateFilePath:l.templateFilePath,utilizedTemplateNames:l.utilizedTemplateNames,enableMultiFrameCrossFilter:null===(s=null===(r=this.config.scannerViewConfig)||void 0===r?void 0:r.enableMultiFrameCrossFilter)||void 0===s||s,mrzFormatType:this.config.mrzFormatType}),c=this.showResultView()?Object.assign(Object.assign({},this.config.resultViewConfig),{container:o[Qa.Result]||io(null===(a=this.config.resultViewConfig)||void 0===a?void 0:a.container)||null}):void 0;return Object.assign(this.config,Object.assign(Object.assign({},l),{scannerViewConfig:h,resultViewConfig:c})),!0}createViewContainers(t){t.textContent="";const e=[Qa.Scanner];return this.showResultView()&&e.push(Qa.Result),e.reduce(((e,i)=>{const n=document.createElement("div");return n.className=`mrz-scanner-${i}-view-container`,Object.assign(n.style,{height:"100%",width:"100%",display:"none",position:"relative"}),t.append(n),e[i]=n,e}),{})}dispose(){var t,e;this.resultView&&(this.resultView.dispose(),this.resultView=null),this.scannerView=null,this.resources.cameraEnhancer&&(this.resources.cameraEnhancer.dispose(),this.resources.cameraEnhancer=null),this.resources.cameraView&&(this.resources.cameraView.dispose(),this.resources.cameraView=null),this.resources.cvRouter&&(this.resources.cvRouter.dispose(),this.resources.cvRouter=null),this.resources.result=null,this.resources.onResultUpdated=null;const i=t=>{const e=io(t);e&&(e.style.display="none",e.textContent="")};i(this.config.container),i(null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container),i(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container),this.isInitialized=!1}async processUploadedFile(t){var e,i,n,r;try{this.showLoadingOverlay("Processing File...");const{cvRouter:s}=this.resources,a=null===(e=this.config.utilizedTemplateNames)||void 0===e?void 0:e.all,o=await s.getSimplifiedSettings(a);o.roiMeasuredInPercentage=!0,o.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await s.updateSettings(a,o);const l=await s.capture(t,a),h=l.items,c=h.filter((t=>t.type===yt.CRIT_ORIGINAL_IMAGE))[0].imageData;c.toCanvas=()=>F(c),c.toBlob=async()=>await k("image/png",c);const d=null==l?void 0:l.textLineResultItems,u=null==l?void 0:l.parsedResultItems;let f={};if(null==d?void 0:d.length){const t=(null===(i=d[0])||void 0===i?void 0:i.text)||"";f=mo(t,u[0])}const g={status:{code:eo.RS_SUCCESS,message:"Success"},originalImageResult:c,data:f,imageData:!0,_imageData:c};null===(r=(n=this.resources).onResultUpdated)||void 0===r||r.call(n,g)}catch(t){return console.error("Failed to process uploaded file:",t),{status:{code:eo.RS_FAILED,message:`Failed to process image: ${t.message||t}`}}}finally{this.hideLoadingOverlay(!1)}}async launch(t){if(this.isCapturing)throw new Error("Capture session already in progress");try{this.isCapturing=!0;const{components:e}=await this.initialize();if(ro(e))throw new Error("MRZ Scanner initialization failed.");if(this.config.container&&(io(this.config.container).style.display="block"),t&&(e.scannerView=null,await this.processUploadedFile(t)),!e.scannerView&&this.resources.result&&e.resultView)return await e.resultView.launch();if(!e.scannerView&&!this.resources.result)throw new Error("Scanner view is required when no previous result exists");if(e.scannerView){const t=await e.scannerView.launch();if((null==t?void 0:t.status.code)!==eo.RS_SUCCESS)return{status:{code:null==t?void 0:t.status.code,message:(null==t?void 0:t.status.message)||"Failed to capture image"}};if(e.resultView)return await e.resultView.launch()}return this.resources.result}catch(t){return alert((null==t?void 0:t.message)||t),console.error((null==t?void 0:t.message)||t),{status:{code:eo.RS_FAILED,message:(null==t?void 0:t.message)||t}}}finally{this.isCapturing=!1,this.dispose()}}}const So={MRZScanner:Eo,MRZScannerView:_o,MRZResultView:yo};export{Fs as CameraEnhancer,qe as CameraEnhancerModule,Nn as CameraView,Fe as CaptureVisionRouter,pe as CaptureVisionRouterModule,Be as CapturedResultReceiver,ua as CodeParser,_a as CodeParserModule,vt as CoreModule,to as DEFAULT_TEMPLATE_NAMES,bi as DrawingItem,Dn as DrawingStyleManager,So as DynamsoftMRZScanner,s as EnumBufferOverflowProtectionMode,yt as EnumCapturedResultItemType,a as EnumColourChannelUsageType,wt as EnumCornerType,xt as EnumCrossVerificationStatus,ai as EnumDrawingItemMediaType,oi as EnumDrawingItemState,li as EnumEnhancedFeatures,Ct as EnumErrorCode,Et as EnumGrayscaleEnhancementMode,St as EnumGrayscaleTransformationMode,o as EnumImagePixelFormat,ve as EnumImageSourceState,bt as EnumImageTagType,Ot as EnumIntermediateResultUnitType,ho as EnumMRZData,$a as EnumMRZDocumentType,Ka as EnumMRZScanMode,Qa as EnumMRZScannerViews,ia as EnumMappingStatus,Tt as EnumPDFReadingMode,Ve as EnumPresetTemplate,It as EnumRasterDataSource,ea as EnumRawTextLineStatus,At as EnumRegionObjectElementType,eo as EnumResultStatus,Rt as EnumSectionType,na as EnumValidationStatus,Ds as Feedback,Bi as GroupDrawingItem,Di as ImageDrawingItem,Ys as ImageEditorView,ya as ImageManager,K as ImageSourceAdapter,je as IntermediateResultReceiver,Qs as LabelRecognizerModule,Kt as LicenseManager,Qt as LicenseModule,ki as LineDrawingItem,co as MRZDataLabel,yo as MRZResultView,Eo as MRZScanner,_o as MRZScannerView,Ja as MultiFrameResultCrossFilter,Ni as QuadDrawingItem,Ti as RectDrawingItem,Mi as TextDrawingItem,Ia as UtilityModule,N as _getNorImageData,M as _saveToFile,k as _toBlob,F as _toCanvas,P as _toImage,dt as bDebug,R as checkIsLink,D as compareVersion,fo as displayMRZDate,rt as doOrWaitAsyncDependency,ot as getNextTaskID,L as handleEngineResourcePaths,ft as innerVersions,_ as isArc,v as isContour,C as isDSImageData,E as isDSRect,S as isImageTag,b as isLineSegment,p as isObject,w as isOriginalDsImageData,T as isPoint,I as isPolygon,x as isQuad,O as isRect,_t as loadWasm,it as mapAsyncDependency,gt as mapPackageRegister,lt as mapTaskCallBack,ht as onLog,A as requestResource,ut as setBDebug,ct as setOnLog,ta as utilsFuncs,nt as waitAsyncDependency,st as worker,mt as workerAutoResources}; diff --git a/dist/mrz-scanner.d.ts b/dist/mrz-scanner.d.ts index 7c656e3..f4eface 100644 --- a/dist/mrz-scanner.d.ts +++ b/dist/mrz-scanner.d.ts @@ -74,7 +74,9 @@ declare enum EnumMRZData { Age = "age", Sex = "sex", IssuingState = "issuingState", + IssuingStateRaw = "issuingStateRaw", Nationality = "nationality", + NationalityRaw = "nationalityRaw", DateOfBirth = "dateOfBirth", DateOfExpiry = "dateOfExpiry" } @@ -82,6 +84,7 @@ interface MRZResult { status: ResultStatus; originalImageResult?: DSImageData; data?: MRZData; + imageData?: boolean; _imageData?: DSImageData; } interface MRZData { @@ -94,7 +97,9 @@ interface MRZData { [EnumMRZData.Age]: number; [EnumMRZData.Sex]: string; [EnumMRZData.IssuingState]: string; + [EnumMRZData.IssuingStateRaw]: string; [EnumMRZData.Nationality]: string; + [EnumMRZData.NationalityRaw]: string; [EnumMRZData.DateOfBirth]: MRZDate; [EnumMRZData.DateOfExpiry]: MRZDate; } @@ -116,7 +121,10 @@ interface MRZScannerViewConfig { showUploadImage?: boolean; showFormatSelector?: boolean; showSoundToggle?: boolean; + showPoweredByDynamsoft?: boolean; enableMultiFrameCrossFilter?: boolean; + uploadAcceptedTypes?: string; + uploadFileConverter?: (file: File) => Promise; } declare class MRZScannerView { private resources; @@ -144,7 +152,8 @@ declare class MRZScannerView { private attachOptionClickListeners; private highlightCameraAndResolutionOption; private toggleSelectCameraBox; - private uploadImage; + private relaunch; + private uploadFile; private toggleSoundFeedback; private calculateScanRegion; private toggleScanGuide; @@ -236,7 +245,13 @@ declare class MRZScanner { private initializeMRZScannerConfig; private createViewContainers; dispose(): void; - launch(): Promise; + /** + * Processes an uploaded image file + * @param imageOrFile The file to process + * @returns Promise with the document result + */ + private processUploadedFile; + launch(imageOrFile: Blob | string | DSImageData | HTMLImageElement | HTMLVideoElement | HTMLCanvasElement): Promise; } declare const DynamsoftMRZScanner: { diff --git a/dist/mrz-scanner.js b/dist/mrz-scanner.js index 6984699..bc884dd 100644 --- a/dist/mrz-scanner.js +++ b/dist/mrz-scanner.js @@ -1 +1 @@ -!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports,require("dynamsoft-core"),require("dynamsoft-license"),require("dynamsoft-capture-vision-router"),require("dynamsoft-camera-enhancer"),require("dynamsoft-code-parser"),require("dynamsoft-label-recognizer"),require("dynamsoft-utility")):"function"==typeof define&&define.amd?define(["exports","dynamsoft-core","dynamsoft-license","dynamsoft-capture-vision-router","dynamsoft-camera-enhancer","dynamsoft-code-parser","dynamsoft-label-recognizer","dynamsoft-utility"],n):n((e="undefined"!=typeof globalThis?globalThis:e||self).Dynamsoft=e.Dynamsoft||{},e.Dynamsoft.Core,e.Dynamsoft.License,e.Dynamsoft.CVR,e.Dynamsoft.DCE,e.Dynamsoft.DCP,e.Dynamsoft.DLR,e.Dynamsoft.Utility)}(this,(function(e,n,t,i,a,s,o,r){"use strict";function c(e){var n=Object.create(null);return e&&Object.keys(e).forEach((function(t){if("default"!==t){var i=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,i.get?i:{enumerable:!0,get:function(){return e[t]}})}})),n.default=e,Object.freeze(n)}var l,d,u,h=c(n),m=c(t),g=c(i),p=c(a),f=c(s),y=c(o),E=c(r);e.EnumMRZScanMode=void 0,(l=e.EnumMRZScanMode||(e.EnumMRZScanMode={})).Passport="passport",l.TD1="td1",l.TD2="td2",l.PassportAndTD1="passportAndTd1",l.PassportAndTD2="passportAndTd2",l.TD1AndTD2="td1AndTd2",l.All="all",e.EnumMRZDocumentType=void 0,(d=e.EnumMRZDocumentType||(e.EnumMRZDocumentType={})).Passport="passport",d.TD1="td1",d.TD2="td2",e.EnumMRZScannerViews=void 0,(u=e.EnumMRZScannerViews||(e.EnumMRZScannerViews={})).Scanner="scanner",u.Result="scan-result";const R={[e.EnumMRZScanMode.Passport]:"ReadPassport",[e.EnumMRZScanMode.TD1]:"ReadId-TD1",[e.EnumMRZScanMode.TD2]:"ReadId-TD2",[e.EnumMRZScanMode.PassportAndTD1]:"ReadPassportAndId-TD1",[e.EnumMRZScanMode.PassportAndTD2]:"ReadPassportAndId-TD2",[e.EnumMRZScanMode.TD1AndTD2]:"ReadId",[e.EnumMRZScanMode.All]:"ReadPassportAndId"};var w;function v(e){if("string"==typeof e){const n=document.querySelector(e);if(!n)throw new Error("Element not found");return n}return e instanceof HTMLElement?e:null}e.EnumResultStatus=void 0,(w=e.EnumResultStatus||(e.EnumResultStatus={}))[w.RS_SUCCESS=0]="RS_SUCCESS",w[w.RS_CANCELLED=1]="RS_CANCELLED",w[w.RS_FAILED=2]="RS_FAILED";function M(e,n){if(!document.getElementById(e)){const t=document.createElement("style");t.id=e,t.textContent=n,document.head.appendChild(t)}}const D=e=>!e||0===Object.keys(e).length;function S(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}const C={"4k":{width:3840,height:2160},"2k":{width:2560,height:1440},"1080p":{width:1920,height:1080},"720p":{width:1280,height:720},"480p":{width:640,height:480}};function T(e,n={}){const{message:t,spinnerSize:i=32}=n,a=document.createElement("div");a.className="dynamsoft-mrz-loading-screen";const s=document.createElement("div");s.className="dynamsoft-mrz-loading";const o=document.createElement("div");o.className="dynamsoft-mrz-loading-content";const r=`\n \n \n \n `;if(o.innerHTML=r,t){const e=document.createElement("div");e.className="dynamsoft-mrz-loading-message",e.textContent=t,o.appendChild(e)}return s.appendChild(o),a.appendChild(s),e.appendChild(a),{element:a,updateMessage:e=>{let n=s.querySelector(".dynamsoft-mrz-loading-message");null!==e?n?n.textContent=e:(n=document.createElement("div"),n.className="dynamsoft-mrz-loading-message",n.textContent=e,o.appendChild(n)):null==n||n.remove()},hide:()=>{a&&a.parentNode&&(a.classList.add("fade-out"),setTimeout((()=>{var e;null===(e=a.parentNode)||void 0===e||e.removeChild(a)}),200))}}}const b='\n .dynamsoft-mrz-loading-screen {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: #323234;\n z-index: 998;\n opacity: 1;\n transition: opacity 0.2s ease-out;\n }\n\n .dynamsoft-mrz-loading-screen.fade-out {\n opacity: 0;\n }\n\n .dynamsoft-mrz-loading {\n position: absolute;\n left: 50%;\n top: 50%;\n color: white;\n z-index: 999;\n transform: translate(-50%, -50%);\n }\n\n .dynamsoft-mrz-loading-content {\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 16px;\n }\n\n .dynamsoft-mrz-loading svg {\n animation: spin 1s linear infinite;\n }\n\n .dynamsoft-mrz-loading-message {\n color: white;\n font-family: "Verdana";\n font-size: 14px;\n text-align: center;\n max-width: 200px;\n line-height: 1.4;\n opacity: 0.9;\n }\n\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n';var Z;e.EnumMRZData=void 0,(Z=e.EnumMRZData||(e.EnumMRZData={})).InvalidFields="invalidFields",Z.DocumentType="documentType",Z.DocumentNumber="documentNumber",Z.MRZText="mrzText",Z.FirstName="firstName",Z.LastName="lastName",Z.Age="age",Z.Sex="sex",Z.IssuingState="issuingState",Z.Nationality="nationality",Z.DateOfBirth="dateOfBirth",Z.DateOfExpiry="dateOfExpiry";const x={[e.EnumMRZData.InvalidFields]:"Invalid Fields",[e.EnumMRZData.DocumentType]:"Document Type",[e.EnumMRZData.DocumentNumber]:"Document Number",[e.EnumMRZData.MRZText]:"MRZ Text",[e.EnumMRZData.FirstName]:"Given Name(s)",[e.EnumMRZData.LastName]:"Surname",[e.EnumMRZData.Age]:"Age",[e.EnumMRZData.Sex]:"Sex",[e.EnumMRZData.IssuingState]:"Issuing State",[e.EnumMRZData.Nationality]:"Nationality",[e.EnumMRZData.DateOfBirth]:"Date Of Birth (YYYY-MM-DD)",[e.EnumMRZData.DateOfExpiry]:"Date Of Expiry (YYYY-MM-DD)"};function z(e,n,t,i=!1){const a=parseInt(e,10);let s;if(i)s=a>=60?1900+a:2e3+a;else{s=a>(new Date).getFullYear()%100?1900+a:2e3+a}return{year:s,month:parseInt(n,10),day:parseInt(t,10)}}function V(e){const n=e=>{var n;return 1===(null===(n=`${e}`)||void 0===n?void 0:n.length)?`0${e}`:e};return`${null==e?void 0:e.year}-${n(null==e?void 0:e.month)}${(null==e?void 0:e.day)&&`-${n(null==e?void 0:e.day)}`}`}function I(n,t){const i=[],a=e=>t.getFieldValidationStatus(e)===s.EnumValidationStatus.VS_FAILED,o=t.codeType,r=function(n){switch(n){case"MRTD_TD1_ID":return e.EnumMRZDocumentType.TD1;case"MRTD_TD2_ID":case"MRTD_TD2_VISA":case"MRTD_TD2_FRENCH_ID":return e.EnumMRZDocumentType.TD2;case"MRTD_TD3_PASSPORT":case"MRTD_TD3_VISA":return e.EnumMRZDocumentType.Passport;default:throw new Error(`Unknown document type: ${n}`)}}(o),c=function(e){switch(e){case"MRTD_TD1_ID":return"ID (TD1)";case"MRTD_TD2_ID":return"ID (TD2)";case"MRTD_TD2_VISA":return"ID (VISA)";case"MRTD_TD2_FRENCH_ID":return"French ID (TD2)";case"MRTD_TD3_PASSPORT":return"Passport (TD3)";case"MRTD_TD3_VISA":return"Visa (TD3)";default:throw new Error(`Unknown document type: ${e}`)}}(o),l=r===e.EnumMRZDocumentType.Passport&&"MRTD_TD3_PASSPORT"===o?"passportNumber":"documentNumber",d=z(t.getFieldValue("birthYear"),t.getFieldValue("birthMonth"),t.getFieldValue("birthDay")),u=z(t.getFieldValue("expiryYear"),t.getFieldValue("expiryMonth"),t.getFieldValue("expiryDay"),!0);["birthYear","birthMonth","birthDay"].forEach((n=>{a(n)&&i.push(e.EnumMRZData.DateOfBirth)})),["expiryYear","expiryMonth","expiryDay"].forEach((n=>{a(n)&&i.push(e.EnumMRZData.DateOfExpiry)}));const h={[e.EnumMRZData.LastName]:t.getFieldValue("primaryIdentifier"),[e.EnumMRZData.FirstName]:t.getFieldValue("secondaryIdentifier"),[e.EnumMRZData.Nationality]:t.getFieldRawValue("nationality"),[e.EnumMRZData.DocumentNumber]:t.getFieldValue(l)||t.getFieldValue("longDocumentNumber"),[e.EnumMRZData.IssuingState]:t.getFieldRawValue("issuingState"),[e.EnumMRZData.Sex]:S(t.getFieldValue("sex"))};Object.keys(h).forEach((n=>{let t=!1;switch(n){case e.EnumMRZData.FirstName:t=a("secondaryIdentifier");break;case e.EnumMRZData.LastName:t=a("primaryIdentifier");break;case e.EnumMRZData.DocumentNumber:t=a(l)||a("longDocumentNumber");break;default:t=a(n)}t&&i.push(n)}));const m=function(e){const n=new Date,t=n.getMonth()+1>e.month||n.getMonth()+1===e.month&&n.getDate()>=e.day;return n.getFullYear()-e.year-(t?0:1)}(d);m<1&&i.push(e.EnumMRZData.Age);return{[e.EnumMRZData.InvalidFields]:i,[e.EnumMRZData.FirstName]:h[e.EnumMRZData.FirstName],[e.EnumMRZData.LastName]:h[e.EnumMRZData.LastName],[e.EnumMRZData.Age]:m,[e.EnumMRZData.DateOfBirth]:d,[e.EnumMRZData.Sex]:h[e.EnumMRZData.Sex],[e.EnumMRZData.Nationality]:h[e.EnumMRZData.Nationality],[e.EnumMRZData.DocumentNumber]:h[e.EnumMRZData.DocumentNumber],[e.EnumMRZData.DateOfExpiry]:u,[e.EnumMRZData.IssuingState]:h[e.EnumMRZData.IssuingState],[e.EnumMRZData.DocumentType]:S(c),[e.EnumMRZData.MRZText]:n}}const L={[e.EnumMRZDocumentType.TD1]:{width:85.6,height:53.98},[e.EnumMRZDocumentType.TD2]:{width:105,height:74},[e.EnumMRZDocumentType.Passport]:{width:125,height:88}};class N{showScannerLoadingOverlay(e){const n=v(this.config.container);this.loadingScreen=T(n,{message:e}),n.style.display="block",n.style.position="relative"}hideScannerLoadingOverlay(e=!1){this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,e&&(v(this.config.container).style.display="none"))}constructor(n,t){this.resources=n,this.config=t,this.isSoundFeedbackOn=!1,this.scanModeManager={[e.EnumMRZDocumentType.Passport]:!0,[e.EnumMRZDocumentType.TD1]:!0,[e.EnumMRZDocumentType.TD2]:!0},this.currentScanMode=e.EnumMRZScanMode.All,this.resizeTimer=null,this.capturedResultItems=[],this.originalImageData=null,this.initialized=!1,this.initializedDCE=!1,this.DCE_ELEMENTS={selectCameraBtn:null,uploadImageBtn:null,soundFeedbackBtn:null,closeScannerBtn:null,scanModeSelectContainer:null,passportModeOption:null,td1ModeOption:null,td2ModeOption:null,toast:null},this.loadingScreen=null,this.handleResize=()=>{this.toggleScanGuide(!1),this.resizeTimer&&window.clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout((()=>{this.toggleScanGuide(!0)}),500)}}async initialize(){if(!this.initialized){this.initializeScanModeManager(),this.currentScanMode=this.getScanMode(),M("dynamsoft-mrz-loading-screen-style",b);try{const{cameraView:e,cameraEnhancer:t,cvRouter:a}=this.resources;if(e.setScanRegionMaskStyle({strokeStyle:"transparent",fillStyle:"transparent",lineWidth:0}),e.setVideoFit("cover"),a.setInput(t),await a.initSettings(this.config.templateFilePath),!0===this.config.enableMultiFrameCrossFilter){const e=new r.MultiFrameResultCrossFilter;e.enableResultCrossVerification(n.EnumCapturedResultItemType.CRIT_TEXT_LINE,!0),e.enableResultDeduplication(n.EnumCapturedResultItemType.CRIT_TEXT_LINE,!0),await a.addResultFilter(e)}const s=new i.CapturedResultReceiver;s.onCapturedResultReceived=e=>this.handleMRZResult(e),await a.addResultReceiver(s),this.toggleSoundFeedback(!1),!1===this.config.showScanGuide&&this.toggleScanGuide(!1),this.initialized=!0}catch(n){let t=(null==n?void 0:n.message)||n;console.error(t),alert(t),this.closeCamera();const i={status:{code:e.EnumResultStatus.RS_FAILED,message:"Dynamsoft MRZ Scanner initialize error"}};this.currentScanResolver(i)}}}initializeElements(){const e=v(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))throw new Error("Shadow root not found");this.DCE_ELEMENTS={selectCameraBtn:n.shadowRoot.querySelector(".dce-mn-select-camera-icon"),uploadImageBtn:n.shadowRoot.querySelector(".dce-mn-upload-image-icon"),soundFeedbackBtn:n.shadowRoot.querySelector(".dce-mn-sound-feedback"),closeScannerBtn:n.shadowRoot.querySelector(".dce-mn-close"),scanModeSelectContainer:n.shadowRoot.querySelector(".dce-mn-scan-mode-select"),passportModeOption:n.shadowRoot.querySelector(".scan-mode-option-passport"),td1ModeOption:n.shadowRoot.querySelector(".scan-mode-option-td1"),td2ModeOption:n.shadowRoot.querySelector(".scan-mode-option-td2"),toast:n.shadowRoot.querySelector(".dce-mn-toast")},this.setupScanModeSelector(),this.assignDCEClickEvents(),this.DCE_ELEMENTS.toast.style.display="none",!1===this.config.showUploadImage&&(this.DCE_ELEMENTS.uploadImageBtn.style.display="none"),!1===this.config.showSoundToggle&&(this.DCE_ELEMENTS.soundFeedbackBtn.style.display="none"),this.initializedDCE=!0}setupScanModeSelector(){if(!1!==this.config.showFormatSelector)switch(this.currentScanMode){case e.EnumMRZScanMode.PassportAndTD1:this.DCE_ELEMENTS.td2ModeOption.style.display="none";break;case e.EnumMRZScanMode.PassportAndTD2:this.DCE_ELEMENTS.td1ModeOption.style.display="none";break;case e.EnumMRZScanMode.TD1AndTD2:this.DCE_ELEMENTS.passportModeOption.style.display="none";break;case e.EnumMRZScanMode.All:break;default:this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}else this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}assignDCEClickEvents(){if(!Object.values(this.DCE_ELEMENTS).every(Boolean))throw new Error("Camera control elements not found");this.closeCamera=this.closeCamera.bind(this),this.DCE_ELEMENTS.uploadImageBtn.onclick=()=>this.uploadImage(),this.DCE_ELEMENTS.soundFeedbackBtn.onclick=()=>this.toggleSoundFeedback(),this.DCE_ELEMENTS.closeScannerBtn.onclick=()=>this.handleCloseBtn(),this.DCE_ELEMENTS.selectCameraBtn.onclick=e=>{e.stopPropagation(),this.toggleSelectCameraBox()},this.DCE_ELEMENTS.passportModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.passportModeOption.style.display&&await this.toggleScanDocType(e.EnumMRZDocumentType.Passport)},this.DCE_ELEMENTS.td1ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td1ModeOption.style.display&&await this.toggleScanDocType(e.EnumMRZDocumentType.TD1)},this.DCE_ELEMENTS.td2ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td2ModeOption.style.display&&await this.toggleScanDocType(e.EnumMRZDocumentType.TD2)}}handleCloseBtn(){this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:e.EnumResultStatus.RS_CANCELLED,message:"Cancelled"}})}attachOptionClickListeners(){const e=v(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const t=n.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings");[...n.shadowRoot.querySelectorAll(".dce-mn-camera-option"),...n.shadowRoot.querySelectorAll(".dce-mn-resolution-option")].forEach((e=>{e.addEventListener("click",(async n=>{const i=e.getAttribute("data-davice-id"),a=e.getAttribute("data-height"),s=e.getAttribute("data-width");i?this.resources.cameraEnhancer.selectCamera(i).then((()=>{this.toggleScanGuide()})):a&&s&&this.resources.cameraEnhancer.setResolution({width:parseInt(s),height:parseInt(a)}).then((()=>{this.toggleScanGuide()})),"none"!==t.style.display&&this.toggleSelectCameraBox()}))}))}highlightCameraAndResolutionOption(){const e=v(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const t=n.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings"),i=t.querySelectorAll(".dce-mn-camera-option"),a=t.querySelectorAll(".dce-mn-resolution-option"),s=this.resources.cameraEnhancer.getSelectedCamera(),o=this.resources.cameraEnhancer.getResolution();i.forEach((e=>{const n=e;n.getAttribute("data-davice-id")===(null==s?void 0:s.deviceId)?n.style.border="2px solid #fe814a":n.style.border="none"}));const r={"480p":"480","720p":"720","1080p":"1080","2k":"1440","4k":"2160"},c=function(e){const n=e.width*e.height,t=e.width/e.height;let i="480p",a=Number.MAX_VALUE;for(const[e,s]of Object.entries(C)){const o=s.width*s.height,r=s.width/s.height,c=.7*Math.abs(o-n)+Math.abs(r-t)*o*.3;c{const n=e,t=n.getAttribute("data-height");n.style.border=t===r[c]?"2px solid #fe814a":"none"}))}toggleSelectCameraBox(){const e=v(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const t=n.shadowRoot.querySelector(".dce-mn-resolution-box");this.highlightCameraAndResolutionOption(),this.attachOptionClickListeners(),t.click()}async uploadImage(){var t,i,a;const{cvRouter:s}=this.resources,o=document.createElement("input");o.type="file",o.accept="image/*",o.style.display="none",document.body.appendChild(o);try{this.showScannerLoadingOverlay("Processing image..."),await this.closeCamera(!1);const r=await new Promise(((e,n)=>{o.onchange=t=>{var i;const a=null===(i=t.target.files)||void 0===i?void 0:i[0];(null==a?void 0:a.type.startsWith("image/"))?e(a):n(new Error("Please select an image file"))},o.addEventListener("cancel",(async()=>{this.hideScannerLoadingOverlay(!1),await this.launch()})),o.click()}));if(!r)return this.hideScannerLoadingOverlay(!1),void await this.launch();const c=this.config.utilizedTemplateNames[this.currentScanMode];if(!1!==this.config.showScanGuide){const e=await s.getSimplifiedSettings(c);e.roiMeasuredInPercentage=!0,e.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await s.updateSettings(c,e)}const l=await s.capture(r,c);this.capturedResultItems=l.items;const d=this.capturedResultItems.filter((e=>e.type===n.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE))[0].imageData;d.toCanvas=()=>{const e=document.createElement("canvas");e.width=d.width,e.height=d.height;const n=e.getContext("2d");if(!n)throw new Error("Failed to get canvas context");const t=new ImageData(new Uint8ClampedArray(d.bytes.buffer),d.width,d.height);return n.putImageData(t,0,0),e},this.originalImageData=d;const u=null==l?void 0:l.textLineResultItems,h=null==l?void 0:l.parsedResultItems;let m={};if(null==u?void 0:u.length){const e=(null===(t=u[0])||void 0===t?void 0:t.text)||"";m=I(e,h[0])}const g={status:{code:e.EnumResultStatus.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,_imageData:this.originalImageData,data:m};null===(a=(i=this.resources).onResultUpdated)||void 0===a||a.call(i,g),this.currentScanResolver(g),this.hideScannerLoadingOverlay(!0)}catch(n){let t=(null==n?void 0:n.message)||n;console.error(t),alert(t),this.closeCamera();const i={status:{code:e.EnumResultStatus.RS_FAILED,message:"Error processing uploaded image"}};this.currentScanResolver(i)}finally{document.body.removeChild(o)}}toggleSoundFeedback(e){this.isSoundFeedbackOn=void 0!==e?e:!this.isSoundFeedbackOn;const n=v(this.config.container),t=n.children[n.children.length-1];if(!(null==t?void 0:t.shadowRoot))return;const i=t.shadowRoot.querySelector(".dce-mn-sound-feedback"),a=i.querySelector(".dce-mn-sound-feedback-on");i.querySelector(".dce-mn-sound-feedback-off").style.display=this.isSoundFeedbackOn?"none":"block",a.style.display=this.isSoundFeedbackOn?"block":"none"}calculateScanRegion(e){const{cameraEnhancer:n,cameraView:t}=this.resources;if(!n||!n.isOpen())return;const i=t.getVisibleRegionOfVideo({inPixels:!0});if(!i)return;const a=t.getVideoElement(),s=a.videoWidth,o=a.videoHeight,r=L[e];let c;const l=i.height-80;if(i.width>i.height){c=.75*l/r.height;c*r.width>.9*i.width&&(c=.9*i.width/r.width)}else{c=.9*i.width/r.width;c*r.height>.75*l&&(c=.75*l/r.height)}const d=c*r.width,u=c*r.height,h=(i.width-d)/2,m=(l-u)/2,g=h,p=h+d,f=m,y=m+u,E=(i.x+g)/s*100,R=(i.x+p)/s*100,w=(i.y+f)/o*100,v=(i.y+y)/o*100,M={left:Math.round(E),right:Math.round(R),top:Math.round(w),bottom:Math.round(v),isMeasuredInPercentage:!0};null==t||t.setScanRegionMaskVisible(!0),n.setScanRegion(M)}toggleScanGuide(n){const t=v(this.config.container),i=t.children[t.children.length-1];if(!(null==i?void 0:i.shadowRoot))return;const a=i.shadowRoot.querySelector(".dce-scanguide-passport"),s=i.shadowRoot.querySelector(".dce-scanguide-td1"),o=i.shadowRoot.querySelector(".dce-scanguide-td2");if(!1===n||!1===this.config.showScanGuide)return a.style.display="none",s.style.display="none",void(o.style.display="none");switch(this.currentScanMode){case e.EnumMRZScanMode.All:case e.EnumMRZScanMode.Passport:case e.EnumMRZScanMode.PassportAndTD1:case e.EnumMRZScanMode.PassportAndTD2:a.style.display="block",s.style.display="none",o.style.display="none",this.calculateScanRegion(e.EnumMRZDocumentType.Passport);break;case e.EnumMRZScanMode.TD1:case e.EnumMRZScanMode.TD1AndTD2:a.style.display="none",s.style.display="block",o.style.display="none",this.calculateScanRegion(e.EnumMRZDocumentType.TD1);break;case e.EnumMRZScanMode.TD2:a.style.display="none",s.style.display="none",o.style.display="block",this.calculateScanRegion(e.EnumMRZDocumentType.TD2)}}async openCamera(){try{this.showScannerLoadingOverlay("Initializing camera...");const{cameraEnhancer:e,cameraView:n}=this.resources,t=v(this.config.container);if(t.style.display="block",e.isOpen())e.isPaused()&&await e.resume();else{const i=n.getUIElement();i.parentElement||t.append(i),await e.open()}!this.initializedDCE&&e.isOpen()&&await this.initializeElements(),window.addEventListener("resize",this.handleResize);const i=t.children[t.children.length-1];if(!(null==i?void 0:i.shadowRoot))throw new Error("Shadow root not found");i.shadowRoot.querySelector(".dce-mn-torch-off").style.display="none",i.shadowRoot.querySelector(".dce-mn-torch-on").style.display="none"}catch(n){let t=(null==n?void 0:n.message)||n;console.error(t),alert(t),this.closeCamera();const i={status:{code:e.EnumResultStatus.RS_FAILED,message:"MRZ Scanner Open Camera Error"}};this.currentScanResolver(i)}finally{this.hideScannerLoadingOverlay()}}async closeCamera(e=!0){try{window.removeEventListener("resize",this.handleResize),this.resizeTimer&&(window.clearTimeout(this.resizeTimer),this.resizeTimer=null);const{cameraEnhancer:n,cameraView:t}=this.resources,i=v(this.config.container);i.style.display=e?"none":"block",(null==t?void 0:t.getUIElement().parentElement)&&i.removeChild(t.getUIElement()),n.close(),this.stopCapturing()}catch(e){let n=(null==e?void 0:e.message)||e;console.error(`Close Camera error: ${n}`)}}pauseCamera(){const{cameraEnhancer:e}=this.resources;e.pause()}stopCapturing(){const{cameraView:e,cvRouter:n}=this.resources;n.stopCapturing(),e.clearAllInnerDrawingItems()}async handleMRZResult(t){var i;if(this.capturedResultItems=t.items,!(t.items.length<=1))try{const{onResultUpdated:s}=this.resources,o=t.items.filter((e=>e.type===n.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE));this.originalImageData=o.length&&o[0].imageData;const r=null==t?void 0:t.textLineResultItems,c=null==t?void 0:t.parsedResultItems;if(r){this.isSoundFeedbackOn&&a.Feedback.beep();const n=(null===(i=null==r?void 0:r[0])||void 0===i?void 0:i.text)||"",t=I(n,c[0]);this.closeCamera();const o={status:{code:e.EnumResultStatus.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,_imageData:this.originalImageData,data:t};null==s||s(o),this.currentScanResolver(o)}}catch(n){let t=(null==n?void 0:n.message)||n;console.error(t),alert(t),this.closeCamera();const i={status:{code:e.EnumResultStatus.RS_FAILED,message:"Error capturing image"}};this.currentScanResolver(i)}}initializeScanModeManager(){const{mrzFormatType:n}=this.config;if(this.scanModeManager={[e.EnumMRZDocumentType.Passport]:!0,[e.EnumMRZDocumentType.TD1]:!0,[e.EnumMRZDocumentType.TD2]:!0},!n||Array.isArray(n)&&0===n.length)return;Object.keys(this.scanModeManager).forEach((e=>{this.scanModeManager[e]=!1}));(Array.isArray(n)?n:[n]).forEach((e=>{this.scanModeManager[e]=!0}))}getScanMode(){const n=Object.entries(this.scanModeManager).filter((([e,n])=>n)).map((([e])=>e)).sort().join(",");return{[e.EnumMRZDocumentType.Passport]:e.EnumMRZScanMode.Passport,[e.EnumMRZDocumentType.TD1]:e.EnumMRZScanMode.TD1,[e.EnumMRZDocumentType.TD2]:e.EnumMRZScanMode.TD2,[`${e.EnumMRZDocumentType.Passport},${e.EnumMRZDocumentType.TD1}`]:e.EnumMRZScanMode.PassportAndTD1,[`${e.EnumMRZDocumentType.Passport},${e.EnumMRZDocumentType.TD2}`]:e.EnumMRZScanMode.PassportAndTD2,[`${e.EnumMRZDocumentType.TD1},${e.EnumMRZDocumentType.TD2}`]:e.EnumMRZScanMode.TD1AndTD2,[`${e.EnumMRZDocumentType.Passport},${e.EnumMRZDocumentType.TD1},${e.EnumMRZDocumentType.TD2}`]:e.EnumMRZScanMode.All,"":e.EnumMRZScanMode.All}[n]}DCEShowToast(e,n=3e3){this.DCE_ELEMENTS.toast&&(this.DCE_ELEMENTS.toast.textContent=e,this.DCE_ELEMENTS.toast.style.display="",setTimeout((()=>{this.DCE_ELEMENTS.toast.style.display="none"}),n))}async startCapturing(){const{cvRouter:t,cameraEnhancer:i}=this.resources,a=this.config.utilizedTemplateNames[this.currentScanMode];try{if(!1!==this.config.showScanGuide){const e=await t.getSimplifiedSettings(a);e.roiMeasuredInPercentage=!0,e.roi.points=[{x:0,y:50},{x:100,y:50},{x:100,y:100},{x:0,y:100}],await t.updateSettings(a,e)}await t.startCapturing(a),i.setPixelFormat(n.EnumImagePixelFormat.IPF_ABGR_8888)}catch(n){let t=(null==n?void 0:n.message)||n;console.error("Failed to start capturing:",t),this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:e.EnumResultStatus.RS_FAILED,message:"Failed to start capturing"}})}}async toggleScanDocType(n){try{if(this.scanModeManager[n]&&0===Object.entries(this.scanModeManager).filter((([e,t])=>t&&e!==n)).length)return console.warn("MRZ Scanner - At least one mode must be enabled"),void this.DCEShowToast("At least one mode must be enabled");this.scanModeManager[n]=!this.scanModeManager[n],this.currentScanMode=this.getScanMode(),this.stopCapturing(),await this.startCapturing(),this.toggleScanGuide(),this.DCE_ELEMENTS.td1ModeOption.classList.toggle("selected",this.scanModeManager[e.EnumMRZDocumentType.TD1]),this.DCE_ELEMENTS.td2ModeOption.classList.toggle("selected",this.scanModeManager[e.EnumMRZDocumentType.TD2]),this.DCE_ELEMENTS.passportModeOption.classList.toggle("selected",this.scanModeManager[e.EnumMRZDocumentType.Passport])}catch(n){let t=(null==n?void 0:n.message)||n;console.error("MRZ Scanner switch scan mode error: ",t),this.closeCamera();const i={status:{code:e.EnumResultStatus.RS_FAILED,message:"MRZ Scanner switch scan mode error"}};this.currentScanResolver(i)}}async launch(){try{await this.initialize();const{cvRouter:e,cameraEnhancer:n}=this.resources;return new Promise((async e=>{this.currentScanResolver=e,await this.openCamera(),!this.initializedDCE&&n.isOpen()&&await this.initializeElements(),await this.startCapturing(),this.toggleScanGuide()}))}catch(n){let t=(null==n?void 0:n.message)||n;console.error("MRZ Scanner launch error: ",t),this.closeCamera();const i={status:{code:e.EnumResultStatus.RS_FAILED,message:"MRZ Scanner launch error"}};this.currentScanResolver(i)}}}const F={rescan:'\n\n\n \n\n\n\n\n\n\n\n',complete:'\n\n\n\n \n\n\n\n\n\n\n\n',failed:'\n \n \n \n\n',info:'\n\n \n \n \n\n'};class _{constructor(e,n,t){this.resources=e,this.config=n,this.scannerView=t,this.editedFields={}}async launch(){try{return v(this.config.container).textContent="",await this.initialize(),v(this.config.container).style.display="flex",new Promise((e=>{this.currentScanResultViewResolver=e}))}catch(e){let n=(null==e?void 0:e.message)||e;throw console.error(n),n}}async handleRescan(){var n;try{if(!this.scannerView)return void console.error("Scanner View not initialized");this.hideView();const t=await this.scannerView.launch();if((null===(n=null==t?void 0:t.status)||void 0===n?void 0:n.code)===e.EnumResultStatus.RS_FAILED)return void(this.currentScanResultViewResolver&&this.currentScanResultViewResolver(t));this.resources.onResultUpdated&&((null==t?void 0:t.status.code)===e.EnumResultStatus.RS_CANCELLED?this.resources.onResultUpdated(this.resources.result):(null==t?void 0:t.status.code)===e.EnumResultStatus.RS_SUCCESS&&this.resources.onResultUpdated(t)),this.dispose(!0),await this.initialize(),v(this.config.container).style.display="flex"}catch(n){throw console.error("Error in rescan handler:",n),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:e.EnumResultStatus.RS_FAILED,message:(null==n?void 0:n.message)||n}}),n}}async handleDone(){var n,t;try{(null===(n=this.resources.result)||void 0===n?void 0:n.data)&&!D(this.editedFields)&&(this.resources.result.data=Object.assign(Object.assign({},this.resources.result.data),this.editedFields),this.resources.onResultUpdated&&this.resources.onResultUpdated(this.resources.result)),(null===(t=this.config)||void 0===t?void 0:t.onDone)&&await this.config.onDone(this.resources.result),this.currentScanResultViewResolver&&this.resources.result&&this.currentScanResultViewResolver(this.resources.result),this.hideView(),this.dispose()}catch(n){throw console.error("Error in done handler:",n),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:e.EnumResultStatus.RS_FAILED,message:(null==n?void 0:n.message)||n}}),n}}createControls(){var e,n,t,i,a,s,o,r;const{toolbarButtonsConfig:c}=this.config;return function(e){M("dynamsoft-mrz-controls-style","\n .dynamsoft-mrz-controls {\n display: flex;\n height: 6rem;\n background-color: #323234;\n align-items: center;\n font-size: 12px;\n font-family: Verdana;\n color: white;\n width: 100%;\n }\n\n .dynamsoft-mrz-control-btn {\n background-color: #323234;\n color: white;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n height: 100%;\n width: 100%;\n gap: 0.5rem;\n text-align: center;\n user-select: none;\n }\n\n .dynamsoft-mrz-control-btn.hide {\n display: none;\n }\n\n .dynamsoft-mrz-control-btn.disabled {\n opacity: 0.4;\n pointer-events: none;\n cursor: default;\n }\n\n .dynamsoft-mrz-control-icon-wrapper {\n flex: 0.75;\n display: flex;\n align-items: flex-end;\n justify-content: center;\n min-height: 40px;\n }\n\n .dynamsoft-mrz-control-icon img,\n .dynamsoft-mrz-control-icon svg {\n width: 32px;\n height: 32px;\n fill: #fe8e14;\n }\n\n .dynamsoft-mrz-control-text {\n flex: 0.5;\n display: flex;\n align-items: flex-start;\n justify-content: center;\n padding-bottom: 0.5rem;\n }\n\n \n @media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-controls {\n flex-direction: column;\n height: 100%;\n width: 5rem;\n }\n\n .dynamsoft-mrz-control-text {\n padding: 0 0.5rem 0.5rem;\n }\n }\n");const n=document.createElement("div");return n.className="dynamsoft-mrz-controls",e.forEach((e=>{const t=document.createElement("div");t.className=`dynamsoft-mrz-control-btn ${null==e?void 0:e.className}`;const i=document.createElement("div");if(i.className="dynamsoft-mrz-control-icon-wrapper",(a=e.icon).trim().startsWith(""))i.innerHTML=e.icon;else{const n=document.createElement("img");n.src=e.icon,n.alt=e.label,n.width=24,n.height=24,i.appendChild(n)}var a;const s=document.createElement("div");s.className="dynamsoft-mrz-control-text",s.textContent=e.label,e.isDisabled&&t.classList.add("disabled"),e.isHidden&&t.classList.add("hide"),t.appendChild(i),t.appendChild(s),e.onClick&&!e.isDisabled&&t.addEventListener("click",e.onClick),n.appendChild(t)})),n}([{id:"dynamsoft-mrz-scanResult-rescan",icon:(null===(e=null==c?void 0:c.rescan)||void 0===e?void 0:e.icon)||F.rescan,label:(null===(n=null==c?void 0:c.rescan)||void 0===n?void 0:n.label)||"Re-scan",onClick:()=>this.handleRescan(),className:`${(null===(t=null==c?void 0:c.rescan)||void 0===t?void 0:t.className)||""}`,isHidden:(null===(i=null==c?void 0:c.rescan)||void 0===i?void 0:i.isHidden)||!1,isDisabled:!this.scannerView},{id:"dynamsoft-mrz-scanResult-done",icon:(null===(a=null==c?void 0:c.done)||void 0===a?void 0:a.icon)||F.complete,label:(null===(s=null==c?void 0:c.done)||void 0===s?void 0:s.label)||"Done",className:`${(null===(o=null==c?void 0:c.done)||void 0===o?void 0:o.className)||""}`,isHidden:(null===(r=null==c?void 0:c.done)||void 0===r?void 0:r.isHidden)||!1,onClick:()=>this.handleDone()}])}handleFieldEdit(n,t){if(n===e.EnumMRZData.DateOfBirth||n===e.EnumMRZData.DateOfExpiry)try{const[e,i,a]=t.split(/[\/\-\.]/);a&&i&&e&&(this.editedFields[n]={day:parseInt(a,10),month:parseInt(i,10),year:parseInt(e,10)})}catch(e){console.error("Error parsing date",e)}else this.editedFields[n]=t}createMRZDataDisplay(){var n;const t=(null===(n=this.resources.result)||void 0===n?void 0:n.data)||{},i=!!this.config.allowResultEditing,a=t.invalidFields||[],s=document.createElement("div");if(s.className="dynamsoft-mrz-data-container",D(t)){const e=document.createElement("div");return e.className="dynamsoft-mrz-data-row empty",e.innerText="No MRZ detected. Please try again.",s.appendChild(e),s}if(a.length>0){const e=document.createElement("div");e.className="dynamsoft-mrz-error-notification",e.innerHTML=`\n
${F.failed}
\n
\n ${i?"Some fields require correction. Please review highlighted fields.":"Some fields contain invalid information. Please rescan the document."}\n
\n `,s.appendChild(e)}else if(0===a.length&&i){const e=document.createElement("div");e.className="dynamsoft-mrz-info-notification",e.innerHTML=`\n
${F.info}
\n
\n Please review all fields to ensure the information is correct.\n
\n `,s.appendChild(e)}return Object.entries(t).forEach((([n,t])=>{var o;if(n===e.EnumMRZData.InvalidFields||!t)return;if(n===e.EnumMRZData.MRZText&&!1===(null===(o=this.config)||void 0===o?void 0:o.showMRZText))return;const r=document.createElement("div");r.className="dynamsoft-mrz-data-row";const c=a.includes(n);c&&r.classList.add("invalid-field");const l=[e.EnumMRZData.MRZText,e.EnumMRZData.DocumentType],d=document.createElement("span");if(d.className="dynamsoft-mrz-data-label",d.innerText=x[n]||n,c){const e=document.createElement("span");if(e.className="dynamsoft-mrz-error-icon",e.innerHTML=F.failed,d.appendChild(e),i){const e=document.createElement("span");e.className="dynamsoft-mrz-error-hint",e.textContent="Please correct this field",d.appendChild(e)}}const u=document.createElement("div");if(u.className="dynamsoft-mrz-data-value",i&&!l.includes(n)){const i=document.createElement("input");i.className="dynamsoft-mrz-data-input",c&&i.classList.add("invalid"),n===e.EnumMRZData.DateOfBirth||n===e.EnumMRZData.DateOfExpiry?(i.value=V(t),i.setAttribute("placeholder","YYYY-MM-DD")):i.value=t,i.addEventListener("input",(e=>{if(this.handleFieldEdit(n,e.target.value),c){i.classList.remove("invalid"),r.classList.remove("invalid-field"),this.editedFields.invalidFields||(this.editedFields.invalidFields=[...a]);const e=this.editedFields.invalidFields.indexOf(n);e>-1&&this.editedFields.invalidFields.splice(e,1)}})),u.appendChild(i)}else n===e.EnumMRZData.MRZText?(u.classList.add("code"),u.innerText=t):n===e.EnumMRZData.DateOfBirth||n===e.EnumMRZData.DateOfExpiry?u.innerText=V(t):u.innerText=t,c&&u.classList.add("invalid-value");r.appendChild(d),r.appendChild(u),s.appendChild(r)})),s}async initialize(){try{if(!this.resources.result)throw Error("Captured image is missing. Please capture an image first!");if(!this.config.container)throw new Error("Please create a Scan Result View Container element");M("dynamsoft-mrz-result-view-style",k);const e=document.createElement("div");if(e.className="dynamsoft-mrz-result-view-container",!1!==this.config.showOriginalImage){const n=this.resources.result.originalImageResult,t=document.createElement("div");let i;t.className="dynamsoft-mrz-result-view-image-container",(null==n?void 0:n.toCanvas)&&(i=null==n?void 0:n.toCanvas()),Object.assign(i.style,{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}),t.appendChild(i),e.appendChild(t)}const n=this.createMRZDataDisplay();e.appendChild(n);const t=this.createControls();e.appendChild(t),v(this.config.container).appendChild(e)}catch(e){let n=(null==e?void 0:e.message)||e;console.error(n),alert(n)}}hideView(){v(this.config.container).style.display="none"}dispose(e=!1){v(this.config.container).textContent="",e||(this.currentScanResultViewResolver=void 0)}}const k="\n .dynamsoft-mrz-result-view-container {\n display: flex;\n width: 100%;\n height: 100%;\n background-color:#575757;\n font-size: 12px;\n flex-direction: column;\n align-items: center;\n }\n\n .dynamsoft-mrz-result-view-image-container {\n width: 100%;\n height: 200px;\n display: flex;\n justify-content: center;\n align-items: center;\n background-color: #323234;\n }\n\n \n.dynamsoft-mrz-data-container {\n font-size: 16px;\n font-family: Verdana;\n color: white;\n overflow: auto;\n width: 100%;\n height: 100%;\n min-height: 0;\n margin: 1rem 0;\n}\n\n.dynamsoft-mrz-data-row {\n padding: 0.5rem 2rem;\n display: flex;\n flex-direction: column;\n gap: 0.5rem;\n transition: background-color 0.3s ease;\n}\n\n.dynamsoft-mrz-data-row.invalid-field {\n background-color: rgba(231, 76, 60, 0.1);\n border-left: 3px solid #e74c3c;\n padding-left: calc(2rem - 3px);\n}\n\n.dynamsoft-mrz-data-label {\n color: #aaa;\n display: flex;\n gap: 0.5rem;\n align-items: end;\n flex-wrap: wrap;\n}\n\n.dynamsoft-mrz-error-notification,\n.dynamsoft-mrz-info-notification {\n color: white;\n padding: 1rem;\n margin: 0.5rem 2rem;\n border-radius: 4px;\n display: flex;\n align-items: center;\n gap: 1rem;\n text-align: start;\n}\n\n.dynamsoft-mrz-error-notification {\n background-color: rgba(231, 76, 60, 0.2);\n}\n\n.dynamsoft-mrz-info-notification {\n background-color: rgba(196, 231, 60, 0.2);\n}\n\n.dynamsoft-mrz-edit-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #aaa;\n}\n\n.dynamsoft-mrz-error-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-info-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: white;\n}\n\n.dynamsoft-mrz-info-message,\n.dynamsoft-mrz-error-message {\n flex: 1;\n}\n\n.dynamsoft-mrz-error-hint {\n font-size: 0.8rem;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-value {\n word-wrap: break-word;\n text-align: start;\n}\n\n.dynamsoft-mrz-data-value.code {\n font-family: monospace;\n}\n\n.dynamsoft-mrz-data-value.invalid-value {\n color: #e74c3c;\n text-decoration: wavy underline #e74c3c;\n text-decoration-skip-ink: none;\n}\n\n.dynamsoft-mrz-data-input {\n width: 100%;\n padding: 5px;\n background-color: rgba(255, 255, 255, 0.1);\n border: 1px solid rgba(255, 255, 255, 0.3);\n color: white;\n border-radius: 4px;\n font-size: 14px;\n transition: all 0.3s ease;\n}\n\n.dynamsoft-mrz-data-input.invalid {\n background-color: rgba(231, 76, 60, 0.1);\n border-color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-input:focus {\n background-color: rgba(255, 255, 255, 0.2);\n border-color: #fe8e14;\n outline: none;\n}\n\n@media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-result-view-container {\n flex-direction: row;\n }\n\n .dynamsoft-mrz-result-view-image-container{\n flex: 1;\n height: 100%;\n }\n\n .dynamsoft-mrz-data-container{\n flex: 1;\n }\n\n .dynamsoft-mrz-data-row:first-of-type {\n padding-top: 2rem;\n }\n\n .dynamsoft-mrz-data-row:last-of-type {\n padding-bottom: 2rem;\n }\n\n .dynamsoft-mrz-data-row.empty {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n padding-top: 0;\n padding-bottom: 0;\n }\n}\n",O={rootDirectory:"https://cdn.jsdelivr.net/npm/"};class A{showLoadingOverlay(e){var n,t;const i=v(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)||v(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container);this.loadingScreen=T(i,{message:e}),i.style.display="block",i.style.position="relative"}hideLoadingOverlay(e=!1){var n,t,i;const a=v(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)||v(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container);this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,e&&(a.style.display="none",(null===(i=this.config)||void 0===i?void 0:i.container)&&(v(this.config.container).style.display="none")))}constructor(e){this.config=e,this.resources={},this.isInitialized=!1,this.isCapturing=!1,this.loadingScreen=null}async initialize(){if(this.isInitialized)return{resources:this.resources,components:{scannerView:this.scannerView,resultView:this.resultView}};try{if(!this.initializeMRZScannerConfig())return console.error("Failed to initialize mrz scanner config"),{resources:this.resources,components:{}};M("dynamsoft-mrz-loading-screen-style",b),this.showLoadingOverlay("Loading...");if(!await this.initializeDCVResources())return this.hideLoadingOverlay(!0),console.error("Failed to initialize DCV resources"),{resources:this.resources,components:{}};this.resources.onResultUpdated=e=>{this.resources.result=e};const e={};return this.config.scannerViewConfig&&(this.scannerView=new N(this.resources,this.config.scannerViewConfig),e.scannerView=this.scannerView,await this.scannerView.initialize()),this.config.resultViewConfig&&(this.resultView=new _(this.resources,this.config.resultViewConfig,this.scannerView),e.resultView=this.resultView),this.isInitialized=!0,{resources:this.resources,components:e}}catch(e){this.isInitialized=!1;const n=`Initialization Failed: ${(null==e?void 0:e.message)||e}`;return alert(n),console.error(n),{resources:this.resources,components:{}}}finally{this.hideLoadingOverlay(!0)}}async initializeDCVResources(){var e,r,c;try{return t.LicenseManager.initLicense((null===(e=this.config)||void 0===e?void 0:e.license)||"",!0),n.CoreModule.engineResourcePaths=D(null===(r=this.config)||void 0===r?void 0:r.engineResourcePaths)?O:this.config.engineResourcePaths,n.CoreModule.loadWasm(["DLR","DCP"]),s.CodeParserModule.loadSpec("MRTD_TD3_PASSPORT"),s.CodeParserModule.loadSpec("MRTD_TD1_ID"),s.CodeParserModule.loadSpec("MRTD_TD2_ID"),o.LabelRecognizerModule.loadRecognitionData("MRZ"),this.resources.cameraView=await a.CameraView.createInstance(null===(c=this.config.scannerViewConfig)||void 0===c?void 0:c.cameraEnhancerUIPath),this.resources.cameraEnhancer=await a.CameraEnhancer.createInstance(this.resources.cameraView),this.resources.cvRouter=await i.CaptureVisionRouter.createInstance(),!0}catch(e){let n=(null==e?void 0:e.message)||e;if(null==n?void 0:n.toLowerCase().includes("license")){const e="The MRZ Scanner license is invalid or has expired. Please contact the site administrator to resolve this issue.";alert(e),console.error(e)}else{const e=`Resource Initialization Failed: ${n}`;alert(e),console.error(e)}return!1}}shouldCreateDefaultContainer(){var e,n;const t=!this.config.container,i=!((null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)||(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container));return t&&i}createDefaultMRZScannerContainer(){const e=document.createElement("div");return e.className="mrz-scanner-main-container",Object.assign(e.style,{height:"100dvh",width:"100%",position:"absolute",left:"0",top:"0",zIndex:"999"}),document.body.append(e),e}checkForTemporaryLicense(e){return!(null==e?void 0:e.length)||(null==e?void 0:e.startsWith("A"))||(null==e?void 0:e.startsWith("L"))||(null==e?void 0:e.startsWith("P"))||(null==e?void 0:e.startsWith("Y"))?"DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9":e}validateViewConfigs(){var e,n,t,i,a,s,o,r;if(!this.config.container){if((null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)&&this.config.showResultView&&!(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container)){const e="MRZResultView container is required when showResultView is true";return alert(e),console.error(e),!1}if(!(null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)&&(null===(i=this.config.resultViewConfig)||void 0===i?void 0:i.container)&&!this.resources.result){const e="Result is needed to create MRZResultView without a scanner view";return alert(e),console.error(e),!1}}try{if(this.config.container&&!v(this.config.container)){const e="Invalid main container reference";return alert(e),console.error(e),!1}if((null===(a=this.config.scannerViewConfig)||void 0===a?void 0:a.container)&&!v(null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.container)){const e="Invalid scanner view container reference";return alert(e),console.error(e),!1}if((null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)&&!v(null===(r=this.config.resultViewConfig)||void 0===r?void 0:r.container)){const e="Invalid result view container reference";return alert(e),console.error(e),!1}}catch(e){const n=`Error accessing container references: ${e.message}`;return alert(n),console.error(n),!1}return!0}showResultView(){var e,n;return!1!==this.config.showResultView&&(this.config.container?!(void 0!==this.config.showResultView||!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container)&&!this.config.container)||!!this.config.showResultView:this.config.showResultView&&!!(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container))}initializeMRZScannerConfig(){var n,t,i,a,s,o,r;this.config=null!==(n=this.config)&&void 0!==n?n:{};if(!this.validateViewConfigs())return!1;this.shouldCreateDefaultContainer()?this.config.container=this.createDefaultMRZScannerContainer():this.config.container&&(this.config.container=v(this.config.container));const c=this.config.container?this.createViewContainers(v(this.config.container)):{},l={license:this.checkForTemporaryLicense(this.config.license),utilizedTemplateNames:Object.fromEntries(Object.values(e.EnumMRZScanMode).map((e=>{var n;return[e,(null===(n=this.config.utilizedTemplateNames)||void 0===n?void 0:n[e])||R[e]]}))),templateFilePath:(null===(t=this.config)||void 0===t?void 0:t.templateFilePath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.0.0/dist/mrz-scanner.template.json"},d=Object.assign(Object.assign({},this.config.scannerViewConfig),{container:c[e.EnumMRZScannerViews.Scanner]||v(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.container)||null,cameraEnhancerUIPath:(null===(a=this.config.scannerViewConfig)||void 0===a?void 0:a.cameraEnhancerUIPath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.0.0/dist/mrz-scanner.ui.html",templateFilePath:l.templateFilePath,utilizedTemplateNames:l.utilizedTemplateNames,enableMultiFrameCrossFilter:null===(o=null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.enableMultiFrameCrossFilter)||void 0===o||o,mrzFormatType:this.config.mrzFormatType}),u=this.showResultView()?Object.assign(Object.assign({},this.config.resultViewConfig),{container:c[e.EnumMRZScannerViews.Result]||v(null===(r=this.config.resultViewConfig)||void 0===r?void 0:r.container)||null}):void 0;return Object.assign(this.config,Object.assign(Object.assign({},l),{scannerViewConfig:d,resultViewConfig:u})),!0}createViewContainers(n){n.textContent="";const t=[e.EnumMRZScannerViews.Scanner];return this.showResultView()&&t.push(e.EnumMRZScannerViews.Result),t.reduce(((e,t)=>{const i=document.createElement("div");return i.className=`mrz-scanner-${t}-view-container`,Object.assign(i.style,{height:"100%",width:"100%",display:"none",position:"relative"}),n.append(i),e[t]=i,e}),{})}dispose(){var e,n;this.resultView&&(this.resultView.dispose(),this.resultView=null),this.scannerView=null,this.resources.cameraEnhancer&&(this.resources.cameraEnhancer.dispose(),this.resources.cameraEnhancer=null),this.resources.cameraView&&(this.resources.cameraView.dispose(),this.resources.cameraView=null),this.resources.cvRouter&&(this.resources.cvRouter.dispose(),this.resources.cvRouter=null),this.resources.result=null,this.resources.onResultUpdated=null;const t=e=>{const n=v(e);n&&(n.style.display="none",n.textContent="")};t(this.config.container),t(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container),t(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container),this.isInitialized=!1}async launch(){if(this.isCapturing)throw new Error("Capture session already in progress");try{this.isCapturing=!0;const{components:n}=await this.initialize();if(D(n))throw new Error("MRZ Scanner initialization failed.");if(this.config.container&&(v(this.config.container).style.display="block"),!n.scannerView&&this.resources.result&&n.resultView)return await n.resultView.launch();if(!n.scannerView&&!this.resources.result)throw new Error("Scanner view is required when no previous result exists");if(n.scannerView){const t=await n.scannerView.launch();if((null==t?void 0:t.status.code)!==e.EnumResultStatus.RS_SUCCESS)return{status:{code:null==t?void 0:t.status.code,message:(null==t?void 0:t.status.message)||"Failed to capture image"}};if(n.resultView)return await n.resultView.launch()}return this.resources.result}catch(n){return alert((null==n?void 0:n.message)||n),console.error((null==n?void 0:n.message)||n),{status:{code:e.EnumResultStatus.RS_FAILED,message:(null==n?void 0:n.message)||n}}}finally{this.isCapturing=!1,this.dispose()}}}const P={MRZScanner:A,MRZScannerView:N,MRZResultView:_};e.Core=h,e.License=m,e.CVR=g,e.DCE=p,e.DCP=f,e.DLR=y,e.Utility=E,e.DEFAULT_TEMPLATE_NAMES=R,e.DynamsoftMRZScanner=P,e.MRZDataLabel=x,e.MRZResultView=_,e.MRZScanner=A,e.MRZScannerView=N,e.displayMRZDate=V})); +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports,require("dynamsoft-core"),require("dynamsoft-license"),require("dynamsoft-capture-vision-router"),require("dynamsoft-camera-enhancer"),require("dynamsoft-code-parser"),require("dynamsoft-label-recognizer"),require("dynamsoft-utility")):"function"==typeof define&&define.amd?define(["exports","dynamsoft-core","dynamsoft-license","dynamsoft-capture-vision-router","dynamsoft-camera-enhancer","dynamsoft-code-parser","dynamsoft-label-recognizer","dynamsoft-utility"],n):n((e="undefined"!=typeof globalThis?globalThis:e||self).Dynamsoft=e.Dynamsoft||{},e.Dynamsoft.Core,e.Dynamsoft.License,e.Dynamsoft.CVR,e.Dynamsoft.DCE,e.Dynamsoft.DCP,e.Dynamsoft.DLR,e.Dynamsoft.Utility)}(this,(function(e,n,t,i,a,s,o,r){"use strict";function l(e){var n=Object.create(null);return e&&Object.keys(e).forEach((function(t){if("default"!==t){var i=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,i.get?i:{enumerable:!0,get:function(){return e[t]}})}})),n.default=e,Object.freeze(n)}var c,d,u,m=l(n),h=l(t),g=l(i),p=l(a),f=l(s),y=l(o),R=l(r);e.EnumMRZScanMode=void 0,(c=e.EnumMRZScanMode||(e.EnumMRZScanMode={})).Passport="passport",c.TD1="td1",c.TD2="td2",c.PassportAndTD1="passportAndTd1",c.PassportAndTD2="passportAndTd2",c.TD1AndTD2="td1AndTd2",c.All="all",e.EnumMRZDocumentType=void 0,(d=e.EnumMRZDocumentType||(e.EnumMRZDocumentType={})).Passport="passport",d.TD1="td1",d.TD2="td2",e.EnumMRZScannerViews=void 0,(u=e.EnumMRZScannerViews||(e.EnumMRZScannerViews={})).Scanner="scanner",u.Result="scan-result";const E={[e.EnumMRZScanMode.Passport]:"ReadPassport",[e.EnumMRZScanMode.TD1]:"ReadId-TD1",[e.EnumMRZScanMode.TD2]:"ReadId-TD2",[e.EnumMRZScanMode.PassportAndTD1]:"ReadPassportAndId-TD1",[e.EnumMRZScanMode.PassportAndTD2]:"ReadPassportAndId-TD2",[e.EnumMRZScanMode.TD1AndTD2]:"ReadId",[e.EnumMRZScanMode.All]:"ReadPassportAndId"};var w;function v(e){if("string"==typeof e){const n=document.querySelector(e);if(!n)throw new Error("Element not found");return n}return e instanceof HTMLElement?e:null}e.EnumResultStatus=void 0,(w=e.EnumResultStatus||(e.EnumResultStatus={}))[w.RS_SUCCESS=0]="RS_SUCCESS",w[w.RS_CANCELLED=1]="RS_CANCELLED",w[w.RS_FAILED=2]="RS_FAILED";function M(e,n){if(!document.getElementById(e)){const t=document.createElement("style");t.id=e,t.textContent=n,document.head.appendChild(t)}}const D=e=>!e||0===Object.keys(e).length;function S(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}const C={"4k":{width:3840,height:2160},"2k":{width:2560,height:1440},"1080p":{width:1920,height:1080},"720p":{width:1280,height:720},"480p":{width:640,height:480}};function T(e,n={}){const{message:t,spinnerSize:i=32}=n,a=document.createElement("div");a.className="dynamsoft-mrz-loading-screen";const s=document.createElement("div");s.className="dynamsoft-mrz-loading";const o=document.createElement("div");o.className="dynamsoft-mrz-loading-content";const r=`\n \n \n \n `;if(o.innerHTML=r,t){const e=document.createElement("div");e.className="dynamsoft-mrz-loading-message",e.textContent=t,o.appendChild(e)}return s.appendChild(o),a.appendChild(s),e.appendChild(a),{element:a,updateMessage:e=>{let n=s.querySelector(".dynamsoft-mrz-loading-message");null!==e?n?n.textContent=e:(n=document.createElement("div"),n.className="dynamsoft-mrz-loading-message",n.textContent=e,o.appendChild(n)):null==n||n.remove()},hide:()=>{a&&a.parentNode&&(a.classList.add("fade-out"),setTimeout((()=>{var e;null===(e=a.parentNode)||void 0===e||e.removeChild(a)}),200))}}}const b='\n .dynamsoft-mrz-loading-screen {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: #323234;\n z-index: 998;\n opacity: 1;\n transition: opacity 0.2s ease-out;\n }\n\n .dynamsoft-mrz-loading-screen.fade-out {\n opacity: 0;\n }\n\n .dynamsoft-mrz-loading {\n position: absolute;\n left: 50%;\n top: 50%;\n color: white;\n z-index: 999;\n transform: translate(-50%, -50%);\n }\n\n .dynamsoft-mrz-loading-content {\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 16px;\n }\n\n .dynamsoft-mrz-loading svg {\n animation: spin 1s linear infinite;\n }\n\n .dynamsoft-mrz-loading-message {\n color: white;\n font-family: "Verdana";\n font-size: 14px;\n text-align: center;\n max-width: 200px;\n line-height: 1.4;\n opacity: 0.9;\n }\n\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n';var Z;e.EnumMRZData=void 0,(Z=e.EnumMRZData||(e.EnumMRZData={})).InvalidFields="invalidFields",Z.DocumentType="documentType",Z.DocumentNumber="documentNumber",Z.MRZText="mrzText",Z.FirstName="firstName",Z.LastName="lastName",Z.Age="age",Z.Sex="sex",Z.IssuingState="issuingState",Z.IssuingStateRaw="issuingStateRaw",Z.Nationality="nationality",Z.NationalityRaw="nationalityRaw",Z.DateOfBirth="dateOfBirth",Z.DateOfExpiry="dateOfExpiry";const x={[e.EnumMRZData.InvalidFields]:"Invalid Fields",[e.EnumMRZData.DocumentType]:"Document Type",[e.EnumMRZData.DocumentNumber]:"Document Number",[e.EnumMRZData.MRZText]:"MRZ Text",[e.EnumMRZData.FirstName]:"Given Name(s)",[e.EnumMRZData.LastName]:"Surname",[e.EnumMRZData.Age]:"Age",[e.EnumMRZData.Sex]:"Sex",[e.EnumMRZData.IssuingState]:"Issuing State",[e.EnumMRZData.IssuingStateRaw]:"Issuing State (Raw Value)",[e.EnumMRZData.Nationality]:"Nationality",[e.EnumMRZData.NationalityRaw]:"Nationality State (Raw Value)",[e.EnumMRZData.DateOfBirth]:"Date Of Birth (YYYY-MM-DD)",[e.EnumMRZData.DateOfExpiry]:"Date Of Expiry (YYYY-MM-DD)"};function z(e,n,t,i=!1){const a=parseInt(e,10);let s;if(i)s=a>=60?1900+a:2e3+a;else{s=a>(new Date).getFullYear()%100?1900+a:2e3+a}return{year:s,month:parseInt(n,10),day:parseInt(t,10)}}function V(e){const n=e=>{var n;return 1===(null===(n=`${e}`)||void 0===n?void 0:n.length)?`0${e}`:e};return`${null==e?void 0:e.year}-${n(null==e?void 0:e.month)}${(null==e?void 0:e.day)&&`-${n(null==e?void 0:e.day)}`}`}function I(e){return"D<<"===e?"D":e}function L(n,t){const i=[],a=e=>t.getFieldValidationStatus(e)===s.EnumValidationStatus.VS_FAILED,o=t.codeType,r=function(n){switch(n){case"MRTD_TD1_ID":return e.EnumMRZDocumentType.TD1;case"MRTD_TD2_ID":case"MRTD_TD2_VISA":case"MRTD_TD2_FRENCH_ID":return e.EnumMRZDocumentType.TD2;case"MRTD_TD3_PASSPORT":case"MRTD_TD3_VISA":return e.EnumMRZDocumentType.Passport;default:throw new Error(`Unknown document type: ${n}`)}}(o),l=function(e){switch(e){case"MRTD_TD1_ID":return"ID (TD1)";case"MRTD_TD2_ID":return"ID (TD2)";case"MRTD_TD2_VISA":return"ID (VISA)";case"MRTD_TD2_FRENCH_ID":return"French ID (TD2)";case"MRTD_TD3_PASSPORT":return"Passport (TD3)";case"MRTD_TD3_VISA":return"Visa (TD3)";default:throw new Error(`Unknown document type: ${e}`)}}(o),c=r===e.EnumMRZDocumentType.Passport&&"MRTD_TD3_PASSPORT"===o?"passportNumber":"documentNumber",d=z(t.getFieldValue("birthYear"),t.getFieldValue("birthMonth"),t.getFieldValue("birthDay")),u=z(t.getFieldValue("expiryYear"),t.getFieldValue("expiryMonth"),t.getFieldValue("expiryDay"),!0);["birthYear","birthMonth","birthDay"].forEach((n=>{a(n)&&i.push(e.EnumMRZData.DateOfBirth)})),["expiryYear","expiryMonth","expiryDay"].forEach((n=>{a(n)&&i.push(e.EnumMRZData.DateOfExpiry)}));const m={[e.EnumMRZData.LastName]:t.getFieldValue("primaryIdentifier"),[e.EnumMRZData.FirstName]:t.getFieldValue("secondaryIdentifier"),[e.EnumMRZData.Nationality]:t.getFieldValue("nationality"),[e.EnumMRZData.NationalityRaw]:I(t.getFieldRawValue("nationality")),[e.EnumMRZData.DocumentNumber]:t.getFieldValue(c)||t.getFieldValue("longDocumentNumber"),[e.EnumMRZData.IssuingState]:t.getFieldValue("issuingState"),[e.EnumMRZData.IssuingStateRaw]:I(t.getFieldRawValue("issuingState")),[e.EnumMRZData.Sex]:S(t.getFieldValue("sex"))};Object.keys(m).forEach((n=>{let t=!1;switch(n){case e.EnumMRZData.FirstName:t=a("secondaryIdentifier");break;case e.EnumMRZData.LastName:t=a("primaryIdentifier");break;case e.EnumMRZData.DocumentNumber:t=a(c)||a("longDocumentNumber");break;default:t=a(n)}t&&i.push(n)}));const h=function(e){const n=new Date,t=n.getMonth()+1>e.month||n.getMonth()+1===e.month&&n.getDate()>=e.day;return n.getFullYear()-e.year-(t?0:1)}(d);h<1&&i.push(e.EnumMRZData.Age);return{[e.EnumMRZData.InvalidFields]:i,[e.EnumMRZData.FirstName]:m[e.EnumMRZData.FirstName],[e.EnumMRZData.LastName]:m[e.EnumMRZData.LastName],[e.EnumMRZData.Age]:h,[e.EnumMRZData.DateOfBirth]:d,[e.EnumMRZData.Sex]:m[e.EnumMRZData.Sex],[e.EnumMRZData.Nationality]:m[e.EnumMRZData.Nationality],[e.EnumMRZData.NationalityRaw]:m[e.EnumMRZData.NationalityRaw],[e.EnumMRZData.DocumentNumber]:m[e.EnumMRZData.DocumentNumber],[e.EnumMRZData.DateOfExpiry]:u,[e.EnumMRZData.IssuingState]:m[e.EnumMRZData.IssuingState],[e.EnumMRZData.IssuingStateRaw]:m[e.EnumMRZData.IssuingStateRaw],[e.EnumMRZData.DocumentType]:S(l),[e.EnumMRZData.MRZText]:n}}const N={[e.EnumMRZDocumentType.TD1]:{width:85.6,height:53.98},[e.EnumMRZDocumentType.TD2]:{width:105,height:74},[e.EnumMRZDocumentType.Passport]:{width:125,height:88}};class _{showScannerLoadingOverlay(e){const n=v(this.config.container);this.loadingScreen=T(n,{message:e}),n.style.display="block",n.style.position="relative"}hideScannerLoadingOverlay(e=!1){this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,e&&(v(this.config.container).style.display="none"))}constructor(n,t){this.resources=n,this.config=t,this.isSoundFeedbackOn=!1,this.scanModeManager={[e.EnumMRZDocumentType.Passport]:!0,[e.EnumMRZDocumentType.TD1]:!0,[e.EnumMRZDocumentType.TD2]:!0},this.currentScanMode=e.EnumMRZScanMode.All,this.resizeTimer=null,this.capturedResultItems=[],this.originalImageData=null,this.initialized=!1,this.initializedDCE=!1,this.DCE_ELEMENTS={selectCameraBtn:null,uploadImageBtn:null,soundFeedbackBtn:null,closeScannerBtn:null,scanModeSelectContainer:null,passportModeOption:null,td1ModeOption:null,td2ModeOption:null,toast:null},this.loadingScreen=null,this.handleResize=()=>{this.toggleScanGuide(!1),this.resizeTimer&&window.clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout((()=>{this.toggleScanGuide(!0)}),500)}}async initialize(){if(!this.initialized){this.initializeScanModeManager(),this.currentScanMode=this.getScanMode(),M("dynamsoft-mrz-loading-screen-style",b);try{const{cameraView:e,cameraEnhancer:t,cvRouter:a}=this.resources;if(e.setScanRegionMaskStyle({strokeStyle:"transparent",fillStyle:"transparent",lineWidth:0}),e.setVideoFit("cover"),a.setInput(t),await a.initSettings(this.config.templateFilePath),!0===this.config.enableMultiFrameCrossFilter){const e=new r.MultiFrameResultCrossFilter;e.enableResultCrossVerification(n.EnumCapturedResultItemType.CRIT_TEXT_LINE,!0),e.enableResultDeduplication(n.EnumCapturedResultItemType.CRIT_TEXT_LINE,!0),await a.addResultFilter(e)}const s=new i.CapturedResultReceiver;s.onCapturedResultReceived=e=>this.handleMRZResult(e),await a.addResultReceiver(s),this.toggleSoundFeedback(!1),!1===this.config.showScanGuide&&this.toggleScanGuide(!1),this.initialized=!0}catch(n){let t=(null==n?void 0:n.message)||n;console.error(t),alert(t),this.closeCamera();const i={status:{code:e.EnumResultStatus.RS_FAILED,message:"Dynamsoft MRZ Scanner initialize error"}};this.currentScanResolver(i)}}}initializeElements(){var e;const n=v(this.config.container),t=n.children[n.children.length-1];if(!(null==t?void 0:t.shadowRoot))throw new Error("Shadow root not found");if(this.DCE_ELEMENTS={selectCameraBtn:t.shadowRoot.querySelector(".dce-mn-select-camera-icon"),uploadImageBtn:t.shadowRoot.querySelector(".dce-mn-upload-image-icon"),soundFeedbackBtn:t.shadowRoot.querySelector(".dce-mn-sound-feedback"),closeScannerBtn:t.shadowRoot.querySelector(".dce-mn-close"),scanModeSelectContainer:t.shadowRoot.querySelector(".dce-mn-scan-mode-select"),passportModeOption:t.shadowRoot.querySelector(".scan-mode-option-passport"),td1ModeOption:t.shadowRoot.querySelector(".scan-mode-option-td1"),td2ModeOption:t.shadowRoot.querySelector(".scan-mode-option-td2"),toast:t.shadowRoot.querySelector(".dce-mn-toast")},this.setupScanModeSelector(),this.assignDCEClickEvents(),this.DCE_ELEMENTS.toast.style.display="none",!1===this.config.showUploadImage&&(this.DCE_ELEMENTS.uploadImageBtn.style.visibility="hidden"),!1===this.config.showSoundToggle&&(this.DCE_ELEMENTS.soundFeedbackBtn.style.visibility="hidden"),!1===(null===(e=this.config)||void 0===e?void 0:e.showPoweredByDynamsoft)){t.shadowRoot.querySelector(".dce-mn-msg-poweredby").style.display="none"}this.initializedDCE=!0}setupScanModeSelector(){if(!1!==this.config.showFormatSelector)switch(this.currentScanMode){case e.EnumMRZScanMode.PassportAndTD1:this.DCE_ELEMENTS.td2ModeOption.style.display="none";break;case e.EnumMRZScanMode.PassportAndTD2:this.DCE_ELEMENTS.td1ModeOption.style.display="none";break;case e.EnumMRZScanMode.TD1AndTD2:this.DCE_ELEMENTS.passportModeOption.style.display="none";break;case e.EnumMRZScanMode.All:break;default:this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}else this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}assignDCEClickEvents(){if(!Object.values(this.DCE_ELEMENTS).every(Boolean))throw new Error("Camera control elements not found");this.closeCamera=this.closeCamera.bind(this),this.DCE_ELEMENTS.uploadImageBtn.onclick=()=>this.uploadFile(),this.DCE_ELEMENTS.soundFeedbackBtn.onclick=()=>this.toggleSoundFeedback(),this.DCE_ELEMENTS.closeScannerBtn.onclick=()=>this.handleCloseBtn(),this.DCE_ELEMENTS.selectCameraBtn.onclick=e=>{e.stopPropagation(),this.toggleSelectCameraBox()},this.DCE_ELEMENTS.passportModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.passportModeOption.style.display&&await this.toggleScanDocType(e.EnumMRZDocumentType.Passport)},this.DCE_ELEMENTS.td1ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td1ModeOption.style.display&&await this.toggleScanDocType(e.EnumMRZDocumentType.TD1)},this.DCE_ELEMENTS.td2ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td2ModeOption.style.display&&await this.toggleScanDocType(e.EnumMRZDocumentType.TD2)}}handleCloseBtn(){this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:e.EnumResultStatus.RS_CANCELLED,message:"Cancelled"}})}attachOptionClickListeners(){const e=v(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const t=n.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings");[...n.shadowRoot.querySelectorAll(".dce-mn-camera-option"),...n.shadowRoot.querySelectorAll(".dce-mn-resolution-option")].forEach((e=>{e.addEventListener("click",(async n=>{const i=e.getAttribute("data-davice-id"),a=e.getAttribute("data-height"),s=e.getAttribute("data-width");i?this.resources.cameraEnhancer.selectCamera(i).then((()=>{this.toggleScanGuide()})):a&&s&&this.resources.cameraEnhancer.setResolution({width:parseInt(s),height:parseInt(a)}).then((()=>{this.toggleScanGuide()})),"none"!==t.style.display&&this.toggleSelectCameraBox()}))}))}highlightCameraAndResolutionOption(){const e=v(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const t=n.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings"),i=t.querySelectorAll(".dce-mn-camera-option"),a=t.querySelectorAll(".dce-mn-resolution-option"),s=this.resources.cameraEnhancer.getSelectedCamera(),o=this.resources.cameraEnhancer.getResolution();i.forEach((e=>{const n=e;n.getAttribute("data-davice-id")===(null==s?void 0:s.deviceId)?n.style.border="2px solid #fe814a":n.style.border="none"}));const r={"480p":"480","720p":"720","1080p":"1080","2k":"1440","4k":"2160"},l=function(e){const n=e.width*e.height,t=e.width/e.height;let i="480p",a=Number.MAX_VALUE;for(const[e,s]of Object.entries(C)){const o=s.width*s.height,r=s.width/s.height,l=.7*Math.abs(o-n)+Math.abs(r-t)*o*.3;l{const n=e,t=n.getAttribute("data-height");n.style.border=t===r[l]?"2px solid #fe814a":"none"}))}toggleSelectCameraBox(){const e=v(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const t=n.shadowRoot.querySelector(".dce-mn-resolution-box");this.highlightCameraAndResolutionOption(),this.attachOptionClickListeners(),t.click()}async relaunch(){}async uploadFile(){var t,i,a,s;const{cvRouter:o}=this.resources,r=document.createElement("input");r.type="file",r.accept=null!==(t=this.config.uploadAcceptedTypes)&&void 0!==t?t:"image/*",r.style.display="none",document.body.appendChild(r);try{this.showScannerLoadingOverlay("Processing file..."),await this.closeCamera(!1);const t=await new Promise(((e,n)=>{r.onchange=t=>{var i;const a=null===(i=t.target.files)||void 0===i?void 0:i[0];a?e(a):n(new Error("No file selected"))},r.addEventListener("cancel",(async()=>{this.hideScannerLoadingOverlay(!1),await this.openCamera(),await this.startCapturing(),this.toggleScanGuide()})),r.click()}));if(!t)return;let l;if(this.config.uploadFileConverter&&!t.type.startsWith("image/"))try{l=await this.config.uploadFileConverter(t)}catch(e){throw new Error(`Error converting file: ${e.message}`)}else{if(!t.type.startsWith("image/"))throw new Error("Unsupported file type. Please provide a converter function for this file type.");l=t}const c=this.config.utilizedTemplateNames[this.currentScanMode];if(!1!==this.config.showScanGuide){const e=await o.getSimplifiedSettings(c);e.roiMeasuredInPercentage=!0,e.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await o.updateSettings(c,e)}const d=await o.capture(l,c);this.capturedResultItems=d.items;const u=this.capturedResultItems.filter((e=>e.type===n.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE));if(0===u.length)throw new Error("No image data found in the captured result");const m=u[0].imageData;m.toCanvas=()=>n._toCanvas(m),m.toBlob=async()=>await n._toBlob("image/png",m),this.originalImageData=m;const h=null==d?void 0:d.textLineResultItems,g=null==d?void 0:d.parsedResultItems;let p={};if(null==h?void 0:h.length){const e=(null===(i=h[0])||void 0===i?void 0:i.text)||"";p=L(e,g[0])}const f={status:{code:e.EnumResultStatus.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,data:p,imageData:!0,_imageData:this.originalImageData};null===(s=(a=this.resources).onResultUpdated)||void 0===s||s.call(a,f),this.currentScanResolver(f)}catch(n){let t=(null==n?void 0:n.message)||n;console.error(t),alert(t),this.closeCamera();const i={status:{code:e.EnumResultStatus.RS_FAILED,message:`Error processing file: ${t}`}};this.currentScanResolver(i)}finally{this.hideScannerLoadingOverlay(!0),document.body.removeChild(r)}}toggleSoundFeedback(e){this.isSoundFeedbackOn=void 0!==e?e:!this.isSoundFeedbackOn;const n=v(this.config.container),t=n.children[n.children.length-1];if(!(null==t?void 0:t.shadowRoot))return;const i=t.shadowRoot.querySelector(".dce-mn-sound-feedback"),a=i.querySelector(".dce-mn-sound-feedback-on");i.querySelector(".dce-mn-sound-feedback-off").style.display=this.isSoundFeedbackOn?"none":"block",a.style.display=this.isSoundFeedbackOn?"block":"none"}calculateScanRegion(e){const{cameraEnhancer:n,cameraView:t}=this.resources;if(!n||!n.isOpen())return;const i=t.getVisibleRegionOfVideo({inPixels:!0});if(!i)return;const a=t.getVideoElement(),s=a.videoWidth,o=a.videoHeight,r=N[e];let l;const c=i.height-80;if(i.width>i.height){l=.75*c/r.height;l*r.width>.9*i.width&&(l=.9*i.width/r.width)}else{l=.9*i.width/r.width;l*r.height>.75*c&&(l=.75*c/r.height)}const d=l*r.width,u=l*r.height,m=(i.width-d)/2,h=(c-u)/2,g=m,p=m+d,f=h,y=h+u,R=(i.x+g)/s*100,E=(i.x+p)/s*100,w=(i.y+f)/o*100,v=(i.y+y)/o*100,M={left:Math.round(R),right:Math.round(E),top:Math.round(w),bottom:Math.round(v),isMeasuredInPercentage:!0};null==t||t.setScanRegionMaskVisible(!0),n.setScanRegion(M)}toggleScanGuide(n){const t=v(this.config.container),i=t.children[t.children.length-1];if(!(null==i?void 0:i.shadowRoot))return;const a=i.shadowRoot.querySelector(".dce-scanguide-passport"),s=i.shadowRoot.querySelector(".dce-scanguide-td1"),o=i.shadowRoot.querySelector(".dce-scanguide-td2");if(!1===n||!1===this.config.showScanGuide)return a.style.display="none",s.style.display="none",void(o.style.display="none");switch(this.currentScanMode){case e.EnumMRZScanMode.All:case e.EnumMRZScanMode.Passport:case e.EnumMRZScanMode.PassportAndTD1:case e.EnumMRZScanMode.PassportAndTD2:a.style.display="block",s.style.display="none",o.style.display="none",this.calculateScanRegion(e.EnumMRZDocumentType.Passport);break;case e.EnumMRZScanMode.TD1:case e.EnumMRZScanMode.TD1AndTD2:a.style.display="none",s.style.display="block",o.style.display="none",this.calculateScanRegion(e.EnumMRZDocumentType.TD1);break;case e.EnumMRZScanMode.TD2:a.style.display="none",s.style.display="none",o.style.display="block",this.calculateScanRegion(e.EnumMRZDocumentType.TD2)}}async openCamera(){try{this.showScannerLoadingOverlay("Initializing camera...");const{cameraEnhancer:e,cameraView:n}=this.resources,t=v(this.config.container);if(t.style.display="block",e.isOpen())e.isPaused()&&await e.resume();else{const i=n.getUIElement();i.parentElement||t.append(i),await e.open()}await e.setResolution({width:2560,height:1440}),!this.initializedDCE&&e.isOpen()&&await this.initializeElements(),window.addEventListener("resize",this.handleResize);const i=t.children[t.children.length-1];if(!(null==i?void 0:i.shadowRoot))throw new Error("Shadow root not found");i.shadowRoot.querySelector(".dce-mn-torch-off").style.display="none",i.shadowRoot.querySelector(".dce-mn-torch-on").style.display="none"}catch(n){let t=(null==n?void 0:n.message)||n;console.error(t),alert(t),this.closeCamera();const i={status:{code:e.EnumResultStatus.RS_FAILED,message:"MRZ Scanner Open Camera Error"}};this.currentScanResolver(i)}finally{this.hideScannerLoadingOverlay()}}async closeCamera(e=!0){try{window.removeEventListener("resize",this.handleResize),this.resizeTimer&&(window.clearTimeout(this.resizeTimer),this.resizeTimer=null);const{cameraEnhancer:n,cameraView:t}=this.resources,i=v(this.config.container);i.style.display=e?"none":"block",(null==t?void 0:t.getUIElement().parentElement)&&i.removeChild(t.getUIElement()),n.close(),this.stopCapturing()}catch(e){let n=(null==e?void 0:e.message)||e;console.error(`Close Camera error: ${n}`)}}pauseCamera(){const{cameraEnhancer:e}=this.resources;e.pause()}stopCapturing(){const{cameraView:e,cvRouter:n}=this.resources;n.stopCapturing(),e.clearAllInnerDrawingItems()}async handleMRZResult(t){var i;if(this.capturedResultItems=t.items,!(t.items.length<=1))try{const{onResultUpdated:s}=this.resources,o=t.items.filter((e=>e.type===n.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE))[0].imageData;o.toCanvas=()=>n._toCanvas(o),o.toBlob=async()=>await n._toBlob("image/png",o),this.originalImageData=o;const r=null==t?void 0:t.textLineResultItems,l=null==t?void 0:t.parsedResultItems;if(r){this.isSoundFeedbackOn&&a.Feedback.beep();const n=(null===(i=null==r?void 0:r[0])||void 0===i?void 0:i.text)||"",t=L(n,l[0]);this.closeCamera();const o={status:{code:e.EnumResultStatus.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,data:t,imageData:!0,_imageData:this.originalImageData};null==s||s(o),this.currentScanResolver(o)}}catch(n){let t=(null==n?void 0:n.message)||n;console.error(t),alert(t),this.closeCamera();const i={status:{code:e.EnumResultStatus.RS_FAILED,message:"Error capturing image"}};this.currentScanResolver(i)}}initializeScanModeManager(){const{mrzFormatType:n}=this.config;if(this.scanModeManager={[e.EnumMRZDocumentType.Passport]:!0,[e.EnumMRZDocumentType.TD1]:!0,[e.EnumMRZDocumentType.TD2]:!0},!n||Array.isArray(n)&&0===n.length)return;Object.keys(this.scanModeManager).forEach((e=>{this.scanModeManager[e]=!1}));(Array.isArray(n)?n:[n]).forEach((e=>{this.scanModeManager[e]=!0}))}getScanMode(){const n=Object.entries(this.scanModeManager).filter((([e,n])=>n)).map((([e])=>e)).sort().join(",");return{[e.EnumMRZDocumentType.Passport]:e.EnumMRZScanMode.Passport,[e.EnumMRZDocumentType.TD1]:e.EnumMRZScanMode.TD1,[e.EnumMRZDocumentType.TD2]:e.EnumMRZScanMode.TD2,[`${e.EnumMRZDocumentType.Passport},${e.EnumMRZDocumentType.TD1}`]:e.EnumMRZScanMode.PassportAndTD1,[`${e.EnumMRZDocumentType.Passport},${e.EnumMRZDocumentType.TD2}`]:e.EnumMRZScanMode.PassportAndTD2,[`${e.EnumMRZDocumentType.TD1},${e.EnumMRZDocumentType.TD2}`]:e.EnumMRZScanMode.TD1AndTD2,[`${e.EnumMRZDocumentType.Passport},${e.EnumMRZDocumentType.TD1},${e.EnumMRZDocumentType.TD2}`]:e.EnumMRZScanMode.All,"":e.EnumMRZScanMode.All}[n]}DCEShowToast(e,n=3e3){this.DCE_ELEMENTS.toast&&(this.DCE_ELEMENTS.toast.textContent=e,this.DCE_ELEMENTS.toast.style.display="",setTimeout((()=>{this.DCE_ELEMENTS.toast.style.display="none"}),n))}async startCapturing(){const{cvRouter:t,cameraEnhancer:i}=this.resources,a=this.config.utilizedTemplateNames[this.currentScanMode];try{if(!1!==this.config.showScanGuide){const e=await t.getSimplifiedSettings(a);e.roiMeasuredInPercentage=!0,e.roi.points=[{x:0,y:50},{x:100,y:50},{x:100,y:100},{x:0,y:100}],await t.updateSettings(a,e)}await t.startCapturing(a),i.setPixelFormat(n.EnumImagePixelFormat.IPF_ABGR_8888)}catch(n){let t=(null==n?void 0:n.message)||n;console.error("Failed to start capturing:",t),this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:e.EnumResultStatus.RS_FAILED,message:"Failed to start capturing"}})}}async toggleScanDocType(n){try{if(this.scanModeManager[n]&&0===Object.entries(this.scanModeManager).filter((([e,t])=>t&&e!==n)).length)return console.warn("MRZ Scanner - At least one mode must be enabled"),void this.DCEShowToast("At least one mode must be enabled");this.scanModeManager[n]=!this.scanModeManager[n],this.currentScanMode=this.getScanMode(),this.stopCapturing(),await this.startCapturing(),this.toggleScanGuide(),this.DCE_ELEMENTS.td1ModeOption.classList.toggle("selected",this.scanModeManager[e.EnumMRZDocumentType.TD1]),this.DCE_ELEMENTS.td2ModeOption.classList.toggle("selected",this.scanModeManager[e.EnumMRZDocumentType.TD2]),this.DCE_ELEMENTS.passportModeOption.classList.toggle("selected",this.scanModeManager[e.EnumMRZDocumentType.Passport])}catch(n){let t=(null==n?void 0:n.message)||n;console.error("MRZ Scanner switch scan mode error: ",t),this.closeCamera();const i={status:{code:e.EnumResultStatus.RS_FAILED,message:"MRZ Scanner switch scan mode error"}};this.currentScanResolver(i)}}async launch(){try{await this.initialize();const{cvRouter:e,cameraEnhancer:n}=this.resources;return new Promise((async e=>{this.currentScanResolver=e,await this.openCamera(),!this.initializedDCE&&n.isOpen()&&await this.initializeElements(),await this.startCapturing(),this.toggleScanGuide()}))}catch(n){let t=(null==n?void 0:n.message)||n;console.error("MRZ Scanner launch error: ",t),this.closeCamera();const i={status:{code:e.EnumResultStatus.RS_FAILED,message:"MRZ Scanner launch error"}};this.currentScanResolver(i)}}}const F={rescan:'\n\n\n \n\n\n\n\n\n\n\n',complete:'\n\n\n\n \n\n\n\n\n\n\n\n',failed:'\n \n \n \n\n',info:'\n\n \n \n \n\n'};class k{constructor(e,n,t){this.resources=e,this.config=n,this.scannerView=t,this.editedFields={}}async launch(){try{return v(this.config.container).textContent="",await this.initialize(),v(this.config.container).style.display="flex",new Promise((e=>{this.currentScanResultViewResolver=e}))}catch(e){let n=(null==e?void 0:e.message)||e;throw console.error(n),n}}async handleRescan(){var n;try{if(!this.scannerView)return void console.error("Scanner View not initialized");this.hideView();const t=await this.scannerView.launch();if((null===(n=null==t?void 0:t.status)||void 0===n?void 0:n.code)===e.EnumResultStatus.RS_FAILED)return void(this.currentScanResultViewResolver&&this.currentScanResultViewResolver(t));this.resources.onResultUpdated&&((null==t?void 0:t.status.code)===e.EnumResultStatus.RS_CANCELLED?this.resources.onResultUpdated(this.resources.result):(null==t?void 0:t.status.code)===e.EnumResultStatus.RS_SUCCESS&&this.resources.onResultUpdated(t)),this.dispose(!0),await this.initialize(),v(this.config.container).style.display="flex"}catch(n){throw console.error("Error in rescan handler:",n),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:e.EnumResultStatus.RS_FAILED,message:(null==n?void 0:n.message)||n}}),n}}async handleDone(){var n,t;try{(null===(n=this.resources.result)||void 0===n?void 0:n.data)&&!D(this.editedFields)&&(this.resources.result.data=Object.assign(Object.assign({},this.resources.result.data),this.editedFields),this.resources.onResultUpdated&&this.resources.onResultUpdated(this.resources.result)),(null===(t=this.config)||void 0===t?void 0:t.onDone)&&await this.config.onDone(this.resources.result),this.currentScanResultViewResolver&&this.resources.result&&this.currentScanResultViewResolver(this.resources.result),this.hideView(),this.dispose()}catch(n){throw console.error("Error in done handler:",n),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:e.EnumResultStatus.RS_FAILED,message:(null==n?void 0:n.message)||n}}),n}}createControls(){var e,n,t,i,a,s,o,r;const{toolbarButtonsConfig:l}=this.config;return function(e){M("dynamsoft-mrz-controls-style","\n .dynamsoft-mrz-controls {\n display: flex;\n height: 6rem;\n background-color: #323234;\n align-items: center;\n font-size: 12px;\n font-family: Verdana;\n color: white;\n width: 100%;\n }\n\n .dynamsoft-mrz-control-btn {\n background-color: #323234;\n color: white;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n height: 100%;\n width: 100%;\n gap: 0.5rem;\n text-align: center;\n user-select: none;\n }\n\n .dynamsoft-mrz-control-btn.hide {\n display: none;\n }\n\n .dynamsoft-mrz-control-btn.disabled {\n opacity: 0.4;\n pointer-events: none;\n cursor: default;\n }\n\n .dynamsoft-mrz-control-icon-wrapper {\n flex: 0.75;\n display: flex;\n align-items: flex-end;\n justify-content: center;\n min-height: 40px;\n }\n\n .dynamsoft-mrz-control-icon img,\n .dynamsoft-mrz-control-icon svg {\n width: 32px;\n height: 32px;\n fill: #fe8e14;\n }\n\n .dynamsoft-mrz-control-text {\n flex: 0.5;\n display: flex;\n align-items: flex-start;\n justify-content: center;\n padding-bottom: 0.5rem;\n }\n\n \n @media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-controls {\n flex-direction: column;\n height: 100%;\n width: 5rem;\n }\n\n .dynamsoft-mrz-control-text {\n padding: 0 0.5rem 0.5rem;\n }\n }\n");const n=document.createElement("div");return n.className="dynamsoft-mrz-controls",e.forEach((e=>{const t=document.createElement("div");t.className=`dynamsoft-mrz-control-btn ${null==e?void 0:e.className}`;const i=document.createElement("div");if(i.className="dynamsoft-mrz-control-icon-wrapper",(a=e.icon).trim().startsWith(""))i.innerHTML=e.icon;else{const n=document.createElement("img");n.src=e.icon,n.alt=e.label,n.width=24,n.height=24,i.appendChild(n)}var a;const s=document.createElement("div");s.className="dynamsoft-mrz-control-text",s.textContent=e.label,e.isDisabled&&t.classList.add("disabled"),e.isHidden&&t.classList.add("hide"),t.appendChild(i),t.appendChild(s),e.onClick&&!e.isDisabled&&t.addEventListener("click",e.onClick),n.appendChild(t)})),n}([{id:"dynamsoft-mrz-scanResult-rescan",icon:(null===(e=null==l?void 0:l.rescan)||void 0===e?void 0:e.icon)||F.rescan,label:(null===(n=null==l?void 0:l.rescan)||void 0===n?void 0:n.label)||"Re-scan",onClick:()=>this.handleRescan(),className:`${(null===(t=null==l?void 0:l.rescan)||void 0===t?void 0:t.className)||""}`,isHidden:(null===(i=null==l?void 0:l.rescan)||void 0===i?void 0:i.isHidden)||!1,isDisabled:!this.scannerView},{id:"dynamsoft-mrz-scanResult-done",icon:(null===(a=null==l?void 0:l.done)||void 0===a?void 0:a.icon)||F.complete,label:(null===(s=null==l?void 0:l.done)||void 0===s?void 0:s.label)||"Done",className:`${(null===(o=null==l?void 0:l.done)||void 0===o?void 0:o.className)||""}`,isHidden:(null===(r=null==l?void 0:l.done)||void 0===r?void 0:r.isHidden)||!1,onClick:()=>this.handleDone()}])}handleFieldEdit(n,t){if(n===e.EnumMRZData.DateOfBirth||n===e.EnumMRZData.DateOfExpiry)try{const[e,i,a]=t.split(/[\/\-\.]/);a&&i&&e&&(this.editedFields[n]={day:parseInt(a,10),month:parseInt(i,10),year:parseInt(e,10)})}catch(e){console.error("Error parsing date",e)}else this.editedFields[n]=t}createMRZDataDisplay(){var n;const t=(null===(n=this.resources.result)||void 0===n?void 0:n.data)||{},i=!!this.config.allowResultEditing,a=t.invalidFields||[],s=document.createElement("div");if(s.className="dynamsoft-mrz-data-container",D(t)){const e=document.createElement("div");return e.className="dynamsoft-mrz-data-row empty",e.innerText="No MRZ detected. Please try again.",s.appendChild(e),s}if(a.length>0){const e=document.createElement("div");e.className="dynamsoft-mrz-error-notification",e.innerHTML=`\n
${F.failed}
\n
\n ${i?"Some fields require correction. Please review highlighted fields.":"Some fields contain invalid information. Please rescan the document."}\n
\n `,s.appendChild(e)}else if(0===a.length&&i){const e=document.createElement("div");e.className="dynamsoft-mrz-info-notification",e.innerHTML=`\n
${F.info}
\n
\n Please review all fields to ensure the information is correct.\n
\n `,s.appendChild(e)}return Object.entries(t).forEach((([n,t])=>{var o;if(n===e.EnumMRZData.InvalidFields||!t)return;if(n===e.EnumMRZData.MRZText&&!1===(null===(o=this.config)||void 0===o?void 0:o.showMRZText))return;const r=document.createElement("div");r.className="dynamsoft-mrz-data-row";const l=a.includes(n);l&&r.classList.add("invalid-field");const c=[e.EnumMRZData.MRZText,e.EnumMRZData.DocumentType,e.EnumMRZData.IssuingStateRaw,e.EnumMRZData.NationalityRaw],d=document.createElement("span");if(d.className="dynamsoft-mrz-data-label",d.innerText=x[n]||n,l){const e=document.createElement("span");if(e.className="dynamsoft-mrz-error-icon",e.innerHTML=F.failed,d.appendChild(e),i){const e=document.createElement("span");e.className="dynamsoft-mrz-error-hint",e.textContent="Please correct this field",d.appendChild(e)}}const u=document.createElement("div");if(u.className="dynamsoft-mrz-data-value",i&&!c.includes(n)){const i=document.createElement("input");i.className="dynamsoft-mrz-data-input",l&&i.classList.add("invalid"),n===e.EnumMRZData.DateOfBirth||n===e.EnumMRZData.DateOfExpiry?(i.value=V(t),i.setAttribute("placeholder","YYYY-MM-DD")):i.value=t,i.addEventListener("input",(e=>{if(this.handleFieldEdit(n,e.target.value),l){i.classList.remove("invalid"),r.classList.remove("invalid-field"),this.editedFields.invalidFields||(this.editedFields.invalidFields=[...a]);const e=this.editedFields.invalidFields.indexOf(n);e>-1&&this.editedFields.invalidFields.splice(e,1)}})),u.appendChild(i)}else n===e.EnumMRZData.MRZText?(u.classList.add("code"),u.innerText=t):n===e.EnumMRZData.DateOfBirth||n===e.EnumMRZData.DateOfExpiry?u.innerText=V(t):u.innerText=t,l&&u.classList.add("invalid-value");r.appendChild(d),r.appendChild(u),s.appendChild(r)})),s}async initialize(){try{if(!this.resources.result)throw Error("Captured image is missing. Please capture an image first!");if(!this.config.container)throw new Error("Please create a Scan Result View Container element");M("dynamsoft-mrz-result-view-style",O);const e=document.createElement("div");if(e.className="dynamsoft-mrz-result-view-container",!1!==this.config.showOriginalImage){const n=this.resources.result.originalImageResult,t=document.createElement("div");let i;t.className="dynamsoft-mrz-result-view-image-container",(null==n?void 0:n.toCanvas)&&(i=null==n?void 0:n.toCanvas()),Object.assign(i.style,{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}),t.appendChild(i),e.appendChild(t)}const n=this.createMRZDataDisplay();e.appendChild(n);const t=this.createControls();e.appendChild(t),v(this.config.container).appendChild(e)}catch(e){let n=(null==e?void 0:e.message)||e;console.error(n),alert(n)}}hideView(){v(this.config.container).style.display="none"}dispose(e=!1){v(this.config.container).textContent="",e||(this.currentScanResultViewResolver=void 0)}}const O="\n .dynamsoft-mrz-result-view-container {\n display: flex;\n width: 100%;\n height: 100%;\n background-color:#575757;\n font-size: 12px;\n flex-direction: column;\n align-items: center;\n }\n\n .dynamsoft-mrz-result-view-image-container {\n width: 100%;\n height: 200px;\n display: flex;\n justify-content: center;\n align-items: center;\n background-color: #323234;\n }\n\n \n.dynamsoft-mrz-data-container {\n font-size: 16px;\n font-family: Verdana;\n color: white;\n overflow: auto;\n width: 100%;\n height: 100%;\n min-height: 0;\n margin: 1rem 0;\n}\n\n.dynamsoft-mrz-data-row {\n padding: 0.5rem 2rem;\n display: flex;\n flex-direction: column;\n gap: 0.5rem;\n transition: background-color 0.3s ease;\n}\n\n.dynamsoft-mrz-data-row.invalid-field {\n background-color: rgba(231, 76, 60, 0.1);\n border-left: 3px solid #e74c3c;\n padding-left: calc(2rem - 3px);\n}\n\n.dynamsoft-mrz-data-label {\n color: #aaa;\n display: flex;\n gap: 0.5rem;\n align-items: end;\n flex-wrap: wrap;\n}\n\n.dynamsoft-mrz-error-notification,\n.dynamsoft-mrz-info-notification {\n color: white;\n padding: 1rem;\n margin: 0.5rem 2rem;\n border-radius: 4px;\n display: flex;\n align-items: center;\n gap: 1rem;\n text-align: start;\n}\n\n.dynamsoft-mrz-error-notification {\n background-color: rgba(231, 76, 60, 0.2);\n}\n\n.dynamsoft-mrz-info-notification {\n background-color: rgba(196, 231, 60, 0.2);\n}\n\n.dynamsoft-mrz-edit-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #aaa;\n}\n\n.dynamsoft-mrz-error-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-info-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: white;\n}\n\n.dynamsoft-mrz-info-message,\n.dynamsoft-mrz-error-message {\n flex: 1;\n}\n\n.dynamsoft-mrz-error-hint {\n font-size: 0.8rem;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-value {\n word-wrap: break-word;\n text-align: start;\n}\n\n.dynamsoft-mrz-data-value.code {\n font-family: monospace;\n}\n\n.dynamsoft-mrz-data-value.invalid-value {\n color: #e74c3c;\n text-decoration: wavy underline #e74c3c;\n text-decoration-skip-ink: none;\n}\n\n.dynamsoft-mrz-data-input {\n width: 100%;\n padding: 5px;\n background-color: rgba(255, 255, 255, 0.1);\n border: 1px solid rgba(255, 255, 255, 0.3);\n color: white;\n border-radius: 4px;\n font-size: 14px;\n transition: all 0.3s ease;\n}\n\n.dynamsoft-mrz-data-input.invalid {\n background-color: rgba(231, 76, 60, 0.1);\n border-color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-input:focus {\n background-color: rgba(255, 255, 255, 0.2);\n border-color: #fe8e14;\n outline: none;\n}\n\n@media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-result-view-container {\n flex-direction: row;\n }\n\n .dynamsoft-mrz-result-view-image-container{\n flex: 1;\n height: 100%;\n }\n\n .dynamsoft-mrz-data-container{\n flex: 1;\n }\n\n .dynamsoft-mrz-data-row:first-of-type {\n padding-top: 2rem;\n }\n\n .dynamsoft-mrz-data-row:last-of-type {\n padding-bottom: 2rem;\n }\n\n .dynamsoft-mrz-data-row.empty {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n padding-top: 0;\n padding-bottom: 0;\n }\n}\n",A={rootDirectory:"https://cdn.jsdelivr.net/npm/"};class P{showLoadingOverlay(e){var n,t;const i=v(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)||v(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container);this.loadingScreen=T(i,{message:e}),i.style.display="block",i.style.position="relative"}hideLoadingOverlay(e=!1){var n,t,i;const a=v(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)||v(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container);this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,a.style.display="none",e&&(null===(i=this.config)||void 0===i?void 0:i.container)&&(v(this.config.container).style.display="none"))}constructor(e){this.config=e,this.resources={},this.isInitialized=!1,this.isCapturing=!1,this.loadingScreen=null}async initialize(){if(this.isInitialized)return{resources:this.resources,components:{scannerView:this.scannerView,resultView:this.resultView}};try{if(!this.initializeMRZScannerConfig())return console.error("Failed to initialize mrz scanner config"),{resources:this.resources,components:{}};M("dynamsoft-mrz-loading-screen-style",b),this.showLoadingOverlay("Loading...");if(!await this.initializeDCVResources())return this.hideLoadingOverlay(!0),console.error("Failed to initialize DCV resources"),{resources:this.resources,components:{}};this.resources.onResultUpdated=e=>{this.resources.result=e};const e={};return this.config.scannerViewConfig&&(this.scannerView=new _(this.resources,this.config.scannerViewConfig),e.scannerView=this.scannerView,await this.scannerView.initialize()),this.config.resultViewConfig&&(this.resultView=new k(this.resources,this.config.resultViewConfig,this.scannerView),e.resultView=this.resultView),this.isInitialized=!0,{resources:this.resources,components:e}}catch(e){this.isInitialized=!1;const n=`Initialization Failed: ${(null==e?void 0:e.message)||e}`;return console.error(n),{resources:this.resources,components:{}}}finally{this.hideLoadingOverlay(!0)}}async initializeDCVResources(){var e,r,l;try{return n.CoreModule.engineResourcePaths=D(null===(e=this.config)||void 0===e?void 0:e.engineResourcePaths)?A:this.config.engineResourcePaths,t.LicenseManager._onAuthMessage=e=>e.replace("(https://www.dynamsoft.com/customer/license/trialLicense?product=unknown&deploymenttype=unknown)","(https://www.dynamsoft.com/customer/license/trialLicense?product=mrz&deploymenttype=web)"),await t.LicenseManager.initLicense((null===(r=this.config)||void 0===r?void 0:r.license)||"",{executeNow:!0}),n.CoreModule.loadWasm(["DLR","DCP"]),s.CodeParserModule.loadSpec("MRTD_TD3_PASSPORT"),s.CodeParserModule.loadSpec("MRTD_TD1_ID"),s.CodeParserModule.loadSpec("MRTD_TD2_ID"),o.LabelRecognizerModule.loadRecognitionData("MRZ"),this.resources.cameraView=await a.CameraView.createInstance(null===(l=this.config.scannerViewConfig)||void 0===l?void 0:l.cameraEnhancerUIPath),this.resources.cameraEnhancer=await a.CameraEnhancer.createInstance(this.resources.cameraView),this.resources.cvRouter=await i.CaptureVisionRouter.createInstance(),!0}catch(e){let n=(null==e?void 0:e.message)||e;if(null==n?void 0:n.toLowerCase().includes("license")){const e="The MRZ Scanner license is invalid or has expired. Please contact the site administrator to resolve this issue.";alert(e),console.error(e)}else{const e=`Resource Initialization Failed: ${n}`;alert(e),console.error(e)}return!1}}shouldCreateDefaultContainer(){var e,n;const t=!this.config.container,i=!((null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)||(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container));return t&&i}createDefaultMRZScannerContainer(){const e=document.createElement("div");return e.className="mrz-scanner-main-container",Object.assign(e.style,{height:"100dvh",width:"100%",position:"absolute",left:"0",top:"0",zIndex:"999"}),document.body.append(e),e}checkForTemporaryLicense(e){return!(null==e?void 0:e.length)||(null==e?void 0:e.startsWith("A"))||(null==e?void 0:e.startsWith("L"))||(null==e?void 0:e.startsWith("P"))||(null==e?void 0:e.startsWith("Y"))?"DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9":e}validateViewConfigs(){var e,n,t,i,a,s,o,r;if(!this.config.container){if((null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)&&this.config.showResultView&&!(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container)){const e="MRZResultView container is required when showResultView is true";return alert(e),console.error(e),!1}if(!(null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)&&(null===(i=this.config.resultViewConfig)||void 0===i?void 0:i.container)&&!this.resources.result){const e="Result is needed to create MRZResultView without a scanner view";return alert(e),console.error(e),!1}}try{if(this.config.container&&!v(this.config.container)){const e="Invalid main container reference";return alert(e),console.error(e),!1}if((null===(a=this.config.scannerViewConfig)||void 0===a?void 0:a.container)&&!v(null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.container)){const e="Invalid scanner view container reference";return alert(e),console.error(e),!1}if((null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)&&!v(null===(r=this.config.resultViewConfig)||void 0===r?void 0:r.container)){const e="Invalid result view container reference";return alert(e),console.error(e),!1}}catch(e){const n=`Error accessing container references: ${e.message}`;return alert(n),console.error(n),!1}return!0}showResultView(){var e,n;return!1!==this.config.showResultView&&(this.config.container?!(void 0!==this.config.showResultView||!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container)&&!this.config.container)||!!this.config.showResultView:this.config.showResultView&&!!(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container))}initializeMRZScannerConfig(){var n,t,i,a,s,o,r;this.config=null!==(n=this.config)&&void 0!==n?n:{};if(!this.validateViewConfigs())return!1;this.shouldCreateDefaultContainer()?this.config.container=this.createDefaultMRZScannerContainer():this.config.container&&(this.config.container=v(this.config.container));const l=this.config.container?this.createViewContainers(v(this.config.container)):{},c={license:this.checkForTemporaryLicense(this.config.license),utilizedTemplateNames:Object.fromEntries(Object.values(e.EnumMRZScanMode).map((e=>{var n;return[e,(null===(n=this.config.utilizedTemplateNames)||void 0===n?void 0:n[e])||E[e]]}))),templateFilePath:(null===(t=this.config)||void 0===t?void 0:t.templateFilePath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.1.0-beta.0514202501/dist/mrz-scanner.template.json"},d=Object.assign(Object.assign({},this.config.scannerViewConfig),{container:l[e.EnumMRZScannerViews.Scanner]||v(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.container)||null,cameraEnhancerUIPath:(null===(a=this.config.scannerViewConfig)||void 0===a?void 0:a.cameraEnhancerUIPath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.1.0-beta.0514202501/dist/mrz-scanner.ui.html",templateFilePath:c.templateFilePath,utilizedTemplateNames:c.utilizedTemplateNames,enableMultiFrameCrossFilter:null===(o=null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.enableMultiFrameCrossFilter)||void 0===o||o,mrzFormatType:this.config.mrzFormatType}),u=this.showResultView()?Object.assign(Object.assign({},this.config.resultViewConfig),{container:l[e.EnumMRZScannerViews.Result]||v(null===(r=this.config.resultViewConfig)||void 0===r?void 0:r.container)||null}):void 0;return Object.assign(this.config,Object.assign(Object.assign({},c),{scannerViewConfig:d,resultViewConfig:u})),!0}createViewContainers(n){n.textContent="";const t=[e.EnumMRZScannerViews.Scanner];return this.showResultView()&&t.push(e.EnumMRZScannerViews.Result),t.reduce(((e,t)=>{const i=document.createElement("div");return i.className=`mrz-scanner-${t}-view-container`,Object.assign(i.style,{height:"100%",width:"100%",display:"none",position:"relative"}),n.append(i),e[t]=i,e}),{})}dispose(){var e,n;this.resultView&&(this.resultView.dispose(),this.resultView=null),this.scannerView=null,this.resources.cameraEnhancer&&(this.resources.cameraEnhancer.dispose(),this.resources.cameraEnhancer=null),this.resources.cameraView&&(this.resources.cameraView.dispose(),this.resources.cameraView=null),this.resources.cvRouter&&(this.resources.cvRouter.dispose(),this.resources.cvRouter=null),this.resources.result=null,this.resources.onResultUpdated=null;const t=e=>{const n=v(e);n&&(n.style.display="none",n.textContent="")};t(this.config.container),t(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container),t(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container),this.isInitialized=!1}async processUploadedFile(t){var i,a,s,o;try{this.showLoadingOverlay("Processing File...");const{cvRouter:r}=this.resources,l=null===(i=this.config.utilizedTemplateNames)||void 0===i?void 0:i.all,c=await r.getSimplifiedSettings(l);c.roiMeasuredInPercentage=!0,c.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await r.updateSettings(l,c);const d=await r.capture(t,l),u=d.items,m=u.filter((e=>e.type===n.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE))[0].imageData;m.toCanvas=()=>n._toCanvas(m),m.toBlob=async()=>await n._toBlob("image/png",m);const h=null==d?void 0:d.textLineResultItems,g=null==d?void 0:d.parsedResultItems;let p={};if(null==h?void 0:h.length){const e=(null===(a=h[0])||void 0===a?void 0:a.text)||"";p=L(e,g[0])}const f={status:{code:e.EnumResultStatus.RS_SUCCESS,message:"Success"},originalImageResult:m,data:p,imageData:!0,_imageData:m};null===(o=(s=this.resources).onResultUpdated)||void 0===o||o.call(s,f)}catch(n){return console.error("Failed to process uploaded file:",n),{status:{code:e.EnumResultStatus.RS_FAILED,message:`Failed to process image: ${n.message||n}`}}}finally{this.hideLoadingOverlay(!1)}}async launch(n){if(this.isCapturing)throw new Error("Capture session already in progress");try{this.isCapturing=!0;const{components:t}=await this.initialize();if(D(t))throw new Error("MRZ Scanner initialization failed.");if(this.config.container&&(v(this.config.container).style.display="block"),n&&(t.scannerView=null,await this.processUploadedFile(n)),!t.scannerView&&this.resources.result&&t.resultView)return await t.resultView.launch();if(!t.scannerView&&!this.resources.result)throw new Error("Scanner view is required when no previous result exists");if(t.scannerView){const n=await t.scannerView.launch();if((null==n?void 0:n.status.code)!==e.EnumResultStatus.RS_SUCCESS)return{status:{code:null==n?void 0:n.status.code,message:(null==n?void 0:n.status.message)||"Failed to capture image"}};if(t.resultView)return await t.resultView.launch()}return this.resources.result}catch(n){return alert((null==n?void 0:n.message)||n),console.error((null==n?void 0:n.message)||n),{status:{code:e.EnumResultStatus.RS_FAILED,message:(null==n?void 0:n.message)||n}}}finally{this.isCapturing=!1,this.dispose()}}}const j={MRZScanner:P,MRZScannerView:_,MRZResultView:k};e.Core=m,e.License=h,e.CVR=g,e.DCE=p,e.DCP=f,e.DLR=y,e.Utility=R,e.DEFAULT_TEMPLATE_NAMES=E,e.DynamsoftMRZScanner=j,e.MRZDataLabel=x,e.MRZResultView=k,e.MRZScanner=P,e.MRZScannerView=_,e.displayMRZDate=V})); diff --git a/dist/mrz-scanner.mjs b/dist/mrz-scanner.mjs index 7369c61..44f4d53 100644 --- a/dist/mrz-scanner.mjs +++ b/dist/mrz-scanner.mjs @@ -1 +1 @@ -import{EnumCapturedResultItemType as e,EnumImagePixelFormat as n,CoreModule as t}from"dynamsoft-core";import*as i from"dynamsoft-core";export{i as Core};import{LicenseManager as s}from"dynamsoft-license";import*as a from"dynamsoft-license";export{a as License};import{CapturedResultReceiver as o,CaptureVisionRouter as r}from"dynamsoft-capture-vision-router";import*as l from"dynamsoft-capture-vision-router";export{l as CVR};import{Feedback as c,CameraView as d,CameraEnhancer as h}from"dynamsoft-camera-enhancer";import*as u from"dynamsoft-camera-enhancer";export{u as DCE};import{EnumValidationStatus as m,CodeParserModule as g}from"dynamsoft-code-parser";import*as p from"dynamsoft-code-parser";export{p as DCP};import{LabelRecognizerModule as f}from"dynamsoft-label-recognizer";import*as y from"dynamsoft-label-recognizer";export{y as DLR};import{MultiFrameResultCrossFilter as w}from"dynamsoft-utility";import*as v from"dynamsoft-utility";export{v as Utility};var S,E,D;!function(e){e.Passport="passport",e.TD1="td1",e.TD2="td2",e.PassportAndTD1="passportAndTd1",e.PassportAndTD2="passportAndTd2",e.TD1AndTD2="td1AndTd2",e.All="all"}(S||(S={})),function(e){e.Passport="passport",e.TD1="td1",e.TD2="td2"}(E||(E={})),function(e){e.Scanner="scanner",e.Result="scan-result"}(D||(D={}));const R={[S.Passport]:"ReadPassport",[S.TD1]:"ReadId-TD1",[S.TD2]:"ReadId-TD2",[S.PassportAndTD1]:"ReadPassportAndId-TD1",[S.PassportAndTD2]:"ReadPassportAndId-TD2",[S.TD1AndTD2]:"ReadId",[S.All]:"ReadPassportAndId"};var C;function T(e){if("string"==typeof e){const n=document.querySelector(e);if(!n)throw new Error("Element not found");return n}return e instanceof HTMLElement?e:null}!function(e){e[e.RS_SUCCESS=0]="RS_SUCCESS",e[e.RS_CANCELLED=1]="RS_CANCELLED",e[e.RS_FAILED=2]="RS_FAILED"}(C||(C={}));function M(e,n){if(!document.getElementById(e)){const t=document.createElement("style");t.id=e,t.textContent=n,document.head.appendChild(t)}}const x=e=>!e||0===Object.keys(e).length;function b(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}const z={"4k":{width:3840,height:2160},"2k":{width:2560,height:1440},"1080p":{width:1920,height:1080},"720p":{width:1280,height:720},"480p":{width:640,height:480}};function V(e,n={}){const{message:t,spinnerSize:i=32}=n,s=document.createElement("div");s.className="dynamsoft-mrz-loading-screen";const a=document.createElement("div");a.className="dynamsoft-mrz-loading";const o=document.createElement("div");o.className="dynamsoft-mrz-loading-content";const r=`\n \n \n \n `;if(o.innerHTML=r,t){const e=document.createElement("div");e.className="dynamsoft-mrz-loading-message",e.textContent=t,o.appendChild(e)}return a.appendChild(o),s.appendChild(a),e.appendChild(s),{element:s,updateMessage:e=>{let n=a.querySelector(".dynamsoft-mrz-loading-message");null!==e?n?n.textContent=e:(n=document.createElement("div"),n.className="dynamsoft-mrz-loading-message",n.textContent=e,o.appendChild(n)):null==n||n.remove()},hide:()=>{s&&s.parentNode&&(s.classList.add("fade-out"),setTimeout((()=>{var e;null===(e=s.parentNode)||void 0===e||e.removeChild(s)}),200))}}}const I='\n .dynamsoft-mrz-loading-screen {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: #323234;\n z-index: 998;\n opacity: 1;\n transition: opacity 0.2s ease-out;\n }\n\n .dynamsoft-mrz-loading-screen.fade-out {\n opacity: 0;\n }\n\n .dynamsoft-mrz-loading {\n position: absolute;\n left: 50%;\n top: 50%;\n color: white;\n z-index: 999;\n transform: translate(-50%, -50%);\n }\n\n .dynamsoft-mrz-loading-content {\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 16px;\n }\n\n .dynamsoft-mrz-loading svg {\n animation: spin 1s linear infinite;\n }\n\n .dynamsoft-mrz-loading-message {\n color: white;\n font-family: "Verdana";\n font-size: 14px;\n text-align: center;\n max-width: 200px;\n line-height: 1.4;\n opacity: 0.9;\n }\n\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n';var L;!function(e){e.InvalidFields="invalidFields",e.DocumentType="documentType",e.DocumentNumber="documentNumber",e.MRZText="mrzText",e.FirstName="firstName",e.LastName="lastName",e.Age="age",e.Sex="sex",e.IssuingState="issuingState",e.Nationality="nationality",e.DateOfBirth="dateOfBirth",e.DateOfExpiry="dateOfExpiry"}(L||(L={}));const N={[L.InvalidFields]:"Invalid Fields",[L.DocumentType]:"Document Type",[L.DocumentNumber]:"Document Number",[L.MRZText]:"MRZ Text",[L.FirstName]:"Given Name(s)",[L.LastName]:"Surname",[L.Age]:"Age",[L.Sex]:"Sex",[L.IssuingState]:"Issuing State",[L.Nationality]:"Nationality",[L.DateOfBirth]:"Date Of Birth (YYYY-MM-DD)",[L.DateOfExpiry]:"Date Of Expiry (YYYY-MM-DD)"};function _(e,n,t,i=!1){const s=parseInt(e,10);let a;if(i)a=s>=60?1900+s:2e3+s;else{a=s>(new Date).getFullYear()%100?1900+s:2e3+s}return{year:a,month:parseInt(n,10),day:parseInt(t,10)}}function k(e){const n=e=>{var n;return 1===(null===(n=`${e}`)||void 0===n?void 0:n.length)?`0${e}`:e};return`${null==e?void 0:e.year}-${n(null==e?void 0:e.month)}${(null==e?void 0:e.day)&&`-${n(null==e?void 0:e.day)}`}`}function F(e,n){const t=[],i=e=>n.getFieldValidationStatus(e)===m.VS_FAILED,s=n.codeType,a=function(e){switch(e){case"MRTD_TD1_ID":return E.TD1;case"MRTD_TD2_ID":case"MRTD_TD2_VISA":case"MRTD_TD2_FRENCH_ID":return E.TD2;case"MRTD_TD3_PASSPORT":case"MRTD_TD3_VISA":return E.Passport;default:throw new Error(`Unknown document type: ${e}`)}}(s),o=function(e){switch(e){case"MRTD_TD1_ID":return"ID (TD1)";case"MRTD_TD2_ID":return"ID (TD2)";case"MRTD_TD2_VISA":return"ID (VISA)";case"MRTD_TD2_FRENCH_ID":return"French ID (TD2)";case"MRTD_TD3_PASSPORT":return"Passport (TD3)";case"MRTD_TD3_VISA":return"Visa (TD3)";default:throw new Error(`Unknown document type: ${e}`)}}(s),r=a===E.Passport&&"MRTD_TD3_PASSPORT"===s?"passportNumber":"documentNumber",l=_(n.getFieldValue("birthYear"),n.getFieldValue("birthMonth"),n.getFieldValue("birthDay")),c=_(n.getFieldValue("expiryYear"),n.getFieldValue("expiryMonth"),n.getFieldValue("expiryDay"),!0);["birthYear","birthMonth","birthDay"].forEach((e=>{i(e)&&t.push(L.DateOfBirth)})),["expiryYear","expiryMonth","expiryDay"].forEach((e=>{i(e)&&t.push(L.DateOfExpiry)}));const d={[L.LastName]:n.getFieldValue("primaryIdentifier"),[L.FirstName]:n.getFieldValue("secondaryIdentifier"),[L.Nationality]:n.getFieldRawValue("nationality"),[L.DocumentNumber]:n.getFieldValue(r)||n.getFieldValue("longDocumentNumber"),[L.IssuingState]:n.getFieldRawValue("issuingState"),[L.Sex]:b(n.getFieldValue("sex"))};Object.keys(d).forEach((e=>{let n=!1;switch(e){case L.FirstName:n=i("secondaryIdentifier");break;case L.LastName:n=i("primaryIdentifier");break;case L.DocumentNumber:n=i(r)||i("longDocumentNumber");break;default:n=i(e)}n&&t.push(e)}));const h=function(e){const n=new Date,t=n.getMonth()+1>e.month||n.getMonth()+1===e.month&&n.getDate()>=e.day;return n.getFullYear()-e.year-(t?0:1)}(l);h<1&&t.push(L.Age);return{[L.InvalidFields]:t,[L.FirstName]:d[L.FirstName],[L.LastName]:d[L.LastName],[L.Age]:h,[L.DateOfBirth]:l,[L.Sex]:d[L.Sex],[L.Nationality]:d[L.Nationality],[L.DocumentNumber]:d[L.DocumentNumber],[L.DateOfExpiry]:c,[L.IssuingState]:d[L.IssuingState],[L.DocumentType]:b(o),[L.MRZText]:e}}const O={[E.TD1]:{width:85.6,height:53.98},[E.TD2]:{width:105,height:74},[E.Passport]:{width:125,height:88}};class A{showScannerLoadingOverlay(e){const n=T(this.config.container);this.loadingScreen=V(n,{message:e}),n.style.display="block",n.style.position="relative"}hideScannerLoadingOverlay(e=!1){this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,e&&(T(this.config.container).style.display="none"))}constructor(e,n){this.resources=e,this.config=n,this.isSoundFeedbackOn=!1,this.scanModeManager={[E.Passport]:!0,[E.TD1]:!0,[E.TD2]:!0},this.currentScanMode=S.All,this.resizeTimer=null,this.capturedResultItems=[],this.originalImageData=null,this.initialized=!1,this.initializedDCE=!1,this.DCE_ELEMENTS={selectCameraBtn:null,uploadImageBtn:null,soundFeedbackBtn:null,closeScannerBtn:null,scanModeSelectContainer:null,passportModeOption:null,td1ModeOption:null,td2ModeOption:null,toast:null},this.loadingScreen=null,this.handleResize=()=>{this.toggleScanGuide(!1),this.resizeTimer&&window.clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout((()=>{this.toggleScanGuide(!0)}),500)}}async initialize(){if(!this.initialized){this.initializeScanModeManager(),this.currentScanMode=this.getScanMode(),M("dynamsoft-mrz-loading-screen-style",I);try{const{cameraView:n,cameraEnhancer:t,cvRouter:i}=this.resources;if(n.setScanRegionMaskStyle({strokeStyle:"transparent",fillStyle:"transparent",lineWidth:0}),n.setVideoFit("cover"),i.setInput(t),await i.initSettings(this.config.templateFilePath),!0===this.config.enableMultiFrameCrossFilter){const n=new w;n.enableResultCrossVerification(e.CRIT_TEXT_LINE,!0),n.enableResultDeduplication(e.CRIT_TEXT_LINE,!0),await i.addResultFilter(n)}const s=new o;s.onCapturedResultReceived=e=>this.handleMRZResult(e),await i.addResultReceiver(s),this.toggleSoundFeedback(!1),!1===this.config.showScanGuide&&this.toggleScanGuide(!1),this.initialized=!0}catch(e){let n=(null==e?void 0:e.message)||e;console.error(n),alert(n),this.closeCamera();const t={status:{code:C.RS_FAILED,message:"Dynamsoft MRZ Scanner initialize error"}};this.currentScanResolver(t)}}}initializeElements(){const e=T(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))throw new Error("Shadow root not found");this.DCE_ELEMENTS={selectCameraBtn:n.shadowRoot.querySelector(".dce-mn-select-camera-icon"),uploadImageBtn:n.shadowRoot.querySelector(".dce-mn-upload-image-icon"),soundFeedbackBtn:n.shadowRoot.querySelector(".dce-mn-sound-feedback"),closeScannerBtn:n.shadowRoot.querySelector(".dce-mn-close"),scanModeSelectContainer:n.shadowRoot.querySelector(".dce-mn-scan-mode-select"),passportModeOption:n.shadowRoot.querySelector(".scan-mode-option-passport"),td1ModeOption:n.shadowRoot.querySelector(".scan-mode-option-td1"),td2ModeOption:n.shadowRoot.querySelector(".scan-mode-option-td2"),toast:n.shadowRoot.querySelector(".dce-mn-toast")},this.setupScanModeSelector(),this.assignDCEClickEvents(),this.DCE_ELEMENTS.toast.style.display="none",!1===this.config.showUploadImage&&(this.DCE_ELEMENTS.uploadImageBtn.style.display="none"),!1===this.config.showSoundToggle&&(this.DCE_ELEMENTS.soundFeedbackBtn.style.display="none"),this.initializedDCE=!0}setupScanModeSelector(){if(!1!==this.config.showFormatSelector)switch(this.currentScanMode){case S.PassportAndTD1:this.DCE_ELEMENTS.td2ModeOption.style.display="none";break;case S.PassportAndTD2:this.DCE_ELEMENTS.td1ModeOption.style.display="none";break;case S.TD1AndTD2:this.DCE_ELEMENTS.passportModeOption.style.display="none";break;case S.All:break;default:this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}else this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}assignDCEClickEvents(){if(!Object.values(this.DCE_ELEMENTS).every(Boolean))throw new Error("Camera control elements not found");this.closeCamera=this.closeCamera.bind(this),this.DCE_ELEMENTS.uploadImageBtn.onclick=()=>this.uploadImage(),this.DCE_ELEMENTS.soundFeedbackBtn.onclick=()=>this.toggleSoundFeedback(),this.DCE_ELEMENTS.closeScannerBtn.onclick=()=>this.handleCloseBtn(),this.DCE_ELEMENTS.selectCameraBtn.onclick=e=>{e.stopPropagation(),this.toggleSelectCameraBox()},this.DCE_ELEMENTS.passportModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.passportModeOption.style.display&&await this.toggleScanDocType(E.Passport)},this.DCE_ELEMENTS.td1ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td1ModeOption.style.display&&await this.toggleScanDocType(E.TD1)},this.DCE_ELEMENTS.td2ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td2ModeOption.style.display&&await this.toggleScanDocType(E.TD2)}}handleCloseBtn(){this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:C.RS_CANCELLED,message:"Cancelled"}})}attachOptionClickListeners(){const e=T(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const t=n.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings");[...n.shadowRoot.querySelectorAll(".dce-mn-camera-option"),...n.shadowRoot.querySelectorAll(".dce-mn-resolution-option")].forEach((e=>{e.addEventListener("click",(async n=>{const i=e.getAttribute("data-davice-id"),s=e.getAttribute("data-height"),a=e.getAttribute("data-width");i?this.resources.cameraEnhancer.selectCamera(i).then((()=>{this.toggleScanGuide()})):s&&a&&this.resources.cameraEnhancer.setResolution({width:parseInt(a),height:parseInt(s)}).then((()=>{this.toggleScanGuide()})),"none"!==t.style.display&&this.toggleSelectCameraBox()}))}))}highlightCameraAndResolutionOption(){const e=T(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const t=n.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings"),i=t.querySelectorAll(".dce-mn-camera-option"),s=t.querySelectorAll(".dce-mn-resolution-option"),a=this.resources.cameraEnhancer.getSelectedCamera(),o=this.resources.cameraEnhancer.getResolution();i.forEach((e=>{const n=e;n.getAttribute("data-davice-id")===(null==a?void 0:a.deviceId)?n.style.border="2px solid #fe814a":n.style.border="none"}));const r={"480p":"480","720p":"720","1080p":"1080","2k":"1440","4k":"2160"},l=function(e){const n=e.width*e.height,t=e.width/e.height;let i="480p",s=Number.MAX_VALUE;for(const[e,a]of Object.entries(z)){const o=a.width*a.height,r=a.width/a.height,l=.7*Math.abs(o-n)+Math.abs(r-t)*o*.3;l{const n=e,t=n.getAttribute("data-height");n.style.border=t===r[l]?"2px solid #fe814a":"none"}))}toggleSelectCameraBox(){const e=T(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const t=n.shadowRoot.querySelector(".dce-mn-resolution-box");this.highlightCameraAndResolutionOption(),this.attachOptionClickListeners(),t.click()}async uploadImage(){var n,t,i;const{cvRouter:s}=this.resources,a=document.createElement("input");a.type="file",a.accept="image/*",a.style.display="none",document.body.appendChild(a);try{this.showScannerLoadingOverlay("Processing image..."),await this.closeCamera(!1);const o=await new Promise(((e,n)=>{a.onchange=t=>{var i;const s=null===(i=t.target.files)||void 0===i?void 0:i[0];(null==s?void 0:s.type.startsWith("image/"))?e(s):n(new Error("Please select an image file"))},a.addEventListener("cancel",(async()=>{this.hideScannerLoadingOverlay(!1),await this.launch()})),a.click()}));if(!o)return this.hideScannerLoadingOverlay(!1),void await this.launch();const r=this.config.utilizedTemplateNames[this.currentScanMode];if(!1!==this.config.showScanGuide){const e=await s.getSimplifiedSettings(r);e.roiMeasuredInPercentage=!0,e.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await s.updateSettings(r,e)}const l=await s.capture(o,r);this.capturedResultItems=l.items;const c=this.capturedResultItems.filter((n=>n.type===e.CRIT_ORIGINAL_IMAGE))[0].imageData;c.toCanvas=()=>{const e=document.createElement("canvas");e.width=c.width,e.height=c.height;const n=e.getContext("2d");if(!n)throw new Error("Failed to get canvas context");const t=new ImageData(new Uint8ClampedArray(c.bytes.buffer),c.width,c.height);return n.putImageData(t,0,0),e},this.originalImageData=c;const d=null==l?void 0:l.textLineResultItems,h=null==l?void 0:l.parsedResultItems;let u={};if(null==d?void 0:d.length){const e=(null===(n=d[0])||void 0===n?void 0:n.text)||"";u=F(e,h[0])}const m={status:{code:C.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,_imageData:this.originalImageData,data:u};null===(i=(t=this.resources).onResultUpdated)||void 0===i||i.call(t,m),this.currentScanResolver(m),this.hideScannerLoadingOverlay(!0)}catch(e){let n=(null==e?void 0:e.message)||e;console.error(n),alert(n),this.closeCamera();const t={status:{code:C.RS_FAILED,message:"Error processing uploaded image"}};this.currentScanResolver(t)}finally{document.body.removeChild(a)}}toggleSoundFeedback(e){this.isSoundFeedbackOn=void 0!==e?e:!this.isSoundFeedbackOn;const n=T(this.config.container),t=n.children[n.children.length-1];if(!(null==t?void 0:t.shadowRoot))return;const i=t.shadowRoot.querySelector(".dce-mn-sound-feedback"),s=i.querySelector(".dce-mn-sound-feedback-on");i.querySelector(".dce-mn-sound-feedback-off").style.display=this.isSoundFeedbackOn?"none":"block",s.style.display=this.isSoundFeedbackOn?"block":"none"}calculateScanRegion(e){const{cameraEnhancer:n,cameraView:t}=this.resources;if(!n||!n.isOpen())return;const i=t.getVisibleRegionOfVideo({inPixels:!0});if(!i)return;const s=t.getVideoElement(),a=s.videoWidth,o=s.videoHeight,r=O[e];let l;const c=i.height-80;if(i.width>i.height){l=.75*c/r.height;l*r.width>.9*i.width&&(l=.9*i.width/r.width)}else{l=.9*i.width/r.width;l*r.height>.75*c&&(l=.75*c/r.height)}const d=l*r.width,h=l*r.height,u=(i.width-d)/2,m=(c-h)/2,g=u,p=u+d,f=m,y=m+h,w=(i.x+g)/a*100,v=(i.x+p)/a*100,S=(i.y+f)/o*100,E=(i.y+y)/o*100,D={left:Math.round(w),right:Math.round(v),top:Math.round(S),bottom:Math.round(E),isMeasuredInPercentage:!0};null==t||t.setScanRegionMaskVisible(!0),n.setScanRegion(D)}toggleScanGuide(e){const n=T(this.config.container),t=n.children[n.children.length-1];if(!(null==t?void 0:t.shadowRoot))return;const i=t.shadowRoot.querySelector(".dce-scanguide-passport"),s=t.shadowRoot.querySelector(".dce-scanguide-td1"),a=t.shadowRoot.querySelector(".dce-scanguide-td2");if(!1===e||!1===this.config.showScanGuide)return i.style.display="none",s.style.display="none",void(a.style.display="none");switch(this.currentScanMode){case S.All:case S.Passport:case S.PassportAndTD1:case S.PassportAndTD2:i.style.display="block",s.style.display="none",a.style.display="none",this.calculateScanRegion(E.Passport);break;case S.TD1:case S.TD1AndTD2:i.style.display="none",s.style.display="block",a.style.display="none",this.calculateScanRegion(E.TD1);break;case S.TD2:i.style.display="none",s.style.display="none",a.style.display="block",this.calculateScanRegion(E.TD2)}}async openCamera(){try{this.showScannerLoadingOverlay("Initializing camera...");const{cameraEnhancer:e,cameraView:n}=this.resources,t=T(this.config.container);if(t.style.display="block",e.isOpen())e.isPaused()&&await e.resume();else{const i=n.getUIElement();i.parentElement||t.append(i),await e.open()}!this.initializedDCE&&e.isOpen()&&await this.initializeElements(),window.addEventListener("resize",this.handleResize);const i=t.children[t.children.length-1];if(!(null==i?void 0:i.shadowRoot))throw new Error("Shadow root not found");i.shadowRoot.querySelector(".dce-mn-torch-off").style.display="none",i.shadowRoot.querySelector(".dce-mn-torch-on").style.display="none"}catch(e){let n=(null==e?void 0:e.message)||e;console.error(n),alert(n),this.closeCamera();const t={status:{code:C.RS_FAILED,message:"MRZ Scanner Open Camera Error"}};this.currentScanResolver(t)}finally{this.hideScannerLoadingOverlay()}}async closeCamera(e=!0){try{window.removeEventListener("resize",this.handleResize),this.resizeTimer&&(window.clearTimeout(this.resizeTimer),this.resizeTimer=null);const{cameraEnhancer:n,cameraView:t}=this.resources,i=T(this.config.container);i.style.display=e?"none":"block",(null==t?void 0:t.getUIElement().parentElement)&&i.removeChild(t.getUIElement()),n.close(),this.stopCapturing()}catch(e){let n=(null==e?void 0:e.message)||e;console.error(`Close Camera error: ${n}`)}}pauseCamera(){const{cameraEnhancer:e}=this.resources;e.pause()}stopCapturing(){const{cameraView:e,cvRouter:n}=this.resources;n.stopCapturing(),e.clearAllInnerDrawingItems()}async handleMRZResult(n){var t;if(this.capturedResultItems=n.items,!(n.items.length<=1))try{const{onResultUpdated:i}=this.resources,s=n.items.filter((n=>n.type===e.CRIT_ORIGINAL_IMAGE));this.originalImageData=s.length&&s[0].imageData;const a=null==n?void 0:n.textLineResultItems,o=null==n?void 0:n.parsedResultItems;if(a){this.isSoundFeedbackOn&&c.beep();const e=(null===(t=null==a?void 0:a[0])||void 0===t?void 0:t.text)||"",n=F(e,o[0]);this.closeCamera();const s={status:{code:C.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,_imageData:this.originalImageData,data:n};null==i||i(s),this.currentScanResolver(s)}}catch(e){let n=(null==e?void 0:e.message)||e;console.error(n),alert(n),this.closeCamera();const t={status:{code:C.RS_FAILED,message:"Error capturing image"}};this.currentScanResolver(t)}}initializeScanModeManager(){const{mrzFormatType:e}=this.config;if(this.scanModeManager={[E.Passport]:!0,[E.TD1]:!0,[E.TD2]:!0},!e||Array.isArray(e)&&0===e.length)return;Object.keys(this.scanModeManager).forEach((e=>{this.scanModeManager[e]=!1}));(Array.isArray(e)?e:[e]).forEach((e=>{this.scanModeManager[e]=!0}))}getScanMode(){const e=Object.entries(this.scanModeManager).filter((([e,n])=>n)).map((([e])=>e)).sort().join(",");return{[E.Passport]:S.Passport,[E.TD1]:S.TD1,[E.TD2]:S.TD2,[`${E.Passport},${E.TD1}`]:S.PassportAndTD1,[`${E.Passport},${E.TD2}`]:S.PassportAndTD2,[`${E.TD1},${E.TD2}`]:S.TD1AndTD2,[`${E.Passport},${E.TD1},${E.TD2}`]:S.All,"":S.All}[e]}DCEShowToast(e,n=3e3){this.DCE_ELEMENTS.toast&&(this.DCE_ELEMENTS.toast.textContent=e,this.DCE_ELEMENTS.toast.style.display="",setTimeout((()=>{this.DCE_ELEMENTS.toast.style.display="none"}),n))}async startCapturing(){const{cvRouter:e,cameraEnhancer:t}=this.resources,i=this.config.utilizedTemplateNames[this.currentScanMode];try{if(!1!==this.config.showScanGuide){const n=await e.getSimplifiedSettings(i);n.roiMeasuredInPercentage=!0,n.roi.points=[{x:0,y:50},{x:100,y:50},{x:100,y:100},{x:0,y:100}],await e.updateSettings(i,n)}await e.startCapturing(i),t.setPixelFormat(n.IPF_ABGR_8888)}catch(e){let n=(null==e?void 0:e.message)||e;console.error("Failed to start capturing:",n),this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:C.RS_FAILED,message:"Failed to start capturing"}})}}async toggleScanDocType(e){try{if(this.scanModeManager[e]&&0===Object.entries(this.scanModeManager).filter((([n,t])=>t&&n!==e)).length)return console.warn("MRZ Scanner - At least one mode must be enabled"),void this.DCEShowToast("At least one mode must be enabled");this.scanModeManager[e]=!this.scanModeManager[e],this.currentScanMode=this.getScanMode(),this.stopCapturing(),await this.startCapturing(),this.toggleScanGuide(),this.DCE_ELEMENTS.td1ModeOption.classList.toggle("selected",this.scanModeManager[E.TD1]),this.DCE_ELEMENTS.td2ModeOption.classList.toggle("selected",this.scanModeManager[E.TD2]),this.DCE_ELEMENTS.passportModeOption.classList.toggle("selected",this.scanModeManager[E.Passport])}catch(e){let n=(null==e?void 0:e.message)||e;console.error("MRZ Scanner switch scan mode error: ",n),this.closeCamera();const t={status:{code:C.RS_FAILED,message:"MRZ Scanner switch scan mode error"}};this.currentScanResolver(t)}}async launch(){try{await this.initialize();const{cvRouter:e,cameraEnhancer:n}=this.resources;return new Promise((async e=>{this.currentScanResolver=e,await this.openCamera(),!this.initializedDCE&&n.isOpen()&&await this.initializeElements(),await this.startCapturing(),this.toggleScanGuide()}))}catch(e){let n=(null==e?void 0:e.message)||e;console.error("MRZ Scanner launch error: ",n),this.closeCamera();const t={status:{code:C.RS_FAILED,message:"MRZ Scanner launch error"}};this.currentScanResolver(t)}}}const P={rescan:'\n\n\n \n\n\n\n\n\n\n\n',complete:'\n\n\n\n \n\n\n\n\n\n\n\n',failed:'\n \n \n \n\n',info:'\n\n \n \n \n\n'};class j{constructor(e,n,t){this.resources=e,this.config=n,this.scannerView=t,this.editedFields={}}async launch(){try{return T(this.config.container).textContent="",await this.initialize(),T(this.config.container).style.display="flex",new Promise((e=>{this.currentScanResultViewResolver=e}))}catch(e){let n=(null==e?void 0:e.message)||e;throw console.error(n),n}}async handleRescan(){var e;try{if(!this.scannerView)return void console.error("Scanner View not initialized");this.hideView();const n=await this.scannerView.launch();if((null===(e=null==n?void 0:n.status)||void 0===e?void 0:e.code)===C.RS_FAILED)return void(this.currentScanResultViewResolver&&this.currentScanResultViewResolver(n));this.resources.onResultUpdated&&((null==n?void 0:n.status.code)===C.RS_CANCELLED?this.resources.onResultUpdated(this.resources.result):(null==n?void 0:n.status.code)===C.RS_SUCCESS&&this.resources.onResultUpdated(n)),this.dispose(!0),await this.initialize(),T(this.config.container).style.display="flex"}catch(e){throw console.error("Error in rescan handler:",e),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:C.RS_FAILED,message:(null==e?void 0:e.message)||e}}),e}}async handleDone(){var e,n;try{(null===(e=this.resources.result)||void 0===e?void 0:e.data)&&!x(this.editedFields)&&(this.resources.result.data=Object.assign(Object.assign({},this.resources.result.data),this.editedFields),this.resources.onResultUpdated&&this.resources.onResultUpdated(this.resources.result)),(null===(n=this.config)||void 0===n?void 0:n.onDone)&&await this.config.onDone(this.resources.result),this.currentScanResultViewResolver&&this.resources.result&&this.currentScanResultViewResolver(this.resources.result),this.hideView(),this.dispose()}catch(e){throw console.error("Error in done handler:",e),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:C.RS_FAILED,message:(null==e?void 0:e.message)||e}}),e}}createControls(){var e,n,t,i,s,a,o,r;const{toolbarButtonsConfig:l}=this.config;return function(e){M("dynamsoft-mrz-controls-style","\n .dynamsoft-mrz-controls {\n display: flex;\n height: 6rem;\n background-color: #323234;\n align-items: center;\n font-size: 12px;\n font-family: Verdana;\n color: white;\n width: 100%;\n }\n\n .dynamsoft-mrz-control-btn {\n background-color: #323234;\n color: white;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n height: 100%;\n width: 100%;\n gap: 0.5rem;\n text-align: center;\n user-select: none;\n }\n\n .dynamsoft-mrz-control-btn.hide {\n display: none;\n }\n\n .dynamsoft-mrz-control-btn.disabled {\n opacity: 0.4;\n pointer-events: none;\n cursor: default;\n }\n\n .dynamsoft-mrz-control-icon-wrapper {\n flex: 0.75;\n display: flex;\n align-items: flex-end;\n justify-content: center;\n min-height: 40px;\n }\n\n .dynamsoft-mrz-control-icon img,\n .dynamsoft-mrz-control-icon svg {\n width: 32px;\n height: 32px;\n fill: #fe8e14;\n }\n\n .dynamsoft-mrz-control-text {\n flex: 0.5;\n display: flex;\n align-items: flex-start;\n justify-content: center;\n padding-bottom: 0.5rem;\n }\n\n \n @media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-controls {\n flex-direction: column;\n height: 100%;\n width: 5rem;\n }\n\n .dynamsoft-mrz-control-text {\n padding: 0 0.5rem 0.5rem;\n }\n }\n");const n=document.createElement("div");return n.className="dynamsoft-mrz-controls",e.forEach((e=>{const t=document.createElement("div");t.className=`dynamsoft-mrz-control-btn ${null==e?void 0:e.className}`;const i=document.createElement("div");if(i.className="dynamsoft-mrz-control-icon-wrapper",(s=e.icon).trim().startsWith(""))i.innerHTML=e.icon;else{const n=document.createElement("img");n.src=e.icon,n.alt=e.label,n.width=24,n.height=24,i.appendChild(n)}var s;const a=document.createElement("div");a.className="dynamsoft-mrz-control-text",a.textContent=e.label,e.isDisabled&&t.classList.add("disabled"),e.isHidden&&t.classList.add("hide"),t.appendChild(i),t.appendChild(a),e.onClick&&!e.isDisabled&&t.addEventListener("click",e.onClick),n.appendChild(t)})),n}([{id:"dynamsoft-mrz-scanResult-rescan",icon:(null===(e=null==l?void 0:l.rescan)||void 0===e?void 0:e.icon)||P.rescan,label:(null===(n=null==l?void 0:l.rescan)||void 0===n?void 0:n.label)||"Re-scan",onClick:()=>this.handleRescan(),className:`${(null===(t=null==l?void 0:l.rescan)||void 0===t?void 0:t.className)||""}`,isHidden:(null===(i=null==l?void 0:l.rescan)||void 0===i?void 0:i.isHidden)||!1,isDisabled:!this.scannerView},{id:"dynamsoft-mrz-scanResult-done",icon:(null===(s=null==l?void 0:l.done)||void 0===s?void 0:s.icon)||P.complete,label:(null===(a=null==l?void 0:l.done)||void 0===a?void 0:a.label)||"Done",className:`${(null===(o=null==l?void 0:l.done)||void 0===o?void 0:o.className)||""}`,isHidden:(null===(r=null==l?void 0:l.done)||void 0===r?void 0:r.isHidden)||!1,onClick:()=>this.handleDone()}])}handleFieldEdit(e,n){if(e===L.DateOfBirth||e===L.DateOfExpiry)try{const[t,i,s]=n.split(/[\/\-\.]/);s&&i&&t&&(this.editedFields[e]={day:parseInt(s,10),month:parseInt(i,10),year:parseInt(t,10)})}catch(e){console.error("Error parsing date",e)}else this.editedFields[e]=n}createMRZDataDisplay(){var e;const n=(null===(e=this.resources.result)||void 0===e?void 0:e.data)||{},t=!!this.config.allowResultEditing,i=n.invalidFields||[],s=document.createElement("div");if(s.className="dynamsoft-mrz-data-container",x(n)){const e=document.createElement("div");return e.className="dynamsoft-mrz-data-row empty",e.innerText="No MRZ detected. Please try again.",s.appendChild(e),s}if(i.length>0){const e=document.createElement("div");e.className="dynamsoft-mrz-error-notification",e.innerHTML=`\n
${P.failed}
\n
\n ${t?"Some fields require correction. Please review highlighted fields.":"Some fields contain invalid information. Please rescan the document."}\n
\n `,s.appendChild(e)}else if(0===i.length&&t){const e=document.createElement("div");e.className="dynamsoft-mrz-info-notification",e.innerHTML=`\n
${P.info}
\n
\n Please review all fields to ensure the information is correct.\n
\n `,s.appendChild(e)}return Object.entries(n).forEach((([e,n])=>{var a;if(e===L.InvalidFields||!n)return;if(e===L.MRZText&&!1===(null===(a=this.config)||void 0===a?void 0:a.showMRZText))return;const o=document.createElement("div");o.className="dynamsoft-mrz-data-row";const r=i.includes(e);r&&o.classList.add("invalid-field");const l=[L.MRZText,L.DocumentType],c=document.createElement("span");if(c.className="dynamsoft-mrz-data-label",c.innerText=N[e]||e,r){const e=document.createElement("span");if(e.className="dynamsoft-mrz-error-icon",e.innerHTML=P.failed,c.appendChild(e),t){const e=document.createElement("span");e.className="dynamsoft-mrz-error-hint",e.textContent="Please correct this field",c.appendChild(e)}}const d=document.createElement("div");if(d.className="dynamsoft-mrz-data-value",t&&!l.includes(e)){const t=document.createElement("input");t.className="dynamsoft-mrz-data-input",r&&t.classList.add("invalid"),e===L.DateOfBirth||e===L.DateOfExpiry?(t.value=k(n),t.setAttribute("placeholder","YYYY-MM-DD")):t.value=n,t.addEventListener("input",(n=>{if(this.handleFieldEdit(e,n.target.value),r){t.classList.remove("invalid"),o.classList.remove("invalid-field"),this.editedFields.invalidFields||(this.editedFields.invalidFields=[...i]);const n=this.editedFields.invalidFields.indexOf(e);n>-1&&this.editedFields.invalidFields.splice(n,1)}})),d.appendChild(t)}else e===L.MRZText?(d.classList.add("code"),d.innerText=n):e===L.DateOfBirth||e===L.DateOfExpiry?d.innerText=k(n):d.innerText=n,r&&d.classList.add("invalid-value");o.appendChild(c),o.appendChild(d),s.appendChild(o)})),s}async initialize(){try{if(!this.resources.result)throw Error("Captured image is missing. Please capture an image first!");if(!this.config.container)throw new Error("Please create a Scan Result View Container element");M("dynamsoft-mrz-result-view-style",B);const e=document.createElement("div");if(e.className="dynamsoft-mrz-result-view-container",!1!==this.config.showOriginalImage){const n=this.resources.result.originalImageResult,t=document.createElement("div");let i;t.className="dynamsoft-mrz-result-view-image-container",(null==n?void 0:n.toCanvas)&&(i=null==n?void 0:n.toCanvas()),Object.assign(i.style,{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}),t.appendChild(i),e.appendChild(t)}const n=this.createMRZDataDisplay();e.appendChild(n);const t=this.createControls();e.appendChild(t),T(this.config.container).appendChild(e)}catch(e){let n=(null==e?void 0:e.message)||e;console.error(n),alert(n)}}hideView(){T(this.config.container).style.display="none"}dispose(e=!1){T(this.config.container).textContent="",e||(this.currentScanResultViewResolver=void 0)}}const B="\n .dynamsoft-mrz-result-view-container {\n display: flex;\n width: 100%;\n height: 100%;\n background-color:#575757;\n font-size: 12px;\n flex-direction: column;\n align-items: center;\n }\n\n .dynamsoft-mrz-result-view-image-container {\n width: 100%;\n height: 200px;\n display: flex;\n justify-content: center;\n align-items: center;\n background-color: #323234;\n }\n\n \n.dynamsoft-mrz-data-container {\n font-size: 16px;\n font-family: Verdana;\n color: white;\n overflow: auto;\n width: 100%;\n height: 100%;\n min-height: 0;\n margin: 1rem 0;\n}\n\n.dynamsoft-mrz-data-row {\n padding: 0.5rem 2rem;\n display: flex;\n flex-direction: column;\n gap: 0.5rem;\n transition: background-color 0.3s ease;\n}\n\n.dynamsoft-mrz-data-row.invalid-field {\n background-color: rgba(231, 76, 60, 0.1);\n border-left: 3px solid #e74c3c;\n padding-left: calc(2rem - 3px);\n}\n\n.dynamsoft-mrz-data-label {\n color: #aaa;\n display: flex;\n gap: 0.5rem;\n align-items: end;\n flex-wrap: wrap;\n}\n\n.dynamsoft-mrz-error-notification,\n.dynamsoft-mrz-info-notification {\n color: white;\n padding: 1rem;\n margin: 0.5rem 2rem;\n border-radius: 4px;\n display: flex;\n align-items: center;\n gap: 1rem;\n text-align: start;\n}\n\n.dynamsoft-mrz-error-notification {\n background-color: rgba(231, 76, 60, 0.2);\n}\n\n.dynamsoft-mrz-info-notification {\n background-color: rgba(196, 231, 60, 0.2);\n}\n\n.dynamsoft-mrz-edit-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #aaa;\n}\n\n.dynamsoft-mrz-error-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-info-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: white;\n}\n\n.dynamsoft-mrz-info-message,\n.dynamsoft-mrz-error-message {\n flex: 1;\n}\n\n.dynamsoft-mrz-error-hint {\n font-size: 0.8rem;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-value {\n word-wrap: break-word;\n text-align: start;\n}\n\n.dynamsoft-mrz-data-value.code {\n font-family: monospace;\n}\n\n.dynamsoft-mrz-data-value.invalid-value {\n color: #e74c3c;\n text-decoration: wavy underline #e74c3c;\n text-decoration-skip-ink: none;\n}\n\n.dynamsoft-mrz-data-input {\n width: 100%;\n padding: 5px;\n background-color: rgba(255, 255, 255, 0.1);\n border: 1px solid rgba(255, 255, 255, 0.3);\n color: white;\n border-radius: 4px;\n font-size: 14px;\n transition: all 0.3s ease;\n}\n\n.dynamsoft-mrz-data-input.invalid {\n background-color: rgba(231, 76, 60, 0.1);\n border-color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-input:focus {\n background-color: rgba(255, 255, 255, 0.2);\n border-color: #fe8e14;\n outline: none;\n}\n\n@media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-result-view-container {\n flex-direction: row;\n }\n\n .dynamsoft-mrz-result-view-image-container{\n flex: 1;\n height: 100%;\n }\n\n .dynamsoft-mrz-data-container{\n flex: 1;\n }\n\n .dynamsoft-mrz-data-row:first-of-type {\n padding-top: 2rem;\n }\n\n .dynamsoft-mrz-data-row:last-of-type {\n padding-bottom: 2rem;\n }\n\n .dynamsoft-mrz-data-row.empty {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n padding-top: 0;\n padding-bottom: 0;\n }\n}\n",Z={rootDirectory:"https://cdn.jsdelivr.net/npm/"};class ${showLoadingOverlay(e){var n,t;const i=T(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)||T(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container);this.loadingScreen=V(i,{message:e}),i.style.display="block",i.style.position="relative"}hideLoadingOverlay(e=!1){var n,t,i;const s=T(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)||T(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container);this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,e&&(s.style.display="none",(null===(i=this.config)||void 0===i?void 0:i.container)&&(T(this.config.container).style.display="none")))}constructor(e){this.config=e,this.resources={},this.isInitialized=!1,this.isCapturing=!1,this.loadingScreen=null}async initialize(){if(this.isInitialized)return{resources:this.resources,components:{scannerView:this.scannerView,resultView:this.resultView}};try{if(!this.initializeMRZScannerConfig())return console.error("Failed to initialize mrz scanner config"),{resources:this.resources,components:{}};M("dynamsoft-mrz-loading-screen-style",I),this.showLoadingOverlay("Loading...");if(!await this.initializeDCVResources())return this.hideLoadingOverlay(!0),console.error("Failed to initialize DCV resources"),{resources:this.resources,components:{}};this.resources.onResultUpdated=e=>{this.resources.result=e};const e={};return this.config.scannerViewConfig&&(this.scannerView=new A(this.resources,this.config.scannerViewConfig),e.scannerView=this.scannerView,await this.scannerView.initialize()),this.config.resultViewConfig&&(this.resultView=new j(this.resources,this.config.resultViewConfig,this.scannerView),e.resultView=this.resultView),this.isInitialized=!0,{resources:this.resources,components:e}}catch(e){this.isInitialized=!1;const n=`Initialization Failed: ${(null==e?void 0:e.message)||e}`;return alert(n),console.error(n),{resources:this.resources,components:{}}}finally{this.hideLoadingOverlay(!0)}}async initializeDCVResources(){var e,n,i;try{return s.initLicense((null===(e=this.config)||void 0===e?void 0:e.license)||"",!0),t.engineResourcePaths=x(null===(n=this.config)||void 0===n?void 0:n.engineResourcePaths)?Z:this.config.engineResourcePaths,t.loadWasm(["DLR","DCP"]),g.loadSpec("MRTD_TD3_PASSPORT"),g.loadSpec("MRTD_TD1_ID"),g.loadSpec("MRTD_TD2_ID"),f.loadRecognitionData("MRZ"),this.resources.cameraView=await d.createInstance(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.cameraEnhancerUIPath),this.resources.cameraEnhancer=await h.createInstance(this.resources.cameraView),this.resources.cvRouter=await r.createInstance(),!0}catch(e){let n=(null==e?void 0:e.message)||e;if(null==n?void 0:n.toLowerCase().includes("license")){const e="The MRZ Scanner license is invalid or has expired. Please contact the site administrator to resolve this issue.";alert(e),console.error(e)}else{const e=`Resource Initialization Failed: ${n}`;alert(e),console.error(e)}return!1}}shouldCreateDefaultContainer(){var e,n;const t=!this.config.container,i=!((null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)||(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container));return t&&i}createDefaultMRZScannerContainer(){const e=document.createElement("div");return e.className="mrz-scanner-main-container",Object.assign(e.style,{height:"100dvh",width:"100%",position:"absolute",left:"0",top:"0",zIndex:"999"}),document.body.append(e),e}checkForTemporaryLicense(e){return!(null==e?void 0:e.length)||(null==e?void 0:e.startsWith("A"))||(null==e?void 0:e.startsWith("L"))||(null==e?void 0:e.startsWith("P"))||(null==e?void 0:e.startsWith("Y"))?"DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9":e}validateViewConfigs(){var e,n,t,i,s,a,o,r;if(!this.config.container){if((null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)&&this.config.showResultView&&!(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container)){const e="MRZResultView container is required when showResultView is true";return alert(e),console.error(e),!1}if(!(null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)&&(null===(i=this.config.resultViewConfig)||void 0===i?void 0:i.container)&&!this.resources.result){const e="Result is needed to create MRZResultView without a scanner view";return alert(e),console.error(e),!1}}try{if(this.config.container&&!T(this.config.container)){const e="Invalid main container reference";return alert(e),console.error(e),!1}if((null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.container)&&!T(null===(a=this.config.scannerViewConfig)||void 0===a?void 0:a.container)){const e="Invalid scanner view container reference";return alert(e),console.error(e),!1}if((null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)&&!T(null===(r=this.config.resultViewConfig)||void 0===r?void 0:r.container)){const e="Invalid result view container reference";return alert(e),console.error(e),!1}}catch(e){const n=`Error accessing container references: ${e.message}`;return alert(n),console.error(n),!1}return!0}showResultView(){var e,n;return!1!==this.config.showResultView&&(this.config.container?!(void 0!==this.config.showResultView||!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container)&&!this.config.container)||!!this.config.showResultView:this.config.showResultView&&!!(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container))}initializeMRZScannerConfig(){var e,n,t,i,s,a,o;this.config=null!==(e=this.config)&&void 0!==e?e:{};if(!this.validateViewConfigs())return!1;this.shouldCreateDefaultContainer()?this.config.container=this.createDefaultMRZScannerContainer():this.config.container&&(this.config.container=T(this.config.container));const r=this.config.container?this.createViewContainers(T(this.config.container)):{},l={license:this.checkForTemporaryLicense(this.config.license),utilizedTemplateNames:Object.fromEntries(Object.values(S).map((e=>{var n;return[e,(null===(n=this.config.utilizedTemplateNames)||void 0===n?void 0:n[e])||R[e]]}))),templateFilePath:(null===(n=this.config)||void 0===n?void 0:n.templateFilePath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.0.0/dist/mrz-scanner.template.json"},c=Object.assign(Object.assign({},this.config.scannerViewConfig),{container:r[D.Scanner]||T(null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)||null,cameraEnhancerUIPath:(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.cameraEnhancerUIPath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.0.0/dist/mrz-scanner.ui.html",templateFilePath:l.templateFilePath,utilizedTemplateNames:l.utilizedTemplateNames,enableMultiFrameCrossFilter:null===(a=null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.enableMultiFrameCrossFilter)||void 0===a||a,mrzFormatType:this.config.mrzFormatType}),d=this.showResultView()?Object.assign(Object.assign({},this.config.resultViewConfig),{container:r[D.Result]||T(null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)||null}):void 0;return Object.assign(this.config,Object.assign(Object.assign({},l),{scannerViewConfig:c,resultViewConfig:d})),!0}createViewContainers(e){e.textContent="";const n=[D.Scanner];return this.showResultView()&&n.push(D.Result),n.reduce(((n,t)=>{const i=document.createElement("div");return i.className=`mrz-scanner-${t}-view-container`,Object.assign(i.style,{height:"100%",width:"100%",display:"none",position:"relative"}),e.append(i),n[t]=i,n}),{})}dispose(){var e,n;this.resultView&&(this.resultView.dispose(),this.resultView=null),this.scannerView=null,this.resources.cameraEnhancer&&(this.resources.cameraEnhancer.dispose(),this.resources.cameraEnhancer=null),this.resources.cameraView&&(this.resources.cameraView.dispose(),this.resources.cameraView=null),this.resources.cvRouter&&(this.resources.cvRouter.dispose(),this.resources.cvRouter=null),this.resources.result=null,this.resources.onResultUpdated=null;const t=e=>{const n=T(e);n&&(n.style.display="none",n.textContent="")};t(this.config.container),t(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container),t(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container),this.isInitialized=!1}async launch(){if(this.isCapturing)throw new Error("Capture session already in progress");try{this.isCapturing=!0;const{components:e}=await this.initialize();if(x(e))throw new Error("MRZ Scanner initialization failed.");if(this.config.container&&(T(this.config.container).style.display="block"),!e.scannerView&&this.resources.result&&e.resultView)return await e.resultView.launch();if(!e.scannerView&&!this.resources.result)throw new Error("Scanner view is required when no previous result exists");if(e.scannerView){const n=await e.scannerView.launch();if((null==n?void 0:n.status.code)!==C.RS_SUCCESS)return{status:{code:null==n?void 0:n.status.code,message:(null==n?void 0:n.status.message)||"Failed to capture image"}};if(e.resultView)return await e.resultView.launch()}return this.resources.result}catch(e){return alert((null==e?void 0:e.message)||e),console.error((null==e?void 0:e.message)||e),{status:{code:C.RS_FAILED,message:(null==e?void 0:e.message)||e}}}finally{this.isCapturing=!1,this.dispose()}}}const q={MRZScanner:$,MRZScannerView:A,MRZResultView:j};export{R as DEFAULT_TEMPLATE_NAMES,q as DynamsoftMRZScanner,L as EnumMRZData,E as EnumMRZDocumentType,S as EnumMRZScanMode,D as EnumMRZScannerViews,C as EnumResultStatus,N as MRZDataLabel,j as MRZResultView,$ as MRZScanner,A as MRZScannerView,k as displayMRZDate}; +import{EnumCapturedResultItemType as e,_toCanvas as t,_toBlob as n,EnumImagePixelFormat as i,CoreModule as s}from"dynamsoft-core";import*as a from"dynamsoft-core";export{a as Core};import{LicenseManager as o}from"dynamsoft-license";import*as r from"dynamsoft-license";export{r as License};import{CapturedResultReceiver as l,CaptureVisionRouter as c}from"dynamsoft-capture-vision-router";import*as d from"dynamsoft-capture-vision-router";export{d as CVR};import{Feedback as h,CameraView as u,CameraEnhancer as m}from"dynamsoft-camera-enhancer";import*as g from"dynamsoft-camera-enhancer";export{g as DCE};import{EnumValidationStatus as p,CodeParserModule as f}from"dynamsoft-code-parser";import*as y from"dynamsoft-code-parser";export{y as DCP};import{LabelRecognizerModule as w}from"dynamsoft-label-recognizer";import*as v from"dynamsoft-label-recognizer";export{v as DLR};import{MultiFrameResultCrossFilter as S}from"dynamsoft-utility";import*as R from"dynamsoft-utility";export{R as Utility};var E,D,C;!function(e){e.Passport="passport",e.TD1="td1",e.TD2="td2",e.PassportAndTD1="passportAndTd1",e.PassportAndTD2="passportAndTd2",e.TD1AndTD2="td1AndTd2",e.All="all"}(E||(E={})),function(e){e.Passport="passport",e.TD1="td1",e.TD2="td2"}(D||(D={})),function(e){e.Scanner="scanner",e.Result="scan-result"}(C||(C={}));const T={[E.Passport]:"ReadPassport",[E.TD1]:"ReadId-TD1",[E.TD2]:"ReadId-TD2",[E.PassportAndTD1]:"ReadPassportAndId-TD1",[E.PassportAndTD2]:"ReadPassportAndId-TD2",[E.TD1AndTD2]:"ReadId",[E.All]:"ReadPassportAndId"};var M;function x(e){if("string"==typeof e){const t=document.querySelector(e);if(!t)throw new Error("Element not found");return t}return e instanceof HTMLElement?e:null}!function(e){e[e.RS_SUCCESS=0]="RS_SUCCESS",e[e.RS_CANCELLED=1]="RS_CANCELLED",e[e.RS_FAILED=2]="RS_FAILED"}(M||(M={}));function b(e,t){if(!document.getElementById(e)){const n=document.createElement("style");n.id=e,n.textContent=t,document.head.appendChild(n)}}const z=e=>!e||0===Object.keys(e).length;function I(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}const V={"4k":{width:3840,height:2160},"2k":{width:2560,height:1440},"1080p":{width:1920,height:1080},"720p":{width:1280,height:720},"480p":{width:640,height:480}};function N(e,t={}){const{message:n,spinnerSize:i=32}=t,s=document.createElement("div");s.className="dynamsoft-mrz-loading-screen";const a=document.createElement("div");a.className="dynamsoft-mrz-loading";const o=document.createElement("div");o.className="dynamsoft-mrz-loading-content";const r=`\n \n \n \n `;if(o.innerHTML=r,n){const e=document.createElement("div");e.className="dynamsoft-mrz-loading-message",e.textContent=n,o.appendChild(e)}return a.appendChild(o),s.appendChild(a),e.appendChild(s),{element:s,updateMessage:e=>{let t=a.querySelector(".dynamsoft-mrz-loading-message");null!==e?t?t.textContent=e:(t=document.createElement("div"),t.className="dynamsoft-mrz-loading-message",t.textContent=e,o.appendChild(t)):null==t||t.remove()},hide:()=>{s&&s.parentNode&&(s.classList.add("fade-out"),setTimeout((()=>{var e;null===(e=s.parentNode)||void 0===e||e.removeChild(s)}),200))}}}const L='\n .dynamsoft-mrz-loading-screen {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: #323234;\n z-index: 998;\n opacity: 1;\n transition: opacity 0.2s ease-out;\n }\n\n .dynamsoft-mrz-loading-screen.fade-out {\n opacity: 0;\n }\n\n .dynamsoft-mrz-loading {\n position: absolute;\n left: 50%;\n top: 50%;\n color: white;\n z-index: 999;\n transform: translate(-50%, -50%);\n }\n\n .dynamsoft-mrz-loading-content {\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 16px;\n }\n\n .dynamsoft-mrz-loading svg {\n animation: spin 1s linear infinite;\n }\n\n .dynamsoft-mrz-loading-message {\n color: white;\n font-family: "Verdana";\n font-size: 14px;\n text-align: center;\n max-width: 200px;\n line-height: 1.4;\n opacity: 0.9;\n }\n\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n';var F;!function(e){e.InvalidFields="invalidFields",e.DocumentType="documentType",e.DocumentNumber="documentNumber",e.MRZText="mrzText",e.FirstName="firstName",e.LastName="lastName",e.Age="age",e.Sex="sex",e.IssuingState="issuingState",e.IssuingStateRaw="issuingStateRaw",e.Nationality="nationality",e.NationalityRaw="nationalityRaw",e.DateOfBirth="dateOfBirth",e.DateOfExpiry="dateOfExpiry"}(F||(F={}));const _={[F.InvalidFields]:"Invalid Fields",[F.DocumentType]:"Document Type",[F.DocumentNumber]:"Document Number",[F.MRZText]:"MRZ Text",[F.FirstName]:"Given Name(s)",[F.LastName]:"Surname",[F.Age]:"Age",[F.Sex]:"Sex",[F.IssuingState]:"Issuing State",[F.IssuingStateRaw]:"Issuing State (Raw Value)",[F.Nationality]:"Nationality",[F.NationalityRaw]:"Nationality State (Raw Value)",[F.DateOfBirth]:"Date Of Birth (YYYY-MM-DD)",[F.DateOfExpiry]:"Date Of Expiry (YYYY-MM-DD)"};function k(e,t,n,i=!1){const s=parseInt(e,10);let a;if(i)a=s>=60?1900+s:2e3+s;else{a=s>(new Date).getFullYear()%100?1900+s:2e3+s}return{year:a,month:parseInt(t,10),day:parseInt(n,10)}}function A(e){const t=e=>{var t;return 1===(null===(t=`${e}`)||void 0===t?void 0:t.length)?`0${e}`:e};return`${null==e?void 0:e.year}-${t(null==e?void 0:e.month)}${(null==e?void 0:e.day)&&`-${t(null==e?void 0:e.day)}`}`}function O(e){return"D<<"===e?"D":e}function P(e,t){const n=[],i=e=>t.getFieldValidationStatus(e)===p.VS_FAILED,s=t.codeType,a=function(e){switch(e){case"MRTD_TD1_ID":return D.TD1;case"MRTD_TD2_ID":case"MRTD_TD2_VISA":case"MRTD_TD2_FRENCH_ID":return D.TD2;case"MRTD_TD3_PASSPORT":case"MRTD_TD3_VISA":return D.Passport;default:throw new Error(`Unknown document type: ${e}`)}}(s),o=function(e){switch(e){case"MRTD_TD1_ID":return"ID (TD1)";case"MRTD_TD2_ID":return"ID (TD2)";case"MRTD_TD2_VISA":return"ID (VISA)";case"MRTD_TD2_FRENCH_ID":return"French ID (TD2)";case"MRTD_TD3_PASSPORT":return"Passport (TD3)";case"MRTD_TD3_VISA":return"Visa (TD3)";default:throw new Error(`Unknown document type: ${e}`)}}(s),r=a===D.Passport&&"MRTD_TD3_PASSPORT"===s?"passportNumber":"documentNumber",l=k(t.getFieldValue("birthYear"),t.getFieldValue("birthMonth"),t.getFieldValue("birthDay")),c=k(t.getFieldValue("expiryYear"),t.getFieldValue("expiryMonth"),t.getFieldValue("expiryDay"),!0);["birthYear","birthMonth","birthDay"].forEach((e=>{i(e)&&n.push(F.DateOfBirth)})),["expiryYear","expiryMonth","expiryDay"].forEach((e=>{i(e)&&n.push(F.DateOfExpiry)}));const d={[F.LastName]:t.getFieldValue("primaryIdentifier"),[F.FirstName]:t.getFieldValue("secondaryIdentifier"),[F.Nationality]:t.getFieldValue("nationality"),[F.NationalityRaw]:O(t.getFieldRawValue("nationality")),[F.DocumentNumber]:t.getFieldValue(r)||t.getFieldValue("longDocumentNumber"),[F.IssuingState]:t.getFieldValue("issuingState"),[F.IssuingStateRaw]:O(t.getFieldRawValue("issuingState")),[F.Sex]:I(t.getFieldValue("sex"))};Object.keys(d).forEach((e=>{let t=!1;switch(e){case F.FirstName:t=i("secondaryIdentifier");break;case F.LastName:t=i("primaryIdentifier");break;case F.DocumentNumber:t=i(r)||i("longDocumentNumber");break;default:t=i(e)}t&&n.push(e)}));const h=function(e){const t=new Date,n=t.getMonth()+1>e.month||t.getMonth()+1===e.month&&t.getDate()>=e.day;return t.getFullYear()-e.year-(n?0:1)}(l);h<1&&n.push(F.Age);return{[F.InvalidFields]:n,[F.FirstName]:d[F.FirstName],[F.LastName]:d[F.LastName],[F.Age]:h,[F.DateOfBirth]:l,[F.Sex]:d[F.Sex],[F.Nationality]:d[F.Nationality],[F.NationalityRaw]:d[F.NationalityRaw],[F.DocumentNumber]:d[F.DocumentNumber],[F.DateOfExpiry]:c,[F.IssuingState]:d[F.IssuingState],[F.IssuingStateRaw]:d[F.IssuingStateRaw],[F.DocumentType]:I(o),[F.MRZText]:e}}const B={[D.TD1]:{width:85.6,height:53.98},[D.TD2]:{width:105,height:74},[D.Passport]:{width:125,height:88}};class j{showScannerLoadingOverlay(e){const t=x(this.config.container);this.loadingScreen=N(t,{message:e}),t.style.display="block",t.style.position="relative"}hideScannerLoadingOverlay(e=!1){this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,e&&(x(this.config.container).style.display="none"))}constructor(e,t){this.resources=e,this.config=t,this.isSoundFeedbackOn=!1,this.scanModeManager={[D.Passport]:!0,[D.TD1]:!0,[D.TD2]:!0},this.currentScanMode=E.All,this.resizeTimer=null,this.capturedResultItems=[],this.originalImageData=null,this.initialized=!1,this.initializedDCE=!1,this.DCE_ELEMENTS={selectCameraBtn:null,uploadImageBtn:null,soundFeedbackBtn:null,closeScannerBtn:null,scanModeSelectContainer:null,passportModeOption:null,td1ModeOption:null,td2ModeOption:null,toast:null},this.loadingScreen=null,this.handleResize=()=>{this.toggleScanGuide(!1),this.resizeTimer&&window.clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout((()=>{this.toggleScanGuide(!0)}),500)}}async initialize(){if(!this.initialized){this.initializeScanModeManager(),this.currentScanMode=this.getScanMode(),b("dynamsoft-mrz-loading-screen-style",L);try{const{cameraView:t,cameraEnhancer:n,cvRouter:i}=this.resources;if(t.setScanRegionMaskStyle({strokeStyle:"transparent",fillStyle:"transparent",lineWidth:0}),t.setVideoFit("cover"),i.setInput(n),await i.initSettings(this.config.templateFilePath),!0===this.config.enableMultiFrameCrossFilter){const t=new S;t.enableResultCrossVerification(e.CRIT_TEXT_LINE,!0),t.enableResultDeduplication(e.CRIT_TEXT_LINE,!0),await i.addResultFilter(t)}const s=new l;s.onCapturedResultReceived=e=>this.handleMRZResult(e),await i.addResultReceiver(s),this.toggleSoundFeedback(!1),!1===this.config.showScanGuide&&this.toggleScanGuide(!1),this.initialized=!0}catch(e){let t=(null==e?void 0:e.message)||e;console.error(t),alert(t),this.closeCamera();const n={status:{code:M.RS_FAILED,message:"Dynamsoft MRZ Scanner initialize error"}};this.currentScanResolver(n)}}}initializeElements(){var e;const t=x(this.config.container),n=t.children[t.children.length-1];if(!(null==n?void 0:n.shadowRoot))throw new Error("Shadow root not found");if(this.DCE_ELEMENTS={selectCameraBtn:n.shadowRoot.querySelector(".dce-mn-select-camera-icon"),uploadImageBtn:n.shadowRoot.querySelector(".dce-mn-upload-image-icon"),soundFeedbackBtn:n.shadowRoot.querySelector(".dce-mn-sound-feedback"),closeScannerBtn:n.shadowRoot.querySelector(".dce-mn-close"),scanModeSelectContainer:n.shadowRoot.querySelector(".dce-mn-scan-mode-select"),passportModeOption:n.shadowRoot.querySelector(".scan-mode-option-passport"),td1ModeOption:n.shadowRoot.querySelector(".scan-mode-option-td1"),td2ModeOption:n.shadowRoot.querySelector(".scan-mode-option-td2"),toast:n.shadowRoot.querySelector(".dce-mn-toast")},this.setupScanModeSelector(),this.assignDCEClickEvents(),this.DCE_ELEMENTS.toast.style.display="none",!1===this.config.showUploadImage&&(this.DCE_ELEMENTS.uploadImageBtn.style.visibility="hidden"),!1===this.config.showSoundToggle&&(this.DCE_ELEMENTS.soundFeedbackBtn.style.visibility="hidden"),!1===(null===(e=this.config)||void 0===e?void 0:e.showPoweredByDynamsoft)){n.shadowRoot.querySelector(".dce-mn-msg-poweredby").style.display="none"}this.initializedDCE=!0}setupScanModeSelector(){if(!1!==this.config.showFormatSelector)switch(this.currentScanMode){case E.PassportAndTD1:this.DCE_ELEMENTS.td2ModeOption.style.display="none";break;case E.PassportAndTD2:this.DCE_ELEMENTS.td1ModeOption.style.display="none";break;case E.TD1AndTD2:this.DCE_ELEMENTS.passportModeOption.style.display="none";break;case E.All:break;default:this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}else this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}assignDCEClickEvents(){if(!Object.values(this.DCE_ELEMENTS).every(Boolean))throw new Error("Camera control elements not found");this.closeCamera=this.closeCamera.bind(this),this.DCE_ELEMENTS.uploadImageBtn.onclick=()=>this.uploadFile(),this.DCE_ELEMENTS.soundFeedbackBtn.onclick=()=>this.toggleSoundFeedback(),this.DCE_ELEMENTS.closeScannerBtn.onclick=()=>this.handleCloseBtn(),this.DCE_ELEMENTS.selectCameraBtn.onclick=e=>{e.stopPropagation(),this.toggleSelectCameraBox()},this.DCE_ELEMENTS.passportModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.passportModeOption.style.display&&await this.toggleScanDocType(D.Passport)},this.DCE_ELEMENTS.td1ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td1ModeOption.style.display&&await this.toggleScanDocType(D.TD1)},this.DCE_ELEMENTS.td2ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td2ModeOption.style.display&&await this.toggleScanDocType(D.TD2)}}handleCloseBtn(){this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:M.RS_CANCELLED,message:"Cancelled"}})}attachOptionClickListeners(){const e=x(this.config.container),t=e.children[e.children.length-1];if(!(null==t?void 0:t.shadowRoot))return;const n=t.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings");[...t.shadowRoot.querySelectorAll(".dce-mn-camera-option"),...t.shadowRoot.querySelectorAll(".dce-mn-resolution-option")].forEach((e=>{e.addEventListener("click",(async t=>{const i=e.getAttribute("data-davice-id"),s=e.getAttribute("data-height"),a=e.getAttribute("data-width");i?this.resources.cameraEnhancer.selectCamera(i).then((()=>{this.toggleScanGuide()})):s&&a&&this.resources.cameraEnhancer.setResolution({width:parseInt(a),height:parseInt(s)}).then((()=>{this.toggleScanGuide()})),"none"!==n.style.display&&this.toggleSelectCameraBox()}))}))}highlightCameraAndResolutionOption(){const e=x(this.config.container),t=e.children[e.children.length-1];if(!(null==t?void 0:t.shadowRoot))return;const n=t.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings"),i=n.querySelectorAll(".dce-mn-camera-option"),s=n.querySelectorAll(".dce-mn-resolution-option"),a=this.resources.cameraEnhancer.getSelectedCamera(),o=this.resources.cameraEnhancer.getResolution();i.forEach((e=>{const t=e;t.getAttribute("data-davice-id")===(null==a?void 0:a.deviceId)?t.style.border="2px solid #fe814a":t.style.border="none"}));const r={"480p":"480","720p":"720","1080p":"1080","2k":"1440","4k":"2160"},l=function(e){const t=e.width*e.height,n=e.width/e.height;let i="480p",s=Number.MAX_VALUE;for(const[e,a]of Object.entries(V)){const o=a.width*a.height,r=a.width/a.height,l=.7*Math.abs(o-t)+Math.abs(r-n)*o*.3;l{const t=e,n=t.getAttribute("data-height");t.style.border=n===r[l]?"2px solid #fe814a":"none"}))}toggleSelectCameraBox(){const e=x(this.config.container),t=e.children[e.children.length-1];if(!(null==t?void 0:t.shadowRoot))return;const n=t.shadowRoot.querySelector(".dce-mn-resolution-box");this.highlightCameraAndResolutionOption(),this.attachOptionClickListeners(),n.click()}async relaunch(){}async uploadFile(){var i,s,a,o;const{cvRouter:r}=this.resources,l=document.createElement("input");l.type="file",l.accept=null!==(i=this.config.uploadAcceptedTypes)&&void 0!==i?i:"image/*",l.style.display="none",document.body.appendChild(l);try{this.showScannerLoadingOverlay("Processing file..."),await this.closeCamera(!1);const i=await new Promise(((e,t)=>{l.onchange=n=>{var i;const s=null===(i=n.target.files)||void 0===i?void 0:i[0];s?e(s):t(new Error("No file selected"))},l.addEventListener("cancel",(async()=>{this.hideScannerLoadingOverlay(!1),await this.openCamera(),await this.startCapturing(),this.toggleScanGuide()})),l.click()}));if(!i)return;let c;if(this.config.uploadFileConverter&&!i.type.startsWith("image/"))try{c=await this.config.uploadFileConverter(i)}catch(e){throw new Error(`Error converting file: ${e.message}`)}else{if(!i.type.startsWith("image/"))throw new Error("Unsupported file type. Please provide a converter function for this file type.");c=i}const d=this.config.utilizedTemplateNames[this.currentScanMode];if(!1!==this.config.showScanGuide){const e=await r.getSimplifiedSettings(d);e.roiMeasuredInPercentage=!0,e.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await r.updateSettings(d,e)}const h=await r.capture(c,d);this.capturedResultItems=h.items;const u=this.capturedResultItems.filter((t=>t.type===e.CRIT_ORIGINAL_IMAGE));if(0===u.length)throw new Error("No image data found in the captured result");const m=u[0].imageData;m.toCanvas=()=>t(m),m.toBlob=async()=>await n("image/png",m),this.originalImageData=m;const g=null==h?void 0:h.textLineResultItems,p=null==h?void 0:h.parsedResultItems;let f={};if(null==g?void 0:g.length){const e=(null===(s=g[0])||void 0===s?void 0:s.text)||"";f=P(e,p[0])}const y={status:{code:M.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,data:f,imageData:!0,_imageData:this.originalImageData};null===(o=(a=this.resources).onResultUpdated)||void 0===o||o.call(a,y),this.currentScanResolver(y)}catch(e){let t=(null==e?void 0:e.message)||e;console.error(t),alert(t),this.closeCamera();const n={status:{code:M.RS_FAILED,message:`Error processing file: ${t}`}};this.currentScanResolver(n)}finally{this.hideScannerLoadingOverlay(!0),document.body.removeChild(l)}}toggleSoundFeedback(e){this.isSoundFeedbackOn=void 0!==e?e:!this.isSoundFeedbackOn;const t=x(this.config.container),n=t.children[t.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const i=n.shadowRoot.querySelector(".dce-mn-sound-feedback"),s=i.querySelector(".dce-mn-sound-feedback-on");i.querySelector(".dce-mn-sound-feedback-off").style.display=this.isSoundFeedbackOn?"none":"block",s.style.display=this.isSoundFeedbackOn?"block":"none"}calculateScanRegion(e){const{cameraEnhancer:t,cameraView:n}=this.resources;if(!t||!t.isOpen())return;const i=n.getVisibleRegionOfVideo({inPixels:!0});if(!i)return;const s=n.getVideoElement(),a=s.videoWidth,o=s.videoHeight,r=B[e];let l;const c=i.height-80;if(i.width>i.height){l=.75*c/r.height;l*r.width>.9*i.width&&(l=.9*i.width/r.width)}else{l=.9*i.width/r.width;l*r.height>.75*c&&(l=.75*c/r.height)}const d=l*r.width,h=l*r.height,u=(i.width-d)/2,m=(c-h)/2,g=u,p=u+d,f=m,y=m+h,w=(i.x+g)/a*100,v=(i.x+p)/a*100,S=(i.y+f)/o*100,R=(i.y+y)/o*100,E={left:Math.round(w),right:Math.round(v),top:Math.round(S),bottom:Math.round(R),isMeasuredInPercentage:!0};null==n||n.setScanRegionMaskVisible(!0),t.setScanRegion(E)}toggleScanGuide(e){const t=x(this.config.container),n=t.children[t.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const i=n.shadowRoot.querySelector(".dce-scanguide-passport"),s=n.shadowRoot.querySelector(".dce-scanguide-td1"),a=n.shadowRoot.querySelector(".dce-scanguide-td2");if(!1===e||!1===this.config.showScanGuide)return i.style.display="none",s.style.display="none",void(a.style.display="none");switch(this.currentScanMode){case E.All:case E.Passport:case E.PassportAndTD1:case E.PassportAndTD2:i.style.display="block",s.style.display="none",a.style.display="none",this.calculateScanRegion(D.Passport);break;case E.TD1:case E.TD1AndTD2:i.style.display="none",s.style.display="block",a.style.display="none",this.calculateScanRegion(D.TD1);break;case E.TD2:i.style.display="none",s.style.display="none",a.style.display="block",this.calculateScanRegion(D.TD2)}}async openCamera(){try{this.showScannerLoadingOverlay("Initializing camera...");const{cameraEnhancer:e,cameraView:t}=this.resources,n=x(this.config.container);if(n.style.display="block",e.isOpen())e.isPaused()&&await e.resume();else{const i=t.getUIElement();i.parentElement||n.append(i),await e.open()}await e.setResolution({width:2560,height:1440}),!this.initializedDCE&&e.isOpen()&&await this.initializeElements(),window.addEventListener("resize",this.handleResize);const i=n.children[n.children.length-1];if(!(null==i?void 0:i.shadowRoot))throw new Error("Shadow root not found");i.shadowRoot.querySelector(".dce-mn-torch-off").style.display="none",i.shadowRoot.querySelector(".dce-mn-torch-on").style.display="none"}catch(e){let t=(null==e?void 0:e.message)||e;console.error(t),alert(t),this.closeCamera();const n={status:{code:M.RS_FAILED,message:"MRZ Scanner Open Camera Error"}};this.currentScanResolver(n)}finally{this.hideScannerLoadingOverlay()}}async closeCamera(e=!0){try{window.removeEventListener("resize",this.handleResize),this.resizeTimer&&(window.clearTimeout(this.resizeTimer),this.resizeTimer=null);const{cameraEnhancer:t,cameraView:n}=this.resources,i=x(this.config.container);i.style.display=e?"none":"block",(null==n?void 0:n.getUIElement().parentElement)&&i.removeChild(n.getUIElement()),t.close(),this.stopCapturing()}catch(e){let t=(null==e?void 0:e.message)||e;console.error(`Close Camera error: ${t}`)}}pauseCamera(){const{cameraEnhancer:e}=this.resources;e.pause()}stopCapturing(){const{cameraView:e,cvRouter:t}=this.resources;t.stopCapturing(),e.clearAllInnerDrawingItems()}async handleMRZResult(i){var s;if(this.capturedResultItems=i.items,!(i.items.length<=1))try{const{onResultUpdated:a}=this.resources,o=i.items.filter((t=>t.type===e.CRIT_ORIGINAL_IMAGE))[0].imageData;o.toCanvas=()=>t(o),o.toBlob=async()=>await n("image/png",o),this.originalImageData=o;const r=null==i?void 0:i.textLineResultItems,l=null==i?void 0:i.parsedResultItems;if(r){this.isSoundFeedbackOn&&h.beep();const e=(null===(s=null==r?void 0:r[0])||void 0===s?void 0:s.text)||"",t=P(e,l[0]);this.closeCamera();const n={status:{code:M.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,data:t,imageData:!0,_imageData:this.originalImageData};null==a||a(n),this.currentScanResolver(n)}}catch(e){let t=(null==e?void 0:e.message)||e;console.error(t),alert(t),this.closeCamera();const n={status:{code:M.RS_FAILED,message:"Error capturing image"}};this.currentScanResolver(n)}}initializeScanModeManager(){const{mrzFormatType:e}=this.config;if(this.scanModeManager={[D.Passport]:!0,[D.TD1]:!0,[D.TD2]:!0},!e||Array.isArray(e)&&0===e.length)return;Object.keys(this.scanModeManager).forEach((e=>{this.scanModeManager[e]=!1}));(Array.isArray(e)?e:[e]).forEach((e=>{this.scanModeManager[e]=!0}))}getScanMode(){const e=Object.entries(this.scanModeManager).filter((([e,t])=>t)).map((([e])=>e)).sort().join(",");return{[D.Passport]:E.Passport,[D.TD1]:E.TD1,[D.TD2]:E.TD2,[`${D.Passport},${D.TD1}`]:E.PassportAndTD1,[`${D.Passport},${D.TD2}`]:E.PassportAndTD2,[`${D.TD1},${D.TD2}`]:E.TD1AndTD2,[`${D.Passport},${D.TD1},${D.TD2}`]:E.All,"":E.All}[e]}DCEShowToast(e,t=3e3){this.DCE_ELEMENTS.toast&&(this.DCE_ELEMENTS.toast.textContent=e,this.DCE_ELEMENTS.toast.style.display="",setTimeout((()=>{this.DCE_ELEMENTS.toast.style.display="none"}),t))}async startCapturing(){const{cvRouter:e,cameraEnhancer:t}=this.resources,n=this.config.utilizedTemplateNames[this.currentScanMode];try{if(!1!==this.config.showScanGuide){const t=await e.getSimplifiedSettings(n);t.roiMeasuredInPercentage=!0,t.roi.points=[{x:0,y:50},{x:100,y:50},{x:100,y:100},{x:0,y:100}],await e.updateSettings(n,t)}await e.startCapturing(n),t.setPixelFormat(i.IPF_ABGR_8888)}catch(e){let t=(null==e?void 0:e.message)||e;console.error("Failed to start capturing:",t),this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:M.RS_FAILED,message:"Failed to start capturing"}})}}async toggleScanDocType(e){try{if(this.scanModeManager[e]&&0===Object.entries(this.scanModeManager).filter((([t,n])=>n&&t!==e)).length)return console.warn("MRZ Scanner - At least one mode must be enabled"),void this.DCEShowToast("At least one mode must be enabled");this.scanModeManager[e]=!this.scanModeManager[e],this.currentScanMode=this.getScanMode(),this.stopCapturing(),await this.startCapturing(),this.toggleScanGuide(),this.DCE_ELEMENTS.td1ModeOption.classList.toggle("selected",this.scanModeManager[D.TD1]),this.DCE_ELEMENTS.td2ModeOption.classList.toggle("selected",this.scanModeManager[D.TD2]),this.DCE_ELEMENTS.passportModeOption.classList.toggle("selected",this.scanModeManager[D.Passport])}catch(e){let t=(null==e?void 0:e.message)||e;console.error("MRZ Scanner switch scan mode error: ",t),this.closeCamera();const n={status:{code:M.RS_FAILED,message:"MRZ Scanner switch scan mode error"}};this.currentScanResolver(n)}}async launch(){try{await this.initialize();const{cvRouter:e,cameraEnhancer:t}=this.resources;return new Promise((async e=>{this.currentScanResolver=e,await this.openCamera(),!this.initializedDCE&&t.isOpen()&&await this.initializeElements(),await this.startCapturing(),this.toggleScanGuide()}))}catch(e){let t=(null==e?void 0:e.message)||e;console.error("MRZ Scanner launch error: ",t),this.closeCamera();const n={status:{code:M.RS_FAILED,message:"MRZ Scanner launch error"}};this.currentScanResolver(n)}}}const $={rescan:'\n\n\n \n\n\n\n\n\n\n\n',complete:'\n\n\n\n \n\n\n\n\n\n\n\n',failed:'\n \n \n \n\n',info:'\n\n \n \n \n\n'};class U{constructor(e,t,n){this.resources=e,this.config=t,this.scannerView=n,this.editedFields={}}async launch(){try{return x(this.config.container).textContent="",await this.initialize(),x(this.config.container).style.display="flex",new Promise((e=>{this.currentScanResultViewResolver=e}))}catch(e){let t=(null==e?void 0:e.message)||e;throw console.error(t),t}}async handleRescan(){var e;try{if(!this.scannerView)return void console.error("Scanner View not initialized");this.hideView();const t=await this.scannerView.launch();if((null===(e=null==t?void 0:t.status)||void 0===e?void 0:e.code)===M.RS_FAILED)return void(this.currentScanResultViewResolver&&this.currentScanResultViewResolver(t));this.resources.onResultUpdated&&((null==t?void 0:t.status.code)===M.RS_CANCELLED?this.resources.onResultUpdated(this.resources.result):(null==t?void 0:t.status.code)===M.RS_SUCCESS&&this.resources.onResultUpdated(t)),this.dispose(!0),await this.initialize(),x(this.config.container).style.display="flex"}catch(e){throw console.error("Error in rescan handler:",e),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:M.RS_FAILED,message:(null==e?void 0:e.message)||e}}),e}}async handleDone(){var e,t;try{(null===(e=this.resources.result)||void 0===e?void 0:e.data)&&!z(this.editedFields)&&(this.resources.result.data=Object.assign(Object.assign({},this.resources.result.data),this.editedFields),this.resources.onResultUpdated&&this.resources.onResultUpdated(this.resources.result)),(null===(t=this.config)||void 0===t?void 0:t.onDone)&&await this.config.onDone(this.resources.result),this.currentScanResultViewResolver&&this.resources.result&&this.currentScanResultViewResolver(this.resources.result),this.hideView(),this.dispose()}catch(e){throw console.error("Error in done handler:",e),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:M.RS_FAILED,message:(null==e?void 0:e.message)||e}}),e}}createControls(){var e,t,n,i,s,a,o,r;const{toolbarButtonsConfig:l}=this.config;return function(e){b("dynamsoft-mrz-controls-style","\n .dynamsoft-mrz-controls {\n display: flex;\n height: 6rem;\n background-color: #323234;\n align-items: center;\n font-size: 12px;\n font-family: Verdana;\n color: white;\n width: 100%;\n }\n\n .dynamsoft-mrz-control-btn {\n background-color: #323234;\n color: white;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n height: 100%;\n width: 100%;\n gap: 0.5rem;\n text-align: center;\n user-select: none;\n }\n\n .dynamsoft-mrz-control-btn.hide {\n display: none;\n }\n\n .dynamsoft-mrz-control-btn.disabled {\n opacity: 0.4;\n pointer-events: none;\n cursor: default;\n }\n\n .dynamsoft-mrz-control-icon-wrapper {\n flex: 0.75;\n display: flex;\n align-items: flex-end;\n justify-content: center;\n min-height: 40px;\n }\n\n .dynamsoft-mrz-control-icon img,\n .dynamsoft-mrz-control-icon svg {\n width: 32px;\n height: 32px;\n fill: #fe8e14;\n }\n\n .dynamsoft-mrz-control-text {\n flex: 0.5;\n display: flex;\n align-items: flex-start;\n justify-content: center;\n padding-bottom: 0.5rem;\n }\n\n \n @media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-controls {\n flex-direction: column;\n height: 100%;\n width: 5rem;\n }\n\n .dynamsoft-mrz-control-text {\n padding: 0 0.5rem 0.5rem;\n }\n }\n");const t=document.createElement("div");return t.className="dynamsoft-mrz-controls",e.forEach((e=>{const n=document.createElement("div");n.className=`dynamsoft-mrz-control-btn ${null==e?void 0:e.className}`;const i=document.createElement("div");if(i.className="dynamsoft-mrz-control-icon-wrapper",(s=e.icon).trim().startsWith(""))i.innerHTML=e.icon;else{const t=document.createElement("img");t.src=e.icon,t.alt=e.label,t.width=24,t.height=24,i.appendChild(t)}var s;const a=document.createElement("div");a.className="dynamsoft-mrz-control-text",a.textContent=e.label,e.isDisabled&&n.classList.add("disabled"),e.isHidden&&n.classList.add("hide"),n.appendChild(i),n.appendChild(a),e.onClick&&!e.isDisabled&&n.addEventListener("click",e.onClick),t.appendChild(n)})),t}([{id:"dynamsoft-mrz-scanResult-rescan",icon:(null===(e=null==l?void 0:l.rescan)||void 0===e?void 0:e.icon)||$.rescan,label:(null===(t=null==l?void 0:l.rescan)||void 0===t?void 0:t.label)||"Re-scan",onClick:()=>this.handleRescan(),className:`${(null===(n=null==l?void 0:l.rescan)||void 0===n?void 0:n.className)||""}`,isHidden:(null===(i=null==l?void 0:l.rescan)||void 0===i?void 0:i.isHidden)||!1,isDisabled:!this.scannerView},{id:"dynamsoft-mrz-scanResult-done",icon:(null===(s=null==l?void 0:l.done)||void 0===s?void 0:s.icon)||$.complete,label:(null===(a=null==l?void 0:l.done)||void 0===a?void 0:a.label)||"Done",className:`${(null===(o=null==l?void 0:l.done)||void 0===o?void 0:o.className)||""}`,isHidden:(null===(r=null==l?void 0:l.done)||void 0===r?void 0:r.isHidden)||!1,onClick:()=>this.handleDone()}])}handleFieldEdit(e,t){if(e===F.DateOfBirth||e===F.DateOfExpiry)try{const[n,i,s]=t.split(/[\/\-\.]/);s&&i&&n&&(this.editedFields[e]={day:parseInt(s,10),month:parseInt(i,10),year:parseInt(n,10)})}catch(e){console.error("Error parsing date",e)}else this.editedFields[e]=t}createMRZDataDisplay(){var e;const t=(null===(e=this.resources.result)||void 0===e?void 0:e.data)||{},n=!!this.config.allowResultEditing,i=t.invalidFields||[],s=document.createElement("div");if(s.className="dynamsoft-mrz-data-container",z(t)){const e=document.createElement("div");return e.className="dynamsoft-mrz-data-row empty",e.innerText="No MRZ detected. Please try again.",s.appendChild(e),s}if(i.length>0){const e=document.createElement("div");e.className="dynamsoft-mrz-error-notification",e.innerHTML=`\n
${$.failed}
\n
\n ${n?"Some fields require correction. Please review highlighted fields.":"Some fields contain invalid information. Please rescan the document."}\n
\n `,s.appendChild(e)}else if(0===i.length&&n){const e=document.createElement("div");e.className="dynamsoft-mrz-info-notification",e.innerHTML=`\n
${$.info}
\n
\n Please review all fields to ensure the information is correct.\n
\n `,s.appendChild(e)}return Object.entries(t).forEach((([e,t])=>{var a;if(e===F.InvalidFields||!t)return;if(e===F.MRZText&&!1===(null===(a=this.config)||void 0===a?void 0:a.showMRZText))return;const o=document.createElement("div");o.className="dynamsoft-mrz-data-row";const r=i.includes(e);r&&o.classList.add("invalid-field");const l=[F.MRZText,F.DocumentType,F.IssuingStateRaw,F.NationalityRaw],c=document.createElement("span");if(c.className="dynamsoft-mrz-data-label",c.innerText=_[e]||e,r){const e=document.createElement("span");if(e.className="dynamsoft-mrz-error-icon",e.innerHTML=$.failed,c.appendChild(e),n){const e=document.createElement("span");e.className="dynamsoft-mrz-error-hint",e.textContent="Please correct this field",c.appendChild(e)}}const d=document.createElement("div");if(d.className="dynamsoft-mrz-data-value",n&&!l.includes(e)){const n=document.createElement("input");n.className="dynamsoft-mrz-data-input",r&&n.classList.add("invalid"),e===F.DateOfBirth||e===F.DateOfExpiry?(n.value=A(t),n.setAttribute("placeholder","YYYY-MM-DD")):n.value=t,n.addEventListener("input",(t=>{if(this.handleFieldEdit(e,t.target.value),r){n.classList.remove("invalid"),o.classList.remove("invalid-field"),this.editedFields.invalidFields||(this.editedFields.invalidFields=[...i]);const t=this.editedFields.invalidFields.indexOf(e);t>-1&&this.editedFields.invalidFields.splice(t,1)}})),d.appendChild(n)}else e===F.MRZText?(d.classList.add("code"),d.innerText=t):e===F.DateOfBirth||e===F.DateOfExpiry?d.innerText=A(t):d.innerText=t,r&&d.classList.add("invalid-value");o.appendChild(c),o.appendChild(d),s.appendChild(o)})),s}async initialize(){try{if(!this.resources.result)throw Error("Captured image is missing. Please capture an image first!");if(!this.config.container)throw new Error("Please create a Scan Result View Container element");b("dynamsoft-mrz-result-view-style",Z);const e=document.createElement("div");if(e.className="dynamsoft-mrz-result-view-container",!1!==this.config.showOriginalImage){const t=this.resources.result.originalImageResult,n=document.createElement("div");let i;n.className="dynamsoft-mrz-result-view-image-container",(null==t?void 0:t.toCanvas)&&(i=null==t?void 0:t.toCanvas()),Object.assign(i.style,{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}),n.appendChild(i),e.appendChild(n)}const t=this.createMRZDataDisplay();e.appendChild(t);const n=this.createControls();e.appendChild(n),x(this.config.container).appendChild(e)}catch(e){let t=(null==e?void 0:e.message)||e;console.error(t),alert(t)}}hideView(){x(this.config.container).style.display="none"}dispose(e=!1){x(this.config.container).textContent="",e||(this.currentScanResultViewResolver=void 0)}}const Z="\n .dynamsoft-mrz-result-view-container {\n display: flex;\n width: 100%;\n height: 100%;\n background-color:#575757;\n font-size: 12px;\n flex-direction: column;\n align-items: center;\n }\n\n .dynamsoft-mrz-result-view-image-container {\n width: 100%;\n height: 200px;\n display: flex;\n justify-content: center;\n align-items: center;\n background-color: #323234;\n }\n\n \n.dynamsoft-mrz-data-container {\n font-size: 16px;\n font-family: Verdana;\n color: white;\n overflow: auto;\n width: 100%;\n height: 100%;\n min-height: 0;\n margin: 1rem 0;\n}\n\n.dynamsoft-mrz-data-row {\n padding: 0.5rem 2rem;\n display: flex;\n flex-direction: column;\n gap: 0.5rem;\n transition: background-color 0.3s ease;\n}\n\n.dynamsoft-mrz-data-row.invalid-field {\n background-color: rgba(231, 76, 60, 0.1);\n border-left: 3px solid #e74c3c;\n padding-left: calc(2rem - 3px);\n}\n\n.dynamsoft-mrz-data-label {\n color: #aaa;\n display: flex;\n gap: 0.5rem;\n align-items: end;\n flex-wrap: wrap;\n}\n\n.dynamsoft-mrz-error-notification,\n.dynamsoft-mrz-info-notification {\n color: white;\n padding: 1rem;\n margin: 0.5rem 2rem;\n border-radius: 4px;\n display: flex;\n align-items: center;\n gap: 1rem;\n text-align: start;\n}\n\n.dynamsoft-mrz-error-notification {\n background-color: rgba(231, 76, 60, 0.2);\n}\n\n.dynamsoft-mrz-info-notification {\n background-color: rgba(196, 231, 60, 0.2);\n}\n\n.dynamsoft-mrz-edit-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #aaa;\n}\n\n.dynamsoft-mrz-error-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-info-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: white;\n}\n\n.dynamsoft-mrz-info-message,\n.dynamsoft-mrz-error-message {\n flex: 1;\n}\n\n.dynamsoft-mrz-error-hint {\n font-size: 0.8rem;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-value {\n word-wrap: break-word;\n text-align: start;\n}\n\n.dynamsoft-mrz-data-value.code {\n font-family: monospace;\n}\n\n.dynamsoft-mrz-data-value.invalid-value {\n color: #e74c3c;\n text-decoration: wavy underline #e74c3c;\n text-decoration-skip-ink: none;\n}\n\n.dynamsoft-mrz-data-input {\n width: 100%;\n padding: 5px;\n background-color: rgba(255, 255, 255, 0.1);\n border: 1px solid rgba(255, 255, 255, 0.3);\n color: white;\n border-radius: 4px;\n font-size: 14px;\n transition: all 0.3s ease;\n}\n\n.dynamsoft-mrz-data-input.invalid {\n background-color: rgba(231, 76, 60, 0.1);\n border-color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-input:focus {\n background-color: rgba(255, 255, 255, 0.2);\n border-color: #fe8e14;\n outline: none;\n}\n\n@media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-result-view-container {\n flex-direction: row;\n }\n\n .dynamsoft-mrz-result-view-image-container{\n flex: 1;\n height: 100%;\n }\n\n .dynamsoft-mrz-data-container{\n flex: 1;\n }\n\n .dynamsoft-mrz-data-row:first-of-type {\n padding-top: 2rem;\n }\n\n .dynamsoft-mrz-data-row:last-of-type {\n padding-bottom: 2rem;\n }\n\n .dynamsoft-mrz-data-row.empty {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n padding-top: 0;\n padding-bottom: 0;\n }\n}\n",q={rootDirectory:"https://cdn.jsdelivr.net/npm/"};class G{showLoadingOverlay(e){var t,n;const i=x(null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)||x(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container);this.loadingScreen=N(i,{message:e}),i.style.display="block",i.style.position="relative"}hideLoadingOverlay(e=!1){var t,n,i;const s=x(null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)||x(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container);this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,s.style.display="none",e&&(null===(i=this.config)||void 0===i?void 0:i.container)&&(x(this.config.container).style.display="none"))}constructor(e){this.config=e,this.resources={},this.isInitialized=!1,this.isCapturing=!1,this.loadingScreen=null}async initialize(){if(this.isInitialized)return{resources:this.resources,components:{scannerView:this.scannerView,resultView:this.resultView}};try{if(!this.initializeMRZScannerConfig())return console.error("Failed to initialize mrz scanner config"),{resources:this.resources,components:{}};b("dynamsoft-mrz-loading-screen-style",L),this.showLoadingOverlay("Loading...");if(!await this.initializeDCVResources())return this.hideLoadingOverlay(!0),console.error("Failed to initialize DCV resources"),{resources:this.resources,components:{}};this.resources.onResultUpdated=e=>{this.resources.result=e};const e={};return this.config.scannerViewConfig&&(this.scannerView=new j(this.resources,this.config.scannerViewConfig),e.scannerView=this.scannerView,await this.scannerView.initialize()),this.config.resultViewConfig&&(this.resultView=new U(this.resources,this.config.resultViewConfig,this.scannerView),e.resultView=this.resultView),this.isInitialized=!0,{resources:this.resources,components:e}}catch(e){this.isInitialized=!1;const t=`Initialization Failed: ${(null==e?void 0:e.message)||e}`;return console.error(t),{resources:this.resources,components:{}}}finally{this.hideLoadingOverlay(!0)}}async initializeDCVResources(){var e,t,n;try{return s.engineResourcePaths=z(null===(e=this.config)||void 0===e?void 0:e.engineResourcePaths)?q:this.config.engineResourcePaths,o._onAuthMessage=e=>e.replace("(https://www.dynamsoft.com/customer/license/trialLicense?product=unknown&deploymenttype=unknown)","(https://www.dynamsoft.com/customer/license/trialLicense?product=mrz&deploymenttype=web)"),await o.initLicense((null===(t=this.config)||void 0===t?void 0:t.license)||"",{executeNow:!0}),s.loadWasm(["DLR","DCP"]),f.loadSpec("MRTD_TD3_PASSPORT"),f.loadSpec("MRTD_TD1_ID"),f.loadSpec("MRTD_TD2_ID"),w.loadRecognitionData("MRZ"),this.resources.cameraView=await u.createInstance(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.cameraEnhancerUIPath),this.resources.cameraEnhancer=await m.createInstance(this.resources.cameraView),this.resources.cvRouter=await c.createInstance(),!0}catch(e){let t=(null==e?void 0:e.message)||e;if(null==t?void 0:t.toLowerCase().includes("license")){const e="The MRZ Scanner license is invalid or has expired. Please contact the site administrator to resolve this issue.";alert(e),console.error(e)}else{const e=`Resource Initialization Failed: ${t}`;alert(e),console.error(e)}return!1}}shouldCreateDefaultContainer(){var e,t;const n=!this.config.container,i=!((null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)||(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container));return n&&i}createDefaultMRZScannerContainer(){const e=document.createElement("div");return e.className="mrz-scanner-main-container",Object.assign(e.style,{height:"100dvh",width:"100%",position:"absolute",left:"0",top:"0",zIndex:"999"}),document.body.append(e),e}checkForTemporaryLicense(e){return!(null==e?void 0:e.length)||(null==e?void 0:e.startsWith("A"))||(null==e?void 0:e.startsWith("L"))||(null==e?void 0:e.startsWith("P"))||(null==e?void 0:e.startsWith("Y"))?"DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9":e}validateViewConfigs(){var e,t,n,i,s,a,o,r;if(!this.config.container){if((null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)&&this.config.showResultView&&!(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container)){const e="MRZResultView container is required when showResultView is true";return alert(e),console.error(e),!1}if(!(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)&&(null===(i=this.config.resultViewConfig)||void 0===i?void 0:i.container)&&!this.resources.result){const e="Result is needed to create MRZResultView without a scanner view";return alert(e),console.error(e),!1}}try{if(this.config.container&&!x(this.config.container)){const e="Invalid main container reference";return alert(e),console.error(e),!1}if((null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.container)&&!x(null===(a=this.config.scannerViewConfig)||void 0===a?void 0:a.container)){const e="Invalid scanner view container reference";return alert(e),console.error(e),!1}if((null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)&&!x(null===(r=this.config.resultViewConfig)||void 0===r?void 0:r.container)){const e="Invalid result view container reference";return alert(e),console.error(e),!1}}catch(e){const t=`Error accessing container references: ${e.message}`;return alert(t),console.error(t),!1}return!0}showResultView(){var e,t;return!1!==this.config.showResultView&&(this.config.container?!(void 0!==this.config.showResultView||!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container)&&!this.config.container)||!!this.config.showResultView:this.config.showResultView&&!!(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container))}initializeMRZScannerConfig(){var e,t,n,i,s,a,o;this.config=null!==(e=this.config)&&void 0!==e?e:{};if(!this.validateViewConfigs())return!1;this.shouldCreateDefaultContainer()?this.config.container=this.createDefaultMRZScannerContainer():this.config.container&&(this.config.container=x(this.config.container));const r=this.config.container?this.createViewContainers(x(this.config.container)):{},l={license:this.checkForTemporaryLicense(this.config.license),utilizedTemplateNames:Object.fromEntries(Object.values(E).map((e=>{var t;return[e,(null===(t=this.config.utilizedTemplateNames)||void 0===t?void 0:t[e])||T[e]]}))),templateFilePath:(null===(t=this.config)||void 0===t?void 0:t.templateFilePath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.1.0-beta.0514202501/dist/mrz-scanner.template.json"},c=Object.assign(Object.assign({},this.config.scannerViewConfig),{container:r[C.Scanner]||x(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)||null,cameraEnhancerUIPath:(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.cameraEnhancerUIPath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.1.0-beta.0514202501/dist/mrz-scanner.ui.html",templateFilePath:l.templateFilePath,utilizedTemplateNames:l.utilizedTemplateNames,enableMultiFrameCrossFilter:null===(a=null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.enableMultiFrameCrossFilter)||void 0===a||a,mrzFormatType:this.config.mrzFormatType}),d=this.showResultView()?Object.assign(Object.assign({},this.config.resultViewConfig),{container:r[C.Result]||x(null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)||null}):void 0;return Object.assign(this.config,Object.assign(Object.assign({},l),{scannerViewConfig:c,resultViewConfig:d})),!0}createViewContainers(e){e.textContent="";const t=[C.Scanner];return this.showResultView()&&t.push(C.Result),t.reduce(((t,n)=>{const i=document.createElement("div");return i.className=`mrz-scanner-${n}-view-container`,Object.assign(i.style,{height:"100%",width:"100%",display:"none",position:"relative"}),e.append(i),t[n]=i,t}),{})}dispose(){var e,t;this.resultView&&(this.resultView.dispose(),this.resultView=null),this.scannerView=null,this.resources.cameraEnhancer&&(this.resources.cameraEnhancer.dispose(),this.resources.cameraEnhancer=null),this.resources.cameraView&&(this.resources.cameraView.dispose(),this.resources.cameraView=null),this.resources.cvRouter&&(this.resources.cvRouter.dispose(),this.resources.cvRouter=null),this.resources.result=null,this.resources.onResultUpdated=null;const n=e=>{const t=x(e);t&&(t.style.display="none",t.textContent="")};n(this.config.container),n(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container),n(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container),this.isInitialized=!1}async processUploadedFile(i){var s,a,o,r;try{this.showLoadingOverlay("Processing File...");const{cvRouter:l}=this.resources,c=null===(s=this.config.utilizedTemplateNames)||void 0===s?void 0:s.all,d=await l.getSimplifiedSettings(c);d.roiMeasuredInPercentage=!0,d.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await l.updateSettings(c,d);const h=await l.capture(i,c),u=h.items,m=u.filter((t=>t.type===e.CRIT_ORIGINAL_IMAGE))[0].imageData;m.toCanvas=()=>t(m),m.toBlob=async()=>await n("image/png",m);const g=null==h?void 0:h.textLineResultItems,p=null==h?void 0:h.parsedResultItems;let f={};if(null==g?void 0:g.length){const e=(null===(a=g[0])||void 0===a?void 0:a.text)||"";f=P(e,p[0])}const y={status:{code:M.RS_SUCCESS,message:"Success"},originalImageResult:m,data:f,imageData:!0,_imageData:m};null===(r=(o=this.resources).onResultUpdated)||void 0===r||r.call(o,y)}catch(e){return console.error("Failed to process uploaded file:",e),{status:{code:M.RS_FAILED,message:`Failed to process image: ${e.message||e}`}}}finally{this.hideLoadingOverlay(!1)}}async launch(e){if(this.isCapturing)throw new Error("Capture session already in progress");try{this.isCapturing=!0;const{components:t}=await this.initialize();if(z(t))throw new Error("MRZ Scanner initialization failed.");if(this.config.container&&(x(this.config.container).style.display="block"),e&&(t.scannerView=null,await this.processUploadedFile(e)),!t.scannerView&&this.resources.result&&t.resultView)return await t.resultView.launch();if(!t.scannerView&&!this.resources.result)throw new Error("Scanner view is required when no previous result exists");if(t.scannerView){const e=await t.scannerView.launch();if((null==e?void 0:e.status.code)!==M.RS_SUCCESS)return{status:{code:null==e?void 0:e.status.code,message:(null==e?void 0:e.status.message)||"Failed to capture image"}};if(t.resultView)return await t.resultView.launch()}return this.resources.result}catch(e){return alert((null==e?void 0:e.message)||e),console.error((null==e?void 0:e.message)||e),{status:{code:M.RS_FAILED,message:(null==e?void 0:e.message)||e}}}finally{this.isCapturing=!1,this.dispose()}}}const H={MRZScanner:G,MRZScannerView:j,MRZResultView:U};export{T as DEFAULT_TEMPLATE_NAMES,H as DynamsoftMRZScanner,F as EnumMRZData,D as EnumMRZDocumentType,E as EnumMRZScanMode,C as EnumMRZScannerViews,M as EnumResultStatus,_ as MRZDataLabel,U as MRZResultView,G as MRZScanner,j as MRZScannerView,A as displayMRZDate}; diff --git a/dist/mrz-scanner.no-content-bundle.esm.js b/dist/mrz-scanner.no-content-bundle.esm.js index 8ed0b3b..e53f642 100644 --- a/dist/mrz-scanner.no-content-bundle.esm.js +++ b/dist/mrz-scanner.no-content-bundle.esm.js @@ -1 +1 @@ -import{EnumCapturedResultItemType as e,EnumImagePixelFormat as n,CoreModule as t}from"dynamsoft-core";export*from"dynamsoft-core";import{LicenseManager as i}from"dynamsoft-license";export*from"dynamsoft-license";import{CapturedResultReceiver as s,CaptureVisionRouter as a}from"dynamsoft-capture-vision-router";export*from"dynamsoft-capture-vision-router";import{Feedback as o,CameraView as r,CameraEnhancer as l}from"dynamsoft-camera-enhancer";export*from"dynamsoft-camera-enhancer";import{LabelRecognizerModule as c}from"dynamsoft-label-recognizer";export*from"dynamsoft-label-recognizer";import{EnumValidationStatus as d,CodeParserModule as h}from"dynamsoft-code-parser";export*from"dynamsoft-code-parser";import{MultiFrameResultCrossFilter as u}from"dynamsoft-utility";export*from"dynamsoft-utility";var m,g,p;!function(e){e.Passport="passport",e.TD1="td1",e.TD2="td2",e.PassportAndTD1="passportAndTd1",e.PassportAndTD2="passportAndTd2",e.TD1AndTD2="td1AndTd2",e.All="all"}(m||(m={})),function(e){e.Passport="passport",e.TD1="td1",e.TD2="td2"}(g||(g={})),function(e){e.Scanner="scanner",e.Result="scan-result"}(p||(p={}));const f={[m.Passport]:"ReadPassport",[m.TD1]:"ReadId-TD1",[m.TD2]:"ReadId-TD2",[m.PassportAndTD1]:"ReadPassportAndId-TD1",[m.PassportAndTD2]:"ReadPassportAndId-TD2",[m.TD1AndTD2]:"ReadId",[m.All]:"ReadPassportAndId"};var y;function w(e){if("string"==typeof e){const n=document.querySelector(e);if(!n)throw new Error("Element not found");return n}return e instanceof HTMLElement?e:null}!function(e){e[e.RS_SUCCESS=0]="RS_SUCCESS",e[e.RS_CANCELLED=1]="RS_CANCELLED",e[e.RS_FAILED=2]="RS_FAILED"}(y||(y={}));function v(e,n){if(!document.getElementById(e)){const t=document.createElement("style");t.id=e,t.textContent=n,document.head.appendChild(t)}}const S=e=>!e||0===Object.keys(e).length;function E(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}const D={"4k":{width:3840,height:2160},"2k":{width:2560,height:1440},"1080p":{width:1920,height:1080},"720p":{width:1280,height:720},"480p":{width:640,height:480}};function R(e,n={}){const{message:t,spinnerSize:i=32}=n,s=document.createElement("div");s.className="dynamsoft-mrz-loading-screen";const a=document.createElement("div");a.className="dynamsoft-mrz-loading";const o=document.createElement("div");o.className="dynamsoft-mrz-loading-content";const r=`\n \n \n \n `;if(o.innerHTML=r,t){const e=document.createElement("div");e.className="dynamsoft-mrz-loading-message",e.textContent=t,o.appendChild(e)}return a.appendChild(o),s.appendChild(a),e.appendChild(s),{element:s,updateMessage:e=>{let n=a.querySelector(".dynamsoft-mrz-loading-message");null!==e?n?n.textContent=e:(n=document.createElement("div"),n.className="dynamsoft-mrz-loading-message",n.textContent=e,o.appendChild(n)):null==n||n.remove()},hide:()=>{s&&s.parentNode&&(s.classList.add("fade-out"),setTimeout((()=>{var e;null===(e=s.parentNode)||void 0===e||e.removeChild(s)}),200))}}}const C='\n .dynamsoft-mrz-loading-screen {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: #323234;\n z-index: 998;\n opacity: 1;\n transition: opacity 0.2s ease-out;\n }\n\n .dynamsoft-mrz-loading-screen.fade-out {\n opacity: 0;\n }\n\n .dynamsoft-mrz-loading {\n position: absolute;\n left: 50%;\n top: 50%;\n color: white;\n z-index: 999;\n transform: translate(-50%, -50%);\n }\n\n .dynamsoft-mrz-loading-content {\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 16px;\n }\n\n .dynamsoft-mrz-loading svg {\n animation: spin 1s linear infinite;\n }\n\n .dynamsoft-mrz-loading-message {\n color: white;\n font-family: "Verdana";\n font-size: 14px;\n text-align: center;\n max-width: 200px;\n line-height: 1.4;\n opacity: 0.9;\n }\n\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n';var T;!function(e){e.InvalidFields="invalidFields",e.DocumentType="documentType",e.DocumentNumber="documentNumber",e.MRZText="mrzText",e.FirstName="firstName",e.LastName="lastName",e.Age="age",e.Sex="sex",e.IssuingState="issuingState",e.Nationality="nationality",e.DateOfBirth="dateOfBirth",e.DateOfExpiry="dateOfExpiry"}(T||(T={}));const M={[T.InvalidFields]:"Invalid Fields",[T.DocumentType]:"Document Type",[T.DocumentNumber]:"Document Number",[T.MRZText]:"MRZ Text",[T.FirstName]:"Given Name(s)",[T.LastName]:"Surname",[T.Age]:"Age",[T.Sex]:"Sex",[T.IssuingState]:"Issuing State",[T.Nationality]:"Nationality",[T.DateOfBirth]:"Date Of Birth (YYYY-MM-DD)",[T.DateOfExpiry]:"Date Of Expiry (YYYY-MM-DD)"};function x(e,n,t,i=!1){const s=parseInt(e,10);let a;if(i)a=s>=60?1900+s:2e3+s;else{a=s>(new Date).getFullYear()%100?1900+s:2e3+s}return{year:a,month:parseInt(n,10),day:parseInt(t,10)}}function b(e){const n=e=>{var n;return 1===(null===(n=`${e}`)||void 0===n?void 0:n.length)?`0${e}`:e};return`${null==e?void 0:e.year}-${n(null==e?void 0:e.month)}${(null==e?void 0:e.day)&&`-${n(null==e?void 0:e.day)}`}`}function z(e,n){const t=[],i=e=>n.getFieldValidationStatus(e)===d.VS_FAILED,s=n.codeType,a=function(e){switch(e){case"MRTD_TD1_ID":return g.TD1;case"MRTD_TD2_ID":case"MRTD_TD2_VISA":case"MRTD_TD2_FRENCH_ID":return g.TD2;case"MRTD_TD3_PASSPORT":case"MRTD_TD3_VISA":return g.Passport;default:throw new Error(`Unknown document type: ${e}`)}}(s),o=function(e){switch(e){case"MRTD_TD1_ID":return"ID (TD1)";case"MRTD_TD2_ID":return"ID (TD2)";case"MRTD_TD2_VISA":return"ID (VISA)";case"MRTD_TD2_FRENCH_ID":return"French ID (TD2)";case"MRTD_TD3_PASSPORT":return"Passport (TD3)";case"MRTD_TD3_VISA":return"Visa (TD3)";default:throw new Error(`Unknown document type: ${e}`)}}(s),r=a===g.Passport&&"MRTD_TD3_PASSPORT"===s?"passportNumber":"documentNumber",l=x(n.getFieldValue("birthYear"),n.getFieldValue("birthMonth"),n.getFieldValue("birthDay")),c=x(n.getFieldValue("expiryYear"),n.getFieldValue("expiryMonth"),n.getFieldValue("expiryDay"),!0);["birthYear","birthMonth","birthDay"].forEach((e=>{i(e)&&t.push(T.DateOfBirth)})),["expiryYear","expiryMonth","expiryDay"].forEach((e=>{i(e)&&t.push(T.DateOfExpiry)}));const h={[T.LastName]:n.getFieldValue("primaryIdentifier"),[T.FirstName]:n.getFieldValue("secondaryIdentifier"),[T.Nationality]:n.getFieldRawValue("nationality"),[T.DocumentNumber]:n.getFieldValue(r)||n.getFieldValue("longDocumentNumber"),[T.IssuingState]:n.getFieldRawValue("issuingState"),[T.Sex]:E(n.getFieldValue("sex"))};Object.keys(h).forEach((e=>{let n=!1;switch(e){case T.FirstName:n=i("secondaryIdentifier");break;case T.LastName:n=i("primaryIdentifier");break;case T.DocumentNumber:n=i(r)||i("longDocumentNumber");break;default:n=i(e)}n&&t.push(e)}));const u=function(e){const n=new Date,t=n.getMonth()+1>e.month||n.getMonth()+1===e.month&&n.getDate()>=e.day;return n.getFullYear()-e.year-(t?0:1)}(l);u<1&&t.push(T.Age);return{[T.InvalidFields]:t,[T.FirstName]:h[T.FirstName],[T.LastName]:h[T.LastName],[T.Age]:u,[T.DateOfBirth]:l,[T.Sex]:h[T.Sex],[T.Nationality]:h[T.Nationality],[T.DocumentNumber]:h[T.DocumentNumber],[T.DateOfExpiry]:c,[T.IssuingState]:h[T.IssuingState],[T.DocumentType]:E(o),[T.MRZText]:e}}const V={[g.TD1]:{width:85.6,height:53.98},[g.TD2]:{width:105,height:74},[g.Passport]:{width:125,height:88}};class I{showScannerLoadingOverlay(e){const n=w(this.config.container);this.loadingScreen=R(n,{message:e}),n.style.display="block",n.style.position="relative"}hideScannerLoadingOverlay(e=!1){this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,e&&(w(this.config.container).style.display="none"))}constructor(e,n){this.resources=e,this.config=n,this.isSoundFeedbackOn=!1,this.scanModeManager={[g.Passport]:!0,[g.TD1]:!0,[g.TD2]:!0},this.currentScanMode=m.All,this.resizeTimer=null,this.capturedResultItems=[],this.originalImageData=null,this.initialized=!1,this.initializedDCE=!1,this.DCE_ELEMENTS={selectCameraBtn:null,uploadImageBtn:null,soundFeedbackBtn:null,closeScannerBtn:null,scanModeSelectContainer:null,passportModeOption:null,td1ModeOption:null,td2ModeOption:null,toast:null},this.loadingScreen=null,this.handleResize=()=>{this.toggleScanGuide(!1),this.resizeTimer&&window.clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout((()=>{this.toggleScanGuide(!0)}),500)}}async initialize(){if(!this.initialized){this.initializeScanModeManager(),this.currentScanMode=this.getScanMode(),v("dynamsoft-mrz-loading-screen-style",C);try{const{cameraView:n,cameraEnhancer:t,cvRouter:i}=this.resources;if(n.setScanRegionMaskStyle({strokeStyle:"transparent",fillStyle:"transparent",lineWidth:0}),n.setVideoFit("cover"),i.setInput(t),await i.initSettings(this.config.templateFilePath),!0===this.config.enableMultiFrameCrossFilter){const n=new u;n.enableResultCrossVerification(e.CRIT_TEXT_LINE,!0),n.enableResultDeduplication(e.CRIT_TEXT_LINE,!0),await i.addResultFilter(n)}const a=new s;a.onCapturedResultReceived=e=>this.handleMRZResult(e),await i.addResultReceiver(a),this.toggleSoundFeedback(!1),!1===this.config.showScanGuide&&this.toggleScanGuide(!1),this.initialized=!0}catch(e){let n=(null==e?void 0:e.message)||e;console.error(n),alert(n),this.closeCamera();const t={status:{code:y.RS_FAILED,message:"Dynamsoft MRZ Scanner initialize error"}};this.currentScanResolver(t)}}}initializeElements(){const e=w(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))throw new Error("Shadow root not found");this.DCE_ELEMENTS={selectCameraBtn:n.shadowRoot.querySelector(".dce-mn-select-camera-icon"),uploadImageBtn:n.shadowRoot.querySelector(".dce-mn-upload-image-icon"),soundFeedbackBtn:n.shadowRoot.querySelector(".dce-mn-sound-feedback"),closeScannerBtn:n.shadowRoot.querySelector(".dce-mn-close"),scanModeSelectContainer:n.shadowRoot.querySelector(".dce-mn-scan-mode-select"),passportModeOption:n.shadowRoot.querySelector(".scan-mode-option-passport"),td1ModeOption:n.shadowRoot.querySelector(".scan-mode-option-td1"),td2ModeOption:n.shadowRoot.querySelector(".scan-mode-option-td2"),toast:n.shadowRoot.querySelector(".dce-mn-toast")},this.setupScanModeSelector(),this.assignDCEClickEvents(),this.DCE_ELEMENTS.toast.style.display="none",!1===this.config.showUploadImage&&(this.DCE_ELEMENTS.uploadImageBtn.style.display="none"),!1===this.config.showSoundToggle&&(this.DCE_ELEMENTS.soundFeedbackBtn.style.display="none"),this.initializedDCE=!0}setupScanModeSelector(){if(!1!==this.config.showFormatSelector)switch(this.currentScanMode){case m.PassportAndTD1:this.DCE_ELEMENTS.td2ModeOption.style.display="none";break;case m.PassportAndTD2:this.DCE_ELEMENTS.td1ModeOption.style.display="none";break;case m.TD1AndTD2:this.DCE_ELEMENTS.passportModeOption.style.display="none";break;case m.All:break;default:this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}else this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}assignDCEClickEvents(){if(!Object.values(this.DCE_ELEMENTS).every(Boolean))throw new Error("Camera control elements not found");this.closeCamera=this.closeCamera.bind(this),this.DCE_ELEMENTS.uploadImageBtn.onclick=()=>this.uploadImage(),this.DCE_ELEMENTS.soundFeedbackBtn.onclick=()=>this.toggleSoundFeedback(),this.DCE_ELEMENTS.closeScannerBtn.onclick=()=>this.handleCloseBtn(),this.DCE_ELEMENTS.selectCameraBtn.onclick=e=>{e.stopPropagation(),this.toggleSelectCameraBox()},this.DCE_ELEMENTS.passportModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.passportModeOption.style.display&&await this.toggleScanDocType(g.Passport)},this.DCE_ELEMENTS.td1ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td1ModeOption.style.display&&await this.toggleScanDocType(g.TD1)},this.DCE_ELEMENTS.td2ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td2ModeOption.style.display&&await this.toggleScanDocType(g.TD2)}}handleCloseBtn(){this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:y.RS_CANCELLED,message:"Cancelled"}})}attachOptionClickListeners(){const e=w(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const t=n.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings");[...n.shadowRoot.querySelectorAll(".dce-mn-camera-option"),...n.shadowRoot.querySelectorAll(".dce-mn-resolution-option")].forEach((e=>{e.addEventListener("click",(async n=>{const i=e.getAttribute("data-davice-id"),s=e.getAttribute("data-height"),a=e.getAttribute("data-width");i?this.resources.cameraEnhancer.selectCamera(i).then((()=>{this.toggleScanGuide()})):s&&a&&this.resources.cameraEnhancer.setResolution({width:parseInt(a),height:parseInt(s)}).then((()=>{this.toggleScanGuide()})),"none"!==t.style.display&&this.toggleSelectCameraBox()}))}))}highlightCameraAndResolutionOption(){const e=w(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const t=n.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings"),i=t.querySelectorAll(".dce-mn-camera-option"),s=t.querySelectorAll(".dce-mn-resolution-option"),a=this.resources.cameraEnhancer.getSelectedCamera(),o=this.resources.cameraEnhancer.getResolution();i.forEach((e=>{const n=e;n.getAttribute("data-davice-id")===(null==a?void 0:a.deviceId)?n.style.border="2px solid #fe814a":n.style.border="none"}));const r={"480p":"480","720p":"720","1080p":"1080","2k":"1440","4k":"2160"},l=function(e){const n=e.width*e.height,t=e.width/e.height;let i="480p",s=Number.MAX_VALUE;for(const[e,a]of Object.entries(D)){const o=a.width*a.height,r=a.width/a.height,l=.7*Math.abs(o-n)+Math.abs(r-t)*o*.3;l{const n=e,t=n.getAttribute("data-height");n.style.border=t===r[l]?"2px solid #fe814a":"none"}))}toggleSelectCameraBox(){const e=w(this.config.container),n=e.children[e.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const t=n.shadowRoot.querySelector(".dce-mn-resolution-box");this.highlightCameraAndResolutionOption(),this.attachOptionClickListeners(),t.click()}async uploadImage(){var n,t,i;const{cvRouter:s}=this.resources,a=document.createElement("input");a.type="file",a.accept="image/*",a.style.display="none",document.body.appendChild(a);try{this.showScannerLoadingOverlay("Processing image..."),await this.closeCamera(!1);const o=await new Promise(((e,n)=>{a.onchange=t=>{var i;const s=null===(i=t.target.files)||void 0===i?void 0:i[0];(null==s?void 0:s.type.startsWith("image/"))?e(s):n(new Error("Please select an image file"))},a.addEventListener("cancel",(async()=>{this.hideScannerLoadingOverlay(!1),await this.launch()})),a.click()}));if(!o)return this.hideScannerLoadingOverlay(!1),void await this.launch();const r=this.config.utilizedTemplateNames[this.currentScanMode];if(!1!==this.config.showScanGuide){const e=await s.getSimplifiedSettings(r);e.roiMeasuredInPercentage=!0,e.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await s.updateSettings(r,e)}const l=await s.capture(o,r);this.capturedResultItems=l.items;const c=this.capturedResultItems.filter((n=>n.type===e.CRIT_ORIGINAL_IMAGE))[0].imageData;c.toCanvas=()=>{const e=document.createElement("canvas");e.width=c.width,e.height=c.height;const n=e.getContext("2d");if(!n)throw new Error("Failed to get canvas context");const t=new ImageData(new Uint8ClampedArray(c.bytes.buffer),c.width,c.height);return n.putImageData(t,0,0),e},this.originalImageData=c;const d=null==l?void 0:l.textLineResultItems,h=null==l?void 0:l.parsedResultItems;let u={};if(null==d?void 0:d.length){const e=(null===(n=d[0])||void 0===n?void 0:n.text)||"";u=z(e,h[0])}const m={status:{code:y.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,_imageData:this.originalImageData,data:u};null===(i=(t=this.resources).onResultUpdated)||void 0===i||i.call(t,m),this.currentScanResolver(m),this.hideScannerLoadingOverlay(!0)}catch(e){let n=(null==e?void 0:e.message)||e;console.error(n),alert(n),this.closeCamera();const t={status:{code:y.RS_FAILED,message:"Error processing uploaded image"}};this.currentScanResolver(t)}finally{document.body.removeChild(a)}}toggleSoundFeedback(e){this.isSoundFeedbackOn=void 0!==e?e:!this.isSoundFeedbackOn;const n=w(this.config.container),t=n.children[n.children.length-1];if(!(null==t?void 0:t.shadowRoot))return;const i=t.shadowRoot.querySelector(".dce-mn-sound-feedback"),s=i.querySelector(".dce-mn-sound-feedback-on");i.querySelector(".dce-mn-sound-feedback-off").style.display=this.isSoundFeedbackOn?"none":"block",s.style.display=this.isSoundFeedbackOn?"block":"none"}calculateScanRegion(e){const{cameraEnhancer:n,cameraView:t}=this.resources;if(!n||!n.isOpen())return;const i=t.getVisibleRegionOfVideo({inPixels:!0});if(!i)return;const s=t.getVideoElement(),a=s.videoWidth,o=s.videoHeight,r=V[e];let l;const c=i.height-80;if(i.width>i.height){l=.75*c/r.height;l*r.width>.9*i.width&&(l=.9*i.width/r.width)}else{l=.9*i.width/r.width;l*r.height>.75*c&&(l=.75*c/r.height)}const d=l*r.width,h=l*r.height,u=(i.width-d)/2,m=(c-h)/2,g=u,p=u+d,f=m,y=m+h,w=(i.x+g)/a*100,v=(i.x+p)/a*100,S=(i.y+f)/o*100,E=(i.y+y)/o*100,D={left:Math.round(w),right:Math.round(v),top:Math.round(S),bottom:Math.round(E),isMeasuredInPercentage:!0};null==t||t.setScanRegionMaskVisible(!0),n.setScanRegion(D)}toggleScanGuide(e){const n=w(this.config.container),t=n.children[n.children.length-1];if(!(null==t?void 0:t.shadowRoot))return;const i=t.shadowRoot.querySelector(".dce-scanguide-passport"),s=t.shadowRoot.querySelector(".dce-scanguide-td1"),a=t.shadowRoot.querySelector(".dce-scanguide-td2");if(!1===e||!1===this.config.showScanGuide)return i.style.display="none",s.style.display="none",void(a.style.display="none");switch(this.currentScanMode){case m.All:case m.Passport:case m.PassportAndTD1:case m.PassportAndTD2:i.style.display="block",s.style.display="none",a.style.display="none",this.calculateScanRegion(g.Passport);break;case m.TD1:case m.TD1AndTD2:i.style.display="none",s.style.display="block",a.style.display="none",this.calculateScanRegion(g.TD1);break;case m.TD2:i.style.display="none",s.style.display="none",a.style.display="block",this.calculateScanRegion(g.TD2)}}async openCamera(){try{this.showScannerLoadingOverlay("Initializing camera...");const{cameraEnhancer:e,cameraView:n}=this.resources,t=w(this.config.container);if(t.style.display="block",e.isOpen())e.isPaused()&&await e.resume();else{const i=n.getUIElement();i.parentElement||t.append(i),await e.open()}!this.initializedDCE&&e.isOpen()&&await this.initializeElements(),window.addEventListener("resize",this.handleResize);const i=t.children[t.children.length-1];if(!(null==i?void 0:i.shadowRoot))throw new Error("Shadow root not found");i.shadowRoot.querySelector(".dce-mn-torch-off").style.display="none",i.shadowRoot.querySelector(".dce-mn-torch-on").style.display="none"}catch(e){let n=(null==e?void 0:e.message)||e;console.error(n),alert(n),this.closeCamera();const t={status:{code:y.RS_FAILED,message:"MRZ Scanner Open Camera Error"}};this.currentScanResolver(t)}finally{this.hideScannerLoadingOverlay()}}async closeCamera(e=!0){try{window.removeEventListener("resize",this.handleResize),this.resizeTimer&&(window.clearTimeout(this.resizeTimer),this.resizeTimer=null);const{cameraEnhancer:n,cameraView:t}=this.resources,i=w(this.config.container);i.style.display=e?"none":"block",(null==t?void 0:t.getUIElement().parentElement)&&i.removeChild(t.getUIElement()),n.close(),this.stopCapturing()}catch(e){let n=(null==e?void 0:e.message)||e;console.error(`Close Camera error: ${n}`)}}pauseCamera(){const{cameraEnhancer:e}=this.resources;e.pause()}stopCapturing(){const{cameraView:e,cvRouter:n}=this.resources;n.stopCapturing(),e.clearAllInnerDrawingItems()}async handleMRZResult(n){var t;if(this.capturedResultItems=n.items,!(n.items.length<=1))try{const{onResultUpdated:i}=this.resources,s=n.items.filter((n=>n.type===e.CRIT_ORIGINAL_IMAGE));this.originalImageData=s.length&&s[0].imageData;const a=null==n?void 0:n.textLineResultItems,r=null==n?void 0:n.parsedResultItems;if(a){this.isSoundFeedbackOn&&o.beep();const e=(null===(t=null==a?void 0:a[0])||void 0===t?void 0:t.text)||"",n=z(e,r[0]);this.closeCamera();const s={status:{code:y.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,_imageData:this.originalImageData,data:n};null==i||i(s),this.currentScanResolver(s)}}catch(e){let n=(null==e?void 0:e.message)||e;console.error(n),alert(n),this.closeCamera();const t={status:{code:y.RS_FAILED,message:"Error capturing image"}};this.currentScanResolver(t)}}initializeScanModeManager(){const{mrzFormatType:e}=this.config;if(this.scanModeManager={[g.Passport]:!0,[g.TD1]:!0,[g.TD2]:!0},!e||Array.isArray(e)&&0===e.length)return;Object.keys(this.scanModeManager).forEach((e=>{this.scanModeManager[e]=!1}));(Array.isArray(e)?e:[e]).forEach((e=>{this.scanModeManager[e]=!0}))}getScanMode(){const e=Object.entries(this.scanModeManager).filter((([e,n])=>n)).map((([e])=>e)).sort().join(",");return{[g.Passport]:m.Passport,[g.TD1]:m.TD1,[g.TD2]:m.TD2,[`${g.Passport},${g.TD1}`]:m.PassportAndTD1,[`${g.Passport},${g.TD2}`]:m.PassportAndTD2,[`${g.TD1},${g.TD2}`]:m.TD1AndTD2,[`${g.Passport},${g.TD1},${g.TD2}`]:m.All,"":m.All}[e]}DCEShowToast(e,n=3e3){this.DCE_ELEMENTS.toast&&(this.DCE_ELEMENTS.toast.textContent=e,this.DCE_ELEMENTS.toast.style.display="",setTimeout((()=>{this.DCE_ELEMENTS.toast.style.display="none"}),n))}async startCapturing(){const{cvRouter:e,cameraEnhancer:t}=this.resources,i=this.config.utilizedTemplateNames[this.currentScanMode];try{if(!1!==this.config.showScanGuide){const n=await e.getSimplifiedSettings(i);n.roiMeasuredInPercentage=!0,n.roi.points=[{x:0,y:50},{x:100,y:50},{x:100,y:100},{x:0,y:100}],await e.updateSettings(i,n)}await e.startCapturing(i),t.setPixelFormat(n.IPF_ABGR_8888)}catch(e){let n=(null==e?void 0:e.message)||e;console.error("Failed to start capturing:",n),this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:y.RS_FAILED,message:"Failed to start capturing"}})}}async toggleScanDocType(e){try{if(this.scanModeManager[e]&&0===Object.entries(this.scanModeManager).filter((([n,t])=>t&&n!==e)).length)return console.warn("MRZ Scanner - At least one mode must be enabled"),void this.DCEShowToast("At least one mode must be enabled");this.scanModeManager[e]=!this.scanModeManager[e],this.currentScanMode=this.getScanMode(),this.stopCapturing(),await this.startCapturing(),this.toggleScanGuide(),this.DCE_ELEMENTS.td1ModeOption.classList.toggle("selected",this.scanModeManager[g.TD1]),this.DCE_ELEMENTS.td2ModeOption.classList.toggle("selected",this.scanModeManager[g.TD2]),this.DCE_ELEMENTS.passportModeOption.classList.toggle("selected",this.scanModeManager[g.Passport])}catch(e){let n=(null==e?void 0:e.message)||e;console.error("MRZ Scanner switch scan mode error: ",n),this.closeCamera();const t={status:{code:y.RS_FAILED,message:"MRZ Scanner switch scan mode error"}};this.currentScanResolver(t)}}async launch(){try{await this.initialize();const{cvRouter:e,cameraEnhancer:n}=this.resources;return new Promise((async e=>{this.currentScanResolver=e,await this.openCamera(),!this.initializedDCE&&n.isOpen()&&await this.initializeElements(),await this.startCapturing(),this.toggleScanGuide()}))}catch(e){let n=(null==e?void 0:e.message)||e;console.error("MRZ Scanner launch error: ",n),this.closeCamera();const t={status:{code:y.RS_FAILED,message:"MRZ Scanner launch error"}};this.currentScanResolver(t)}}}const L={rescan:'\n\n\n \n\n\n\n\n\n\n\n',complete:'\n\n\n\n \n\n\n\n\n\n\n\n',failed:'\n \n \n \n\n',info:'\n\n \n \n \n\n'};class N{constructor(e,n,t){this.resources=e,this.config=n,this.scannerView=t,this.editedFields={}}async launch(){try{return w(this.config.container).textContent="",await this.initialize(),w(this.config.container).style.display="flex",new Promise((e=>{this.currentScanResultViewResolver=e}))}catch(e){let n=(null==e?void 0:e.message)||e;throw console.error(n),n}}async handleRescan(){var e;try{if(!this.scannerView)return void console.error("Scanner View not initialized");this.hideView();const n=await this.scannerView.launch();if((null===(e=null==n?void 0:n.status)||void 0===e?void 0:e.code)===y.RS_FAILED)return void(this.currentScanResultViewResolver&&this.currentScanResultViewResolver(n));this.resources.onResultUpdated&&((null==n?void 0:n.status.code)===y.RS_CANCELLED?this.resources.onResultUpdated(this.resources.result):(null==n?void 0:n.status.code)===y.RS_SUCCESS&&this.resources.onResultUpdated(n)),this.dispose(!0),await this.initialize(),w(this.config.container).style.display="flex"}catch(e){throw console.error("Error in rescan handler:",e),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:y.RS_FAILED,message:(null==e?void 0:e.message)||e}}),e}}async handleDone(){var e,n;try{(null===(e=this.resources.result)||void 0===e?void 0:e.data)&&!S(this.editedFields)&&(this.resources.result.data=Object.assign(Object.assign({},this.resources.result.data),this.editedFields),this.resources.onResultUpdated&&this.resources.onResultUpdated(this.resources.result)),(null===(n=this.config)||void 0===n?void 0:n.onDone)&&await this.config.onDone(this.resources.result),this.currentScanResultViewResolver&&this.resources.result&&this.currentScanResultViewResolver(this.resources.result),this.hideView(),this.dispose()}catch(e){throw console.error("Error in done handler:",e),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:y.RS_FAILED,message:(null==e?void 0:e.message)||e}}),e}}createControls(){var e,n,t,i,s,a,o,r;const{toolbarButtonsConfig:l}=this.config;return function(e){v("dynamsoft-mrz-controls-style","\n .dynamsoft-mrz-controls {\n display: flex;\n height: 6rem;\n background-color: #323234;\n align-items: center;\n font-size: 12px;\n font-family: Verdana;\n color: white;\n width: 100%;\n }\n\n .dynamsoft-mrz-control-btn {\n background-color: #323234;\n color: white;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n height: 100%;\n width: 100%;\n gap: 0.5rem;\n text-align: center;\n user-select: none;\n }\n\n .dynamsoft-mrz-control-btn.hide {\n display: none;\n }\n\n .dynamsoft-mrz-control-btn.disabled {\n opacity: 0.4;\n pointer-events: none;\n cursor: default;\n }\n\n .dynamsoft-mrz-control-icon-wrapper {\n flex: 0.75;\n display: flex;\n align-items: flex-end;\n justify-content: center;\n min-height: 40px;\n }\n\n .dynamsoft-mrz-control-icon img,\n .dynamsoft-mrz-control-icon svg {\n width: 32px;\n height: 32px;\n fill: #fe8e14;\n }\n\n .dynamsoft-mrz-control-text {\n flex: 0.5;\n display: flex;\n align-items: flex-start;\n justify-content: center;\n padding-bottom: 0.5rem;\n }\n\n \n @media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-controls {\n flex-direction: column;\n height: 100%;\n width: 5rem;\n }\n\n .dynamsoft-mrz-control-text {\n padding: 0 0.5rem 0.5rem;\n }\n }\n");const n=document.createElement("div");return n.className="dynamsoft-mrz-controls",e.forEach((e=>{const t=document.createElement("div");t.className=`dynamsoft-mrz-control-btn ${null==e?void 0:e.className}`;const i=document.createElement("div");if(i.className="dynamsoft-mrz-control-icon-wrapper",(s=e.icon).trim().startsWith(""))i.innerHTML=e.icon;else{const n=document.createElement("img");n.src=e.icon,n.alt=e.label,n.width=24,n.height=24,i.appendChild(n)}var s;const a=document.createElement("div");a.className="dynamsoft-mrz-control-text",a.textContent=e.label,e.isDisabled&&t.classList.add("disabled"),e.isHidden&&t.classList.add("hide"),t.appendChild(i),t.appendChild(a),e.onClick&&!e.isDisabled&&t.addEventListener("click",e.onClick),n.appendChild(t)})),n}([{id:"dynamsoft-mrz-scanResult-rescan",icon:(null===(e=null==l?void 0:l.rescan)||void 0===e?void 0:e.icon)||L.rescan,label:(null===(n=null==l?void 0:l.rescan)||void 0===n?void 0:n.label)||"Re-scan",onClick:()=>this.handleRescan(),className:`${(null===(t=null==l?void 0:l.rescan)||void 0===t?void 0:t.className)||""}`,isHidden:(null===(i=null==l?void 0:l.rescan)||void 0===i?void 0:i.isHidden)||!1,isDisabled:!this.scannerView},{id:"dynamsoft-mrz-scanResult-done",icon:(null===(s=null==l?void 0:l.done)||void 0===s?void 0:s.icon)||L.complete,label:(null===(a=null==l?void 0:l.done)||void 0===a?void 0:a.label)||"Done",className:`${(null===(o=null==l?void 0:l.done)||void 0===o?void 0:o.className)||""}`,isHidden:(null===(r=null==l?void 0:l.done)||void 0===r?void 0:r.isHidden)||!1,onClick:()=>this.handleDone()}])}handleFieldEdit(e,n){if(e===T.DateOfBirth||e===T.DateOfExpiry)try{const[t,i,s]=n.split(/[\/\-\.]/);s&&i&&t&&(this.editedFields[e]={day:parseInt(s,10),month:parseInt(i,10),year:parseInt(t,10)})}catch(e){console.error("Error parsing date",e)}else this.editedFields[e]=n}createMRZDataDisplay(){var e;const n=(null===(e=this.resources.result)||void 0===e?void 0:e.data)||{},t=!!this.config.allowResultEditing,i=n.invalidFields||[],s=document.createElement("div");if(s.className="dynamsoft-mrz-data-container",S(n)){const e=document.createElement("div");return e.className="dynamsoft-mrz-data-row empty",e.innerText="No MRZ detected. Please try again.",s.appendChild(e),s}if(i.length>0){const e=document.createElement("div");e.className="dynamsoft-mrz-error-notification",e.innerHTML=`\n
${L.failed}
\n
\n ${t?"Some fields require correction. Please review highlighted fields.":"Some fields contain invalid information. Please rescan the document."}\n
\n `,s.appendChild(e)}else if(0===i.length&&t){const e=document.createElement("div");e.className="dynamsoft-mrz-info-notification",e.innerHTML=`\n
${L.info}
\n
\n Please review all fields to ensure the information is correct.\n
\n `,s.appendChild(e)}return Object.entries(n).forEach((([e,n])=>{var a;if(e===T.InvalidFields||!n)return;if(e===T.MRZText&&!1===(null===(a=this.config)||void 0===a?void 0:a.showMRZText))return;const o=document.createElement("div");o.className="dynamsoft-mrz-data-row";const r=i.includes(e);r&&o.classList.add("invalid-field");const l=[T.MRZText,T.DocumentType],c=document.createElement("span");if(c.className="dynamsoft-mrz-data-label",c.innerText=M[e]||e,r){const e=document.createElement("span");if(e.className="dynamsoft-mrz-error-icon",e.innerHTML=L.failed,c.appendChild(e),t){const e=document.createElement("span");e.className="dynamsoft-mrz-error-hint",e.textContent="Please correct this field",c.appendChild(e)}}const d=document.createElement("div");if(d.className="dynamsoft-mrz-data-value",t&&!l.includes(e)){const t=document.createElement("input");t.className="dynamsoft-mrz-data-input",r&&t.classList.add("invalid"),e===T.DateOfBirth||e===T.DateOfExpiry?(t.value=b(n),t.setAttribute("placeholder","YYYY-MM-DD")):t.value=n,t.addEventListener("input",(n=>{if(this.handleFieldEdit(e,n.target.value),r){t.classList.remove("invalid"),o.classList.remove("invalid-field"),this.editedFields.invalidFields||(this.editedFields.invalidFields=[...i]);const n=this.editedFields.invalidFields.indexOf(e);n>-1&&this.editedFields.invalidFields.splice(n,1)}})),d.appendChild(t)}else e===T.MRZText?(d.classList.add("code"),d.innerText=n):e===T.DateOfBirth||e===T.DateOfExpiry?d.innerText=b(n):d.innerText=n,r&&d.classList.add("invalid-value");o.appendChild(c),o.appendChild(d),s.appendChild(o)})),s}async initialize(){try{if(!this.resources.result)throw Error("Captured image is missing. Please capture an image first!");if(!this.config.container)throw new Error("Please create a Scan Result View Container element");v("dynamsoft-mrz-result-view-style",_);const e=document.createElement("div");if(e.className="dynamsoft-mrz-result-view-container",!1!==this.config.showOriginalImage){const n=this.resources.result.originalImageResult,t=document.createElement("div");let i;t.className="dynamsoft-mrz-result-view-image-container",(null==n?void 0:n.toCanvas)&&(i=null==n?void 0:n.toCanvas()),Object.assign(i.style,{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}),t.appendChild(i),e.appendChild(t)}const n=this.createMRZDataDisplay();e.appendChild(n);const t=this.createControls();e.appendChild(t),w(this.config.container).appendChild(e)}catch(e){let n=(null==e?void 0:e.message)||e;console.error(n),alert(n)}}hideView(){w(this.config.container).style.display="none"}dispose(e=!1){w(this.config.container).textContent="",e||(this.currentScanResultViewResolver=void 0)}}const _="\n .dynamsoft-mrz-result-view-container {\n display: flex;\n width: 100%;\n height: 100%;\n background-color:#575757;\n font-size: 12px;\n flex-direction: column;\n align-items: center;\n }\n\n .dynamsoft-mrz-result-view-image-container {\n width: 100%;\n height: 200px;\n display: flex;\n justify-content: center;\n align-items: center;\n background-color: #323234;\n }\n\n \n.dynamsoft-mrz-data-container {\n font-size: 16px;\n font-family: Verdana;\n color: white;\n overflow: auto;\n width: 100%;\n height: 100%;\n min-height: 0;\n margin: 1rem 0;\n}\n\n.dynamsoft-mrz-data-row {\n padding: 0.5rem 2rem;\n display: flex;\n flex-direction: column;\n gap: 0.5rem;\n transition: background-color 0.3s ease;\n}\n\n.dynamsoft-mrz-data-row.invalid-field {\n background-color: rgba(231, 76, 60, 0.1);\n border-left: 3px solid #e74c3c;\n padding-left: calc(2rem - 3px);\n}\n\n.dynamsoft-mrz-data-label {\n color: #aaa;\n display: flex;\n gap: 0.5rem;\n align-items: end;\n flex-wrap: wrap;\n}\n\n.dynamsoft-mrz-error-notification,\n.dynamsoft-mrz-info-notification {\n color: white;\n padding: 1rem;\n margin: 0.5rem 2rem;\n border-radius: 4px;\n display: flex;\n align-items: center;\n gap: 1rem;\n text-align: start;\n}\n\n.dynamsoft-mrz-error-notification {\n background-color: rgba(231, 76, 60, 0.2);\n}\n\n.dynamsoft-mrz-info-notification {\n background-color: rgba(196, 231, 60, 0.2);\n}\n\n.dynamsoft-mrz-edit-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #aaa;\n}\n\n.dynamsoft-mrz-error-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-info-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: white;\n}\n\n.dynamsoft-mrz-info-message,\n.dynamsoft-mrz-error-message {\n flex: 1;\n}\n\n.dynamsoft-mrz-error-hint {\n font-size: 0.8rem;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-value {\n word-wrap: break-word;\n text-align: start;\n}\n\n.dynamsoft-mrz-data-value.code {\n font-family: monospace;\n}\n\n.dynamsoft-mrz-data-value.invalid-value {\n color: #e74c3c;\n text-decoration: wavy underline #e74c3c;\n text-decoration-skip-ink: none;\n}\n\n.dynamsoft-mrz-data-input {\n width: 100%;\n padding: 5px;\n background-color: rgba(255, 255, 255, 0.1);\n border: 1px solid rgba(255, 255, 255, 0.3);\n color: white;\n border-radius: 4px;\n font-size: 14px;\n transition: all 0.3s ease;\n}\n\n.dynamsoft-mrz-data-input.invalid {\n background-color: rgba(231, 76, 60, 0.1);\n border-color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-input:focus {\n background-color: rgba(255, 255, 255, 0.2);\n border-color: #fe8e14;\n outline: none;\n}\n\n@media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-result-view-container {\n flex-direction: row;\n }\n\n .dynamsoft-mrz-result-view-image-container{\n flex: 1;\n height: 100%;\n }\n\n .dynamsoft-mrz-data-container{\n flex: 1;\n }\n\n .dynamsoft-mrz-data-row:first-of-type {\n padding-top: 2rem;\n }\n\n .dynamsoft-mrz-data-row:last-of-type {\n padding-bottom: 2rem;\n }\n\n .dynamsoft-mrz-data-row.empty {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n padding-top: 0;\n padding-bottom: 0;\n }\n}\n",k={rootDirectory:"https://cdn.jsdelivr.net/npm/"};class F{showLoadingOverlay(e){var n,t;const i=w(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)||w(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container);this.loadingScreen=R(i,{message:e}),i.style.display="block",i.style.position="relative"}hideLoadingOverlay(e=!1){var n,t,i;const s=w(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)||w(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container);this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,e&&(s.style.display="none",(null===(i=this.config)||void 0===i?void 0:i.container)&&(w(this.config.container).style.display="none")))}constructor(e){this.config=e,this.resources={},this.isInitialized=!1,this.isCapturing=!1,this.loadingScreen=null}async initialize(){if(this.isInitialized)return{resources:this.resources,components:{scannerView:this.scannerView,resultView:this.resultView}};try{if(!this.initializeMRZScannerConfig())return console.error("Failed to initialize mrz scanner config"),{resources:this.resources,components:{}};v("dynamsoft-mrz-loading-screen-style",C),this.showLoadingOverlay("Loading...");if(!await this.initializeDCVResources())return this.hideLoadingOverlay(!0),console.error("Failed to initialize DCV resources"),{resources:this.resources,components:{}};this.resources.onResultUpdated=e=>{this.resources.result=e};const e={};return this.config.scannerViewConfig&&(this.scannerView=new I(this.resources,this.config.scannerViewConfig),e.scannerView=this.scannerView,await this.scannerView.initialize()),this.config.resultViewConfig&&(this.resultView=new N(this.resources,this.config.resultViewConfig,this.scannerView),e.resultView=this.resultView),this.isInitialized=!0,{resources:this.resources,components:e}}catch(e){this.isInitialized=!1;const n=`Initialization Failed: ${(null==e?void 0:e.message)||e}`;return alert(n),console.error(n),{resources:this.resources,components:{}}}finally{this.hideLoadingOverlay(!0)}}async initializeDCVResources(){var e,n,s;try{return i.initLicense((null===(e=this.config)||void 0===e?void 0:e.license)||"",!0),t.engineResourcePaths=S(null===(n=this.config)||void 0===n?void 0:n.engineResourcePaths)?k:this.config.engineResourcePaths,t.loadWasm(["DLR","DCP"]),h.loadSpec("MRTD_TD3_PASSPORT"),h.loadSpec("MRTD_TD1_ID"),h.loadSpec("MRTD_TD2_ID"),c.loadRecognitionData("MRZ"),this.resources.cameraView=await r.createInstance(null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.cameraEnhancerUIPath),this.resources.cameraEnhancer=await l.createInstance(this.resources.cameraView),this.resources.cvRouter=await a.createInstance(),!0}catch(e){let n=(null==e?void 0:e.message)||e;if(null==n?void 0:n.toLowerCase().includes("license")){const e="The MRZ Scanner license is invalid or has expired. Please contact the site administrator to resolve this issue.";alert(e),console.error(e)}else{const e=`Resource Initialization Failed: ${n}`;alert(e),console.error(e)}return!1}}shouldCreateDefaultContainer(){var e,n;const t=!this.config.container,i=!((null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)||(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container));return t&&i}createDefaultMRZScannerContainer(){const e=document.createElement("div");return e.className="mrz-scanner-main-container",Object.assign(e.style,{height:"100dvh",width:"100%",position:"absolute",left:"0",top:"0",zIndex:"999"}),document.body.append(e),e}checkForTemporaryLicense(e){return!(null==e?void 0:e.length)||(null==e?void 0:e.startsWith("A"))||(null==e?void 0:e.startsWith("L"))||(null==e?void 0:e.startsWith("P"))||(null==e?void 0:e.startsWith("Y"))?"DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9":e}validateViewConfigs(){var e,n,t,i,s,a,o,r;if(!this.config.container){if((null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)&&this.config.showResultView&&!(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container)){const e="MRZResultView container is required when showResultView is true";return alert(e),console.error(e),!1}if(!(null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)&&(null===(i=this.config.resultViewConfig)||void 0===i?void 0:i.container)&&!this.resources.result){const e="Result is needed to create MRZResultView without a scanner view";return alert(e),console.error(e),!1}}try{if(this.config.container&&!w(this.config.container)){const e="Invalid main container reference";return alert(e),console.error(e),!1}if((null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.container)&&!w(null===(a=this.config.scannerViewConfig)||void 0===a?void 0:a.container)){const e="Invalid scanner view container reference";return alert(e),console.error(e),!1}if((null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)&&!w(null===(r=this.config.resultViewConfig)||void 0===r?void 0:r.container)){const e="Invalid result view container reference";return alert(e),console.error(e),!1}}catch(e){const n=`Error accessing container references: ${e.message}`;return alert(n),console.error(n),!1}return!0}showResultView(){var e,n;return!1!==this.config.showResultView&&(this.config.container?!(void 0!==this.config.showResultView||!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container)&&!this.config.container)||!!this.config.showResultView:this.config.showResultView&&!!(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container))}initializeMRZScannerConfig(){var e,n,t,i,s,a,o;this.config=null!==(e=this.config)&&void 0!==e?e:{};if(!this.validateViewConfigs())return!1;this.shouldCreateDefaultContainer()?this.config.container=this.createDefaultMRZScannerContainer():this.config.container&&(this.config.container=w(this.config.container));const r=this.config.container?this.createViewContainers(w(this.config.container)):{},l={license:this.checkForTemporaryLicense(this.config.license),utilizedTemplateNames:Object.fromEntries(Object.values(m).map((e=>{var n;return[e,(null===(n=this.config.utilizedTemplateNames)||void 0===n?void 0:n[e])||f[e]]}))),templateFilePath:(null===(n=this.config)||void 0===n?void 0:n.templateFilePath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.0.0/dist/mrz-scanner.template.json"},c=Object.assign(Object.assign({},this.config.scannerViewConfig),{container:r[p.Scanner]||w(null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)||null,cameraEnhancerUIPath:(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.cameraEnhancerUIPath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.0.0/dist/mrz-scanner.ui.html",templateFilePath:l.templateFilePath,utilizedTemplateNames:l.utilizedTemplateNames,enableMultiFrameCrossFilter:null===(a=null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.enableMultiFrameCrossFilter)||void 0===a||a,mrzFormatType:this.config.mrzFormatType}),d=this.showResultView()?Object.assign(Object.assign({},this.config.resultViewConfig),{container:r[p.Result]||w(null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)||null}):void 0;return Object.assign(this.config,Object.assign(Object.assign({},l),{scannerViewConfig:c,resultViewConfig:d})),!0}createViewContainers(e){e.textContent="";const n=[p.Scanner];return this.showResultView()&&n.push(p.Result),n.reduce(((n,t)=>{const i=document.createElement("div");return i.className=`mrz-scanner-${t}-view-container`,Object.assign(i.style,{height:"100%",width:"100%",display:"none",position:"relative"}),e.append(i),n[t]=i,n}),{})}dispose(){var e,n;this.resultView&&(this.resultView.dispose(),this.resultView=null),this.scannerView=null,this.resources.cameraEnhancer&&(this.resources.cameraEnhancer.dispose(),this.resources.cameraEnhancer=null),this.resources.cameraView&&(this.resources.cameraView.dispose(),this.resources.cameraView=null),this.resources.cvRouter&&(this.resources.cvRouter.dispose(),this.resources.cvRouter=null),this.resources.result=null,this.resources.onResultUpdated=null;const t=e=>{const n=w(e);n&&(n.style.display="none",n.textContent="")};t(this.config.container),t(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container),t(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container),this.isInitialized=!1}async launch(){if(this.isCapturing)throw new Error("Capture session already in progress");try{this.isCapturing=!0;const{components:e}=await this.initialize();if(S(e))throw new Error("MRZ Scanner initialization failed.");if(this.config.container&&(w(this.config.container).style.display="block"),!e.scannerView&&this.resources.result&&e.resultView)return await e.resultView.launch();if(!e.scannerView&&!this.resources.result)throw new Error("Scanner view is required when no previous result exists");if(e.scannerView){const n=await e.scannerView.launch();if((null==n?void 0:n.status.code)!==y.RS_SUCCESS)return{status:{code:null==n?void 0:n.status.code,message:(null==n?void 0:n.status.message)||"Failed to capture image"}};if(e.resultView)return await e.resultView.launch()}return this.resources.result}catch(e){return alert((null==e?void 0:e.message)||e),console.error((null==e?void 0:e.message)||e),{status:{code:y.RS_FAILED,message:(null==e?void 0:e.message)||e}}}finally{this.isCapturing=!1,this.dispose()}}}const O={MRZScanner:F,MRZScannerView:I,MRZResultView:N};export{f as DEFAULT_TEMPLATE_NAMES,O as DynamsoftMRZScanner,T as EnumMRZData,g as EnumMRZDocumentType,m as EnumMRZScanMode,p as EnumMRZScannerViews,y as EnumResultStatus,M as MRZDataLabel,N as MRZResultView,F as MRZScanner,I as MRZScannerView,b as displayMRZDate}; +import{EnumCapturedResultItemType as e,_toCanvas as t,_toBlob as n,EnumImagePixelFormat as i,CoreModule as s}from"dynamsoft-core";export*from"dynamsoft-core";import{LicenseManager as a}from"dynamsoft-license";export*from"dynamsoft-license";import{CapturedResultReceiver as o,CaptureVisionRouter as r}from"dynamsoft-capture-vision-router";export*from"dynamsoft-capture-vision-router";import{Feedback as l,CameraView as c,CameraEnhancer as d}from"dynamsoft-camera-enhancer";export*from"dynamsoft-camera-enhancer";import{LabelRecognizerModule as h}from"dynamsoft-label-recognizer";export*from"dynamsoft-label-recognizer";import{EnumValidationStatus as u,CodeParserModule as m}from"dynamsoft-code-parser";export*from"dynamsoft-code-parser";import{MultiFrameResultCrossFilter as g}from"dynamsoft-utility";export*from"dynamsoft-utility";var p,f,y;!function(e){e.Passport="passport",e.TD1="td1",e.TD2="td2",e.PassportAndTD1="passportAndTd1",e.PassportAndTD2="passportAndTd2",e.TD1AndTD2="td1AndTd2",e.All="all"}(p||(p={})),function(e){e.Passport="passport",e.TD1="td1",e.TD2="td2"}(f||(f={})),function(e){e.Scanner="scanner",e.Result="scan-result"}(y||(y={}));const w={[p.Passport]:"ReadPassport",[p.TD1]:"ReadId-TD1",[p.TD2]:"ReadId-TD2",[p.PassportAndTD1]:"ReadPassportAndId-TD1",[p.PassportAndTD2]:"ReadPassportAndId-TD2",[p.TD1AndTD2]:"ReadId",[p.All]:"ReadPassportAndId"};var v;function S(e){if("string"==typeof e){const t=document.querySelector(e);if(!t)throw new Error("Element not found");return t}return e instanceof HTMLElement?e:null}!function(e){e[e.RS_SUCCESS=0]="RS_SUCCESS",e[e.RS_CANCELLED=1]="RS_CANCELLED",e[e.RS_FAILED=2]="RS_FAILED"}(v||(v={}));function E(e,t){if(!document.getElementById(e)){const n=document.createElement("style");n.id=e,n.textContent=t,document.head.appendChild(n)}}const R=e=>!e||0===Object.keys(e).length;function D(e){return e?e.charAt(0).toUpperCase()+e.slice(1):""}const C={"4k":{width:3840,height:2160},"2k":{width:2560,height:1440},"1080p":{width:1920,height:1080},"720p":{width:1280,height:720},"480p":{width:640,height:480}};function T(e,t={}){const{message:n,spinnerSize:i=32}=t,s=document.createElement("div");s.className="dynamsoft-mrz-loading-screen";const a=document.createElement("div");a.className="dynamsoft-mrz-loading";const o=document.createElement("div");o.className="dynamsoft-mrz-loading-content";const r=`\n \n \n \n `;if(o.innerHTML=r,n){const e=document.createElement("div");e.className="dynamsoft-mrz-loading-message",e.textContent=n,o.appendChild(e)}return a.appendChild(o),s.appendChild(a),e.appendChild(s),{element:s,updateMessage:e=>{let t=a.querySelector(".dynamsoft-mrz-loading-message");null!==e?t?t.textContent=e:(t=document.createElement("div"),t.className="dynamsoft-mrz-loading-message",t.textContent=e,o.appendChild(t)):null==t||t.remove()},hide:()=>{s&&s.parentNode&&(s.classList.add("fade-out"),setTimeout((()=>{var e;null===(e=s.parentNode)||void 0===e||e.removeChild(s)}),200))}}}const M='\n .dynamsoft-mrz-loading-screen {\n position: absolute;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: #323234;\n z-index: 998;\n opacity: 1;\n transition: opacity 0.2s ease-out;\n }\n\n .dynamsoft-mrz-loading-screen.fade-out {\n opacity: 0;\n }\n\n .dynamsoft-mrz-loading {\n position: absolute;\n left: 50%;\n top: 50%;\n color: white;\n z-index: 999;\n transform: translate(-50%, -50%);\n }\n\n .dynamsoft-mrz-loading-content {\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 16px;\n }\n\n .dynamsoft-mrz-loading svg {\n animation: spin 1s linear infinite;\n }\n\n .dynamsoft-mrz-loading-message {\n color: white;\n font-family: "Verdana";\n font-size: 14px;\n text-align: center;\n max-width: 200px;\n line-height: 1.4;\n opacity: 0.9;\n }\n\n @keyframes spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n }\n';var x;!function(e){e.InvalidFields="invalidFields",e.DocumentType="documentType",e.DocumentNumber="documentNumber",e.MRZText="mrzText",e.FirstName="firstName",e.LastName="lastName",e.Age="age",e.Sex="sex",e.IssuingState="issuingState",e.IssuingStateRaw="issuingStateRaw",e.Nationality="nationality",e.NationalityRaw="nationalityRaw",e.DateOfBirth="dateOfBirth",e.DateOfExpiry="dateOfExpiry"}(x||(x={}));const b={[x.InvalidFields]:"Invalid Fields",[x.DocumentType]:"Document Type",[x.DocumentNumber]:"Document Number",[x.MRZText]:"MRZ Text",[x.FirstName]:"Given Name(s)",[x.LastName]:"Surname",[x.Age]:"Age",[x.Sex]:"Sex",[x.IssuingState]:"Issuing State",[x.IssuingStateRaw]:"Issuing State (Raw Value)",[x.Nationality]:"Nationality",[x.NationalityRaw]:"Nationality State (Raw Value)",[x.DateOfBirth]:"Date Of Birth (YYYY-MM-DD)",[x.DateOfExpiry]:"Date Of Expiry (YYYY-MM-DD)"};function z(e,t,n,i=!1){const s=parseInt(e,10);let a;if(i)a=s>=60?1900+s:2e3+s;else{a=s>(new Date).getFullYear()%100?1900+s:2e3+s}return{year:a,month:parseInt(t,10),day:parseInt(n,10)}}function I(e){const t=e=>{var t;return 1===(null===(t=`${e}`)||void 0===t?void 0:t.length)?`0${e}`:e};return`${null==e?void 0:e.year}-${t(null==e?void 0:e.month)}${(null==e?void 0:e.day)&&`-${t(null==e?void 0:e.day)}`}`}function V(e){return"D<<"===e?"D":e}function N(e,t){const n=[],i=e=>t.getFieldValidationStatus(e)===u.VS_FAILED,s=t.codeType,a=function(e){switch(e){case"MRTD_TD1_ID":return f.TD1;case"MRTD_TD2_ID":case"MRTD_TD2_VISA":case"MRTD_TD2_FRENCH_ID":return f.TD2;case"MRTD_TD3_PASSPORT":case"MRTD_TD3_VISA":return f.Passport;default:throw new Error(`Unknown document type: ${e}`)}}(s),o=function(e){switch(e){case"MRTD_TD1_ID":return"ID (TD1)";case"MRTD_TD2_ID":return"ID (TD2)";case"MRTD_TD2_VISA":return"ID (VISA)";case"MRTD_TD2_FRENCH_ID":return"French ID (TD2)";case"MRTD_TD3_PASSPORT":return"Passport (TD3)";case"MRTD_TD3_VISA":return"Visa (TD3)";default:throw new Error(`Unknown document type: ${e}`)}}(s),r=a===f.Passport&&"MRTD_TD3_PASSPORT"===s?"passportNumber":"documentNumber",l=z(t.getFieldValue("birthYear"),t.getFieldValue("birthMonth"),t.getFieldValue("birthDay")),c=z(t.getFieldValue("expiryYear"),t.getFieldValue("expiryMonth"),t.getFieldValue("expiryDay"),!0);["birthYear","birthMonth","birthDay"].forEach((e=>{i(e)&&n.push(x.DateOfBirth)})),["expiryYear","expiryMonth","expiryDay"].forEach((e=>{i(e)&&n.push(x.DateOfExpiry)}));const d={[x.LastName]:t.getFieldValue("primaryIdentifier"),[x.FirstName]:t.getFieldValue("secondaryIdentifier"),[x.Nationality]:t.getFieldValue("nationality"),[x.NationalityRaw]:V(t.getFieldRawValue("nationality")),[x.DocumentNumber]:t.getFieldValue(r)||t.getFieldValue("longDocumentNumber"),[x.IssuingState]:t.getFieldValue("issuingState"),[x.IssuingStateRaw]:V(t.getFieldRawValue("issuingState")),[x.Sex]:D(t.getFieldValue("sex"))};Object.keys(d).forEach((e=>{let t=!1;switch(e){case x.FirstName:t=i("secondaryIdentifier");break;case x.LastName:t=i("primaryIdentifier");break;case x.DocumentNumber:t=i(r)||i("longDocumentNumber");break;default:t=i(e)}t&&n.push(e)}));const h=function(e){const t=new Date,n=t.getMonth()+1>e.month||t.getMonth()+1===e.month&&t.getDate()>=e.day;return t.getFullYear()-e.year-(n?0:1)}(l);h<1&&n.push(x.Age);return{[x.InvalidFields]:n,[x.FirstName]:d[x.FirstName],[x.LastName]:d[x.LastName],[x.Age]:h,[x.DateOfBirth]:l,[x.Sex]:d[x.Sex],[x.Nationality]:d[x.Nationality],[x.NationalityRaw]:d[x.NationalityRaw],[x.DocumentNumber]:d[x.DocumentNumber],[x.DateOfExpiry]:c,[x.IssuingState]:d[x.IssuingState],[x.IssuingStateRaw]:d[x.IssuingStateRaw],[x.DocumentType]:D(o),[x.MRZText]:e}}const L={[f.TD1]:{width:85.6,height:53.98},[f.TD2]:{width:105,height:74},[f.Passport]:{width:125,height:88}};class F{showScannerLoadingOverlay(e){const t=S(this.config.container);this.loadingScreen=T(t,{message:e}),t.style.display="block",t.style.position="relative"}hideScannerLoadingOverlay(e=!1){this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,e&&(S(this.config.container).style.display="none"))}constructor(e,t){this.resources=e,this.config=t,this.isSoundFeedbackOn=!1,this.scanModeManager={[f.Passport]:!0,[f.TD1]:!0,[f.TD2]:!0},this.currentScanMode=p.All,this.resizeTimer=null,this.capturedResultItems=[],this.originalImageData=null,this.initialized=!1,this.initializedDCE=!1,this.DCE_ELEMENTS={selectCameraBtn:null,uploadImageBtn:null,soundFeedbackBtn:null,closeScannerBtn:null,scanModeSelectContainer:null,passportModeOption:null,td1ModeOption:null,td2ModeOption:null,toast:null},this.loadingScreen=null,this.handleResize=()=>{this.toggleScanGuide(!1),this.resizeTimer&&window.clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout((()=>{this.toggleScanGuide(!0)}),500)}}async initialize(){if(!this.initialized){this.initializeScanModeManager(),this.currentScanMode=this.getScanMode(),E("dynamsoft-mrz-loading-screen-style",M);try{const{cameraView:t,cameraEnhancer:n,cvRouter:i}=this.resources;if(t.setScanRegionMaskStyle({strokeStyle:"transparent",fillStyle:"transparent",lineWidth:0}),t.setVideoFit("cover"),i.setInput(n),await i.initSettings(this.config.templateFilePath),!0===this.config.enableMultiFrameCrossFilter){const t=new g;t.enableResultCrossVerification(e.CRIT_TEXT_LINE,!0),t.enableResultDeduplication(e.CRIT_TEXT_LINE,!0),await i.addResultFilter(t)}const s=new o;s.onCapturedResultReceived=e=>this.handleMRZResult(e),await i.addResultReceiver(s),this.toggleSoundFeedback(!1),!1===this.config.showScanGuide&&this.toggleScanGuide(!1),this.initialized=!0}catch(e){let t=(null==e?void 0:e.message)||e;console.error(t),alert(t),this.closeCamera();const n={status:{code:v.RS_FAILED,message:"Dynamsoft MRZ Scanner initialize error"}};this.currentScanResolver(n)}}}initializeElements(){var e;const t=S(this.config.container),n=t.children[t.children.length-1];if(!(null==n?void 0:n.shadowRoot))throw new Error("Shadow root not found");if(this.DCE_ELEMENTS={selectCameraBtn:n.shadowRoot.querySelector(".dce-mn-select-camera-icon"),uploadImageBtn:n.shadowRoot.querySelector(".dce-mn-upload-image-icon"),soundFeedbackBtn:n.shadowRoot.querySelector(".dce-mn-sound-feedback"),closeScannerBtn:n.shadowRoot.querySelector(".dce-mn-close"),scanModeSelectContainer:n.shadowRoot.querySelector(".dce-mn-scan-mode-select"),passportModeOption:n.shadowRoot.querySelector(".scan-mode-option-passport"),td1ModeOption:n.shadowRoot.querySelector(".scan-mode-option-td1"),td2ModeOption:n.shadowRoot.querySelector(".scan-mode-option-td2"),toast:n.shadowRoot.querySelector(".dce-mn-toast")},this.setupScanModeSelector(),this.assignDCEClickEvents(),this.DCE_ELEMENTS.toast.style.display="none",!1===this.config.showUploadImage&&(this.DCE_ELEMENTS.uploadImageBtn.style.visibility="hidden"),!1===this.config.showSoundToggle&&(this.DCE_ELEMENTS.soundFeedbackBtn.style.visibility="hidden"),!1===(null===(e=this.config)||void 0===e?void 0:e.showPoweredByDynamsoft)){n.shadowRoot.querySelector(".dce-mn-msg-poweredby").style.display="none"}this.initializedDCE=!0}setupScanModeSelector(){if(!1!==this.config.showFormatSelector)switch(this.currentScanMode){case p.PassportAndTD1:this.DCE_ELEMENTS.td2ModeOption.style.display="none";break;case p.PassportAndTD2:this.DCE_ELEMENTS.td1ModeOption.style.display="none";break;case p.TD1AndTD2:this.DCE_ELEMENTS.passportModeOption.style.display="none";break;case p.All:break;default:this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}else this.DCE_ELEMENTS.scanModeSelectContainer.style.display="none"}assignDCEClickEvents(){if(!Object.values(this.DCE_ELEMENTS).every(Boolean))throw new Error("Camera control elements not found");this.closeCamera=this.closeCamera.bind(this),this.DCE_ELEMENTS.uploadImageBtn.onclick=()=>this.uploadFile(),this.DCE_ELEMENTS.soundFeedbackBtn.onclick=()=>this.toggleSoundFeedback(),this.DCE_ELEMENTS.closeScannerBtn.onclick=()=>this.handleCloseBtn(),this.DCE_ELEMENTS.selectCameraBtn.onclick=e=>{e.stopPropagation(),this.toggleSelectCameraBox()},this.DCE_ELEMENTS.passportModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.passportModeOption.style.display&&await this.toggleScanDocType(f.Passport)},this.DCE_ELEMENTS.td1ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td1ModeOption.style.display&&await this.toggleScanDocType(f.TD1)},this.DCE_ELEMENTS.td2ModeOption.onclick=async()=>{"none"!==this.DCE_ELEMENTS.td2ModeOption.style.display&&await this.toggleScanDocType(f.TD2)}}handleCloseBtn(){this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:v.RS_CANCELLED,message:"Cancelled"}})}attachOptionClickListeners(){const e=S(this.config.container),t=e.children[e.children.length-1];if(!(null==t?void 0:t.shadowRoot))return;const n=t.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings");[...t.shadowRoot.querySelectorAll(".dce-mn-camera-option"),...t.shadowRoot.querySelectorAll(".dce-mn-resolution-option")].forEach((e=>{e.addEventListener("click",(async t=>{const i=e.getAttribute("data-davice-id"),s=e.getAttribute("data-height"),a=e.getAttribute("data-width");i?this.resources.cameraEnhancer.selectCamera(i).then((()=>{this.toggleScanGuide()})):s&&a&&this.resources.cameraEnhancer.setResolution({width:parseInt(a),height:parseInt(s)}).then((()=>{this.toggleScanGuide()})),"none"!==n.style.display&&this.toggleSelectCameraBox()}))}))}highlightCameraAndResolutionOption(){const e=S(this.config.container),t=e.children[e.children.length-1];if(!(null==t?void 0:t.shadowRoot))return;const n=t.shadowRoot.querySelector(".dce-mn-camera-and-resolution-settings"),i=n.querySelectorAll(".dce-mn-camera-option"),s=n.querySelectorAll(".dce-mn-resolution-option"),a=this.resources.cameraEnhancer.getSelectedCamera(),o=this.resources.cameraEnhancer.getResolution();i.forEach((e=>{const t=e;t.getAttribute("data-davice-id")===(null==a?void 0:a.deviceId)?t.style.border="2px solid #fe814a":t.style.border="none"}));const r={"480p":"480","720p":"720","1080p":"1080","2k":"1440","4k":"2160"},l=function(e){const t=e.width*e.height,n=e.width/e.height;let i="480p",s=Number.MAX_VALUE;for(const[e,a]of Object.entries(C)){const o=a.width*a.height,r=a.width/a.height,l=.7*Math.abs(o-t)+Math.abs(r-n)*o*.3;l{const t=e,n=t.getAttribute("data-height");t.style.border=n===r[l]?"2px solid #fe814a":"none"}))}toggleSelectCameraBox(){const e=S(this.config.container),t=e.children[e.children.length-1];if(!(null==t?void 0:t.shadowRoot))return;const n=t.shadowRoot.querySelector(".dce-mn-resolution-box");this.highlightCameraAndResolutionOption(),this.attachOptionClickListeners(),n.click()}async relaunch(){}async uploadFile(){var i,s,a,o;const{cvRouter:r}=this.resources,l=document.createElement("input");l.type="file",l.accept=null!==(i=this.config.uploadAcceptedTypes)&&void 0!==i?i:"image/*",l.style.display="none",document.body.appendChild(l);try{this.showScannerLoadingOverlay("Processing file..."),await this.closeCamera(!1);const i=await new Promise(((e,t)=>{l.onchange=n=>{var i;const s=null===(i=n.target.files)||void 0===i?void 0:i[0];s?e(s):t(new Error("No file selected"))},l.addEventListener("cancel",(async()=>{this.hideScannerLoadingOverlay(!1),await this.openCamera(),await this.startCapturing(),this.toggleScanGuide()})),l.click()}));if(!i)return;let c;if(this.config.uploadFileConverter&&!i.type.startsWith("image/"))try{c=await this.config.uploadFileConverter(i)}catch(e){throw new Error(`Error converting file: ${e.message}`)}else{if(!i.type.startsWith("image/"))throw new Error("Unsupported file type. Please provide a converter function for this file type.");c=i}const d=this.config.utilizedTemplateNames[this.currentScanMode];if(!1!==this.config.showScanGuide){const e=await r.getSimplifiedSettings(d);e.roiMeasuredInPercentage=!0,e.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await r.updateSettings(d,e)}const h=await r.capture(c,d);this.capturedResultItems=h.items;const u=this.capturedResultItems.filter((t=>t.type===e.CRIT_ORIGINAL_IMAGE));if(0===u.length)throw new Error("No image data found in the captured result");const m=u[0].imageData;m.toCanvas=()=>t(m),m.toBlob=async()=>await n("image/png",m),this.originalImageData=m;const g=null==h?void 0:h.textLineResultItems,p=null==h?void 0:h.parsedResultItems;let f={};if(null==g?void 0:g.length){const e=(null===(s=g[0])||void 0===s?void 0:s.text)||"";f=N(e,p[0])}const y={status:{code:v.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,data:f,imageData:!0,_imageData:this.originalImageData};null===(o=(a=this.resources).onResultUpdated)||void 0===o||o.call(a,y),this.currentScanResolver(y)}catch(e){let t=(null==e?void 0:e.message)||e;console.error(t),alert(t),this.closeCamera();const n={status:{code:v.RS_FAILED,message:`Error processing file: ${t}`}};this.currentScanResolver(n)}finally{this.hideScannerLoadingOverlay(!0),document.body.removeChild(l)}}toggleSoundFeedback(e){this.isSoundFeedbackOn=void 0!==e?e:!this.isSoundFeedbackOn;const t=S(this.config.container),n=t.children[t.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const i=n.shadowRoot.querySelector(".dce-mn-sound-feedback"),s=i.querySelector(".dce-mn-sound-feedback-on");i.querySelector(".dce-mn-sound-feedback-off").style.display=this.isSoundFeedbackOn?"none":"block",s.style.display=this.isSoundFeedbackOn?"block":"none"}calculateScanRegion(e){const{cameraEnhancer:t,cameraView:n}=this.resources;if(!t||!t.isOpen())return;const i=n.getVisibleRegionOfVideo({inPixels:!0});if(!i)return;const s=n.getVideoElement(),a=s.videoWidth,o=s.videoHeight,r=L[e];let l;const c=i.height-80;if(i.width>i.height){l=.75*c/r.height;l*r.width>.9*i.width&&(l=.9*i.width/r.width)}else{l=.9*i.width/r.width;l*r.height>.75*c&&(l=.75*c/r.height)}const d=l*r.width,h=l*r.height,u=(i.width-d)/2,m=(c-h)/2,g=u,p=u+d,f=m,y=m+h,w=(i.x+g)/a*100,v=(i.x+p)/a*100,S=(i.y+f)/o*100,E=(i.y+y)/o*100,R={left:Math.round(w),right:Math.round(v),top:Math.round(S),bottom:Math.round(E),isMeasuredInPercentage:!0};null==n||n.setScanRegionMaskVisible(!0),t.setScanRegion(R)}toggleScanGuide(e){const t=S(this.config.container),n=t.children[t.children.length-1];if(!(null==n?void 0:n.shadowRoot))return;const i=n.shadowRoot.querySelector(".dce-scanguide-passport"),s=n.shadowRoot.querySelector(".dce-scanguide-td1"),a=n.shadowRoot.querySelector(".dce-scanguide-td2");if(!1===e||!1===this.config.showScanGuide)return i.style.display="none",s.style.display="none",void(a.style.display="none");switch(this.currentScanMode){case p.All:case p.Passport:case p.PassportAndTD1:case p.PassportAndTD2:i.style.display="block",s.style.display="none",a.style.display="none",this.calculateScanRegion(f.Passport);break;case p.TD1:case p.TD1AndTD2:i.style.display="none",s.style.display="block",a.style.display="none",this.calculateScanRegion(f.TD1);break;case p.TD2:i.style.display="none",s.style.display="none",a.style.display="block",this.calculateScanRegion(f.TD2)}}async openCamera(){try{this.showScannerLoadingOverlay("Initializing camera...");const{cameraEnhancer:e,cameraView:t}=this.resources,n=S(this.config.container);if(n.style.display="block",e.isOpen())e.isPaused()&&await e.resume();else{const i=t.getUIElement();i.parentElement||n.append(i),await e.open()}await e.setResolution({width:2560,height:1440}),!this.initializedDCE&&e.isOpen()&&await this.initializeElements(),window.addEventListener("resize",this.handleResize);const i=n.children[n.children.length-1];if(!(null==i?void 0:i.shadowRoot))throw new Error("Shadow root not found");i.shadowRoot.querySelector(".dce-mn-torch-off").style.display="none",i.shadowRoot.querySelector(".dce-mn-torch-on").style.display="none"}catch(e){let t=(null==e?void 0:e.message)||e;console.error(t),alert(t),this.closeCamera();const n={status:{code:v.RS_FAILED,message:"MRZ Scanner Open Camera Error"}};this.currentScanResolver(n)}finally{this.hideScannerLoadingOverlay()}}async closeCamera(e=!0){try{window.removeEventListener("resize",this.handleResize),this.resizeTimer&&(window.clearTimeout(this.resizeTimer),this.resizeTimer=null);const{cameraEnhancer:t,cameraView:n}=this.resources,i=S(this.config.container);i.style.display=e?"none":"block",(null==n?void 0:n.getUIElement().parentElement)&&i.removeChild(n.getUIElement()),t.close(),this.stopCapturing()}catch(e){let t=(null==e?void 0:e.message)||e;console.error(`Close Camera error: ${t}`)}}pauseCamera(){const{cameraEnhancer:e}=this.resources;e.pause()}stopCapturing(){const{cameraView:e,cvRouter:t}=this.resources;t.stopCapturing(),e.clearAllInnerDrawingItems()}async handleMRZResult(i){var s;if(this.capturedResultItems=i.items,!(i.items.length<=1))try{const{onResultUpdated:a}=this.resources,o=i.items.filter((t=>t.type===e.CRIT_ORIGINAL_IMAGE))[0].imageData;o.toCanvas=()=>t(o),o.toBlob=async()=>await n("image/png",o),this.originalImageData=o;const r=null==i?void 0:i.textLineResultItems,c=null==i?void 0:i.parsedResultItems;if(r){this.isSoundFeedbackOn&&l.beep();const e=(null===(s=null==r?void 0:r[0])||void 0===s?void 0:s.text)||"",t=N(e,c[0]);this.closeCamera();const n={status:{code:v.RS_SUCCESS,message:"Success"},originalImageResult:this.originalImageData,data:t,imageData:!0,_imageData:this.originalImageData};null==a||a(n),this.currentScanResolver(n)}}catch(e){let t=(null==e?void 0:e.message)||e;console.error(t),alert(t),this.closeCamera();const n={status:{code:v.RS_FAILED,message:"Error capturing image"}};this.currentScanResolver(n)}}initializeScanModeManager(){const{mrzFormatType:e}=this.config;if(this.scanModeManager={[f.Passport]:!0,[f.TD1]:!0,[f.TD2]:!0},!e||Array.isArray(e)&&0===e.length)return;Object.keys(this.scanModeManager).forEach((e=>{this.scanModeManager[e]=!1}));(Array.isArray(e)?e:[e]).forEach((e=>{this.scanModeManager[e]=!0}))}getScanMode(){const e=Object.entries(this.scanModeManager).filter((([e,t])=>t)).map((([e])=>e)).sort().join(",");return{[f.Passport]:p.Passport,[f.TD1]:p.TD1,[f.TD2]:p.TD2,[`${f.Passport},${f.TD1}`]:p.PassportAndTD1,[`${f.Passport},${f.TD2}`]:p.PassportAndTD2,[`${f.TD1},${f.TD2}`]:p.TD1AndTD2,[`${f.Passport},${f.TD1},${f.TD2}`]:p.All,"":p.All}[e]}DCEShowToast(e,t=3e3){this.DCE_ELEMENTS.toast&&(this.DCE_ELEMENTS.toast.textContent=e,this.DCE_ELEMENTS.toast.style.display="",setTimeout((()=>{this.DCE_ELEMENTS.toast.style.display="none"}),t))}async startCapturing(){const{cvRouter:e,cameraEnhancer:t}=this.resources,n=this.config.utilizedTemplateNames[this.currentScanMode];try{if(!1!==this.config.showScanGuide){const t=await e.getSimplifiedSettings(n);t.roiMeasuredInPercentage=!0,t.roi.points=[{x:0,y:50},{x:100,y:50},{x:100,y:100},{x:0,y:100}],await e.updateSettings(n,t)}await e.startCapturing(n),t.setPixelFormat(i.IPF_ABGR_8888)}catch(e){let t=(null==e?void 0:e.message)||e;console.error("Failed to start capturing:",t),this.closeCamera(),this.currentScanResolver&&this.currentScanResolver({status:{code:v.RS_FAILED,message:"Failed to start capturing"}})}}async toggleScanDocType(e){try{if(this.scanModeManager[e]&&0===Object.entries(this.scanModeManager).filter((([t,n])=>n&&t!==e)).length)return console.warn("MRZ Scanner - At least one mode must be enabled"),void this.DCEShowToast("At least one mode must be enabled");this.scanModeManager[e]=!this.scanModeManager[e],this.currentScanMode=this.getScanMode(),this.stopCapturing(),await this.startCapturing(),this.toggleScanGuide(),this.DCE_ELEMENTS.td1ModeOption.classList.toggle("selected",this.scanModeManager[f.TD1]),this.DCE_ELEMENTS.td2ModeOption.classList.toggle("selected",this.scanModeManager[f.TD2]),this.DCE_ELEMENTS.passportModeOption.classList.toggle("selected",this.scanModeManager[f.Passport])}catch(e){let t=(null==e?void 0:e.message)||e;console.error("MRZ Scanner switch scan mode error: ",t),this.closeCamera();const n={status:{code:v.RS_FAILED,message:"MRZ Scanner switch scan mode error"}};this.currentScanResolver(n)}}async launch(){try{await this.initialize();const{cvRouter:e,cameraEnhancer:t}=this.resources;return new Promise((async e=>{this.currentScanResolver=e,await this.openCamera(),!this.initializedDCE&&t.isOpen()&&await this.initializeElements(),await this.startCapturing(),this.toggleScanGuide()}))}catch(e){let t=(null==e?void 0:e.message)||e;console.error("MRZ Scanner launch error: ",t),this.closeCamera();const n={status:{code:v.RS_FAILED,message:"MRZ Scanner launch error"}};this.currentScanResolver(n)}}}const _={rescan:'\n\n\n \n\n\n\n\n\n\n\n',complete:'\n\n\n\n \n\n\n\n\n\n\n\n',failed:'\n \n \n \n\n',info:'\n\n \n \n \n\n'};class k{constructor(e,t,n){this.resources=e,this.config=t,this.scannerView=n,this.editedFields={}}async launch(){try{return S(this.config.container).textContent="",await this.initialize(),S(this.config.container).style.display="flex",new Promise((e=>{this.currentScanResultViewResolver=e}))}catch(e){let t=(null==e?void 0:e.message)||e;throw console.error(t),t}}async handleRescan(){var e;try{if(!this.scannerView)return void console.error("Scanner View not initialized");this.hideView();const t=await this.scannerView.launch();if((null===(e=null==t?void 0:t.status)||void 0===e?void 0:e.code)===v.RS_FAILED)return void(this.currentScanResultViewResolver&&this.currentScanResultViewResolver(t));this.resources.onResultUpdated&&((null==t?void 0:t.status.code)===v.RS_CANCELLED?this.resources.onResultUpdated(this.resources.result):(null==t?void 0:t.status.code)===v.RS_SUCCESS&&this.resources.onResultUpdated(t)),this.dispose(!0),await this.initialize(),S(this.config.container).style.display="flex"}catch(e){throw console.error("Error in rescan handler:",e),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:v.RS_FAILED,message:(null==e?void 0:e.message)||e}}),e}}async handleDone(){var e,t;try{(null===(e=this.resources.result)||void 0===e?void 0:e.data)&&!R(this.editedFields)&&(this.resources.result.data=Object.assign(Object.assign({},this.resources.result.data),this.editedFields),this.resources.onResultUpdated&&this.resources.onResultUpdated(this.resources.result)),(null===(t=this.config)||void 0===t?void 0:t.onDone)&&await this.config.onDone(this.resources.result),this.currentScanResultViewResolver&&this.resources.result&&this.currentScanResultViewResolver(this.resources.result),this.hideView(),this.dispose()}catch(e){throw console.error("Error in done handler:",e),this.currentScanResultViewResolver&&this.currentScanResultViewResolver({status:{code:v.RS_FAILED,message:(null==e?void 0:e.message)||e}}),e}}createControls(){var e,t,n,i,s,a,o,r;const{toolbarButtonsConfig:l}=this.config;return function(e){E("dynamsoft-mrz-controls-style","\n .dynamsoft-mrz-controls {\n display: flex;\n height: 6rem;\n background-color: #323234;\n align-items: center;\n font-size: 12px;\n font-family: Verdana;\n color: white;\n width: 100%;\n }\n\n .dynamsoft-mrz-control-btn {\n background-color: #323234;\n color: white;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n height: 100%;\n width: 100%;\n gap: 0.5rem;\n text-align: center;\n user-select: none;\n }\n\n .dynamsoft-mrz-control-btn.hide {\n display: none;\n }\n\n .dynamsoft-mrz-control-btn.disabled {\n opacity: 0.4;\n pointer-events: none;\n cursor: default;\n }\n\n .dynamsoft-mrz-control-icon-wrapper {\n flex: 0.75;\n display: flex;\n align-items: flex-end;\n justify-content: center;\n min-height: 40px;\n }\n\n .dynamsoft-mrz-control-icon img,\n .dynamsoft-mrz-control-icon svg {\n width: 32px;\n height: 32px;\n fill: #fe8e14;\n }\n\n .dynamsoft-mrz-control-text {\n flex: 0.5;\n display: flex;\n align-items: flex-start;\n justify-content: center;\n padding-bottom: 0.5rem;\n }\n\n \n @media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-controls {\n flex-direction: column;\n height: 100%;\n width: 5rem;\n }\n\n .dynamsoft-mrz-control-text {\n padding: 0 0.5rem 0.5rem;\n }\n }\n");const t=document.createElement("div");return t.className="dynamsoft-mrz-controls",e.forEach((e=>{const n=document.createElement("div");n.className=`dynamsoft-mrz-control-btn ${null==e?void 0:e.className}`;const i=document.createElement("div");if(i.className="dynamsoft-mrz-control-icon-wrapper",(s=e.icon).trim().startsWith(""))i.innerHTML=e.icon;else{const t=document.createElement("img");t.src=e.icon,t.alt=e.label,t.width=24,t.height=24,i.appendChild(t)}var s;const a=document.createElement("div");a.className="dynamsoft-mrz-control-text",a.textContent=e.label,e.isDisabled&&n.classList.add("disabled"),e.isHidden&&n.classList.add("hide"),n.appendChild(i),n.appendChild(a),e.onClick&&!e.isDisabled&&n.addEventListener("click",e.onClick),t.appendChild(n)})),t}([{id:"dynamsoft-mrz-scanResult-rescan",icon:(null===(e=null==l?void 0:l.rescan)||void 0===e?void 0:e.icon)||_.rescan,label:(null===(t=null==l?void 0:l.rescan)||void 0===t?void 0:t.label)||"Re-scan",onClick:()=>this.handleRescan(),className:`${(null===(n=null==l?void 0:l.rescan)||void 0===n?void 0:n.className)||""}`,isHidden:(null===(i=null==l?void 0:l.rescan)||void 0===i?void 0:i.isHidden)||!1,isDisabled:!this.scannerView},{id:"dynamsoft-mrz-scanResult-done",icon:(null===(s=null==l?void 0:l.done)||void 0===s?void 0:s.icon)||_.complete,label:(null===(a=null==l?void 0:l.done)||void 0===a?void 0:a.label)||"Done",className:`${(null===(o=null==l?void 0:l.done)||void 0===o?void 0:o.className)||""}`,isHidden:(null===(r=null==l?void 0:l.done)||void 0===r?void 0:r.isHidden)||!1,onClick:()=>this.handleDone()}])}handleFieldEdit(e,t){if(e===x.DateOfBirth||e===x.DateOfExpiry)try{const[n,i,s]=t.split(/[\/\-\.]/);s&&i&&n&&(this.editedFields[e]={day:parseInt(s,10),month:parseInt(i,10),year:parseInt(n,10)})}catch(e){console.error("Error parsing date",e)}else this.editedFields[e]=t}createMRZDataDisplay(){var e;const t=(null===(e=this.resources.result)||void 0===e?void 0:e.data)||{},n=!!this.config.allowResultEditing,i=t.invalidFields||[],s=document.createElement("div");if(s.className="dynamsoft-mrz-data-container",R(t)){const e=document.createElement("div");return e.className="dynamsoft-mrz-data-row empty",e.innerText="No MRZ detected. Please try again.",s.appendChild(e),s}if(i.length>0){const e=document.createElement("div");e.className="dynamsoft-mrz-error-notification",e.innerHTML=`\n
${_.failed}
\n
\n ${n?"Some fields require correction. Please review highlighted fields.":"Some fields contain invalid information. Please rescan the document."}\n
\n `,s.appendChild(e)}else if(0===i.length&&n){const e=document.createElement("div");e.className="dynamsoft-mrz-info-notification",e.innerHTML=`\n
${_.info}
\n
\n Please review all fields to ensure the information is correct.\n
\n `,s.appendChild(e)}return Object.entries(t).forEach((([e,t])=>{var a;if(e===x.InvalidFields||!t)return;if(e===x.MRZText&&!1===(null===(a=this.config)||void 0===a?void 0:a.showMRZText))return;const o=document.createElement("div");o.className="dynamsoft-mrz-data-row";const r=i.includes(e);r&&o.classList.add("invalid-field");const l=[x.MRZText,x.DocumentType,x.IssuingStateRaw,x.NationalityRaw],c=document.createElement("span");if(c.className="dynamsoft-mrz-data-label",c.innerText=b[e]||e,r){const e=document.createElement("span");if(e.className="dynamsoft-mrz-error-icon",e.innerHTML=_.failed,c.appendChild(e),n){const e=document.createElement("span");e.className="dynamsoft-mrz-error-hint",e.textContent="Please correct this field",c.appendChild(e)}}const d=document.createElement("div");if(d.className="dynamsoft-mrz-data-value",n&&!l.includes(e)){const n=document.createElement("input");n.className="dynamsoft-mrz-data-input",r&&n.classList.add("invalid"),e===x.DateOfBirth||e===x.DateOfExpiry?(n.value=I(t),n.setAttribute("placeholder","YYYY-MM-DD")):n.value=t,n.addEventListener("input",(t=>{if(this.handleFieldEdit(e,t.target.value),r){n.classList.remove("invalid"),o.classList.remove("invalid-field"),this.editedFields.invalidFields||(this.editedFields.invalidFields=[...i]);const t=this.editedFields.invalidFields.indexOf(e);t>-1&&this.editedFields.invalidFields.splice(t,1)}})),d.appendChild(n)}else e===x.MRZText?(d.classList.add("code"),d.innerText=t):e===x.DateOfBirth||e===x.DateOfExpiry?d.innerText=I(t):d.innerText=t,r&&d.classList.add("invalid-value");o.appendChild(c),o.appendChild(d),s.appendChild(o)})),s}async initialize(){try{if(!this.resources.result)throw Error("Captured image is missing. Please capture an image first!");if(!this.config.container)throw new Error("Please create a Scan Result View Container element");E("dynamsoft-mrz-result-view-style",A);const e=document.createElement("div");if(e.className="dynamsoft-mrz-result-view-container",!1!==this.config.showOriginalImage){const t=this.resources.result.originalImageResult,n=document.createElement("div");let i;n.className="dynamsoft-mrz-result-view-image-container",(null==t?void 0:t.toCanvas)&&(i=null==t?void 0:t.toCanvas()),Object.assign(i.style,{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}),n.appendChild(i),e.appendChild(n)}const t=this.createMRZDataDisplay();e.appendChild(t);const n=this.createControls();e.appendChild(n),S(this.config.container).appendChild(e)}catch(e){let t=(null==e?void 0:e.message)||e;console.error(t),alert(t)}}hideView(){S(this.config.container).style.display="none"}dispose(e=!1){S(this.config.container).textContent="",e||(this.currentScanResultViewResolver=void 0)}}const A="\n .dynamsoft-mrz-result-view-container {\n display: flex;\n width: 100%;\n height: 100%;\n background-color:#575757;\n font-size: 12px;\n flex-direction: column;\n align-items: center;\n }\n\n .dynamsoft-mrz-result-view-image-container {\n width: 100%;\n height: 200px;\n display: flex;\n justify-content: center;\n align-items: center;\n background-color: #323234;\n }\n\n \n.dynamsoft-mrz-data-container {\n font-size: 16px;\n font-family: Verdana;\n color: white;\n overflow: auto;\n width: 100%;\n height: 100%;\n min-height: 0;\n margin: 1rem 0;\n}\n\n.dynamsoft-mrz-data-row {\n padding: 0.5rem 2rem;\n display: flex;\n flex-direction: column;\n gap: 0.5rem;\n transition: background-color 0.3s ease;\n}\n\n.dynamsoft-mrz-data-row.invalid-field {\n background-color: rgba(231, 76, 60, 0.1);\n border-left: 3px solid #e74c3c;\n padding-left: calc(2rem - 3px);\n}\n\n.dynamsoft-mrz-data-label {\n color: #aaa;\n display: flex;\n gap: 0.5rem;\n align-items: end;\n flex-wrap: wrap;\n}\n\n.dynamsoft-mrz-error-notification,\n.dynamsoft-mrz-info-notification {\n color: white;\n padding: 1rem;\n margin: 0.5rem 2rem;\n border-radius: 4px;\n display: flex;\n align-items: center;\n gap: 1rem;\n text-align: start;\n}\n\n.dynamsoft-mrz-error-notification {\n background-color: rgba(231, 76, 60, 0.2);\n}\n\n.dynamsoft-mrz-info-notification {\n background-color: rgba(196, 231, 60, 0.2);\n}\n\n.dynamsoft-mrz-edit-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #aaa;\n}\n\n.dynamsoft-mrz-error-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-info-icon {\n display: flex;\n align-items: center;\n justify-content: center;\n color: white;\n}\n\n.dynamsoft-mrz-info-message,\n.dynamsoft-mrz-error-message {\n flex: 1;\n}\n\n.dynamsoft-mrz-error-hint {\n font-size: 0.8rem;\n color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-value {\n word-wrap: break-word;\n text-align: start;\n}\n\n.dynamsoft-mrz-data-value.code {\n font-family: monospace;\n}\n\n.dynamsoft-mrz-data-value.invalid-value {\n color: #e74c3c;\n text-decoration: wavy underline #e74c3c;\n text-decoration-skip-ink: none;\n}\n\n.dynamsoft-mrz-data-input {\n width: 100%;\n padding: 5px;\n background-color: rgba(255, 255, 255, 0.1);\n border: 1px solid rgba(255, 255, 255, 0.3);\n color: white;\n border-radius: 4px;\n font-size: 14px;\n transition: all 0.3s ease;\n}\n\n.dynamsoft-mrz-data-input.invalid {\n background-color: rgba(231, 76, 60, 0.1);\n border-color: #e74c3c;\n}\n\n.dynamsoft-mrz-data-input:focus {\n background-color: rgba(255, 255, 255, 0.2);\n border-color: #fe8e14;\n outline: none;\n}\n\n@media screen and (orientation: landscape) and (max-width: 1024px) and (max-height: 600px) {\n .dynamsoft-mrz-result-view-container {\n flex-direction: row;\n }\n\n .dynamsoft-mrz-result-view-image-container{\n flex: 1;\n height: 100%;\n }\n\n .dynamsoft-mrz-data-container{\n flex: 1;\n }\n\n .dynamsoft-mrz-data-row:first-of-type {\n padding-top: 2rem;\n }\n\n .dynamsoft-mrz-data-row:last-of-type {\n padding-bottom: 2rem;\n }\n\n .dynamsoft-mrz-data-row.empty {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n padding-top: 0;\n padding-bottom: 0;\n }\n}\n",O={rootDirectory:"https://cdn.jsdelivr.net/npm/"};class P{showLoadingOverlay(e){var t,n;const i=S(null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)||S(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container);this.loadingScreen=T(i,{message:e}),i.style.display="block",i.style.position="relative"}hideLoadingOverlay(e=!1){var t,n,i;const s=S(null===(t=this.config.scannerViewConfig)||void 0===t?void 0:t.container)||S(null===(n=this.config.resultViewConfig)||void 0===n?void 0:n.container);this.loadingScreen&&(this.loadingScreen.hide(),this.loadingScreen=null,s.style.display="none",e&&(null===(i=this.config)||void 0===i?void 0:i.container)&&(S(this.config.container).style.display="none"))}constructor(e){this.config=e,this.resources={},this.isInitialized=!1,this.isCapturing=!1,this.loadingScreen=null}async initialize(){if(this.isInitialized)return{resources:this.resources,components:{scannerView:this.scannerView,resultView:this.resultView}};try{if(!this.initializeMRZScannerConfig())return console.error("Failed to initialize mrz scanner config"),{resources:this.resources,components:{}};E("dynamsoft-mrz-loading-screen-style",M),this.showLoadingOverlay("Loading...");if(!await this.initializeDCVResources())return this.hideLoadingOverlay(!0),console.error("Failed to initialize DCV resources"),{resources:this.resources,components:{}};this.resources.onResultUpdated=e=>{this.resources.result=e};const e={};return this.config.scannerViewConfig&&(this.scannerView=new F(this.resources,this.config.scannerViewConfig),e.scannerView=this.scannerView,await this.scannerView.initialize()),this.config.resultViewConfig&&(this.resultView=new k(this.resources,this.config.resultViewConfig,this.scannerView),e.resultView=this.resultView),this.isInitialized=!0,{resources:this.resources,components:e}}catch(e){this.isInitialized=!1;const t=`Initialization Failed: ${(null==e?void 0:e.message)||e}`;return console.error(t),{resources:this.resources,components:{}}}finally{this.hideLoadingOverlay(!0)}}async initializeDCVResources(){var e,t,n;try{return s.engineResourcePaths=R(null===(e=this.config)||void 0===e?void 0:e.engineResourcePaths)?O:this.config.engineResourcePaths,a._onAuthMessage=e=>e.replace("(https://www.dynamsoft.com/customer/license/trialLicense?product=unknown&deploymenttype=unknown)","(https://www.dynamsoft.com/customer/license/trialLicense?product=mrz&deploymenttype=web)"),await a.initLicense((null===(t=this.config)||void 0===t?void 0:t.license)||"",{executeNow:!0}),s.loadWasm(["DLR","DCP"]),m.loadSpec("MRTD_TD3_PASSPORT"),m.loadSpec("MRTD_TD1_ID"),m.loadSpec("MRTD_TD2_ID"),h.loadRecognitionData("MRZ"),this.resources.cameraView=await c.createInstance(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.cameraEnhancerUIPath),this.resources.cameraEnhancer=await d.createInstance(this.resources.cameraView),this.resources.cvRouter=await r.createInstance(),!0}catch(e){let t=(null==e?void 0:e.message)||e;if(null==t?void 0:t.toLowerCase().includes("license")){const e="The MRZ Scanner license is invalid or has expired. Please contact the site administrator to resolve this issue.";alert(e),console.error(e)}else{const e=`Resource Initialization Failed: ${t}`;alert(e),console.error(e)}return!1}}shouldCreateDefaultContainer(){var e,t;const n=!this.config.container,i=!((null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)||(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container));return n&&i}createDefaultMRZScannerContainer(){const e=document.createElement("div");return e.className="mrz-scanner-main-container",Object.assign(e.style,{height:"100dvh",width:"100%",position:"absolute",left:"0",top:"0",zIndex:"999"}),document.body.append(e),e}checkForTemporaryLicense(e){return!(null==e?void 0:e.length)||(null==e?void 0:e.startsWith("A"))||(null==e?void 0:e.startsWith("L"))||(null==e?void 0:e.startsWith("P"))||(null==e?void 0:e.startsWith("Y"))?"DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9":e}validateViewConfigs(){var e,t,n,i,s,a,o,r;if(!this.config.container){if((null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container)&&this.config.showResultView&&!(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container)){const e="MRZResultView container is required when showResultView is true";return alert(e),console.error(e),!1}if(!(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)&&(null===(i=this.config.resultViewConfig)||void 0===i?void 0:i.container)&&!this.resources.result){const e="Result is needed to create MRZResultView without a scanner view";return alert(e),console.error(e),!1}}try{if(this.config.container&&!S(this.config.container)){const e="Invalid main container reference";return alert(e),console.error(e),!1}if((null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.container)&&!S(null===(a=this.config.scannerViewConfig)||void 0===a?void 0:a.container)){const e="Invalid scanner view container reference";return alert(e),console.error(e),!1}if((null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)&&!S(null===(r=this.config.resultViewConfig)||void 0===r?void 0:r.container)){const e="Invalid result view container reference";return alert(e),console.error(e),!1}}catch(e){const t=`Error accessing container references: ${e.message}`;return alert(t),console.error(t),!1}return!0}showResultView(){var e,t;return!1!==this.config.showResultView&&(this.config.container?!(void 0!==this.config.showResultView||!(null===(e=this.config.resultViewConfig)||void 0===e?void 0:e.container)&&!this.config.container)||!!this.config.showResultView:this.config.showResultView&&!!(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container))}initializeMRZScannerConfig(){var e,t,n,i,s,a,o;this.config=null!==(e=this.config)&&void 0!==e?e:{};if(!this.validateViewConfigs())return!1;this.shouldCreateDefaultContainer()?this.config.container=this.createDefaultMRZScannerContainer():this.config.container&&(this.config.container=S(this.config.container));const r=this.config.container?this.createViewContainers(S(this.config.container)):{},l={license:this.checkForTemporaryLicense(this.config.license),utilizedTemplateNames:Object.fromEntries(Object.values(p).map((e=>{var t;return[e,(null===(t=this.config.utilizedTemplateNames)||void 0===t?void 0:t[e])||w[e]]}))),templateFilePath:(null===(t=this.config)||void 0===t?void 0:t.templateFilePath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.1.0-beta.0514202501/dist/mrz-scanner.template.json"},c=Object.assign(Object.assign({},this.config.scannerViewConfig),{container:r[y.Scanner]||S(null===(n=this.config.scannerViewConfig)||void 0===n?void 0:n.container)||null,cameraEnhancerUIPath:(null===(i=this.config.scannerViewConfig)||void 0===i?void 0:i.cameraEnhancerUIPath)||"https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.1.0-beta.0514202501/dist/mrz-scanner.ui.html",templateFilePath:l.templateFilePath,utilizedTemplateNames:l.utilizedTemplateNames,enableMultiFrameCrossFilter:null===(a=null===(s=this.config.scannerViewConfig)||void 0===s?void 0:s.enableMultiFrameCrossFilter)||void 0===a||a,mrzFormatType:this.config.mrzFormatType}),d=this.showResultView()?Object.assign(Object.assign({},this.config.resultViewConfig),{container:r[y.Result]||S(null===(o=this.config.resultViewConfig)||void 0===o?void 0:o.container)||null}):void 0;return Object.assign(this.config,Object.assign(Object.assign({},l),{scannerViewConfig:c,resultViewConfig:d})),!0}createViewContainers(e){e.textContent="";const t=[y.Scanner];return this.showResultView()&&t.push(y.Result),t.reduce(((t,n)=>{const i=document.createElement("div");return i.className=`mrz-scanner-${n}-view-container`,Object.assign(i.style,{height:"100%",width:"100%",display:"none",position:"relative"}),e.append(i),t[n]=i,t}),{})}dispose(){var e,t;this.resultView&&(this.resultView.dispose(),this.resultView=null),this.scannerView=null,this.resources.cameraEnhancer&&(this.resources.cameraEnhancer.dispose(),this.resources.cameraEnhancer=null),this.resources.cameraView&&(this.resources.cameraView.dispose(),this.resources.cameraView=null),this.resources.cvRouter&&(this.resources.cvRouter.dispose(),this.resources.cvRouter=null),this.resources.result=null,this.resources.onResultUpdated=null;const n=e=>{const t=S(e);t&&(t.style.display="none",t.textContent="")};n(this.config.container),n(null===(e=this.config.scannerViewConfig)||void 0===e?void 0:e.container),n(null===(t=this.config.resultViewConfig)||void 0===t?void 0:t.container),this.isInitialized=!1}async processUploadedFile(i){var s,a,o,r;try{this.showLoadingOverlay("Processing File...");const{cvRouter:l}=this.resources,c=null===(s=this.config.utilizedTemplateNames)||void 0===s?void 0:s.all,d=await l.getSimplifiedSettings(c);d.roiMeasuredInPercentage=!0,d.roi.points=[{x:0,y:0},{x:100,y:0},{x:100,y:100},{x:0,y:100}],await l.updateSettings(c,d);const h=await l.capture(i,c),u=h.items,m=u.filter((t=>t.type===e.CRIT_ORIGINAL_IMAGE))[0].imageData;m.toCanvas=()=>t(m),m.toBlob=async()=>await n("image/png",m);const g=null==h?void 0:h.textLineResultItems,p=null==h?void 0:h.parsedResultItems;let f={};if(null==g?void 0:g.length){const e=(null===(a=g[0])||void 0===a?void 0:a.text)||"";f=N(e,p[0])}const y={status:{code:v.RS_SUCCESS,message:"Success"},originalImageResult:m,data:f,imageData:!0,_imageData:m};null===(r=(o=this.resources).onResultUpdated)||void 0===r||r.call(o,y)}catch(e){return console.error("Failed to process uploaded file:",e),{status:{code:v.RS_FAILED,message:`Failed to process image: ${e.message||e}`}}}finally{this.hideLoadingOverlay(!1)}}async launch(e){if(this.isCapturing)throw new Error("Capture session already in progress");try{this.isCapturing=!0;const{components:t}=await this.initialize();if(R(t))throw new Error("MRZ Scanner initialization failed.");if(this.config.container&&(S(this.config.container).style.display="block"),e&&(t.scannerView=null,await this.processUploadedFile(e)),!t.scannerView&&this.resources.result&&t.resultView)return await t.resultView.launch();if(!t.scannerView&&!this.resources.result)throw new Error("Scanner view is required when no previous result exists");if(t.scannerView){const e=await t.scannerView.launch();if((null==e?void 0:e.status.code)!==v.RS_SUCCESS)return{status:{code:null==e?void 0:e.status.code,message:(null==e?void 0:e.status.message)||"Failed to capture image"}};if(t.resultView)return await t.resultView.launch()}return this.resources.result}catch(e){return alert((null==e?void 0:e.message)||e),console.error((null==e?void 0:e.message)||e),{status:{code:v.RS_FAILED,message:(null==e?void 0:e.message)||e}}}finally{this.isCapturing=!1,this.dispose()}}}const B={MRZScanner:P,MRZScannerView:F,MRZResultView:k};export{w as DEFAULT_TEMPLATE_NAMES,B as DynamsoftMRZScanner,x as EnumMRZData,f as EnumMRZDocumentType,p as EnumMRZScanMode,y as EnumMRZScannerViews,v as EnumResultStatus,b as MRZDataLabel,k as MRZResultView,P as MRZScanner,F as MRZScannerView,I as displayMRZDate}; diff --git a/dist/mrz-scanner.ui.html b/dist/mrz-scanner.ui.html index 0d7b3e0..b9ce3cd 100644 --- a/dist/mrz-scanner.ui.html +++ b/dist/mrz-scanner.ui.html @@ -8,69 +8,67 @@ id="video-resolution" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" - width="36" - height="21" - viewBox="0 0 36 21" + width="29.308" + height="16.998" + viewBox="0 0 29.308 16.998" > - - + + - - - + + - - + + + + + + + + + @@ -93,181 +91,316 @@
- - - - - - - - - - - + + + + + + + + + + + + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
-
-
- - - - +
+ + + + + + + + + + + + + + + + + + + + - - - - - - - - -
-
- - - A - - - - - - - - - - - - - - -
-
- - - - -
+ + +
+
+ + + + + + + + + + + + + + + +
- - - - + + + - - - - - - - - + H219.4z M234.1,241.4v7.3h7.3v-7.3H234.1z" /> + + + + + + + + \ No newline at end of file diff --git a/samples/demo/index.html b/samples/demo/index.html index 6ec4af9..7f7657b 100644 --- a/samples/demo/index.html +++ b/samples/demo/index.html @@ -5,9 +5,9 @@ Dynamsoft MRZ Scanner - + - + diff --git a/samples/hello-world.html b/samples/hello-world.html index 73f20a0..066b699 100644 --- a/samples/hello-world.html +++ b/samples/hello-world.html @@ -4,9 +4,9 @@ Dynamsoft MRZ Scanner - Hello World + + - - @@ -22,6 +22,9 @@

Dynamsoft MRZ Scanner

// Initialize the Dynamsoft MRZ Scanner const mrzscanner = new Dynamsoft.MRZScanner({ license: "YOUR_LICENSE_KEY_HERE", + scannerViewConfig: { + cameraEnhancerUIPath: "../dist/mrz-scanner.ui.html", + }, }); (async () => { diff --git a/samples/scenarios/use-file-input.html b/samples/scenarios/use-file-input.html new file mode 100644 index 0000000..f9b0327 --- /dev/null +++ b/samples/scenarios/use-file-input.html @@ -0,0 +1,170 @@ + + + + + + Dynamsoft MRZ Scanner - Use File Input + + + + + + + + + + + + + +
+ + + diff --git a/src/MRZScanner.ts b/src/MRZScanner.ts index 962daf1..7b7e9c1 100644 --- a/src/MRZScanner.ts +++ b/src/MRZScanner.ts @@ -1,8 +1,17 @@ import { LicenseManager } from "dynamsoft-license"; -import { CoreModule, EngineResourcePaths } from "dynamsoft-core"; +import { + _toBlob, + _toCanvas, + CoreModule, + DSImageData, + EngineResourcePaths, + EnumCapturedResultItemType, + MimeType, + OriginalImageResultItem, +} from "dynamsoft-core"; import { CaptureVisionRouter } from "dynamsoft-capture-vision-router"; import { CameraEnhancer, CameraView } from "dynamsoft-camera-enhancer"; -import { CodeParserModule } from "dynamsoft-code-parser"; +import { CodeParserModule, ParsedResultItem } from "dynamsoft-code-parser"; import { LabelRecognizerModule } from "dynamsoft-label-recognizer"; import { DEFAULT_TEMPLATE_NAMES, @@ -14,14 +23,15 @@ import { } from "./views/utils/types"; import { createStyle, getElement, isEmptyObject } from "./views/utils"; import MRZScannerView, { MRZScannerViewConfig } from "./views/MRZScannerView"; -import { MRZResult } from "./views/utils/MRZParser"; +import { MRZData, MRZResult, processMRZData } from "./views/utils/MRZParser"; import MRZResultView, { MRZResultViewConfig } from "./views/MRZResultView"; import { DEFAULT_LOADING_SCREEN_STYLE, showLoadingScreen } from "./views/utils/LoadingScreen"; // Default DCE UI path -const DEFAULT_DCE_UI_PATH = "https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.0.0/dist/mrz-scanner.ui.html"; +const DEFAULT_DCE_UI_PATH = + "https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.1.0-beta.0514202501/dist/mrz-scanner.ui.html"; // TODO const DEFAULT_MRZ_SCANNER_TEMPLATE_PATH = - "https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.0.0/dist/mrz-scanner.template.json"; + "https://cdn.jsdelivr.net/npm/dynamsoft-mrz-scanner@2.1.0-beta.0514202501/dist/mrz-scanner.template.json"; // TODO const DEFAULT_DCV_ENGINE_RESOURCE_PATHS = { rootDirectory: "https://cdn.jsdelivr.net/npm/" }; const DEFAULT_CONTAINER_HEIGHT = "100dvh"; @@ -77,13 +87,10 @@ class MRZScanner { if (this.loadingScreen) { this.loadingScreen.hide(); this.loadingScreen = null; + configContainer.style.display = "none"; - if (hideContainer) { - configContainer.style.display = "none"; - - if (this.config?.container) { - getElement(this.config.container).style.display = "none"; - } + if (hideContainer && this.config?.container) { + getElement(this.config.container).style.display = "none"; } } } @@ -156,9 +163,8 @@ class MRZScanner { let errMsg = ex?.message || ex; const error = `Initialization Failed: ${errMsg}`; - - alert(error); console.error(error); + return { resources: this.resources, components: {} }; } finally { this.hideLoadingOverlay(true); @@ -167,15 +173,21 @@ class MRZScanner { private async initializeDCVResources(): Promise { try { - LicenseManager.initLicense(this.config?.license || "", true); - //The following code uses the jsDelivr CDN, feel free to change it to your own location of these files CoreModule.engineResourcePaths = isEmptyObject(this.config?.engineResourcePaths) ? DEFAULT_DCV_ENGINE_RESOURCE_PATHS : this.config.engineResourcePaths; - // Optional. Used to load wasm resources in advance, reducing latency between video playing and document modules. + // Change trial link to include product and deploymenttype + (LicenseManager as any)._onAuthMessage = (message: string) => + message.replace( + "(https://www.dynamsoft.com/customer/license/trialLicense?product=unknown&deploymenttype=unknown)", + "(https://www.dynamsoft.com/customer/license/trialLicense?product=mrz&deploymenttype=web)" + ); + + await LicenseManager.initLicense(this.config?.license || "", { executeNow: true }); + // Optional. Used to load wasm resources in advance, reducing latency between video playing and document modules. // Can add other specs. Please check https://www.dynamsoft.com/code-parser/docs/core/code-types/mrtd.html CoreModule.loadWasm(["DLR", "DCP"]); CodeParserModule.loadSpec("MRTD_TD3_PASSPORT"); @@ -440,7 +452,95 @@ class MRZScanner { this.isInitialized = false; } - async launch(): Promise { + /** + * Processes an uploaded image file + * @param imageOrFile The file to process + * @returns Promise with the document result + */ + private async processUploadedFile( + imageOrFile: Blob | string | DSImageData | HTMLImageElement | HTMLVideoElement | HTMLCanvasElement + ): Promise { + try { + this.showLoadingOverlay("Processing File..."); + + const { cvRouter } = this.resources; + + // Use CaptureVisionRouter to process the image + const currentTemplate = this.config.utilizedTemplateNames?.all; + + const newSettings = await cvRouter.getSimplifiedSettings(currentTemplate); + newSettings.roiMeasuredInPercentage = true; + newSettings.roi.points = [ + { + x: 0, + y: 0, + }, + { + x: 100, + y: 0, + }, + { + x: 100, + y: 100, + }, + { + x: 0, + y: 100, + }, + ]; + await cvRouter.updateSettings(currentTemplate, newSettings); + const capturedResult = await cvRouter.capture(imageOrFile, currentTemplate); + const resultItems = capturedResult.items; + const originalImage = resultItems.filter( + (item) => item.type === EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE + ) as OriginalImageResultItem[]; + + const imageData = originalImage[0].imageData; + (imageData as any).toCanvas = () => _toCanvas(imageData); + (imageData as any).toBlob = async () => await _toBlob(`image/png` as MimeType, imageData); + + const textLineResultItems = capturedResult?.textLineResultItems; + const parsedResultItems = capturedResult?.parsedResultItems; + + let processedData = {} as MRZData; + + if (textLineResultItems?.length) { + const mrzText = textLineResultItems[0]?.text || ""; + const parsedResult = parsedResultItems[0] as ParsedResultItem; + + processedData = processMRZData(mrzText, parsedResult); + } + + const mrzResult = { + status: { + code: EnumResultStatus.RS_SUCCESS, + message: "Success", + }, + originalImageResult: imageData, + data: processedData, + + // Used for MWC + imageData: true, + _imageData: imageData, + }; + // Emit result through shared resources + this.resources.onResultUpdated?.(mrzResult); + } catch (error) { + console.error("Failed to process uploaded file:", error); + return { + status: { + code: EnumResultStatus.RS_FAILED, + message: `Failed to process image: ${error.message || error}`, + }, + }; + } finally { + this.hideLoadingOverlay(false); + } + } + + async launch( + imageOrFile: Blob | string | DSImageData | HTMLImageElement | HTMLVideoElement | HTMLCanvasElement + ): Promise { if (this.isCapturing) { throw new Error("Capture session already in progress"); } @@ -457,6 +557,12 @@ class MRZScanner { getElement(this.config.container).style.display = "block"; } + // Handle direct file upload if provided + if (imageOrFile) { + components.scannerView = null; + await this.processUploadedFile(imageOrFile); + } + // Special case handling for direct views with existing results if (!components.scannerView && this.resources.result) { if (components.resultView) return await components.resultView.launch(); diff --git a/src/mrz-scanner.ui.html b/src/mrz-scanner.ui.html index 0d7b3e0..b9ce3cd 100644 --- a/src/mrz-scanner.ui.html +++ b/src/mrz-scanner.ui.html @@ -8,69 +8,67 @@ id="video-resolution" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" - width="36" - height="21" - viewBox="0 0 36 21" + width="29.308" + height="16.998" + viewBox="0 0 29.308 16.998" > - - + + - - - + + - - + + + + + + + + +
@@ -93,181 +91,316 @@
- - - - - - - - - - - + + + + + + + + + + + + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
-
-
- - - - +
+ + + + + + + + + + + + + + + + + + + + - - - - - - - - -
-
- - - A - - - - - - - - - - - - - - -
-
- - - - -
+ + +
+
+ + + + + + + + + + + + + + + +
Promise; // Function to convert non-image files to blobs } const MRZScanGuideRatios: Record = { @@ -209,11 +220,16 @@ export default class MRZScannerView { // Hide configs if (this.config.showUploadImage === false) { - this.DCE_ELEMENTS.uploadImageBtn.style.display = "none"; + this.DCE_ELEMENTS.uploadImageBtn.style.visibility = "hidden"; } if (this.config.showSoundToggle === false) { - this.DCE_ELEMENTS.soundFeedbackBtn.style.display = "none"; + this.DCE_ELEMENTS.soundFeedbackBtn.style.visibility = "hidden"; + } + + if (this.config?.showPoweredByDynamsoft === false) { + const poweredByDynamsoft = DCEContainer.shadowRoot.querySelector(".dce-mn-msg-poweredby") as HTMLElement; + poweredByDynamsoft.style.display = "none"; } this.initializedDCE = true; @@ -250,7 +266,7 @@ export default class MRZScannerView { this.closeCamera = this.closeCamera.bind(this); - this.DCE_ELEMENTS.uploadImageBtn.onclick = () => this.uploadImage(); + this.DCE_ELEMENTS.uploadImageBtn.onclick = () => this.uploadFile(); this.DCE_ELEMENTS.soundFeedbackBtn.onclick = () => this.toggleSoundFeedback(); this.DCE_ELEMENTS.closeScannerBtn.onclick = () => this.handleCloseBtn(); @@ -393,26 +409,31 @@ export default class MRZScannerView { settingsBox.click(); } - private async uploadImage() { + private async relaunch() { + return; + } + + private async uploadFile() { const { cvRouter } = this.resources; // Create hidden file input const input = document.createElement("input"); input.type = "file"; - input.accept = "image/*"; + input.accept = this.config.uploadAcceptedTypes ?? "image/*"; input.style.display = "none"; document.body.appendChild(input); try { - this.showScannerLoadingOverlay("Processing image..."); + this.showScannerLoadingOverlay("Processing file..."); await this.closeCamera(false); // Get file from input const file = await new Promise((resolve, reject) => { input.onchange = (e: Event) => { const f = (e.target as HTMLInputElement).files?.[0]; - if (!f?.type.startsWith("image/")) { - reject(new Error("Please select an image file")); + + if (!f) { + reject(new Error("No file selected")); return; } resolve(f); @@ -420,69 +441,67 @@ export default class MRZScannerView { input.addEventListener("cancel", async () => { this.hideScannerLoadingOverlay(false); - await this.launch(); + // Start capturing + await this.openCamera(); + + await this.startCapturing(); + + //Show scan guide + this.toggleScanGuide(); }); input.click(); }); if (!file) { - this.hideScannerLoadingOverlay(false); - await this.launch(); - return; } - // Convert file to blob - const currentTemplate = this.config.utilizedTemplateNames[this.currentScanMode]; + let fileBlob: Blob; + + // Use custom converter if provided and file is not an image + if (this.config.uploadFileConverter && !file.type.startsWith("image/")) { + try { + fileBlob = await this.config.uploadFileConverter(file); + } catch (error) { + throw new Error(`Error converting file: ${error.message}`); + } + } else if (file.type.startsWith("image/")) { + // For images, use existing conversion path + fileBlob = file; + } else { + throw new Error("Unsupported file type. Please provide a converter function for this file type."); + } + // Update ROI for full image scanning + const currentTemplate = this.config.utilizedTemplateNames[this.currentScanMode]; if (this.config.showScanGuide !== false) { - // Update ROI if scanGuide can be shown const newSettings = await cvRouter.getSimplifiedSettings(currentTemplate); newSettings.roiMeasuredInPercentage = true; newSettings.roi.points = [ - { - x: 0, - y: 0, - }, - { - x: 100, - y: 0, - }, - { - x: 100, - y: 100, - }, - { - x: 0, - y: 100, - }, + { x: 0, y: 0 }, + { x: 100, y: 0 }, + { x: 100, y: 100 }, + { x: 0, y: 100 }, ]; await cvRouter.updateSettings(currentTemplate, newSettings); } - const capturedResult = await cvRouter.capture(file, currentTemplate); + // Capture mrz from file + const capturedResult = await cvRouter.capture(fileBlob, currentTemplate); this.capturedResultItems = capturedResult.items; const originalImage = this.capturedResultItems.filter( (item) => item.type === EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE ) as OriginalImageResultItem[]; - const imageData = originalImage[0].imageData; - (imageData as any).toCanvas = () => { - const canvas = document.createElement("canvas"); - canvas.width = imageData.width; - canvas.height = imageData.height; - const ctx = canvas.getContext("2d"); - if (!ctx) { - throw new Error("Failed to get canvas context"); - } + if (originalImage.length === 0) { + throw new Error("No image data found in the captured result"); + } - // Create ImageData from the bytes - const imgData = new ImageData(new Uint8ClampedArray(imageData.bytes.buffer), imageData.width, imageData.height); - ctx.putImageData(imgData, 0, 0); + const imageData = originalImage[0].imageData; + (imageData as any).toCanvas = () => _toCanvas(imageData); + (imageData as any).toBlob = async () => await _toBlob(`image/png` as MimeType, imageData); - return canvas; - }; this.originalImageData = imageData; const textLineResultItems = capturedResult?.textLineResultItems; @@ -493,7 +512,6 @@ export default class MRZScannerView { if (textLineResultItems?.length) { const mrzText = textLineResultItems[0]?.text || ""; const parsedResult = parsedResultItems[0] as ParsedResultItem; - processedData = processMRZData(mrzText, parsedResult); } @@ -503,17 +521,14 @@ export default class MRZScannerView { message: "Success", }, originalImageResult: this.originalImageData, - _imageData: this.originalImageData, data: processedData, + + imageData: true, + _imageData: this.originalImageData, }; - // Emit result through shared resources - this.resources.onResultUpdated?.(mrzResult); - // Resolve scan promise + this.resources.onResultUpdated?.(mrzResult); this.currentScanResolver(mrzResult); - - // Done processing - this.hideScannerLoadingOverlay(true); } catch (ex: any) { let errMsg = ex?.message || ex; console.error(errMsg); @@ -523,11 +538,12 @@ export default class MRZScannerView { const result = { status: { code: EnumResultStatus.RS_FAILED, - message: "Error processing uploaded image", + message: `Error processing file: ${errMsg}`, }, }; this.currentScanResolver(result); } finally { + this.hideScannerLoadingOverlay(true); document.body.removeChild(input); } } @@ -704,6 +720,12 @@ export default class MRZScannerView { await cameraEnhancer.resume(); } + // Try to set default as 2k + await cameraEnhancer.setResolution({ + width: 2560, + height: 1440, + }); + // Assign element if (!this.initializedDCE && cameraEnhancer.isOpen()) { await this.initializeElements(); @@ -789,8 +811,12 @@ export default class MRZScannerView { const originalImage = result.items.filter( (item) => item.type === EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE ) as OriginalImageResultItem[]; - this.originalImageData = originalImage.length && originalImage[0].imageData; + const imageData = originalImage[0].imageData; + (imageData as any).toCanvas = () => _toCanvas(imageData); + (imageData as any).toBlob = async () => await _toBlob(`image/png` as MimeType, imageData); + + this.originalImageData = imageData; const textLineResultItems = result?.textLineResultItems; const parsedResultItems = result?.parsedResultItems; @@ -812,8 +838,11 @@ export default class MRZScannerView { message: "Success", }, originalImageResult: this.originalImageData, - _imageData: this.originalImageData, data: processedData, + + // Used for MWC + imageData: true, + _imageData: this.originalImageData, }; // Emit result through shared resources diff --git a/src/views/utils/MRZParser.ts b/src/views/utils/MRZParser.ts index a4b0891..f732e8d 100644 --- a/src/views/utils/MRZParser.ts +++ b/src/views/utils/MRZParser.ts @@ -14,7 +14,9 @@ export enum EnumMRZData { Age = "age", Sex = "sex", IssuingState = "issuingState", + IssuingStateRaw = "issuingStateRaw", Nationality = "nationality", + NationalityRaw = "nationalityRaw", DateOfBirth = "dateOfBirth", DateOfExpiry = "dateOfExpiry", } @@ -24,6 +26,8 @@ export interface MRZResult { originalImageResult?: DSImageData; data?: MRZData; + // Used for MWC + imageData?: boolean; _imageData?: DSImageData; } @@ -37,7 +41,9 @@ export interface MRZData { [EnumMRZData.Age]: number; [EnumMRZData.Sex]: string; [EnumMRZData.IssuingState]: string; + [EnumMRZData.IssuingStateRaw]: string; [EnumMRZData.Nationality]: string; + [EnumMRZData.NationalityRaw]: string; [EnumMRZData.DateOfBirth]: MRZDate; [EnumMRZData.DateOfExpiry]: MRZDate; } @@ -59,7 +65,9 @@ export const MRZDataLabel: Record = { [EnumMRZData.Age]: "Age", [EnumMRZData.Sex]: "Sex", [EnumMRZData.IssuingState]: "Issuing State", + [EnumMRZData.IssuingStateRaw]: "Issuing State (Raw Value)", [EnumMRZData.Nationality]: "Nationality", + [EnumMRZData.NationalityRaw]: "Nationality State (Raw Value)", [EnumMRZData.DateOfBirth]: "Date Of Birth (YYYY-MM-DD)", [EnumMRZData.DateOfExpiry]: "Date Of Expiry (YYYY-MM-DD)", }; @@ -138,6 +146,11 @@ function documentTypeLabel(codeType: string): string { } } +function processRawCountryCodes(result: string) { + // As of DCV 2.6.1000, there's a bug with DCP (Dynamsoft Code Parser) where German nationality and issuing state is noted as `D<<` + return result === "D<<" ? "D" : result; +} + export function processMRZData(mrzText: string, parsedResult: ParsedResultItem): MRZData | null { const invalidFields: EnumMRZData[] = []; @@ -188,10 +201,12 @@ export function processMRZData(mrzText: string, parsedResult: ParsedResultItem): const fields = { [EnumMRZData.LastName]: parsedResult.getFieldValue("primaryIdentifier"), [EnumMRZData.FirstName]: parsedResult.getFieldValue("secondaryIdentifier"), - [EnumMRZData.Nationality]: parsedResult.getFieldRawValue("nationality"), + [EnumMRZData.Nationality]: parsedResult.getFieldValue("nationality"), + [EnumMRZData.NationalityRaw]: processRawCountryCodes(parsedResult.getFieldRawValue("nationality")), [EnumMRZData.DocumentNumber]: parsedResult.getFieldValue(documentNumberField) || parsedResult.getFieldValue("longDocumentNumber"), - [EnumMRZData.IssuingState]: parsedResult.getFieldRawValue("issuingState"), + [EnumMRZData.IssuingState]: parsedResult.getFieldValue("issuingState"), + [EnumMRZData.IssuingStateRaw]: processRawCountryCodes(parsedResult.getFieldRawValue("issuingState")), [EnumMRZData.Sex]: capitalize(parsedResult.getFieldValue("sex")), }; @@ -228,9 +243,11 @@ export function processMRZData(mrzText: string, parsedResult: ParsedResultItem): [EnumMRZData.DateOfBirth]: dateOfBirth, [EnumMRZData.Sex]: fields[EnumMRZData.Sex], [EnumMRZData.Nationality]: fields[EnumMRZData.Nationality], + [EnumMRZData.NationalityRaw]: fields[EnumMRZData.NationalityRaw], [EnumMRZData.DocumentNumber]: fields[EnumMRZData.DocumentNumber], [EnumMRZData.DateOfExpiry]: dateOfExpiry, [EnumMRZData.IssuingState]: fields[EnumMRZData.IssuingState], + [EnumMRZData.IssuingStateRaw]: fields[EnumMRZData.IssuingStateRaw], [EnumMRZData.DocumentType]: capitalize(docTypeLabel), [EnumMRZData.MRZText]: mrzText, };